repo_name stringlengths 6 100 | path stringlengths 4 294 | copies stringlengths 1 5 | size stringlengths 4 6 | content stringlengths 606 896k | license stringclasses 15
values |
|---|---|---|---|---|---|
jank3/django | django/core/exceptions.py | 486 | 5276 | """
Global Django exception and warning classes.
"""
from django.utils import six
from django.utils.encoding import force_text
class FieldDoesNotExist(Exception):
"""The requested model field does not exist"""
pass
class DjangoRuntimeWarning(RuntimeWarning):
pass
class AppRegistryNotReady(Exception):
"""The django.apps registry is not populated yet"""
pass
class ObjectDoesNotExist(Exception):
"""The requested object does not exist"""
silent_variable_failure = True
class MultipleObjectsReturned(Exception):
"""The query returned multiple objects when only one was expected."""
pass
class SuspiciousOperation(Exception):
"""The user did something suspicious"""
class SuspiciousMultipartForm(SuspiciousOperation):
"""Suspect MIME request in multipart form data"""
pass
class SuspiciousFileOperation(SuspiciousOperation):
"""A Suspicious filesystem operation was attempted"""
pass
class DisallowedHost(SuspiciousOperation):
"""HTTP_HOST header contains invalid value"""
pass
class DisallowedRedirect(SuspiciousOperation):
"""Redirect to scheme not in allowed list"""
pass
class PermissionDenied(Exception):
"""The user did not have permission to do that"""
pass
class ViewDoesNotExist(Exception):
"""The requested view does not exist"""
pass
class MiddlewareNotUsed(Exception):
"""This middleware is not used in this server configuration"""
pass
class ImproperlyConfigured(Exception):
"""Django is somehow improperly configured"""
pass
class FieldError(Exception):
"""Some kind of problem with a model field."""
pass
NON_FIELD_ERRORS = '__all__'
class ValidationError(Exception):
"""An error while validating data."""
def __init__(self, message, code=None, params=None):
"""
The `message` argument can be a single error, a list of errors, or a
dictionary that maps field names to lists of errors. What we define as
an "error" can be either a simple string or an instance of
ValidationError with its message attribute set, and what we define as
list or dictionary can be an actual `list` or `dict` or an instance
of ValidationError with its `error_list` or `error_dict` attribute set.
"""
# PY2 can't pickle naive exception: http://bugs.python.org/issue1692335.
super(ValidationError, self).__init__(message, code, params)
if isinstance(message, ValidationError):
if hasattr(message, 'error_dict'):
message = message.error_dict
# PY2 has a `message` property which is always there so we can't
# duck-type on it. It was introduced in Python 2.5 and already
# deprecated in Python 2.6.
elif not hasattr(message, 'message' if six.PY3 else 'code'):
message = message.error_list
else:
message, code, params = message.message, message.code, message.params
if isinstance(message, dict):
self.error_dict = {}
for field, messages in message.items():
if not isinstance(messages, ValidationError):
messages = ValidationError(messages)
self.error_dict[field] = messages.error_list
elif isinstance(message, list):
self.error_list = []
for message in message:
# Normalize plain strings to instances of ValidationError.
if not isinstance(message, ValidationError):
message = ValidationError(message)
if hasattr(message, 'error_dict'):
self.error_list.extend(sum(message.error_dict.values(), []))
else:
self.error_list.extend(message.error_list)
else:
self.message = message
self.code = code
self.params = params
self.error_list = [self]
@property
def message_dict(self):
# Trigger an AttributeError if this ValidationError
# doesn't have an error_dict.
getattr(self, 'error_dict')
return dict(self)
@property
def messages(self):
if hasattr(self, 'error_dict'):
return sum(dict(self).values(), [])
return list(self)
def update_error_dict(self, error_dict):
if hasattr(self, 'error_dict'):
for field, error_list in self.error_dict.items():
error_dict.setdefault(field, []).extend(error_list)
else:
error_dict.setdefault(NON_FIELD_ERRORS, []).extend(self.error_list)
return error_dict
def __iter__(self):
if hasattr(self, 'error_dict'):
for field, errors in self.error_dict.items():
yield field, list(ValidationError(errors))
else:
for error in self.error_list:
message = error.message
if error.params:
message %= error.params
yield force_text(message)
def __str__(self):
if hasattr(self, 'error_dict'):
return repr(dict(self))
return repr(list(self))
def __repr__(self):
return 'ValidationError(%s)' % self
| bsd-3-clause |
Zhang-O/small | tensor__cpu/http/spyser_liyou.py | 1 | 5473 | import urllib.request
from bs4 import BeautifulSoup
import re
import urllib.parse
import xlsxwriter
import pandas as pd
import numpy as np
from urllib import request, parse
from urllib.error import URLError
import json
import multiprocessing
import time
# 详情页面的 地址 存放在这里面
urls_of_detail = []
total_pages = 0
# 要爬取的内容 按序存成数组
_1 = []
_2 = []
_3 = []
_4 = []
_5 = []
issue_date_sum = []
project_address_sum = []
project_sector_sum = []
project_content_sum = []
company_name_sum = []
company_staff_sum = []
company_phone_sum = []
# 一级网址
url = 'http://www.stc.gov.cn/ZWGK/TZGG/GGSB/'
# page 表示第几页
def get_urls(url,page):
# 构造 form 数据
# postdata = urllib.parse.urlencode({'currDistrict': '', 'pageNo': page,'hpjgName_hidden':'','keyWordName':''})
# postdata = postdata.encode('utf-8')
#
# #发送请求
# response = urllib.request.urlopen(url, data=postdata)
# html_cont = response.read()
if page == 0:
url = url + 'index.htm'
else:
url = url + 'index_' + str(page) + '.htm'
req = request.Request(url=url)
res_data = request.urlopen(req)
# print(res_data)
html_cont = res_data.read()
# 解析文档树
soup = BeautifulSoup(html_cont, 'html.parser', from_encoding='utf-8')
#
# # 用正则表达式 查找 二级网站的网址 所在的 元素 tr
trs = soup.find_all('a', href=re.compile(r"^./201"))
# # 把 二级网站的网址存到 urls_of_detail 中
for i in trs:
# print(i['href'][2:])
urls_of_detail.append(i['href'][2:])
def get_info(url,second_url):
# s = urllib.request.urlopen(urls_of_detail[0])
# 请求文档
second_url = url + second_url
s = urllib.request.urlopen(second_url)
# 解析文档
soup = BeautifulSoup(s, 'html.parser', from_encoding='utf-8')
# 查找的内容 在 td 元素内 ,且没有任何唯一标识 ,找到所有td ,查看每个待爬取得内容在 list 中 的索引
div = soup.find_all('div', class_=re.compile(r"TRS_Editor"))
trs = div[0].find_all('tr')
trs = trs[1:]
# print(trs[0])
print('trs num',len(trs))
for tr in trs:
tds = tr.find_all('td')
if len(tds[0].find_all('font')) > 0 :
if tds[3].find_all('font')[0].string == None:
print(second_url)
_1.append(tds[0].find_all('font')[0].string)
_2.append(tds[1].find_all('font')[0].string)
_3.append(tds[2].find_all('font')[0].string)
_4.append(tds[3].find_all('font')[0].string)
if len(tds) == 5:
_5.append(tds[4].find_all('font')[0].string)
else:
_5.append('null')
elif len(tds[0].find_all('p')) > 0 :
# if tds[3].find_all('p')[0].string == None:
# print(second_url)
_1.append(tds[0].find_all('p')[0].string)
_2.append(tds[1].find_all('p')[0].string)
_3.append(tds[2].find_all('p')[0].string)
if len(tds[3].find_all('p')) > 0:
_4.append(tds[3].find_all('p')[0].string)
else:
_4.append(tds[3].string)
if len(tds) == 5:
_5.append(tds[4])
else:
_5.append('null')
else:
if tds[3].string == None:
print(second_url)
_1.append(tds[0].string)
_2.append(tds[1].string)
if len(tds[2].find_all('span'))>0 and tds[2].find_all('span')[0].string == None:
_3.append(tds[2].string)
else:
_3.append(tds[2].string)
_4.append(tds[3].string)
if len(tds) == 5:
_5.append(tds[4].string)
else:
_5.append('null')
# elif len(tds[0].find_all('td'))
# print(len(tds))
# print(tds[0].string)
# print(tds[1].string)
# print(tds[2].string)
# print(tds[3].string)
# print(response.read().decode('utf-8','ignore'))
# 网站显示一共有 1036 页
num0 =0
for page in range(0,7):
num0 += 1
# print(num0)
get_urls(url, page)
# 把所有的二级网站 存成文本
with open('urls_all_liyou','w') as f:
f.write(str(urls_of_detail))
# print(len(urls_of_detail))
# print(len(set(urls_of_detail)))
print('urls num :' , len(urls_of_detail))
num=0 # 这个主要用于调试 爬的过程中如果出错 看看是在哪个网址出的
for second_url in urls_of_detail:
num += 1
print('page num : ', num)
if num in [15,42]:
continue
if num > 54:
break
get_info(url, second_url)
print('end ----------')
print(len(_1))
workbook = xlsxwriter.Workbook('./liyou.xlsx')
# 1.------------------ 创建一个 worksheet 存放具体分数-------------------------------
ws = workbook.add_worksheet('liyou')
#设置宽度
ws.set_column('A:A', 25)
ws.set_column('B:B', 25)
ws.set_column('C:C', 15)
ws.set_column('D:D', 15)
ws.set_column('E:E', 15)
# 写表头
ws.write(0, 0, '序号')
ws.write(0, 1, '区域')
ws.write(0, 2, '类型')
ws.write(0, 3, '设置地点')
ws.write(0, 4, '方向')
number = len(_1)
for i in range(number):
ws.write(i + 1, 0, str(_1[i]))
ws.write(i + 1, 1, str(_2[i]))
ws.write(i + 1, 2, str(_3[i]))
ws.write(i + 1, 3, str(_4[i]))
ws.write(i + 1, 4, str(_5[i]))
workbook.close()
| mit |
takeshineshiro/wagtail | wagtail/wagtailadmin/tests/test_page_chooser.py | 12 | 12788 | from django.test import TestCase
from django.core.urlresolvers import reverse
from wagtail.wagtailcore.models import Page
from wagtail.tests.testapp.models import SimplePage, EventPage, EventIndex
from wagtail.tests.utils import WagtailTestUtils
class TestChooserBrowse(TestCase, WagtailTestUtils):
def setUp(self):
self.root_page = Page.objects.get(id=2)
# Add child page
self.child_page = SimplePage()
self.child_page.title = "foobarbaz"
self.child_page.slug = "foobarbaz"
self.root_page.add_child(instance=self.child_page)
self.login()
def get(self, params={}):
return self.client.get(reverse('wagtailadmin_choose_page'), params)
def test_simple(self):
response = self.get()
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/browse.html')
class TestChooserBrowseChild(TestCase, WagtailTestUtils):
def setUp(self):
self.root_page = Page.objects.get(id=2)
# Add child page
self.child_page = SimplePage()
self.child_page.title = "foobarbaz"
self.child_page.slug = "foobarbaz"
self.root_page.add_child(instance=self.child_page)
self.login()
def get(self, params={}):
return self.client.get(reverse('wagtailadmin_choose_page_child',
args=(self.root_page.id,)), params)
def get_invalid(self, params={}):
return self.client.get(reverse('wagtailadmin_choose_page_child',
args=(9999999,)), params)
def test_simple(self):
response = self.get()
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/browse.html')
def test_get_invalid(self):
self.assertEqual(self.get_invalid().status_code, 404)
def test_with_page_type(self):
# Add a page that is not a SimplePage
event_page = EventPage(
title="event",
slug="event",
)
self.root_page.add_child(instance=event_page)
# Add a page with a child page
event_index_page = EventIndex(
title="events",
slug="events",
)
self.root_page.add_child(instance=event_index_page)
event_index_page.add_child(instance=EventPage(
title="other event",
slug="other-event",
))
# Send request
response = self.get({'page_type': 'tests.simplepage'})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/browse.html')
self.assertEqual(response.context['page_type_string'], 'tests.simplepage')
pages = {
page.id: page
for page in response.context['pages'].object_list
}
# Child page is a simple page directly underneath root
# so should appear in the list
self.assertIn(self.child_page.id, pages)
self.assertTrue(pages[self.child_page.id].can_choose)
self.assertFalse(pages[self.child_page.id].can_descend)
# Event page is not a simple page and is not descendable either
# so should not appear in the list
self.assertNotIn(event_page.id, pages)
# Event index page is not a simple page but has a child and is therefore descendable
# so should appear in the list
self.assertIn(event_index_page.id, pages)
self.assertFalse(pages[event_index_page.id].can_choose)
self.assertTrue(pages[event_index_page.id].can_descend)
def test_with_blank_page_type(self):
# a blank page_type parameter should be equivalent to an absent parameter
# (or an explicit page_type of wagtailcore.page)
response = self.get({'page_type': ''})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/browse.html')
def test_with_multiple_page_types(self):
# Add a page that is not a SimplePage
event_page = EventPage(
title="event",
slug="event",
)
self.root_page.add_child(instance=event_page)
# Send request
response = self.get({'page_type': 'tests.simplepage,tests.eventpage'})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/browse.html')
self.assertEqual(response.context['page_type_string'], 'tests.simplepage,tests.eventpage')
pages = {
page.id: page
for page in response.context['pages'].object_list
}
# Simple page in results, as before
self.assertIn(self.child_page.id, pages)
self.assertTrue(pages[self.child_page.id].can_choose)
# Event page should now also be choosable
self.assertIn(event_page.id, pages)
self.assertTrue(pages[self.child_page.id].can_choose)
def test_with_unknown_page_type(self):
response = self.get({'page_type': 'foo.bar'})
self.assertEqual(response.status_code, 404)
def test_with_bad_page_type(self):
response = self.get({'page_type': 'wagtailcore.site'})
self.assertEqual(response.status_code, 404)
def test_with_invalid_page_type(self):
response = self.get({'page_type': 'foo'})
self.assertEqual(response.status_code, 404)
def setup_pagination_test_data(self):
# Create lots of pages
for i in range(100):
new_page = SimplePage(
title="foobarbaz",
slug="foobarbaz",
)
self.root_page.add_child(instance=new_page)
def test_pagination_basic(self):
self.setup_pagination_test_data()
response = self.get()
self.assertEqual(response.context['pages'].paginator.num_pages, 5)
self.assertEqual(response.context['pages'].number, 1)
def test_pagination_another_page(self):
self.setup_pagination_test_data()
response = self.get({'p': 2})
self.assertEqual(response.context['pages'].number, 2)
def test_pagination_invalid_page(self):
self.setup_pagination_test_data()
response = self.get({'p': 'foo'})
self.assertEqual(response.context['pages'].number, 1)
def test_pagination_out_of_range_page(self):
self.setup_pagination_test_data()
response = self.get({'p': 100})
self.assertEqual(response.context['pages'].number, 5)
class TestChooserSearch(TestCase, WagtailTestUtils):
def setUp(self):
self.root_page = Page.objects.get(id=2)
# Add child page
self.child_page = SimplePage()
self.child_page.title = "foobarbaz"
self.child_page.slug = "foobarbaz"
self.root_page.add_child(instance=self.child_page)
self.login()
def get(self, params=None):
return self.client.get(reverse('wagtailadmin_choose_page_search'), params or {})
def test_simple(self):
response = self.get({'q': "foobarbaz"})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/_search_results.html')
self.assertContains(response, "There is one match")
self.assertContains(response, "foobarbaz")
def test_search_no_results(self):
response = self.get({'q': "quux"})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "There are 0 matches")
def test_with_page_type(self):
# Add a page that is not a SimplePage
event_page = EventPage(
title="foo",
slug="foo",
)
self.root_page.add_child(instance=event_page)
# Send request
response = self.get({'q': "foo", 'page_type': 'tests.simplepage'})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/_search_results.html')
self.assertEqual(response.context['page_type_string'], 'tests.simplepage')
pages = {
page.id: page
for page in response.context['pages']
}
self.assertIn(self.child_page.id, pages)
# Not a simple page
self.assertNotIn(event_page.id, pages)
def test_with_blank_page_type(self):
# a blank page_type parameter should be equivalent to an absent parameter
# (or an explicit page_type of wagtailcore.page)
response = self.get({'q': "foobarbaz", 'page_type': ''})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/_search_results.html')
self.assertContains(response, "There is one match")
self.assertContains(response, "foobarbaz")
def test_with_multiple_page_types(self):
# Add a page that is not a SimplePage
event_page = EventPage(
title="foo",
slug="foo",
)
self.root_page.add_child(instance=event_page)
# Send request
response = self.get({'q': "foo", 'page_type': 'tests.simplepage,tests.eventpage'})
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/_search_results.html')
self.assertEqual(response.context['page_type_string'], 'tests.simplepage,tests.eventpage')
pages = {
page.id: page
for page in response.context['pages']
}
# Simple page in results, as before
self.assertIn(self.child_page.id, pages)
# Event page should now also be choosable
self.assertIn(event_page.id, pages)
def test_with_unknown_page_type(self):
response = self.get({'page_type': 'foo.bar'})
self.assertEqual(response.status_code, 404)
def test_with_bad_page_type(self):
response = self.get({'page_type': 'wagtailcore.site'})
self.assertEqual(response.status_code, 404)
def test_with_invalid_page_type(self):
response = self.get({'page_type': 'foo'})
self.assertEqual(response.status_code, 404)
class TestChooserExternalLink(TestCase, WagtailTestUtils):
def setUp(self):
self.login()
def get(self, params={}):
return self.client.get(reverse('wagtailadmin_choose_page_external_link'), params)
def post(self, post_data={}):
return self.client.post(reverse('wagtailadmin_choose_page_external_link'), post_data)
def test_simple(self):
response = self.get()
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/external_link.html')
def test_get_with_param(self):
self.assertEqual(self.get({'prompt_for_link_text': 'foo'}).status_code, 200)
def test_create_link(self):
response = self.post({'url': 'http://www.example.com/'})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "'onload'") # indicates success / post back to calling page
self.assertContains(response, "'url': 'http://www.example.com/',")
self.assertContains(response, "'title': 'http://www.example.com/'")
def test_invalid_url(self):
response = self.post({'url': 'ntp://www.example.com'})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "'html'") # indicates failure / show error message
self.assertContains(response, "Enter a valid URL.")
def test_allow_local_url(self):
response = self.post({'url': '/admin/'})
self.assertEqual(response.status_code, 200)
self.assertContains(response, "'onload'") # indicates success / post back to calling page
self.assertContains(response, "'url': '/admin/',")
self.assertContains(response, "'title': '/admin/'")
class TestChooserEmailLink(TestCase, WagtailTestUtils):
def setUp(self):
self.login()
def get(self, params={}):
return self.client.get(reverse('wagtailadmin_choose_page_email_link'), params)
def post(self, post_data={}):
return self.client.post(reverse('wagtailadmin_choose_page_email_link'), post_data)
def test_simple(self):
response = self.get()
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'wagtailadmin/chooser/email_link.html')
def test_get_with_param(self):
self.assertEqual(self.get({'prompt_for_link_text': 'foo'}).status_code, 200)
def test_create_link(self):
request = self.post({'email_address': 'example@example.com'})
self.assertContains(request, "'url': 'mailto:example@example.com',")
self.assertContains(request, "'title': 'example@example.com'")
| bsd-3-clause |
zxsted/scipy | scipy/ndimage/io.py | 69 | 1320 | from __future__ import division, print_function, absolute_import
__all__ = ['imread']
from numpy import array
def imread(fname, flatten=False, mode=None):
"""
Read an image from a file as an array.
Parameters
----------
fname : str
Image file name, e.g. ``test.jpg``, or a file object.
flatten : bool, optional
If true, convert the output to grey-scale. Default is False.
mode : str, optional
mode to convert image to, e.g. ``RGB``.
Returns
-------
img_array : ndarray
The different colour bands/channels are stored in the
third dimension, such that a grey-image is MxN, an
RGB-image MxNx3 and an RGBA-image MxNx4.
Raises
------
ImportError
If the Python Imaging Library (PIL) can not be imported.
"""
try:
from PIL import Image
except ImportError:
raise ImportError("Could not import the Python Imaging Library (PIL)"
" required to load image files. Please refer to"
" http://pypi.python.org/pypi/PIL/ for installation"
" instructions.")
im = Image.open(fname)
if mode:
im = im.convert(mode)
if flatten:
im = im.convert('F')
result = array(im)
return result
| bsd-3-clause |
zhanqxun/cv_fish | win32/test/test_win32pipe.py | 4 | 5680 | import unittest
import time
import threading
from pywin32_testutil import str2bytes # py3k-friendly helper
import win32pipe
import win32file
import win32event
import pywintypes
import winerror
import win32con
class PipeTests(unittest.TestCase):
pipename = "\\\\.\\pipe\\python_test_pipe"
def _serverThread(self, pipe_handle, event, wait_time):
# just do one connection and terminate.
hr = win32pipe.ConnectNamedPipe(pipe_handle)
self.failUnless(hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr,))
hr, got = win32file.ReadFile(pipe_handle, 100)
self.failUnlessEqual(got, str2bytes("foo\0bar"))
time.sleep(wait_time)
win32file.WriteFile(pipe_handle, str2bytes("bar\0foo"))
pipe_handle.Close()
event.set()
def startPipeServer(self, event, wait_time = 0):
openMode = win32pipe.PIPE_ACCESS_DUPLEX
pipeMode = win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT
sa = pywintypes.SECURITY_ATTRIBUTES()
sa.SetSecurityDescriptorDacl ( 1, None, 0 )
pipe_handle = win32pipe.CreateNamedPipe(self.pipename,
openMode,
pipeMode,
win32pipe.PIPE_UNLIMITED_INSTANCES,
0,
0,
2000,
sa)
threading.Thread(target=self._serverThread, args=(pipe_handle, event, wait_time)).start()
def testCallNamedPipe(self):
event = threading.Event()
self.startPipeServer(event)
got = win32pipe.CallNamedPipe(self.pipename,str2bytes("foo\0bar"), 1024, win32pipe.NMPWAIT_WAIT_FOREVER)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def testTransactNamedPipeBlocking(self):
event = threading.Event()
self.startPipeServer(event)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
0, # win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), 1024, None)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def testTransactNamedPipeBlockingBuffer(self):
# Like testTransactNamedPipeBlocking, but a pre-allocated buffer is
# passed (not really that useful, but it exercises the code path)
event = threading.Event()
self.startPipeServer(event)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
0, # win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
buffer = win32file.AllocateReadBuffer(1024)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, None)
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
def testTransactNamedPipeAsync(self):
event = threading.Event()
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None)
self.startPipeServer(event, 0.5)
open_mode = win32con.GENERIC_READ | win32con.GENERIC_WRITE
hpipe = win32file.CreateFile(self.pipename,
open_mode,
0, # no sharing
None, # default security
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_OVERLAPPED,
None)
# set to message mode.
win32pipe.SetNamedPipeHandleState(
hpipe, win32pipe.PIPE_READMODE_MESSAGE, None, None)
buffer = win32file.AllocateReadBuffer(1024)
hr, got = win32pipe.TransactNamedPipe(hpipe, str2bytes("foo\0bar"), buffer, overlapped)
self.failUnlessEqual(hr, winerror.ERROR_IO_PENDING)
nbytes = win32file.GetOverlappedResult(hpipe, overlapped, True)
got = buffer[:nbytes]
self.failUnlessEqual(got, str2bytes("bar\0foo"))
event.wait(5)
self.failUnless(event.isSet(), "Pipe server thread didn't terminate")
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
gdhungana/desispec | py/desispec/test/test_cosmics.py | 2 | 3730 | """
test desispec.cosmics
"""
import unittest
import numpy as np
from desispec.image import Image
from desispec.cosmics import reject_cosmic_rays_ala_sdss, reject_cosmic_rays
from desispec.log import get_logger
from desispec.maskbits import ccdmask
#- Create a DESI logger at level WARNING to quiet down the fiberflat calc
import logging
log = get_logger(logging.WARNING)
class TestCosmics(unittest.TestCase):
def setUp(self):
#- pixels with a cosmic ray
self.pix = np.zeros((53,50))
self.ivar = np.ones(self.pix.shape)
for i in range(12,20) :
self.pix[i,i]=100
#- pixels with a PSF-like object
self.psfpix = np.zeros(self.pix.shape)
for i in range(35,45):
for j in range(35,45):
r2 = (i-40)**2 + (j-40)**2
self.psfpix[i,j] = np.exp(-r2/2.0)
#- a bad pixel mask that goes through the PSF-like object
self.badmask = np.zeros(self.pix.shape, dtype=np.uint32)
self.badmask[:, 39] = ccdmask.BAD
def test_rejection_ala_sdss(self):
"""
Very basic test of reject_cosmic_rays_ala_sdss
"""
#- Does it reject a diagonal cosmic ray?
image = Image(self.pix, self.ivar, camera="r0")
rejected=reject_cosmic_rays_ala_sdss(image,dilate=False)
diff=np.sum(np.abs((self.pix>0).astype(int) - rejected.astype(int)))
self.assertTrue(diff==0)
#- Does it not find a PSF-like object?
image = Image(self.psfpix, self.ivar, camera="r0")
rejected=reject_cosmic_rays_ala_sdss(image,dilate=False)
diff=np.sum(np.abs((self.pix>0).astype(int) - rejected.astype(int)))
self.assertTrue(np.all(self.psfpix*(rejected==0) == self.psfpix))
#- Can it find one and not the other?
image = Image(self.pix+self.psfpix, self.ivar, camera="r0")
rejected=reject_cosmic_rays_ala_sdss(image,dilate=False)
diff=np.sum(np.abs((self.pix>0).astype(int) - rejected.astype(int)))
self.assertTrue(np.all(self.psfpix*(rejected==0) == self.psfpix))
diff=np.sum(np.abs((self.pix>0).astype(int) - rejected.astype(int)))
self.assertTrue(diff==0)
def test_psf_with_bad_column(self):
'''test a PSF-like spot with a masked column going through it'''
image = Image(self.psfpix, self.ivar, mask=self.badmask, camera="r0")
image.pix[self.badmask>0] = 0
rejected=reject_cosmic_rays_ala_sdss(image,dilate=False)
self.assertTrue(not np.any(rejected))
def test_different_cameras(self):
'''test a PSF-like spot with a masked column going through it'''
for camera in ('b0', 'r1', 'z2'):
image = Image(self.pix, self.ivar, mask=self.badmask, camera=camera)
rejected = reject_cosmic_rays_ala_sdss(image,dilate=False)
cosmic = image.pix > 0
self.assertTrue(np.all(rejected[cosmic]))
#- camera must be valid
with self.assertRaises(KeyError):
image = Image(self.pix, self.ivar, mask=self.badmask, camera='a0')
rejected = reject_cosmic_rays_ala_sdss(image,dilate=False)
def test_reject_cosmics(self):
"""
Test that the generic cosmics interface updates the mask
"""
image = Image(self.pix, self.ivar, camera="r0")
reject_cosmic_rays(image)
cosmic = (image.pix > 0)
self.assertTrue(np.all(image.mask[cosmic] & ccdmask.COSMIC))
#- This runs all test* functions in any TestCase class in this file
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
lastweek/gem5 | src/arch/x86/isa/insts/general_purpose/compare_and_test/bounds.py | 41 | 2471 | # Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# 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 copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Gabe Black
microcode = '''
def macroop BOUND_R_M {
ld t1, seg, sib, disp, dataSize="env.dataSize * 2"
srli t2, t1, "env.dataSize * 8"
sub t1, t1, reg, flags=(ECF,)
fault "new BoundRange", flags=(CECF,)
sub t2, reg, t2, flags=(ECF,)
fault "new BoundRange", flags=(CECF,)
};
def macroop BOUND_R_P {
fault "new UnimpInstFault"
};
'''
| bsd-3-clause |
abenzbiria/clients_odoo | addons/product_margin/__openerp__.py | 121 | 1927 | # -*- 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': 'Margins by Products',
'version': '1.0',
'category': 'Sales Management',
'description': """
Adds a reporting menu in products that computes sales, purchases, margins and other interesting indicators based on invoices.
=============================================================================================================================
The wizard to launch the report has several options to help you get the data you need.
""",
'author': 'OpenERP SA',
'depends': ['account'],
'data': [
'security/ir.model.access.csv',
'wizard/product_margin_view.xml',
'product_margin_view.xml'
],
'test':['test/product_margin.yml'],
'demo': [],
'installable': True,
'auto_install': False,
'images': ['images/open_margins.jpeg','images/product_margins_form.jpeg', 'images/product_margins_list.jpeg'],
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
eleonrk/SickRage | lib/hachoir_parser/misc/pdf.py | 95 | 16790 | """
Adobe Portable Document Format (PDF) parser.
Author: Christophe Gisquet <christophe.gisquet@free.fr>
"""
from hachoir_parser import Parser
from hachoir_core.field import (
Field, FieldSet,
ParserError,
GenericVector,
UInt8, UInt16, UInt32,
String,
RawBytes)
from hachoir_core.endian import LITTLE_ENDIAN
from hachoir_core.text_handler import textHandler, hexadecimal
MAGIC = "%PDF-"
ENDMAGIC = "%%EOF"
def getLineEnd(s, pos=None):
if pos == None:
pos = (s.absolute_address+s.current_size)//8
end = s.stream.searchBytesLength("\x0D", False, 8*pos)
other_end = s.stream.searchBytesLength("\x0A", False, 8*pos)
if end == None or (other_end != None and other_end < end):
return other_end
return end
# TODO: rewrite to account for all possible terminations: ' ', '/', '\0XD'
# But this probably requires changing *ALL* of the places they are used,
# as ' ' is swallowed but not the others
def getElementEnd(s, limit=' ', offset=0):
addr = s.absolute_address+s.current_size
addr += 8*offset
pos = s.stream.searchBytesLength(limit, True, addr)
if pos == None:
#s.info("Can't find '%s' starting at %u" % (limit, addr))
return None
return pos
class PDFNumber(Field):
LIMITS = ['[', '/', '\x0D', ']']
"""
sprintf("%i") or sprinf("%.?f")
"""
def __init__(self, parent, name, desc=None):
Field.__init__(self, parent, name, description=desc)
# Get size
size = getElementEnd(parent)
for limit in self.LIMITS:
other_size = getElementEnd(parent, limit)
if other_size != None:
other_size -= 1
if size == None or other_size < size:
size = other_size
self._size = 8*size
# Get value
val = parent.stream.readBytes(self.absolute_address, size)
self.info("Number: size=%u value='%s'" % (size, val))
if val.find('.') != -1:
self.createValue = lambda: float(val)
else:
self.createValue = lambda: int(val)
class PDFString(Field):
"""
A string of the shape:
( This string \
uses 3 lines \
with the CR(LF) inhibited )
"""
def __init__(self, parent, name, desc=None):
Field.__init__(self, parent, name, description=desc)
val = ""
count = 1
off = 1
while not parent.eof:
char = parent.stream.readBytes(self.absolute_address+8*off, 1)
# Non-ASCII
if not char.isalpha() or char == '\\':
off += 1
continue
if char == '(':
count += 1
if char == ')':
count -= 1
# Parenthesis block = 0 => end of string
if count == 0:
off += 1
break
# Add it to the string
val += char
self._size = 8*off
self.createValue = lambda: val
class PDFName(Field):
LIMITS = ['[', '/', '<', ']']
"""
String starting with '/', where characters may be written using their
ASCII code (exemple: '#20' would be ' '
' ', ']' and '\0' are supposed not to be part of the name
"""
def __init__(self, parent, name, desc=None):
Field.__init__(self, parent, name, description=desc)
if parent.stream.readBytes(self.absolute_address, 1) != '/':
raise ParserError("Unknown PDFName '%s'" %
parent.stream.readBytes(self.absolute_address, 10))
size = getElementEnd(parent, offset=1)
#other_size = getElementEnd(parent, '[')-1
#if size == None or (other_size != None and other_size < size):
# size = other_size
for limit in self.LIMITS:
other_size = getElementEnd(parent, limit, 1)
if other_size != None:
other_size -= 1
if size == None or other_size < size:
#self.info("New size: %u" % other_size)
size = other_size
self._size = 8*(size+1)
# Value should be without the initial '/' and final ' '
self.createValue = lambda: parent.stream.readBytes(self.absolute_address+8, size).strip(' ')
class PDFID(Field):
"""
Not described as an object, but let's do as it was.
This ID has the shape <hexadecimal ASCII string>
"""
def __init__(self, parent, name, desc=None):
Field.__init__(self, parent, name, description=desc)
self._size = 8*getElementEnd(parent, '>')
self.createValue = lambda: parent.stream.readBytes(self.absolute_address+8, (self._size//8)-1)
class NotABool(Exception): pass
class PDFBool(Field):
"""
"true" or "false" string standing for the boolean value
"""
def __init__(self, parent, name, desc=None):
Field.__init__(self, parent, name, description=desc)
if parent.stream.readBytes(self.absolute_address, 4) == "true":
self._size = 4
self.createValue = lambda: True
elif parent.stream.readBytes(self.absolute_address, 5) == "false":
self._size = 5
self.createValue = lambda: False
raise NotABool
class LineEnd(FieldSet):
"""
Made of 0x0A, 0x0D (we may include several line ends)
"""
def createFields(self):
while not self.eof:
addr = self.absolute_address+self.current_size
char = self.stream.readBytes(addr, 1)
if char == '\x0A':
yield UInt8(self, "lf", "Line feed")
elif char == '\x0D':
yield UInt8(self, "cr", "Line feed")
else:
self.info("Line ends at %u/%u, len %u" %
(addr, self.stream._size, self.current_size))
break
class PDFDictionaryPair(FieldSet):
def createFields(self):
yield PDFName(self, "name", getElementEnd(self))
for field in parsePDFType(self):
yield field
class PDFDictionary(FieldSet):
def createFields(self):
yield String(self, "dict_start", 2)
while not self.eof:
addr = self.absolute_address+self.current_size
if self.stream.readBytes(addr, 2) != '>>':
for field in parsePDFType(self):
yield field
else:
break
yield String(self, "dict_end", 2)
class PDFArray(FieldSet):
"""
Array of possibly non-homogeneous elements, starting with '[' and ending
with ']'
"""
def createFields(self):
yield String(self, "array_start", 1)
while self.stream.readBytes(self.absolute_address+self.current_size, 1) != ']':
for field in parsePDFType(self):
yield field
yield String(self, "array_end", 1)
def parsePDFType(s):
addr = s.absolute_address+s.current_size
char = s.stream.readBytes(addr, 1)
if char == '/':
yield PDFName(s, "type[]", getElementEnd(s))
elif char == '<':
if s.stream.readBytes(addr+8, 1) == '<':
yield PDFDictionary(s, "dict[]")
else:
yield PDFID(s, "id[]")
elif char == '(':
yield PDFString(s, "string[]")
elif char == '[':
yield PDFArray(s, "array[]")
else:
# First parse size
size = getElementEnd(s)
for limit in ['/', '>', '<']:
other_size = getElementEnd(s, limit)
if other_size != None:
other_size -= 1
if size == None or (other_size>0 and other_size < size):
size = other_size
# Get element
name = s.stream.readBytes(addr, size)
char = s.stream.readBytes(addr+8*size+8, 1)
if name.count(' ') > 1 and char == '<':
# Probably a catalog
yield Catalog(s, "catalog[]")
elif name[0] in ('.','-','+', '0', '1', '2', '3', \
'4', '5', '6', '7', '8', '9'):
s.info("Not a catalog: %u spaces and end='%s'" % (name.count(' '), char))
yield PDFNumber(s, "integer[]")
else:
s.info("Trying to parse '%s': %u bytes" % \
(s.stream.readBytes(s.absolute_address+s.current_size, 4), size))
yield String(s, "unknown[]", size)
class Header(FieldSet):
def createFields(self):
yield String(self, "marker", 5, MAGIC)
length = getLineEnd(self, 4)
if length != None:
#self.info("Found at position %08X" % len)
yield String(self, "version", length-1)
yield LineEnd(self, "line_end")
else:
self.warning("Can't determine version!")
def createDescription(self):
return "PDF version %s" % self["version"].display
class Body(FieldSet):
def __init__(self, parent, name, desc=None):
FieldSet.__init__(self, parent, name, desc)
pos = self.stream.searchBytesLength(CrossReferenceTable.MAGIC, False)
if pos == None:
raise ParserError("Can't find xref starting at %u" %
(self.absolute_address//8))
self._size = 8*pos-self.absolute_address
def createFields(self):
while self.stream.readBytes(self.absolute_address+self.current_size, 1) == '%':
size = getLineEnd(self, 4)
if size == 2:
yield textHandler(UInt16(self, "crc32"), hexadecimal)
elif size == 4:
yield textHandler(UInt32(self, "crc32"), hexadecimal)
elif self.stream.readBytes(self.absolute_address+self.current_size, size).isalpha():
yield String(self, "comment[]", size)
else:
RawBytes(self, "unknown_data[]", size)
yield LineEnd(self, "line_end[]")
#abs_offset = self.current_size//8
# TODO: yield objects that read offsets and deduce size from
# "/cross_ref_table/sub_section[]/entries/item[]"
offsets = []
for subsection in self.array("/cross_ref_table/sub_section"):
for obj in subsection.array("entries/item"):
if "byte_offset" in obj:
# Could be inserted already sorted
offsets.append(obj["byte_offset"].value)
offsets.append(self["/cross_ref_table"].absolute_address//8)
offsets.sort()
for index in xrange(len(offsets)-1):
yield Catalog(self, "object[]", size=offsets[index+1]-offsets[index])
class Entry(FieldSet):
static_size = 20*8
def createFields(self):
typ = self.stream.readBytes(self.absolute_address+17*8, 1)
if typ == 'n':
yield PDFNumber(self, "byte_offset")
elif typ == 'f':
yield PDFNumber(self, "next_free_object_number")
else:
yield PDFNumber(self, "unknown_string")
yield PDFNumber(self, "generation_number")
yield UInt8(self, "type")
yield LineEnd(self, "line_end")
def createDescription(self):
if self["type"].value == 'n':
return "In-use entry at offset %u" % int(self["byte_offset"].value)
elif self["type"].value == 'f':
return "Free entry before in-use object %u" % \
int(self["next_free_object_number"].value)
else:
return "unknown %s" % self["unknown_string"].value
class SubSection(FieldSet):
def __init__(self, parent, name, desc=None):
FieldSet.__init__(self, parent, name, desc)
self.info("Got entry count: '%s'" % self["entry_count"].value)
self._size = self.current_size + 8*20*int(self["entry_count"].value) \
+ self["line_end"].size
def createFields(self):
yield PDFNumber(self, "start_number",
"Object number of first entry in subsection")
self.info("start_number = %i" % self["start_number"].value)
yield PDFNumber(self, "entry_count", "Number of entries in subsection")
self.info("entry_count = %i" % self["entry_count"].value)
yield LineEnd(self, "line_end")
yield GenericVector(self, "entries", int(self["entry_count"].value),
Entry)
#yield LineEnd(self, "line_end[]")
def createDescription(self):
return "Subsection with %s elements, starting at %s" % \
(self["entry_count"].value, self["start_number"])
class CrossReferenceTable(FieldSet):
MAGIC = "xref"
def __init__(self, parent, name, desc=None):
FieldSet.__init__(self, parent, name, description=desc)
pos = self.stream.searchBytesLength(Trailer.MAGIC, False)
if pos == None:
raise ParserError("Can't find '%s' starting at %u" \
(Trailer.MAGIC, self.absolute_address//8))
self._size = 8*pos-self.absolute_address
def createFields(self):
yield RawBytes(self, "marker", len(self.MAGIC))
yield LineEnd(self, "line_end[]")
while not self.eof:
yield SubSection(self, "sub_section[]")
class Catalog(FieldSet):
END_NAME = ['<', '/', '[']
def __init__(self, parent, name, size=None, desc=None):
FieldSet.__init__(self, parent, name, description=desc)
if size != None:
self._size = 8*size
# object catalogs are ended with "obj"
elif self["object"].value == "obj":
size = self.stream.searchBytesLength("endobj", False)
if size != None:
self._size = 8*(size+2)
def createFields(self):
yield PDFNumber(self, "index")
yield PDFNumber(self, "unknown[]")
length = getElementEnd(self)
for limit in self.END_NAME:
new_length = getElementEnd(self, limit)-len(limit)
if length == None or (new_length != None and new_length < length):
length = new_length
yield String(self, "object", length, strip=' ')
if self.stream.readBytes(self.absolute_address+self.current_size, 2) == '<<':
yield PDFDictionary(self, "key_list")
# End of catalog: this one has "endobj"
if self["object"].value == "obj":
yield LineEnd(self, "line_end[]")
yield String(self, "end_object", len("endobj"))
yield LineEnd(self, "line_end[]")
class Trailer(FieldSet):
MAGIC = "trailer"
def createFields(self):
yield RawBytes(self, "marker", len(self.MAGIC))
yield LineEnd(self, "line_end[]")
yield String(self, "start_attribute_marker", 2)
addr = self.absolute_address + self.current_size
while self.stream.readBytes(addr, 2) != '>>':
t = PDFName(self, "type[]")
yield t
name = t.value
self.info("Parsing PDFName '%s'" % name)
if name == "Size":
yield PDFNumber(self, "size", "Entries in the file cross-reference section")
elif name == "Prev":
yield PDFNumber(self, "offset")
elif name == "Root":
yield Catalog(self, "object_catalog")
elif name == "Info":
yield Catalog(self, "info")
elif name == "ID":
yield PDFArray(self, "id")
elif name == "Encrypt":
yield PDFDictionary(self, "decrypt")
else:
raise ParserError("Don't know trailer type '%s'" % name)
addr = self.absolute_address + self.current_size
yield String(self, "end_attribute_marker", 2)
yield LineEnd(self, "line_end[]")
yield String(self, "start_xref", 9)
yield LineEnd(self, "line_end[]")
yield PDFNumber(self, "cross_ref_table_start_address")
yield LineEnd(self, "line_end[]")
yield String(self, "end_marker", len(ENDMAGIC))
yield LineEnd(self, "line_end[]")
class PDFDocument(Parser):
endian = LITTLE_ENDIAN
PARSER_TAGS = {
"id": "pdf",
"category": "misc",
"file_ext": ("pdf",),
"mime": (u"application/pdf",),
"min_size": (5+4)*8,
"magic": ((MAGIC, 5),),
"description": "Portable Document Format (PDF) document"
}
def validate(self):
if self.stream.readBytes(0, len(MAGIC)) != MAGIC:
return "Invalid magic string"
return True
# Size is not always determined by position of "%%EOF":
# - updated documents have several of those
# - PDF files should be parsed from *end*
# => TODO: find when a document has been updated
def createFields(self):
yield Header(self, "header")
yield Body(self, "body")
yield CrossReferenceTable(self, "cross_ref_table")
yield Trailer(self, "trailer")
| gpl-3.0 |
coolbombom/CouchPotatoServer | libs/pyutil/benchmarks/bench_xor.py | 106 | 1658 | #!/usr/bin/env python
# Copyright (c) 2002-2010 Zooko Wilcox-O'Hearn
# This file is part of pyutil; see README.rst for licensing terms.
import hmac, sys, random
from pyutil.assertutil import _assert
from pyutil.xor import xor
from pyutil import benchfunc
from pyutil import randutil
SFUNCS = [hmac._strxor, xor.py_xor,]
SFNAMES = ["hmac", "pyutil py",]
inputs = {}
def _help_init_string(N):
global inputs
if not inputs.has_key(N):
inputs[N] = [randutil.insecurerandstr(N), randutil.insecurerandstr(N),]
def _help_make_bench_xor(f):
def g(n):
assert inputs.has_key(n)
_assert(isinstance(inputs[n][0], str), "Required to be a string.", inputs[n][0])
assert len(inputs[n][0]) == n
_assert(isinstance(inputs[n][1], str), "Required to be a string.", inputs[n][1])
assert len(inputs[n][1]) == n
for SF in SFUNCS:
assert f(inputs[n][0], inputs[n][1]) == SF(inputs[n][0], inputs[n][1])
return f(inputs[n][0], inputs[n][1])
return g
def bench(SETSIZES=[2**x for x in range(0, 22, 3)]):
random.seed(0)
if len(SFUNCS) <= 1: print ""
maxnamel = max(map(len, SFNAMES))
for SETSIZE in SETSIZES:
seed = random.random()
# print "seed: ", seed
random.seed(seed)
i = 0
if len(SFUNCS) > 1: print ""
for FUNC in SFUNCS:
funcname = SFNAMES[i] + " " * (maxnamel - len(SFNAMES[i]))
print "%s" % funcname,
sys.stdout.flush()
benchfunc.rep_bench(_help_make_bench_xor(FUNC), SETSIZE, initfunc=_help_init_string, MAXREPS=2**9, MAXTIME=30)
i = i + 1
bench()
| gpl-3.0 |
spisneha25/django | django/contrib/gis/feeds.py | 336 | 5978 | from __future__ import unicode_literals
from django.contrib.syndication.views import Feed as BaseFeed
from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
class GeoFeedMixin(object):
"""
This mixin provides the necessary routines for SyndicationFeed subclasses
to produce simple GeoRSS or W3C Geo elements.
"""
def georss_coords(self, coords):
"""
In GeoRSS coordinate pairs are ordered by lat/lon and separated by
a single white space. Given a tuple of coordinates, this will return
a unicode GeoRSS representation.
"""
return ' '.join('%f %f' % (coord[1], coord[0]) for coord in coords)
def add_georss_point(self, handler, coords, w3c_geo=False):
"""
Adds a GeoRSS point with the given coords using the given handler.
Handles the differences between simple GeoRSS and the more popular
W3C Geo specification.
"""
if w3c_geo:
lon, lat = coords[:2]
handler.addQuickElement('geo:lat', '%f' % lat)
handler.addQuickElement('geo:lon', '%f' % lon)
else:
handler.addQuickElement('georss:point', self.georss_coords((coords,)))
def add_georss_element(self, handler, item, w3c_geo=False):
"""
This routine adds a GeoRSS XML element using the given item and handler.
"""
# Getting the Geometry object.
geom = item.get('geometry')
if geom is not None:
if isinstance(geom, (list, tuple)):
# Special case if a tuple/list was passed in. The tuple may be
# a point or a box
box_coords = None
if isinstance(geom[0], (list, tuple)):
# Box: ( (X0, Y0), (X1, Y1) )
if len(geom) == 2:
box_coords = geom
else:
raise ValueError('Only should be two sets of coordinates.')
else:
if len(geom) == 2:
# Point: (X, Y)
self.add_georss_point(handler, geom, w3c_geo=w3c_geo)
elif len(geom) == 4:
# Box: (X0, Y0, X1, Y1)
box_coords = (geom[:2], geom[2:])
else:
raise ValueError('Only should be 2 or 4 numeric elements.')
# If a GeoRSS box was given via tuple.
if box_coords is not None:
if w3c_geo:
raise ValueError('Cannot use simple GeoRSS box in W3C Geo feeds.')
handler.addQuickElement('georss:box', self.georss_coords(box_coords))
else:
# Getting the lower-case geometry type.
gtype = str(geom.geom_type).lower()
if gtype == 'point':
self.add_georss_point(handler, geom.coords, w3c_geo=w3c_geo)
else:
if w3c_geo:
raise ValueError('W3C Geo only supports Point geometries.')
# For formatting consistent w/the GeoRSS simple standard:
# http://georss.org/1.0#simple
if gtype in ('linestring', 'linearring'):
handler.addQuickElement('georss:line', self.georss_coords(geom.coords))
elif gtype in ('polygon',):
# Only support the exterior ring.
handler.addQuickElement('georss:polygon', self.georss_coords(geom[0].coords))
else:
raise ValueError('Geometry type "%s" not supported.' % geom.geom_type)
# ### SyndicationFeed subclasses ###
class GeoRSSFeed(Rss201rev2Feed, GeoFeedMixin):
def rss_attributes(self):
attrs = super(GeoRSSFeed, self).rss_attributes()
attrs['xmlns:georss'] = 'http://www.georss.org/georss'
return attrs
def add_item_elements(self, handler, item):
super(GeoRSSFeed, self).add_item_elements(handler, item)
self.add_georss_element(handler, item)
def add_root_elements(self, handler):
super(GeoRSSFeed, self).add_root_elements(handler)
self.add_georss_element(handler, self.feed)
class GeoAtom1Feed(Atom1Feed, GeoFeedMixin):
def root_attributes(self):
attrs = super(GeoAtom1Feed, self).root_attributes()
attrs['xmlns:georss'] = 'http://www.georss.org/georss'
return attrs
def add_item_elements(self, handler, item):
super(GeoAtom1Feed, self).add_item_elements(handler, item)
self.add_georss_element(handler, item)
def add_root_elements(self, handler):
super(GeoAtom1Feed, self).add_root_elements(handler)
self.add_georss_element(handler, self.feed)
class W3CGeoFeed(Rss201rev2Feed, GeoFeedMixin):
def rss_attributes(self):
attrs = super(W3CGeoFeed, self).rss_attributes()
attrs['xmlns:geo'] = 'http://www.w3.org/2003/01/geo/wgs84_pos#'
return attrs
def add_item_elements(self, handler, item):
super(W3CGeoFeed, self).add_item_elements(handler, item)
self.add_georss_element(handler, item, w3c_geo=True)
def add_root_elements(self, handler):
super(W3CGeoFeed, self).add_root_elements(handler)
self.add_georss_element(handler, self.feed, w3c_geo=True)
# ### Feed subclass ###
class Feed(BaseFeed):
"""
This is a subclass of the `Feed` from `django.contrib.syndication`.
This allows users to define a `geometry(obj)` and/or `item_geometry(item)`
methods on their own subclasses so that geo-referenced information may
placed in the feed.
"""
feed_type = GeoRSSFeed
def feed_extra_kwargs(self, obj):
return {'geometry': self.__get_dynamic_attr('geometry', obj)}
def item_extra_kwargs(self, item):
return {'geometry': self.__get_dynamic_attr('item_geometry', item)}
| bsd-3-clause |
davelab6/pyfontaine | fontaine/charsets/noto_glyphs/notosansgeorgian_bold.py | 2 | 5263 | # -*- coding: utf-8 -*-
class Charset(object):
common_name = 'NotoSansGeorgian-Bold'
native_name = ''
def glyphs(self):
glyphs = []
glyphs.append(0x0044) #uni10EA
glyphs.append(0x0046) #uni10EC
glyphs.append(0x0045) #uni10EB
glyphs.append(0x0048) #uni10EE
glyphs.append(0x0047) #uni10ED
glyphs.append(0x0049) #uni10EF
glyphs.append(0x007E) #uniFEFF
glyphs.append(0x007D) #uni0589
glyphs.append(0x004E) #uni10F4
glyphs.append(0x004F) #uni10F5
glyphs.append(0x0050) #uni10F6
glyphs.append(0x0051) #uni10F7
glyphs.append(0x004A) #uni10F0
glyphs.append(0x004B) #uni10F1
glyphs.append(0x004C) #uni10F2
glyphs.append(0x004D) #uni10F3
glyphs.append(0x0052) #uni10F8
glyphs.append(0x0053) #uni10F9
glyphs.append(0x0054) #uni10FA
glyphs.append(0x0055) #uni10FB
glyphs.append(0x0056) #uni10FC
glyphs.append(0x0002) #nonmarkingreturn
glyphs.append(0x003B) #uni10E1
glyphs.append(0x003A) #uni10E0
glyphs.append(0x003D) #uni10E3
glyphs.append(0x003C) #uni10E2
glyphs.append(0x003F) #uni10E5
glyphs.append(0x003E) #uni10E4
glyphs.append(0x0041) #uni10E7
glyphs.append(0x0040) #uni10E6
glyphs.append(0x0043) #uni10E9
glyphs.append(0x0042) #uni10E8
glyphs.append(0x0003) #space
glyphs.append(0x0032) #uni10D8
glyphs.append(0x0033) #uni10D9
glyphs.append(0x0030) #uni10D6
glyphs.append(0x0031) #uni10D7
glyphs.append(0x002E) #uni10D4
glyphs.append(0x002F) #uni10D5
glyphs.append(0x002C) #uni10D2
glyphs.append(0x002D) #uni10D3
glyphs.append(0x002A) #uni10D0
glyphs.append(0x002B) #uni10D1
glyphs.append(0x0039) #uni10DF
glyphs.append(0x0037) #uni10DD
glyphs.append(0x0038) #uni10DE
glyphs.append(0x0035) #uni10DB
glyphs.append(0x0036) #uni10DC
glyphs.append(0x0034) #uni10DA
glyphs.append(0x0000) #.notdef
glyphs.append(0x0027) #uni10C3
glyphs.append(0x0026) #uni10C2
glyphs.append(0x0025) #uni10C1
glyphs.append(0x0024) #uni10C0
glyphs.append(0x0029) #uni10C5
glyphs.append(0x0028) #uni10C4
glyphs.append(0x0066) #uni2D0F
glyphs.append(0x0065) #uni2D0E
glyphs.append(0x0064) #uni2D0D
glyphs.append(0x0063) #uni2D0C
glyphs.append(0x0062) #uni2D0B
glyphs.append(0x0061) #uni2D0A
glyphs.append(0x0012) #uni10AE
glyphs.append(0x0011) #uni10AD
glyphs.append(0x0013) #uni10AF
glyphs.append(0x000E) #uni10AA
glyphs.append(0x0010) #uni10AC
glyphs.append(0x000F) #uni10AB
glyphs.append(0x001C) #uni10B8
glyphs.append(0x001D) #uni10B9
glyphs.append(0x0014) #uni10B0
glyphs.append(0x0015) #uni10B1
glyphs.append(0x0016) #uni10B2
glyphs.append(0x0017) #uni10B3
glyphs.append(0x0018) #uni10B4
glyphs.append(0x0019) #uni10B5
glyphs.append(0x001A) #uni10B6
glyphs.append(0x001B) #uni10B7
glyphs.append(0x001E) #uni10BA
glyphs.append(0x001F) #uni10BB
glyphs.append(0x0020) #uni10BC
glyphs.append(0x0021) #uni10BD
glyphs.append(0x0022) #uni10BE
glyphs.append(0x0023) #uni10BF
glyphs.append(0x0009) #uni10A5
glyphs.append(0x0008) #uni10A4
glyphs.append(0x000B) #uni10A7
glyphs.append(0x000A) #uni10A6
glyphs.append(0x0005) #uni10A1
glyphs.append(0x0004) #uni10A0
glyphs.append(0x0007) #uni10A3
glyphs.append(0x0006) #uni10A2
glyphs.append(0x000D) #uni10A9
glyphs.append(0x000C) #uni10A8
glyphs.append(0x005E) #uni2D07
glyphs.append(0x005D) #uni2D06
glyphs.append(0x005C) #uni2D05
glyphs.append(0x005B) #uni2D04
glyphs.append(0x005A) #uni2D03
glyphs.append(0x0059) #uni2D02
glyphs.append(0x0058) #uni2D01
glyphs.append(0x0057) #uni2D00
glyphs.append(0x0060) #uni2D09
glyphs.append(0x005F) #uni2D08
glyphs.append(0x0001) #null
glyphs.append(0x006B) #uni2D14
glyphs.append(0x006C) #uni2D15
glyphs.append(0x006D) #uni2D16
glyphs.append(0x006E) #uni2D17
glyphs.append(0x0067) #uni2D10
glyphs.append(0x0068) #uni2D11
glyphs.append(0x0069) #uni2D12
glyphs.append(0x006A) #uni2D13
glyphs.append(0x006F) #uni2D18
glyphs.append(0x0070) #uni2D19
glyphs.append(0x0074) #uni2D1D
glyphs.append(0x0075) #uni2D1E
glyphs.append(0x0076) #uni2D1F
glyphs.append(0x0071) #uni2D1A
glyphs.append(0x0072) #uni2D1B
glyphs.append(0x0073) #uni2D1C
glyphs.append(0x0078) #uni2D21
glyphs.append(0x0077) #uni2D20
glyphs.append(0x007A) #uni2D23
glyphs.append(0x0079) #uni2D22
glyphs.append(0x007C) #uni2D25
glyphs.append(0x007B) #uni2D24
return glyphs
| gpl-3.0 |
DStauffman/dstauffman | dstauffman/numba/optimized.py | 1 | 6619 | r"""
Replacement utilities that are optimized for speed using numba but not numpy.
Notes
-----
#. Written by David C. Stauffer in July 2020.
#. Moved into a submodule by David C. Stauffer in February 2021.
"""
#%% Imports
from __future__ import annotations
import doctest
import math
from typing import Sequence
import unittest
from dstauffman.numba.passthrough import fake_jit, HAVE_NUMBA, ncjit, TARGET
if HAVE_NUMBA:
from numba import float32, float64, int32, int64, vectorize # type: ignore[attr-defined]
else:
float32 = float64 = int32 = int64 = vectorize = fake_jit
#%% np_any
@ncjit
def np_any(x: Sequence, /) -> bool:
r"""
Returns true if anything in the vector is true.
Parameters
----------
x : array_like
Input array
Notes
-----
#. Replacement for np.any with short-circuiting.
It is faster if something is likely True, but slower if it has to check the entire array.
#. Written by David C. Stauffer in July 2020.
Examples
--------
>>> from dstauffman.numba import np_any
>>> import numpy as np
>>> x = np.zeros(1000, dtype=bool)
>>> print(np_any(x))
False
>>> x[333] = True
>>> print(np_any(x))
True
"""
for i in range(len(x)):
if x[i]:
return True
return False
#%% np_all
@ncjit
def np_all(x: Sequence, /) -> bool:
r"""
Returns true if everything in the vector is true.
Parameters
----------
x : array_like
Input array
Notes
-----
#. Replacement for np.all with short-circuiting.
It is faster if something is likely False, but slower if it has to check the entire array.
#. Written by David C. Stauffer in July 2020.
Examples
--------
>>> from dstauffman.numba import np_all
>>> import numpy as np
>>> x = np.ones(1000, dtype=bool)
>>> print(np_all(x))
True
>>> x[333] = False
>>> print(np_all(x))
False
"""
for i in range(len(x)):
if not x[i]:
return False
return True
#%% issorted_opt
@ncjit
def issorted_opt(x: Sequence, /, descend: bool = False) -> bool:
r"""
Tells whether the given array is sorted or not.
Parameters
----------
x : array_like
Input array
descend : bool, optional, default is False
Whether to check that the array is sorted in descending order
Notes
-----
#. Written by David C. Stauffer in July 2020.
Examples
--------
>>> from dstauffman.numba import issorted_opt
>>> import numpy as np
>>> x = np.array([1, 3, 3, 5, 7])
>>> print(issorted_opt(x))
True
>>> y = np.array([3, 5, 1, 7])
>>> print(issorted_opt(y))
False
"""
if descend:
for i in range(len(x)-1):
if x[i+1] > x[i]:
return False
else:
for i in range(len(x)-1):
if x[i+1] < x[i] :
return False
return True
#%% Functions - prob_to_rate_opt
@vectorize([float64(float64, float64)], nopython=True, target=TARGET, cache=True)
def prob_to_rate_opt(prob: float, time: float) -> float:
r"""
Convert a given probability and time to a rate.
Parameters
----------
prob : numpy.ndarray
Probability of event happening over the given time
time : float
Time for the given probability in years
Returns
-------
rate : numpy.ndarray
Equivalent annual rate for the given probability and time
Notes
-----
#. Written by David C. Stauffer in January 2016.
Examples
--------
>>> from dstauffman.numba import HAVE_NUMBA, prob_to_rate_opt
>>> import numpy as np
>>> prob = np.array([0, 0.1, 1])
>>> time = 3
>>> rate = prob_to_rate_opt(prob, time) if HAVE_NUMBA else [prob_to_rate_opt(p, time) for p in prob]
>>> print(np.array_str(np.asanyarray(rate), precision=8)) # doctest: +NORMALIZE_WHITESPACE
[0. 0.03512017 inf]
"""
# check ranges
if prob < 0:
raise ValueError('Probability must be >= 0')
if prob > 1:
raise ValueError('Probability must be <= 1')
# calculate rate
if prob == 1:
return math.inf
if prob == 0:
return prob
return -math.log(1 - prob) / time
#%% Functions - rate_to_prob_opt
@vectorize([float64(float64, float64)], nopython=True, target=TARGET, cache=True)
def rate_to_prob_opt(rate: float, time: float) -> float:
r"""
Convert a given rate and time to a probability.
Parameters
----------
rate : float
Annual rate for the given time
time : float
Time period for the desired probability to be calculated from, in years
Returns
-------
float
Equivalent probability of event happening over the given time
Notes
-----
#. Written by David C. Stauffer in January 2016.
#. Converted to numba version by David C. Stauffer in November 2020.
Examples
--------
>>> from dstauffman.numba import HAVE_NUMBA, rate_to_prob_opt
>>> import numpy as np
>>> rate = np.array([0, 0.1, 1, 100, np.inf])
>>> time = 1./12
>>> prob = rate_to_prob_opt(rate, time) if HAVE_NUMBA else [rate_to_prob_opt(r, time) for r in rate]
>>> print(np.array_str(np.asanyarray(prob), precision=8)) # doctest: +NORMALIZE_WHITESPACE
[0. 0.00829871 0.07995559 0.99975963 1. ]
"""
# check ranges
if rate < 0:
raise ValueError('Rate must be >= 0')
# calculate probability
return 1 - math.exp(-rate * time)
#%% Functions - zero_divide
@vectorize([float64(float64, float64), float32(float32, float32), float32(int32, int32), \
float64(int64, int64)], nopython=True, target=TARGET, cache=True)
def zero_divide(num: float, den: float) -> float:
r"""
Numba compatible version of np.divide(num, den, out=np.zeros_like(num), where=den!=0).
Parameters
----------
num : float
Numerator
den : float
Denominator
Returns
-------
float
result of divison, except return zero for anything divided by zero, including 0/0
Notes
-----
#. Written by David C. Stauffer in February 2021.
Examples
--------
>>> from dstauffman.numba import zero_divide
>>> print(zero_divide(1., .2))
5.0
>>> print(zero_divide(3.14, 0.))
0.0
>>> print(zero_divide(0., 0.))
0.0
"""
if den == 0.:
return 0.
return num / den
#%% Unit test
if __name__ == '__main__':
unittest.main(module='dstauffman.tests.test_numba_optimized', exit=False)
doctest.testmod(verbose=False)
| lgpl-3.0 |
janplus/xbmc-addons-chinese | plugin.video.bdyun/resources/modules/rsa/pkcs1.py | 81 | 12230 | # -*- coding: utf-8 -*-
#
# Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
#
# 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
#
# https://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.
"""Functions for PKCS#1 version 1.5 encryption and signing
This module implements certain functionality from PKCS#1 version 1.5. For a
very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes
At least 8 bytes of random padding is used when encrypting a message. This makes
these methods much more secure than the ones in the ``rsa`` module.
WARNING: this module leaks information when decryption fails. The exceptions
that are raised contain the Python traceback information, which can be used to
deduce where in the process the failure occurred. DO NOT PASS SUCH INFORMATION
to your users.
"""
import hashlib
import os
from rsa._compat import b
from rsa import common, transform, core
# ASN.1 codes that describe the hash algorithm used.
HASH_ASN1 = {
'MD5': b('\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10'),
'SHA-1': b('\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14'),
'SHA-256': b('\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20'),
'SHA-384': b('\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30'),
'SHA-512': b('\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40'),
}
HASH_METHODS = {
'MD5': hashlib.md5,
'SHA-1': hashlib.sha1,
'SHA-256': hashlib.sha256,
'SHA-384': hashlib.sha384,
'SHA-512': hashlib.sha512,
}
class CryptoError(Exception):
"""Base class for all exceptions in this module."""
class DecryptionError(CryptoError):
"""Raised when decryption fails."""
class VerificationError(CryptoError):
"""Raised when verification fails."""
def _pad_for_encryption(message, target_length):
r"""Pads the message for encryption, returning the padded message.
:return: 00 02 RANDOM_DATA 00 MESSAGE
>>> block = _pad_for_encryption(b'hello', 16)
>>> len(block)
16
>>> block[0:2]
b'\x00\x02'
>>> block[-6:]
b'\x00hello'
"""
max_msglength = target_length - 11
msglength = len(message)
if msglength > max_msglength:
raise OverflowError('%i bytes needed for message, but there is only'
' space for %i' % (msglength, max_msglength))
# Get random padding
padding = b('')
padding_length = target_length - msglength - 3
# We remove 0-bytes, so we'll end up with less padding than we've asked for,
# so keep adding data until we're at the correct length.
while len(padding) < padding_length:
needed_bytes = padding_length - len(padding)
# Always read at least 8 bytes more than we need, and trim off the rest
# after removing the 0-bytes. This increases the chance of getting
# enough bytes, especially when needed_bytes is small
new_padding = os.urandom(needed_bytes + 5)
new_padding = new_padding.replace(b('\x00'), b(''))
padding = padding + new_padding[:needed_bytes]
assert len(padding) == padding_length
return b('').join([b('\x00\x02'),
padding,
b('\x00'),
message])
def _pad_for_signing(message, target_length):
r"""Pads the message for signing, returning the padded message.
The padding is always a repetition of FF bytes.
:return: 00 01 PADDING 00 MESSAGE
>>> block = _pad_for_signing(b'hello', 16)
>>> len(block)
16
>>> block[0:2]
b'\x00\x01'
>>> block[-6:]
b'\x00hello'
>>> block[2:-6]
b'\xff\xff\xff\xff\xff\xff\xff\xff'
"""
max_msglength = target_length - 11
msglength = len(message)
if msglength > max_msglength:
raise OverflowError('%i bytes needed for message, but there is only'
' space for %i' % (msglength, max_msglength))
padding_length = target_length - msglength - 3
return b('').join([b('\x00\x01'),
padding_length * b('\xff'),
b('\x00'),
message])
def encrypt(message, pub_key):
"""Encrypts the given message using PKCS#1 v1.5
:param message: the message to encrypt. Must be a byte string no longer than
``k-11`` bytes, where ``k`` is the number of bytes needed to encode
the ``n`` component of the public key.
:param pub_key: the :py:class:`rsa.PublicKey` to encrypt with.
:raise OverflowError: when the message is too large to fit in the padded
block.
>>> from rsa import key, common
>>> (pub_key, priv_key) = key.newkeys(256)
>>> message = b'hello'
>>> crypto = encrypt(message, pub_key)
The crypto text should be just as long as the public key 'n' component:
>>> len(crypto) == common.byte_size(pub_key.n)
True
"""
keylength = common.byte_size(pub_key.n)
padded = _pad_for_encryption(message, keylength)
payload = transform.bytes2int(padded)
encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
block = transform.int2bytes(encrypted, keylength)
return block
def decrypt(crypto, priv_key):
r"""Decrypts the given message using PKCS#1 v1.5
The decryption is considered 'failed' when the resulting cleartext doesn't
start with the bytes 00 02, or when the 00 byte between the padding and
the message cannot be found.
:param crypto: the crypto text as returned by :py:func:`rsa.encrypt`
:param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with.
:raise DecryptionError: when the decryption fails. No details are given as
to why the code thinks the decryption fails, as this would leak
information about the private key.
>>> import rsa
>>> (pub_key, priv_key) = rsa.newkeys(256)
It works with strings:
>>> crypto = encrypt(b'hello', pub_key)
>>> decrypt(crypto, priv_key)
b'hello'
And with binary data:
>>> crypto = encrypt(b'\x00\x00\x00\x00\x01', pub_key)
>>> decrypt(crypto, priv_key)
b'\x00\x00\x00\x00\x01'
Altering the encrypted information will *likely* cause a
:py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use
:py:func:`rsa.sign`.
.. warning::
Never display the stack trace of a
:py:class:`rsa.pkcs1.DecryptionError` exception. It shows where in the
code the exception occurred, and thus leaks information about the key.
It's only a tiny bit of information, but every bit makes cracking the
keys easier.
>>> crypto = encrypt(b'hello', pub_key)
>>> crypto = crypto[0:5] + b'X' + crypto[6:] # change a byte
>>> decrypt(crypto, priv_key)
Traceback (most recent call last):
...
rsa.pkcs1.DecryptionError: Decryption failed
"""
blocksize = common.byte_size(priv_key.n)
encrypted = transform.bytes2int(crypto)
decrypted = priv_key.blinded_decrypt(encrypted)
cleartext = transform.int2bytes(decrypted, blocksize)
# If we can't find the cleartext marker, decryption failed.
if cleartext[0:2] != b('\x00\x02'):
raise DecryptionError('Decryption failed')
# Find the 00 separator between the padding and the message
try:
sep_idx = cleartext.index(b('\x00'), 2)
except ValueError:
raise DecryptionError('Decryption failed')
return cleartext[sep_idx + 1:]
def sign(message, priv_key, hash):
"""Signs the message with the private key.
Hashes the message, then signs the hash with the given key. This is known
as a "detached signature", because the message itself isn't altered.
:param message: the message to sign. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
:param priv_key: the :py:class:`rsa.PrivateKey` to sign with
:param hash: the hash method used on the message. Use 'MD5', 'SHA-1',
'SHA-256', 'SHA-384' or 'SHA-512'.
:return: a message signature block.
:raise OverflowError: if the private key is too small to contain the
requested hash.
"""
# Get the ASN1 code for this hash method
if hash not in HASH_ASN1:
raise ValueError('Invalid hash method: %s' % hash)
asn1code = HASH_ASN1[hash]
# Calculate the hash
hash = _hash(message, hash)
# Encrypt the hash with the private key
cleartext = asn1code + hash
keylength = common.byte_size(priv_key.n)
padded = _pad_for_signing(cleartext, keylength)
payload = transform.bytes2int(padded)
encrypted = priv_key.blinded_encrypt(payload)
block = transform.int2bytes(encrypted, keylength)
return block
def verify(message, signature, pub_key):
"""Verifies that the signature matches the message.
The hash method is detected automatically from the signature.
:param message: the signed message. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
:param signature: the signature block, as created with :py:func:`rsa.sign`.
:param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
:raise VerificationError: when the signature doesn't match the message.
"""
keylength = common.byte_size(pub_key.n)
encrypted = transform.bytes2int(signature)
decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
clearsig = transform.int2bytes(decrypted, keylength)
# Get the hash method
method_name = _find_method_hash(clearsig)
message_hash = _hash(message, method_name)
# Reconstruct the expected padded hash
cleartext = HASH_ASN1[method_name] + message_hash
expected = _pad_for_signing(cleartext, keylength)
# Compare with the signed one
if expected != clearsig:
raise VerificationError('Verification failed')
return True
def _hash(message, method_name):
"""Returns the message digest.
:param message: the signed message. Can be an 8-bit string or a file-like
object. If ``message`` has a ``read()`` method, it is assumed to be a
file-like object.
:param method_name: the hash method, must be a key of
:py:const:`HASH_METHODS`.
"""
if method_name not in HASH_METHODS:
raise ValueError('Invalid hash method: %s' % method_name)
method = HASH_METHODS[method_name]
hasher = method()
if hasattr(message, 'read') and hasattr(message.read, '__call__'):
# Late import to prevent DeprecationWarnings.
from . import varblock
# read as 1K blocks
for block in varblock.yield_fixedblocks(message, 1024):
hasher.update(block)
else:
# hash the message object itself.
hasher.update(message)
return hasher.digest()
def _find_method_hash(clearsig):
"""Finds the hash method.
:param clearsig: full padded ASN1 and hash.
:return: the used hash method.
:raise VerificationFailed: when the hash method cannot be found
"""
for (hashname, asn1code) in HASH_ASN1.items():
if asn1code in clearsig:
return hashname
raise VerificationError('Verification failed')
__all__ = ['encrypt', 'decrypt', 'sign', 'verify',
'DecryptionError', 'VerificationError', 'CryptoError']
if __name__ == '__main__':
print('Running doctests 1000x or until failure')
import doctest
for count in range(1000):
(failures, tests) = doctest.testmod()
if failures:
break
if count and count % 100 == 0:
print('%i times' % count)
print('Doctests done')
| gpl-2.0 |
vnsofthe/odoo-dev | addons/account/wizard/account_chart.py | 271 | 5191 | # -*- 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 openerp.osv import fields, osv
class account_chart(osv.osv_memory):
"""
For Chart of Accounts
"""
_name = "account.chart"
_description = "Account chart"
_columns = {
'fiscalyear': fields.many2one('account.fiscalyear', \
'Fiscal year', \
help='Keep empty for all open fiscal years'),
'period_from': fields.many2one('account.period', 'Start period'),
'period_to': fields.many2one('account.period', 'End period'),
'target_move': fields.selection([('posted', 'All Posted Entries'),
('all', 'All Entries'),
], 'Target Moves', required=True),
}
def _get_fiscalyear(self, cr, uid, context=None):
"""Return default Fiscalyear value"""
return self.pool.get('account.fiscalyear').find(cr, uid, context=context)
def onchange_fiscalyear(self, cr, uid, ids, fiscalyear_id=False, context=None):
res = {}
if fiscalyear_id:
start_period = end_period = False
cr.execute('''
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
ORDER BY p.date_start ASC, p.special DESC
LIMIT 1) AS period_start
UNION ALL
SELECT * FROM (SELECT p.id
FROM account_period p
LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
WHERE f.id = %s
AND p.date_start < NOW()
ORDER BY p.date_stop DESC
LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
periods = [i[0] for i in cr.fetchall()]
if periods:
start_period = periods[0]
if len(periods) > 1:
end_period = periods[1]
res['value'] = {'period_from': start_period, 'period_to': end_period}
else:
res['value'] = {'period_from': False, 'period_to': False}
return res
def account_chart_open_window(self, cr, uid, ids, context=None):
"""
Opens chart of Accounts
@param cr: the current row, from the database cursor,
@param uid: the current user’s ID for security checks,
@param ids: List of account chart’s IDs
@return: dictionary of Open account chart window on given fiscalyear and all Entries or posted entries
"""
mod_obj = self.pool.get('ir.model.data')
act_obj = self.pool.get('ir.actions.act_window')
period_obj = self.pool.get('account.period')
fy_obj = self.pool.get('account.fiscalyear')
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
result = mod_obj.get_object_reference(cr, uid, 'account', 'action_account_tree')
id = result and result[1] or False
result = act_obj.read(cr, uid, [id], context=context)[0]
fiscalyear_id = data.get('fiscalyear', False) and data['fiscalyear'][0] or False
result['periods'] = []
if data['period_from'] and data['period_to']:
period_from = data.get('period_from', False) and data['period_from'][0] or False
period_to = data.get('period_to', False) and data['period_to'][0] or False
result['periods'] = period_obj.build_ctx_periods(cr, uid, period_from, period_to)
result['context'] = str({'fiscalyear': fiscalyear_id, 'periods': result['periods'], \
'state': data['target_move']})
if fiscalyear_id:
result['name'] += ':' + fy_obj.read(cr, uid, [fiscalyear_id], context=context)[0]['code']
return result
_defaults = {
'target_move': 'posted',
'fiscalyear': _get_fiscalyear,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
Nik0las1984/mudpyl | mudpyl/net/nvt.py | 1 | 5604 | """This module contains tools for emulating a network virtual terminal. See
RFC 854 for details of the NVT commands, and VT100 documentation for the
colour codes.
"""
from mudpyl.metaline import Metaline, RunLengthList
from mudpyl.colours import NORMAL_CODES, fg_code, bg_code, WHITE, BLACK
import re
ALL_RESET = '0'
BOLDON = '1'
BOLDOFF = '22'
FG_FLAG = '3'
BG_FLAG = '4'
GROUND_RESET = '8'
colour_pattern = re.compile( "\x1b" + #ESC
r"\[" #open square bracket
r"(\d+" #open group, initial digits
r"(?:;\d{1,2})*" #following digits
r")" #close the group
"m" #just an 'm'
)
toremove = set('\000' #NUL
'\007' #BEL
'\013' #VT
'\014') #FF
BS = '\010'
HT = '\011' #AKA '\t' and tab.
HT_replacement = ' ' #four spaces
def make_string_sane(string):
"""Process (in most cases, this means 'ignore') the NVT characters in the
input string.
"""
#simple characters don't need any special machinery.
for char in toremove:
string = string.replace(char, '')
#do it backspace by backspace because otherwise, if there were multiple
#backspaces in a row, it gets confused and backspaces over backspaces.
while BS in string:
#take off leading backspaces so that the following regex doesn't get
#confused.
string = string.lstrip(BS)
string = re.sub('.' + BS, '', string, 1)
#swap tabs for four whitespaces.
string = string.replace(HT, HT_replacement)
return string
class ColourCodeParser(object):
"""A stateful colour code parser."""
def __init__(self):
self.fore = WHITE
self.back = BLACK
self.bold = False
def _parseline(self, line):
"""Feed it lines of VT100-infested text, and it splits it all up.
This returns a threeple: a string, the foreground colours, and the
background colours. The string is simple enough. The background list
is a list of integers corresponding to WHITE, GREEN, etc. The
foreground list is made up of two-ples: the first is the integer
colour, and the second is whether bold is on or off.
The lists of fore and back changes isn't redundant -- there are no
changes that could be removed without losing colour information.
"""
#this is a performance hotspot, so minimise the number of attribute
#lookups and modifications
fore = self.fore
bold = self.bold
back = self.back
backs = [(0, back)]
fores = [(0, (fore, bold))]
text = ''
prev_end = 0
for match in colour_pattern.finditer(line):
text += line[prev_end:match.start()]
prev_end = match.end()
codes = match.group(1)
for code in codes.split(';'):
code = code.lstrip('0') #normalisation.
if not code:
#leading zeroes been stripped from ALL_RESET
if fore != WHITE or bold:
fore = WHITE
bold = False
fores.append((len(text), (fore, bold)))
if back != BLACK:
back = BLACK
backs.append((len(text), back))
elif code == BOLDON and not bold:
bold = True
fores.append((len(text), (fore, bold)))
elif code == BOLDOFF and bold:
bold = False
fores.append((len(text), (fore, bold)))
elif code.startswith(FG_FLAG):
code = code[1:]
if code == GROUND_RESET:
code = WHITE
if code in NORMAL_CODES and code != fore:
fore = code
fores.append((len(text), (fore, bold)))
elif code.startswith(BG_FLAG):
code = code[1:]
if code == GROUND_RESET:
code = BLACK
if code in NORMAL_CODES and code != back:
back = code
backs.append((len(text), back))
#We don't really care about chopped colour codes. This class is
#actually going to be tossed whole lines (ie, \r\n or similar
#terminated), and any escape code of the form "\x1b[\r\n30m" or
#similar is broken anyway. I'll probably be proved wrong somehow
#on this one...
if len(line) - 1 > prev_end:
text += line[prev_end:]
self.fore = fore
self.back = back
self.bold = bold
return (fores, backs, text)
def parseline(self, line):
"""Interpret the VT100 codes in line and returns a Metaline, replete
with RunLengthLists, that splits the text, foreground and background
into three separate channels.
"""
fores, backs, cleanline = self._parseline(line)
rlfores = RunLengthList(((length, fg_code(colour, bold))
for (length, (colour, bold)) in fores),
_normalised = True)
rlbacks = RunLengthList(((length, bg_code(colour))
for (length, colour) in backs),
_normalised = True)
return Metaline(cleanline, rlfores, rlbacks)
| gpl-2.0 |
devs1991/test_edx_docmode | venv/lib/python2.7/site-packages/selenium/webdriver/firefox/firefox_profile.py | 6 | 14052 | # Copyright 2014 Software Freedom Conservancy
# Copyright 2008-2011 WebDriver committers
# Copyright 2008-2011 Google 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.
from __future__ import with_statement
import base64
import copy
import json
import os
import re
import shutil
import sys
import tempfile
import zipfile
try:
from cStringIO import StringIO as BytesIO
bytes = str
str = basestring
except ImportError:
from io import BytesIO
from xml.dom import minidom
from selenium.webdriver.common.proxy import ProxyType
from selenium.common.exceptions import WebDriverException
WEBDRIVER_EXT = "webdriver.xpi"
WEBDRIVER_PREFERENCES = "webdriver_prefs.json"
EXTENSION_NAME = "fxdriver@googlecode.com"
class AddonFormatError(Exception):
"""Exception for not well-formed add-on manifest files"""
class FirefoxProfile(object):
ANONYMOUS_PROFILE_NAME = "WEBDRIVER_ANONYMOUS_PROFILE"
DEFAULT_PREFERENCES = None
def __init__(self, profile_directory=None):
"""
Initialises a new instance of a Firefox Profile
:args:
- profile_directory: Directory of profile that you want to use.
This defaults to None and will create a new
directory when object is created.
"""
if not FirefoxProfile.DEFAULT_PREFERENCES:
with open(os.path.join(os.path.dirname(__file__),
WEBDRIVER_PREFERENCES)) as default_prefs:
FirefoxProfile.DEFAULT_PREFERENCES = json.load(default_prefs)
self.default_preferences = copy.deepcopy(
FirefoxProfile.DEFAULT_PREFERENCES['mutable'])
self.native_events_enabled = True
self.profile_dir = profile_directory
self.tempfolder = None
if self.profile_dir is None:
self.profile_dir = self._create_tempfolder()
else:
self.tempfolder = tempfile.mkdtemp()
newprof = os.path.join(self.tempfolder, "webdriver-py-profilecopy")
shutil.copytree(self.profile_dir, newprof,
ignore=shutil.ignore_patterns("parent.lock", "lock", ".parentlock"))
self.profile_dir = newprof
self._read_existing_userjs(os.path.join(self.profile_dir, "user.js"))
self.extensionsDir = os.path.join(self.profile_dir, "extensions")
self.userPrefs = os.path.join(self.profile_dir, "user.js")
#Public Methods
def set_preference(self, key, value):
"""
sets the preference that we want in the profile.
"""
self.default_preferences[key] = value
def add_extension(self, extension=WEBDRIVER_EXT):
self._install_extension(extension)
def update_preferences(self):
for key, value in FirefoxProfile.DEFAULT_PREFERENCES['frozen'].items():
self.default_preferences[key] = value
self._write_user_prefs(self.default_preferences)
#Properties
@property
def path(self):
"""
Gets the profile directory that is currently being used
"""
return self.profile_dir
@property
def port(self):
"""
Gets the port that WebDriver is working on
"""
return self._port
@port.setter
def port(self, port):
"""
Sets the port that WebDriver will be running on
"""
if not isinstance(port, int):
raise WebDriverException("Port needs to be an integer")
try:
port = int(port)
if port < 1 or port > 65535:
raise WebDriverException("Port number must be in the range 1..65535")
except (ValueError, TypeError) as e:
raise WebDriverException("Port needs to be an integer")
self._port = port
self.set_preference("webdriver_firefox_port", self._port)
@property
def accept_untrusted_certs(self):
return self.default_preferences["webdriver_accept_untrusted_certs"]
@accept_untrusted_certs.setter
def accept_untrusted_certs(self, value):
if value not in [True, False]:
raise WebDriverException("Please pass in a Boolean to this call")
self.set_preference("webdriver_accept_untrusted_certs", value)
@property
def assume_untrusted_cert_issuer(self):
return self.default_preferences["webdriver_assume_untrusted_issuer"]
@assume_untrusted_cert_issuer.setter
def assume_untrusted_cert_issuer(self, value):
if value not in [True, False]:
raise WebDriverException("Please pass in a Boolean to this call")
self.set_preference("webdriver_assume_untrusted_issuer", value)
@property
def native_events_enabled(self):
return self.default_preferences['webdriver_enable_native_events']
@native_events_enabled.setter
def native_events_enabled(self, value):
if value not in [True, False]:
raise WebDriverException("Please pass in a Boolean to this call")
self.set_preference("webdriver_enable_native_events", value)
@property
def encoded(self):
"""
A zipped, base64 encoded string of profile directory
for use with remote WebDriver JSON wire protocol
"""
fp = BytesIO()
zipped = zipfile.ZipFile(fp, 'w', zipfile.ZIP_DEFLATED)
path_root = len(self.path) + 1 # account for trailing slash
for base, dirs, files in os.walk(self.path):
for fyle in files:
filename = os.path.join(base, fyle)
zipped.write(filename, filename[path_root:])
zipped.close()
return base64.encodestring(fp.getvalue())
def set_proxy(self, proxy):
import warnings
warnings.warn(
"This method has been deprecated. Please pass in the proxy object to the Driver Object",
DeprecationWarning)
if proxy is None:
raise ValueError("proxy can not be None")
if proxy.proxy_type is ProxyType.UNSPECIFIED:
return
self.set_preference("network.proxy.type", proxy.proxy_type['ff_value'])
if proxy.proxy_type is ProxyType.MANUAL:
self.set_preference("network.proxy.no_proxies_on", proxy.no_proxy)
self._set_manual_proxy_preference("ftp", proxy.ftp_proxy)
self._set_manual_proxy_preference("http", proxy.http_proxy)
self._set_manual_proxy_preference("ssl", proxy.ssl_proxy)
self._set_manual_proxy_preference("socks", proxy.socks_proxy)
elif proxy.proxy_type is ProxyType.PAC:
self.set_preference("network.proxy.autoconfig_url", proxy.proxy_autoconfig_url)
def _set_manual_proxy_preference(self, key, setting):
if setting is None or setting is '':
return
host_details = setting.split(":")
self.set_preference("network.proxy.%s" % key, host_details[0])
if len(host_details) > 1:
self.set_preference("network.proxy.%s_port" % key, int(host_details[1]))
def _create_tempfolder(self):
"""
Creates a temp folder to store User.js and the extension
"""
return tempfile.mkdtemp()
def _write_user_prefs(self, user_prefs):
"""
writes the current user prefs dictionary to disk
"""
with open(self.userPrefs, "w") as f:
for key, value in user_prefs.items():
f.write('user_pref("%s", %s);\n' % (key, json.dumps(value)))
def _read_existing_userjs(self, userjs):
import warnings
PREF_RE = re.compile(r'user_pref\("(.*)",\s(.*)\)')
try:
with open(userjs) as f:
for usr in f:
matches = re.search(PREF_RE, usr)
try:
self.default_preferences[matches.group(1)] = json.loads(matches.group(2))
except:
warnings.warn("(skipping) failed to json.loads existing preference: " +
matches.group(1) + matches.group(2))
except:
# The profile given hasn't had any changes made, i.e no users.js
pass
def _install_extension(self, addon, unpack=True):
"""
Installs addon from a filepath, url
or directory of addons in the profile.
- path: url, path to .xpi, or directory of addons
- unpack: whether to unpack unless specified otherwise in the install.rdf
"""
if addon == WEBDRIVER_EXT:
addon = os.path.join(os.path.dirname(__file__), WEBDRIVER_EXT)
tmpdir = None
xpifile = None
if addon.endswith('.xpi'):
tmpdir = tempfile.mkdtemp(suffix='.' + os.path.split(addon)[-1])
compressed_file = zipfile.ZipFile(addon, 'r')
for name in compressed_file.namelist():
if name.endswith('/'):
os.makedirs(os.path.join(tmpdir, name))
else:
if not os.path.isdir(os.path.dirname(os.path.join(tmpdir, name))):
os.makedirs(os.path.dirname(os.path.join(tmpdir, name)))
data = compressed_file.read(name)
with open(os.path.join(tmpdir, name), 'wb') as f:
f.write(data)
xpifile = addon
addon = tmpdir
# determine the addon id
addon_details = self._addon_details(addon)
addon_id = addon_details.get('id')
assert addon_id, 'The addon id could not be found: %s' % addon
# copy the addon to the profile
extensions_path = os.path.join(self.profile_dir, 'extensions')
addon_path = os.path.join(extensions_path, addon_id)
if not unpack and not addon_details['unpack'] and xpifile:
if not os.path.exists(extensions_path):
os.makedirs(extensions_path)
shutil.copy(xpifile, addon_path + '.xpi')
else:
shutil.copytree(addon, addon_path, symlinks=True)
# remove the temporary directory, if any
if tmpdir:
shutil.rmtree(tmpdir)
def _addon_details(self, addon_path):
"""
Returns a dictionary of details about the addon.
:param addon_path: path to the add-on directory or XPI
Returns::
{'id': u'rainbow@colors.org', # id of the addon
'version': u'1.4', # version of the addon
'name': u'Rainbow', # name of the addon
'unpack': False } # whether to unpack the addon
"""
details = {
'id': None,
'unpack': False,
'name': None,
'version': None
}
def get_namespace_id(doc, url):
attributes = doc.documentElement.attributes
namespace = ""
for i in range(attributes.length):
if attributes.item(i).value == url:
if ":" in attributes.item(i).name:
# If the namespace is not the default one remove 'xlmns:'
namespace = attributes.item(i).name.split(':')[1] + ":"
break
return namespace
def get_text(element):
"""Retrieve the text value of a given node"""
rc = []
for node in element.childNodes:
if node.nodeType == node.TEXT_NODE:
rc.append(node.data)
return ''.join(rc).strip()
if not os.path.exists(addon_path):
raise IOError('Add-on path does not exist: %s' % addon_path)
try:
if zipfile.is_zipfile(addon_path):
# Bug 944361 - We cannot use 'with' together with zipFile because
# it will cause an exception thrown in Python 2.6.
try:
compressed_file = zipfile.ZipFile(addon_path, 'r')
manifest = compressed_file.read('install.rdf')
finally:
compressed_file.close()
elif os.path.isdir(addon_path):
with open(os.path.join(addon_path, 'install.rdf'), 'r') as f:
manifest = f.read()
else:
raise IOError('Add-on path is neither an XPI nor a directory: %s' % addon_path)
except (IOError, KeyError) as e:
raise AddonFormatError(str(e), sys.exc_info()[2])
try:
doc = minidom.parseString(manifest)
# Get the namespaces abbreviations
em = get_namespace_id(doc, 'http://www.mozilla.org/2004/em-rdf#')
rdf = get_namespace_id(doc, 'http://www.w3.org/1999/02/22-rdf-syntax-ns#')
description = doc.getElementsByTagName(rdf + 'Description').item(0)
for node in description.childNodes:
# Remove the namespace prefix from the tag for comparison
entry = node.nodeName.replace(em, "")
if entry in details.keys():
details.update({entry: get_text(node)})
except Exception as e:
raise AddonFormatError(str(e), sys.exc_info()[2])
# turn unpack into a true/false value
if isinstance(details['unpack'], str):
details['unpack'] = details['unpack'].lower() == 'true'
# If no ID is set, the add-on is invalid
if details.get('id') is None:
raise AddonFormatError('Add-on id could not be found.')
return details
| agpl-3.0 |
willingc/oh-mainline | vendor/packages/Pygments/scripts/vim2pygments.py | 127 | 26283 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Vim Colorscheme Converter
~~~~~~~~~~~~~~~~~~~~~~~~~
This script converts vim colorscheme files to valid pygments
style classes meant for putting into modules.
:copyright 2006 by Armin Ronacher.
:license: BSD, see LICENSE for details.
"""
import sys
import re
from os import path
from cStringIO import StringIO
split_re = re.compile(r'(?<!\\)\s+')
SCRIPT_NAME = 'Vim Colorscheme Converter'
SCRIPT_VERSION = '0.1'
COLORS = {
# Numeric Colors
'0': '#000000',
'1': '#c00000',
'2': '#008000',
'3': '#808000',
'4': '#0000c0',
'5': '#c000c0',
'6': '#008080',
'7': '#c0c0c0',
'8': '#808080',
'9': '#ff6060',
'10': '#00ff00',
'11': '#ffff00',
'12': '#8080ff',
'13': '#ff40ff',
'14': '#00ffff',
'15': '#ffffff',
# Named Colors
'alice': '#f0f8ff',
'aliceblue': '#f0f8ff',
'antique': '#faebd7',
'antiquewhite': '#faebd7',
'antiquewhite1': '#ffefdb',
'antiquewhite2': '#eedfcc',
'antiquewhite3': '#cdc0b0',
'antiquewhite4': '#8b8378',
'aquamarine': '#7fffd4',
'aquamarine1': '#7fffd4',
'aquamarine2': '#76eec6',
'aquamarine3': '#66cdaa',
'aquamarine4': '#458b74',
'azure': '#f0ffff',
'azure1': '#f0ffff',
'azure2': '#e0eeee',
'azure3': '#c1cdcd',
'azure4': '#838b8b',
'beige': '#f5f5dc',
'bisque': '#ffe4c4',
'bisque1': '#ffe4c4',
'bisque2': '#eed5b7',
'bisque3': '#cdb79e',
'bisque4': '#8b7d6b',
'black': '#000000',
'blanched': '#ffebcd',
'blanchedalmond': '#ffebcd',
'blue': '#8a2be2',
'blue1': '#0000ff',
'blue2': '#0000ee',
'blue3': '#0000cd',
'blue4': '#00008b',
'blueviolet': '#8a2be2',
'brown': '#a52a2a',
'brown1': '#ff4040',
'brown2': '#ee3b3b',
'brown3': '#cd3333',
'brown4': '#8b2323',
'burlywood': '#deb887',
'burlywood1': '#ffd39b',
'burlywood2': '#eec591',
'burlywood3': '#cdaa7d',
'burlywood4': '#8b7355',
'cadet': '#5f9ea0',
'cadetblue': '#5f9ea0',
'cadetblue1': '#98f5ff',
'cadetblue2': '#8ee5ee',
'cadetblue3': '#7ac5cd',
'cadetblue4': '#53868b',
'chartreuse': '#7fff00',
'chartreuse1': '#7fff00',
'chartreuse2': '#76ee00',
'chartreuse3': '#66cd00',
'chartreuse4': '#458b00',
'chocolate': '#d2691e',
'chocolate1': '#ff7f24',
'chocolate2': '#ee7621',
'chocolate3': '#cd661d',
'chocolate4': '#8b4513',
'coral': '#ff7f50',
'coral1': '#ff7256',
'coral2': '#ee6a50',
'coral3': '#cd5b45',
'coral4': '#8b3e2f',
'cornflower': '#6495ed',
'cornflowerblue': '#6495ed',
'cornsilk': '#fff8dc',
'cornsilk1': '#fff8dc',
'cornsilk2': '#eee8cd',
'cornsilk3': '#cdc8b1',
'cornsilk4': '#8b8878',
'cyan': '#00ffff',
'cyan1': '#00ffff',
'cyan2': '#00eeee',
'cyan3': '#00cdcd',
'cyan4': '#008b8b',
'dark': '#8b0000',
'darkblue': '#00008b',
'darkcyan': '#008b8b',
'darkgoldenrod': '#b8860b',
'darkgoldenrod1': '#ffb90f',
'darkgoldenrod2': '#eead0e',
'darkgoldenrod3': '#cd950c',
'darkgoldenrod4': '#8b6508',
'darkgray': '#a9a9a9',
'darkgreen': '#006400',
'darkgrey': '#a9a9a9',
'darkkhaki': '#bdb76b',
'darkmagenta': '#8b008b',
'darkolivegreen': '#556b2f',
'darkolivegreen1': '#caff70',
'darkolivegreen2': '#bcee68',
'darkolivegreen3': '#a2cd5a',
'darkolivegreen4': '#6e8b3d',
'darkorange': '#ff8c00',
'darkorange1': '#ff7f00',
'darkorange2': '#ee7600',
'darkorange3': '#cd6600',
'darkorange4': '#8b4500',
'darkorchid': '#9932cc',
'darkorchid1': '#bf3eff',
'darkorchid2': '#b23aee',
'darkorchid3': '#9a32cd',
'darkorchid4': '#68228b',
'darkred': '#8b0000',
'darksalmon': '#e9967a',
'darkseagreen': '#8fbc8f',
'darkseagreen1': '#c1ffc1',
'darkseagreen2': '#b4eeb4',
'darkseagreen3': '#9bcd9b',
'darkseagreen4': '#698b69',
'darkslateblue': '#483d8b',
'darkslategray': '#2f4f4f',
'darkslategray1': '#97ffff',
'darkslategray2': '#8deeee',
'darkslategray3': '#79cdcd',
'darkslategray4': '#528b8b',
'darkslategrey': '#2f4f4f',
'darkturquoise': '#00ced1',
'darkviolet': '#9400d3',
'deep': '#ff1493',
'deeppink': '#ff1493',
'deeppink1': '#ff1493',
'deeppink2': '#ee1289',
'deeppink3': '#cd1076',
'deeppink4': '#8b0a50',
'deepskyblue': '#00bfff',
'deepskyblue1': '#00bfff',
'deepskyblue2': '#00b2ee',
'deepskyblue3': '#009acd',
'deepskyblue4': '#00688b',
'dim': '#696969',
'dimgray': '#696969',
'dimgrey': '#696969',
'dodger': '#1e90ff',
'dodgerblue': '#1e90ff',
'dodgerblue1': '#1e90ff',
'dodgerblue2': '#1c86ee',
'dodgerblue3': '#1874cd',
'dodgerblue4': '#104e8b',
'firebrick': '#b22222',
'firebrick1': '#ff3030',
'firebrick2': '#ee2c2c',
'firebrick3': '#cd2626',
'firebrick4': '#8b1a1a',
'floral': '#fffaf0',
'floralwhite': '#fffaf0',
'forest': '#228b22',
'forestgreen': '#228b22',
'gainsboro': '#dcdcdc',
'ghost': '#f8f8ff',
'ghostwhite': '#f8f8ff',
'gold': '#ffd700',
'gold1': '#ffd700',
'gold2': '#eec900',
'gold3': '#cdad00',
'gold4': '#8b7500',
'goldenrod': '#daa520',
'goldenrod1': '#ffc125',
'goldenrod2': '#eeb422',
'goldenrod3': '#cd9b1d',
'goldenrod4': '#8b6914',
'gray': '#bebebe',
'gray0': '#000000',
'gray1': '#030303',
'gray10': '#1a1a1a',
'gray100': '#ffffff',
'gray11': '#1c1c1c',
'gray12': '#1f1f1f',
'gray13': '#212121',
'gray14': '#242424',
'gray15': '#262626',
'gray16': '#292929',
'gray17': '#2b2b2b',
'gray18': '#2e2e2e',
'gray19': '#303030',
'gray2': '#050505',
'gray20': '#333333',
'gray21': '#363636',
'gray22': '#383838',
'gray23': '#3b3b3b',
'gray24': '#3d3d3d',
'gray25': '#404040',
'gray26': '#424242',
'gray27': '#454545',
'gray28': '#474747',
'gray29': '#4a4a4a',
'gray3': '#080808',
'gray30': '#4d4d4d',
'gray31': '#4f4f4f',
'gray32': '#525252',
'gray33': '#545454',
'gray34': '#575757',
'gray35': '#595959',
'gray36': '#5c5c5c',
'gray37': '#5e5e5e',
'gray38': '#616161',
'gray39': '#636363',
'gray4': '#0a0a0a',
'gray40': '#666666',
'gray41': '#696969',
'gray42': '#6b6b6b',
'gray43': '#6e6e6e',
'gray44': '#707070',
'gray45': '#737373',
'gray46': '#757575',
'gray47': '#787878',
'gray48': '#7a7a7a',
'gray49': '#7d7d7d',
'gray5': '#0d0d0d',
'gray50': '#7f7f7f',
'gray51': '#828282',
'gray52': '#858585',
'gray53': '#878787',
'gray54': '#8a8a8a',
'gray55': '#8c8c8c',
'gray56': '#8f8f8f',
'gray57': '#919191',
'gray58': '#949494',
'gray59': '#969696',
'gray6': '#0f0f0f',
'gray60': '#999999',
'gray61': '#9c9c9c',
'gray62': '#9e9e9e',
'gray63': '#a1a1a1',
'gray64': '#a3a3a3',
'gray65': '#a6a6a6',
'gray66': '#a8a8a8',
'gray67': '#ababab',
'gray68': '#adadad',
'gray69': '#b0b0b0',
'gray7': '#121212',
'gray70': '#b3b3b3',
'gray71': '#b5b5b5',
'gray72': '#b8b8b8',
'gray73': '#bababa',
'gray74': '#bdbdbd',
'gray75': '#bfbfbf',
'gray76': '#c2c2c2',
'gray77': '#c4c4c4',
'gray78': '#c7c7c7',
'gray79': '#c9c9c9',
'gray8': '#141414',
'gray80': '#cccccc',
'gray81': '#cfcfcf',
'gray82': '#d1d1d1',
'gray83': '#d4d4d4',
'gray84': '#d6d6d6',
'gray85': '#d9d9d9',
'gray86': '#dbdbdb',
'gray87': '#dedede',
'gray88': '#e0e0e0',
'gray89': '#e3e3e3',
'gray9': '#171717',
'gray90': '#e5e5e5',
'gray91': '#e8e8e8',
'gray92': '#ebebeb',
'gray93': '#ededed',
'gray94': '#f0f0f0',
'gray95': '#f2f2f2',
'gray96': '#f5f5f5',
'gray97': '#f7f7f7',
'gray98': '#fafafa',
'gray99': '#fcfcfc',
'green': '#adff2f',
'green1': '#00ff00',
'green2': '#00ee00',
'green3': '#00cd00',
'green4': '#008b00',
'greenyellow': '#adff2f',
'grey': '#bebebe',
'grey0': '#000000',
'grey1': '#030303',
'grey10': '#1a1a1a',
'grey100': '#ffffff',
'grey11': '#1c1c1c',
'grey12': '#1f1f1f',
'grey13': '#212121',
'grey14': '#242424',
'grey15': '#262626',
'grey16': '#292929',
'grey17': '#2b2b2b',
'grey18': '#2e2e2e',
'grey19': '#303030',
'grey2': '#050505',
'grey20': '#333333',
'grey21': '#363636',
'grey22': '#383838',
'grey23': '#3b3b3b',
'grey24': '#3d3d3d',
'grey25': '#404040',
'grey26': '#424242',
'grey27': '#454545',
'grey28': '#474747',
'grey29': '#4a4a4a',
'grey3': '#080808',
'grey30': '#4d4d4d',
'grey31': '#4f4f4f',
'grey32': '#525252',
'grey33': '#545454',
'grey34': '#575757',
'grey35': '#595959',
'grey36': '#5c5c5c',
'grey37': '#5e5e5e',
'grey38': '#616161',
'grey39': '#636363',
'grey4': '#0a0a0a',
'grey40': '#666666',
'grey41': '#696969',
'grey42': '#6b6b6b',
'grey43': '#6e6e6e',
'grey44': '#707070',
'grey45': '#737373',
'grey46': '#757575',
'grey47': '#787878',
'grey48': '#7a7a7a',
'grey49': '#7d7d7d',
'grey5': '#0d0d0d',
'grey50': '#7f7f7f',
'grey51': '#828282',
'grey52': '#858585',
'grey53': '#878787',
'grey54': '#8a8a8a',
'grey55': '#8c8c8c',
'grey56': '#8f8f8f',
'grey57': '#919191',
'grey58': '#949494',
'grey59': '#969696',
'grey6': '#0f0f0f',
'grey60': '#999999',
'grey61': '#9c9c9c',
'grey62': '#9e9e9e',
'grey63': '#a1a1a1',
'grey64': '#a3a3a3',
'grey65': '#a6a6a6',
'grey66': '#a8a8a8',
'grey67': '#ababab',
'grey68': '#adadad',
'grey69': '#b0b0b0',
'grey7': '#121212',
'grey70': '#b3b3b3',
'grey71': '#b5b5b5',
'grey72': '#b8b8b8',
'grey73': '#bababa',
'grey74': '#bdbdbd',
'grey75': '#bfbfbf',
'grey76': '#c2c2c2',
'grey77': '#c4c4c4',
'grey78': '#c7c7c7',
'grey79': '#c9c9c9',
'grey8': '#141414',
'grey80': '#cccccc',
'grey81': '#cfcfcf',
'grey82': '#d1d1d1',
'grey83': '#d4d4d4',
'grey84': '#d6d6d6',
'grey85': '#d9d9d9',
'grey86': '#dbdbdb',
'grey87': '#dedede',
'grey88': '#e0e0e0',
'grey89': '#e3e3e3',
'grey9': '#171717',
'grey90': '#e5e5e5',
'grey91': '#e8e8e8',
'grey92': '#ebebeb',
'grey93': '#ededed',
'grey94': '#f0f0f0',
'grey95': '#f2f2f2',
'grey96': '#f5f5f5',
'grey97': '#f7f7f7',
'grey98': '#fafafa',
'grey99': '#fcfcfc',
'honeydew': '#f0fff0',
'honeydew1': '#f0fff0',
'honeydew2': '#e0eee0',
'honeydew3': '#c1cdc1',
'honeydew4': '#838b83',
'hot': '#ff69b4',
'hotpink': '#ff69b4',
'hotpink1': '#ff6eb4',
'hotpink2': '#ee6aa7',
'hotpink3': '#cd6090',
'hotpink4': '#8b3a62',
'indian': '#cd5c5c',
'indianred': '#cd5c5c',
'indianred1': '#ff6a6a',
'indianred2': '#ee6363',
'indianred3': '#cd5555',
'indianred4': '#8b3a3a',
'ivory': '#fffff0',
'ivory1': '#fffff0',
'ivory2': '#eeeee0',
'ivory3': '#cdcdc1',
'ivory4': '#8b8b83',
'khaki': '#f0e68c',
'khaki1': '#fff68f',
'khaki2': '#eee685',
'khaki3': '#cdc673',
'khaki4': '#8b864e',
'lavender': '#fff0f5',
'lavenderblush': '#fff0f5',
'lavenderblush1': '#fff0f5',
'lavenderblush2': '#eee0e5',
'lavenderblush3': '#cdc1c5',
'lavenderblush4': '#8b8386',
'lawn': '#7cfc00',
'lawngreen': '#7cfc00',
'lemon': '#fffacd',
'lemonchiffon': '#fffacd',
'lemonchiffon1': '#fffacd',
'lemonchiffon2': '#eee9bf',
'lemonchiffon3': '#cdc9a5',
'lemonchiffon4': '#8b8970',
'light': '#90ee90',
'lightblue': '#add8e6',
'lightblue1': '#bfefff',
'lightblue2': '#b2dfee',
'lightblue3': '#9ac0cd',
'lightblue4': '#68838b',
'lightcoral': '#f08080',
'lightcyan': '#e0ffff',
'lightcyan1': '#e0ffff',
'lightcyan2': '#d1eeee',
'lightcyan3': '#b4cdcd',
'lightcyan4': '#7a8b8b',
'lightgoldenrod': '#eedd82',
'lightgoldenrod1': '#ffec8b',
'lightgoldenrod2': '#eedc82',
'lightgoldenrod3': '#cdbe70',
'lightgoldenrod4': '#8b814c',
'lightgoldenrodyellow': '#fafad2',
'lightgray': '#d3d3d3',
'lightgreen': '#90ee90',
'lightgrey': '#d3d3d3',
'lightpink': '#ffb6c1',
'lightpink1': '#ffaeb9',
'lightpink2': '#eea2ad',
'lightpink3': '#cd8c95',
'lightpink4': '#8b5f65',
'lightsalmon': '#ffa07a',
'lightsalmon1': '#ffa07a',
'lightsalmon2': '#ee9572',
'lightsalmon3': '#cd8162',
'lightsalmon4': '#8b5742',
'lightseagreen': '#20b2aa',
'lightskyblue': '#87cefa',
'lightskyblue1': '#b0e2ff',
'lightskyblue2': '#a4d3ee',
'lightskyblue3': '#8db6cd',
'lightskyblue4': '#607b8b',
'lightslateblue': '#8470ff',
'lightslategray': '#778899',
'lightslategrey': '#778899',
'lightsteelblue': '#b0c4de',
'lightsteelblue1': '#cae1ff',
'lightsteelblue2': '#bcd2ee',
'lightsteelblue3': '#a2b5cd',
'lightsteelblue4': '#6e7b8b',
'lightyellow': '#ffffe0',
'lightyellow1': '#ffffe0',
'lightyellow2': '#eeeed1',
'lightyellow3': '#cdcdb4',
'lightyellow4': '#8b8b7a',
'lime': '#32cd32',
'limegreen': '#32cd32',
'linen': '#faf0e6',
'magenta': '#ff00ff',
'magenta1': '#ff00ff',
'magenta2': '#ee00ee',
'magenta3': '#cd00cd',
'magenta4': '#8b008b',
'maroon': '#b03060',
'maroon1': '#ff34b3',
'maroon2': '#ee30a7',
'maroon3': '#cd2990',
'maroon4': '#8b1c62',
'medium': '#9370db',
'mediumaquamarine': '#66cdaa',
'mediumblue': '#0000cd',
'mediumorchid': '#ba55d3',
'mediumorchid1': '#e066ff',
'mediumorchid2': '#d15fee',
'mediumorchid3': '#b452cd',
'mediumorchid4': '#7a378b',
'mediumpurple': '#9370db',
'mediumpurple1': '#ab82ff',
'mediumpurple2': '#9f79ee',
'mediumpurple3': '#8968cd',
'mediumpurple4': '#5d478b',
'mediumseagreen': '#3cb371',
'mediumslateblue': '#7b68ee',
'mediumspringgreen': '#00fa9a',
'mediumturquoise': '#48d1cc',
'mediumvioletred': '#c71585',
'midnight': '#191970',
'midnightblue': '#191970',
'mint': '#f5fffa',
'mintcream': '#f5fffa',
'misty': '#ffe4e1',
'mistyrose': '#ffe4e1',
'mistyrose1': '#ffe4e1',
'mistyrose2': '#eed5d2',
'mistyrose3': '#cdb7b5',
'mistyrose4': '#8b7d7b',
'moccasin': '#ffe4b5',
'navajo': '#ffdead',
'navajowhite': '#ffdead',
'navajowhite1': '#ffdead',
'navajowhite2': '#eecfa1',
'navajowhite3': '#cdb38b',
'navajowhite4': '#8b795e',
'navy': '#000080',
'navyblue': '#000080',
'old': '#fdf5e6',
'oldlace': '#fdf5e6',
'olive': '#6b8e23',
'olivedrab': '#6b8e23',
'olivedrab1': '#c0ff3e',
'olivedrab2': '#b3ee3a',
'olivedrab3': '#9acd32',
'olivedrab4': '#698b22',
'orange': '#ff4500',
'orange1': '#ffa500',
'orange2': '#ee9a00',
'orange3': '#cd8500',
'orange4': '#8b5a00',
'orangered': '#ff4500',
'orangered1': '#ff4500',
'orangered2': '#ee4000',
'orangered3': '#cd3700',
'orangered4': '#8b2500',
'orchid': '#da70d6',
'orchid1': '#ff83fa',
'orchid2': '#ee7ae9',
'orchid3': '#cd69c9',
'orchid4': '#8b4789',
'pale': '#db7093',
'palegoldenrod': '#eee8aa',
'palegreen': '#98fb98',
'palegreen1': '#9aff9a',
'palegreen2': '#90ee90',
'palegreen3': '#7ccd7c',
'palegreen4': '#548b54',
'paleturquoise': '#afeeee',
'paleturquoise1': '#bbffff',
'paleturquoise2': '#aeeeee',
'paleturquoise3': '#96cdcd',
'paleturquoise4': '#668b8b',
'palevioletred': '#db7093',
'palevioletred1': '#ff82ab',
'palevioletred2': '#ee799f',
'palevioletred3': '#cd6889',
'palevioletred4': '#8b475d',
'papaya': '#ffefd5',
'papayawhip': '#ffefd5',
'peach': '#ffdab9',
'peachpuff': '#ffdab9',
'peachpuff1': '#ffdab9',
'peachpuff2': '#eecbad',
'peachpuff3': '#cdaf95',
'peachpuff4': '#8b7765',
'peru': '#cd853f',
'pink': '#ffc0cb',
'pink1': '#ffb5c5',
'pink2': '#eea9b8',
'pink3': '#cd919e',
'pink4': '#8b636c',
'plum': '#dda0dd',
'plum1': '#ffbbff',
'plum2': '#eeaeee',
'plum3': '#cd96cd',
'plum4': '#8b668b',
'powder': '#b0e0e6',
'powderblue': '#b0e0e6',
'purple': '#a020f0',
'purple1': '#9b30ff',
'purple2': '#912cee',
'purple3': '#7d26cd',
'purple4': '#551a8b',
'red': '#ff0000',
'red1': '#ff0000',
'red2': '#ee0000',
'red3': '#cd0000',
'red4': '#8b0000',
'rosy': '#bc8f8f',
'rosybrown': '#bc8f8f',
'rosybrown1': '#ffc1c1',
'rosybrown2': '#eeb4b4',
'rosybrown3': '#cd9b9b',
'rosybrown4': '#8b6969',
'royal': '#4169e1',
'royalblue': '#4169e1',
'royalblue1': '#4876ff',
'royalblue2': '#436eee',
'royalblue3': '#3a5fcd',
'royalblue4': '#27408b',
'saddle': '#8b4513',
'saddlebrown': '#8b4513',
'salmon': '#fa8072',
'salmon1': '#ff8c69',
'salmon2': '#ee8262',
'salmon3': '#cd7054',
'salmon4': '#8b4c39',
'sandy': '#f4a460',
'sandybrown': '#f4a460',
'sea': '#2e8b57',
'seagreen': '#2e8b57',
'seagreen1': '#54ff9f',
'seagreen2': '#4eee94',
'seagreen3': '#43cd80',
'seagreen4': '#2e8b57',
'seashell': '#fff5ee',
'seashell1': '#fff5ee',
'seashell2': '#eee5de',
'seashell3': '#cdc5bf',
'seashell4': '#8b8682',
'sienna': '#a0522d',
'sienna1': '#ff8247',
'sienna2': '#ee7942',
'sienna3': '#cd6839',
'sienna4': '#8b4726',
'sky': '#87ceeb',
'skyblue': '#87ceeb',
'skyblue1': '#87ceff',
'skyblue2': '#7ec0ee',
'skyblue3': '#6ca6cd',
'skyblue4': '#4a708b',
'slate': '#6a5acd',
'slateblue': '#6a5acd',
'slateblue1': '#836fff',
'slateblue2': '#7a67ee',
'slateblue3': '#6959cd',
'slateblue4': '#473c8b',
'slategray': '#708090',
'slategray1': '#c6e2ff',
'slategray2': '#b9d3ee',
'slategray3': '#9fb6cd',
'slategray4': '#6c7b8b',
'slategrey': '#708090',
'snow': '#fffafa',
'snow1': '#fffafa',
'snow2': '#eee9e9',
'snow3': '#cdc9c9',
'snow4': '#8b8989',
'spring': '#00ff7f',
'springgreen': '#00ff7f',
'springgreen1': '#00ff7f',
'springgreen2': '#00ee76',
'springgreen3': '#00cd66',
'springgreen4': '#008b45',
'steel': '#4682b4',
'steelblue': '#4682b4',
'steelblue1': '#63b8ff',
'steelblue2': '#5cacee',
'steelblue3': '#4f94cd',
'steelblue4': '#36648b',
'tan': '#d2b48c',
'tan1': '#ffa54f',
'tan2': '#ee9a49',
'tan3': '#cd853f',
'tan4': '#8b5a2b',
'thistle': '#d8bfd8',
'thistle1': '#ffe1ff',
'thistle2': '#eed2ee',
'thistle3': '#cdb5cd',
'thistle4': '#8b7b8b',
'tomato': '#ff6347',
'tomato1': '#ff6347',
'tomato2': '#ee5c42',
'tomato3': '#cd4f39',
'tomato4': '#8b3626',
'turquoise': '#40e0d0',
'turquoise1': '#00f5ff',
'turquoise2': '#00e5ee',
'turquoise3': '#00c5cd',
'turquoise4': '#00868b',
'violet': '#ee82ee',
'violetred': '#d02090',
'violetred1': '#ff3e96',
'violetred2': '#ee3a8c',
'violetred3': '#cd3278',
'violetred4': '#8b2252',
'wheat': '#f5deb3',
'wheat1': '#ffe7ba',
'wheat2': '#eed8ae',
'wheat3': '#cdba96',
'wheat4': '#8b7e66',
'white': '#ffffff',
'whitesmoke': '#f5f5f5',
'yellow': '#ffff00',
'yellow1': '#ffff00',
'yellow2': '#eeee00',
'yellow3': '#cdcd00',
'yellow4': '#8b8b00',
'yellowgreen': '#9acd32'
}
TOKENS = {
'normal': '',
'string': 'String',
'number': 'Number',
'float': 'Number.Float',
'constant': 'Name.Constant',
'number': 'Number',
'statement': ('Keyword', 'Name.Tag'),
'identifier': 'Name.Variable',
'operator': 'Operator.Word',
'label': 'Name.Label',
'exception': 'Name.Exception',
'function': ('Name.Function', 'Name.Attribute'),
'preproc': 'Comment.Preproc',
'comment': 'Comment',
'type': 'Keyword.Type',
'diffadd': 'Generic.Inserted',
'diffdelete': 'Generic.Deleted',
'error': 'Generic.Error',
'errormsg': 'Generic.Traceback',
'title': ('Generic.Heading', 'Generic.Subheading'),
'underlined': 'Generic.Emph',
'special': 'Name.Entity',
'nontext': 'Generic.Output'
}
TOKEN_TYPES = set()
for token in TOKENS.itervalues():
if not isinstance(token, tuple):
token = (token,)
for token in token:
if token:
TOKEN_TYPES.add(token.split('.')[0])
def get_vim_color(color):
if color.startswith('#'):
if len(color) == 7:
return color
else:
return '#%s0' % '0'.join(color)[1:]
return COLORS.get(color.lower())
def find_colors(code):
colors = {'Normal': {}}
bg_color = None
def set(attrib, value):
if token not in colors:
colors[token] = {}
if key.startswith('gui') or attrib not in colors[token]:
colors[token][attrib] = value
for line in code.splitlines():
if line.startswith('"'):
continue
parts = split_re.split(line.strip())
if len(parts) == 2 and parts[0] == 'set':
p = parts[1].split()
if p[0] == 'background' and p[1] == 'dark':
token = 'Normal'
bg_color = '#000000'
elif len(parts) > 2 and \
len(parts[0]) >= 2 and \
'highlight'.startswith(parts[0]):
token = parts[1].lower()
if token not in TOKENS:
continue
for item in parts[2:]:
p = item.split('=', 1)
if not len(p) == 2:
continue
key, value = p
if key in ('ctermfg', 'guifg'):
color = get_vim_color(value)
if color:
set('color', color)
elif key in ('ctermbg', 'guibg'):
color = get_vim_color(value)
if color:
set('bgcolor', color)
elif key in ('term', 'cterm', 'gui'):
items = value.split(',')
for item in items:
item = item.lower()
if item == 'none':
set('noinherit', True)
elif item == 'bold':
set('bold', True)
elif item == 'underline':
set('underline', True)
elif item == 'italic':
set('italic', True)
if bg_color is not None and not colors['Normal'].get('bgcolor'):
colors['Normal']['bgcolor'] = bg_color
color_map = {}
for token, styles in colors.iteritems():
if token in TOKENS:
tmp = []
if styles.get('noinherit'):
tmp.append('noinherit')
if 'color' in styles:
tmp.append(styles['color'])
if 'bgcolor' in styles:
tmp.append('bg:' + styles['bgcolor'])
if styles.get('bold'):
tmp.append('bold')
if styles.get('italic'):
tmp.append('italic')
if styles.get('underline'):
tmp.append('underline')
tokens = TOKENS[token]
if not isinstance(tokens, tuple):
tokens = (tokens,)
for token in tokens:
color_map[token] = ' '.join(tmp)
default_token = color_map.pop('')
return default_token, color_map
class StyleWriter(object):
def __init__(self, code, name):
self.code = code
self.name = name.lower()
def write_header(self, out):
out.write('# -*- coding: utf-8 -*-\n"""\n')
out.write(' %s Colorscheme\n' % self.name.title())
out.write(' %s\n\n' % ('~' * (len(self.name) + 12)))
out.write(' Converted by %s\n' % SCRIPT_NAME)
out.write('"""\nfrom pygments.style import Style\n')
out.write('from pygments.token import Token, %s\n\n' % ', '.join(TOKEN_TYPES))
out.write('class %sStyle(Style):\n\n' % self.name.title())
def write(self, out):
self.write_header(out)
default_token, tokens = find_colors(self.code)
tokens = tokens.items()
tokens.sort(lambda a, b: cmp(len(a[0]), len(a[1])))
bg_color = [x[3:] for x in default_token.split() if x.startswith('bg:')]
if bg_color:
out.write(' background_color = %r\n' % bg_color[0])
out.write(' styles = {\n')
out.write(' %-20s%r,\n' % ('Token:', default_token))
for token, definition in tokens:
if definition:
out.write(' %-20s%r,\n' % (token + ':', definition))
out.write(' }')
def __repr__(self):
out = StringIO()
self.write_style(out)
return out.getvalue()
def convert(filename, stream=None):
name = path.basename(filename)
if name.endswith('.vim'):
name = name[:-4]
f = file(filename)
code = f.read()
f.close()
writer = StyleWriter(code, name)
if stream is not None:
out = stream
else:
out = StringIO()
writer.write(out)
if stream is None:
return out.getvalue()
def main():
if len(sys.argv) != 2 or sys.argv[1] in ('-h', '--help'):
print 'Usage: %s <filename.vim>' % sys.argv[0]
return 2
if sys.argv[1] in ('-v', '--version'):
print '%s %s' % (SCRIPT_NAME, SCRIPT_VERSION)
return
filename = sys.argv[1]
if not (path.exists(filename) and path.isfile(filename)):
print 'Error: %s not found' % filename
return 1
convert(filename, sys.stdout)
sys.stdout.write('\n')
if __name__ == '__main__':
sys.exit(main() or 0)
| agpl-3.0 |
ARudiuk/mne-python | mne/channels/interpolation.py | 4 | 6510 | # Authors: Denis Engemann <denis.engemann@gmail.com>
#
# License: BSD (3-clause)
import numpy as np
from numpy.polynomial.legendre import legval
from scipy import linalg
from ..utils import logger, warn
from ..io.pick import pick_types, pick_channels, pick_info
from ..surface import _normalize_vectors
from ..bem import _fit_sphere
from ..forward import _map_meg_channels
def _calc_g(cosang, stiffness=4, num_lterms=50):
"""Calculate spherical spline g function between points on a sphere.
Parameters
----------
cosang : array-like of float, shape(n_channels, n_channels)
cosine of angles between pairs of points on a spherical surface. This
is equivalent to the dot product of unit vectors.
stiffness : float
stiffness of the spline.
num_lterms : int
number of Legendre terms to evaluate.
Returns
-------
G : np.ndrarray of float, shape(n_channels, n_channels)
The G matrix.
"""
factors = [(2 * n + 1) / (n ** stiffness * (n + 1) ** stiffness *
4 * np.pi) for n in range(1, num_lterms + 1)]
return legval(cosang, [0] + factors)
def _make_interpolation_matrix(pos_from, pos_to, alpha=1e-5):
"""Compute interpolation matrix based on spherical splines
Implementation based on [1]
Parameters
----------
pos_from : np.ndarray of float, shape(n_good_sensors, 3)
The positions to interpoloate from.
pos_to : np.ndarray of float, shape(n_bad_sensors, 3)
The positions to interpoloate.
alpha : float
Regularization parameter. Defaults to 1e-5.
Returns
-------
interpolation : np.ndarray of float, shape(len(pos_from), len(pos_to))
The interpolation matrix that maps good signals to the location
of bad signals.
References
----------
[1] Perrin, F., Pernier, J., Bertrand, O. and Echallier, JF. (1989).
Spherical splines for scalp potential and current density mapping.
Electroencephalography Clinical Neurophysiology, Feb; 72(2):184-7.
"""
pos_from = pos_from.copy()
pos_to = pos_to.copy()
# normalize sensor positions to sphere
_normalize_vectors(pos_from)
_normalize_vectors(pos_to)
# cosine angles between source positions
cosang_from = pos_from.dot(pos_from.T)
cosang_to_from = pos_to.dot(pos_from.T)
G_from = _calc_g(cosang_from)
G_to_from = _calc_g(cosang_to_from)
if alpha is not None:
G_from.flat[::len(G_from) + 1] += alpha
n_channels = G_from.shape[0] # G_from should be square matrix
C = np.r_[np.c_[G_from, np.ones((n_channels, 1))],
np.c_[np.ones((1, n_channels)), 0]]
C_inv = linalg.pinv(C)
interpolation = np.c_[G_to_from,
np.ones((G_to_from.shape[0], 1))].dot(C_inv[:, :-1])
return interpolation
def _do_interp_dots(inst, interpolation, goods_idx, bads_idx):
"""Dot product of channel mapping matrix to channel data
"""
from ..io.base import _BaseRaw
from ..epochs import _BaseEpochs
from ..evoked import Evoked
if isinstance(inst, _BaseRaw):
inst._data[bads_idx] = interpolation.dot(inst._data[goods_idx])
elif isinstance(inst, _BaseEpochs):
inst._data[:, bads_idx, :] = np.einsum('ij,xjy->xiy', interpolation,
inst._data[:, goods_idx, :])
elif isinstance(inst, Evoked):
inst.data[bads_idx] = interpolation.dot(inst.data[goods_idx])
else:
raise ValueError('Inputs of type {0} are not supported'
.format(type(inst)))
def _interpolate_bads_eeg(inst):
"""Interpolate bad EEG channels
Operates in place.
Parameters
----------
inst : mne.io.Raw, mne.Epochs or mne.Evoked
The data to interpolate. Must be preloaded.
"""
bads_idx = np.zeros(len(inst.ch_names), dtype=np.bool)
goods_idx = np.zeros(len(inst.ch_names), dtype=np.bool)
picks = pick_types(inst.info, meg=False, eeg=True, exclude=[])
inst.info._check_consistency()
bads_idx[picks] = [inst.ch_names[ch] in inst.info['bads'] for ch in picks]
if len(picks) == 0 or len(bads_idx) == 0:
return
goods_idx[picks] = True
goods_idx[bads_idx] = False
pos = inst._get_channel_positions(picks)
# Make sure only EEG are used
bads_idx_pos = bads_idx[picks]
goods_idx_pos = goods_idx[picks]
pos_good = pos[goods_idx_pos]
pos_bad = pos[bads_idx_pos]
# test spherical fit
radius, center = _fit_sphere(pos_good)
distance = np.sqrt(np.sum((pos_good - center) ** 2, 1))
distance = np.mean(distance / radius)
if np.abs(1. - distance) > 0.1:
warn('Your spherical fit is poor, interpolation results are '
'likely to be inaccurate.')
logger.info('Computing interpolation matrix from {0} sensor '
'positions'.format(len(pos_good)))
interpolation = _make_interpolation_matrix(pos_good, pos_bad)
logger.info('Interpolating {0} sensors'.format(len(pos_bad)))
_do_interp_dots(inst, interpolation, goods_idx, bads_idx)
def _interpolate_bads_meg(inst, mode='accurate', verbose=None):
"""Interpolate bad channels from data in good channels.
Parameters
----------
inst : mne.io.Raw, mne.Epochs or mne.Evoked
The data to interpolate. Must be preloaded.
mode : str
Either `'accurate'` or `'fast'`, determines the quality of the
Legendre polynomial expansion used for interpolation. `'fast'` should
be sufficient for most applications.
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
"""
picks_meg = pick_types(inst.info, meg=True, eeg=False, exclude=[])
ch_names = [inst.info['ch_names'][p] for p in picks_meg]
picks_good = pick_types(inst.info, meg=True, eeg=False, exclude='bads')
# select the bad meg channel to be interpolated
if len(inst.info['bads']) == 0:
picks_bad = []
else:
picks_bad = pick_channels(ch_names, inst.info['bads'],
exclude=[])
# return without doing anything if there are no meg channels
if len(picks_meg) == 0 or len(picks_bad) == 0:
return
info_from = pick_info(inst.info, picks_good)
info_to = pick_info(inst.info, picks_bad)
mapping = _map_meg_channels(info_from, info_to, mode=mode)
_do_interp_dots(inst, mapping, picks_good, picks_bad)
| bsd-3-clause |
sanghinitin/golismero | thirdparty_libs/nltk/tokenize/__init__.py | 17 | 3600 | # -*- coding: utf-8 -*-
# Natural Language Toolkit: Tokenizers
#
# Copyright (C) 2001-2012 NLTK Project
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# Steven Bird <sb@csse.unimelb.edu.au> (minor additions)
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
r"""
NLTK Tokenizer Package
Tokenizers divide strings into lists of substrings. For example,
tokenizers can be used to find the list of sentences or words in a
string.
>>> from nltk.tokenize import word_tokenize, wordpunct_tokenize, sent_tokenize
>>> s = '''Good muffins cost $3.88\nin New York. Please buy me
... two of them.\n\nThanks.'''
>>> wordpunct_tokenize(s)
['Good', 'muffins', 'cost', '$', '3', '.', '88', 'in', 'New', 'York', '.',
'Please', 'buy', 'me', 'two', 'of', 'them', '.', 'Thanks', '.']
>>> sent_tokenize(s)
['Good muffins cost $3.88\nin New York.', 'Please buy me\ntwo of them.', 'Thanks.']
>>> [word_tokenize(t) for t in sent_tokenize(s)]
[['Good', 'muffins', 'cost', '$', '3.88', 'in', 'New', 'York', '.'],
['Please', 'buy', 'me', 'two', 'of', 'them', '.'], ['Thanks', '.']]
Caution: only use ``word_tokenize()`` on individual sentences.
Caution: when tokenizing a Unicode string, make sure you are not
using an encoded version of the string (it may be necessary to
decode it first, e.g. with ``s.decode("utf8")``.
NLTK tokenizers can produce token-spans, represented as tuples of integers
having the same semantics as string slices, to support efficient comparison
of tokenizers. (These methods are implemented as generators.)
>>> from nltk.tokenize import WhitespaceTokenizer
>>> list(WhitespaceTokenizer().span_tokenize(s))
[(0, 4), (5, 12), (13, 17), (18, 23), (24, 26), (27, 30), (31, 36), (38, 44),
(45, 48), (49, 51), (52, 55), (56, 58), (59, 64), (66, 73)]
There are numerous ways to tokenize text. If you need more control over
tokenization, see the other methods provided in this package.
For further information, please see Chapter 3 of the NLTK book.
"""
from nltk.data import load
from nltk.tokenize.simple import (SpaceTokenizer, TabTokenizer, LineTokenizer,
line_tokenize)
from nltk.tokenize.regexp import (RegexpTokenizer, WhitespaceTokenizer,
BlanklineTokenizer, WordPunctTokenizer,
wordpunct_tokenize, regexp_tokenize,
blankline_tokenize)
from nltk.tokenize.punkt import PunktSentenceTokenizer, PunktWordTokenizer
from nltk.tokenize.sexpr import SExprTokenizer, sexpr_tokenize
from nltk.tokenize.treebank import TreebankWordTokenizer
try:
import numpy
except ImportError:
pass
else:
from nltk.tokenize.texttiling import TextTilingTokenizer
# Standard sentence tokenizer.
def sent_tokenize(text):
"""
Return a sentence-tokenized copy of *text*,
using NLTK's recommended sentence tokenizer
(currently :class:`.PunktSentenceTokenizer`).
"""
tokenizer = load('tokenizers/punkt/english.pickle')
return tokenizer.tokenize(text)
# Standard word tokenizer.
_word_tokenize = TreebankWordTokenizer().tokenize
def word_tokenize(text):
"""
Return a tokenized copy of *text*,
using NLTK's recommended word tokenizer
(currently :class:`.TreebankWordTokenizer`).
This tokenizer is designed to work on a sentence at a time.
"""
return _word_tokenize(text)
if __name__ == "__main__":
import doctest
doctest.testmod(optionflags=doctest.NORMALIZE_WHITESPACE)
| gpl-2.0 |
ruby32/solarcoin | qa/rpc-tests/assumevalid.py | 45 | 7764 | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
assumevalid.py
Test logic for skipping signature validation on blocks which we've assumed
valid (https://github.com/bitcoin/bitcoin/pull/9484)
We build a chain that includes and invalid signature for one of the
transactions:
0: genesis block
1: block 1 with coinbase transaction output.
2-101: bury that block with 100 blocks so the coinbase transaction
output can be spent
102: a block containing a transaction spending the coinbase
transaction output. The transaction has an invalid signature.
103-2202: bury the bad block with just over two weeks' worth of blocks
(2100 blocks)
Start three nodes:
- node0 has no -assumevalid parameter. Try to sync to block 2202. It will
reject block 102 and only sync as far as block 101
- node1 has -assumevalid set to the hash of block 102. Try to sync to
block 2202. node1 will sync all the way to block 2202.
- node2 has -assumevalid set to the hash of block 102. Try to sync to
block 200. node2 will reject block 102 since it's assumed valid, but it
isn't buried by at least two weeks' work.
'''
from test_framework.mininode import *
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
from test_framework.blocktools import create_block, create_coinbase
from test_framework.key import CECKey
from test_framework.script import *
class BaseNode(SingleNodeConnCB):
def __init__(self):
SingleNodeConnCB.__init__(self)
self.last_inv = None
self.last_headers = None
self.last_block = None
self.last_getdata = None
self.block_announced = False
self.last_getheaders = None
self.disconnected = False
self.last_blockhash_announced = None
def on_close(self, conn):
self.disconnected = True
def wait_for_disconnect(self, timeout=60):
test_function = lambda: self.disconnected
assert(wait_until(test_function, timeout=timeout))
return
def send_header_for_blocks(self, new_blocks):
headers_message = msg_headers()
headers_message.headers = [ CBlockHeader(b) for b in new_blocks ]
self.send_message(headers_message)
class SendHeadersTest(BitcoinTestFramework):
def __init__(self):
super().__init__()
self.setup_clean_chain = True
self.num_nodes = 3
def setup_network(self):
# Start node0. We don't start the other nodes yet since
# we need to pre-mine a block with an invalid transaction
# signature so we can pass in the block hash as assumevalid.
self.nodes = []
self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"]))
def run_test(self):
# Connect to node0
node0 = BaseNode()
connections = []
connections.append(NodeConn('127.0.0.1', p2p_port(0), self.nodes[0], node0))
node0.add_connection(connections[0])
NetworkThread().start() # Start up network handling in another thread
node0.wait_for_verack()
# Build the blockchain
self.tip = int(self.nodes[0].getbestblockhash(), 16)
self.block_time = self.nodes[0].getblock(self.nodes[0].getbestblockhash())['time'] + 1
self.blocks = []
# Get a pubkey for the coinbase TXO
coinbase_key = CECKey()
coinbase_key.set_secretbytes(b"horsebattery")
coinbase_pubkey = coinbase_key.get_pubkey()
# Create the first block with a coinbase output to our key
height = 1
block = create_block(self.tip, create_coinbase(height, coinbase_pubkey), self.block_time)
self.blocks.append(block)
self.block_time += 1
block.solve()
# Save the coinbase for later
self.block1 = block
self.tip = block.sha256
height += 1
# Bury the block 100 deep so the coinbase output is spendable
for i in range(100):
block = create_block(self.tip, create_coinbase(height), self.block_time)
block.solve()
self.blocks.append(block)
self.tip = block.sha256
self.block_time += 1
height += 1
# Create a transaction spending the coinbase output with an invalid (null) signature
tx = CTransaction()
tx.vin.append(CTxIn(COutPoint(self.block1.vtx[0].sha256, 0), scriptSig=b""))
tx.vout.append(CTxOut(49*100000000, CScript([OP_TRUE])))
tx.calc_sha256()
block102 = create_block(self.tip, create_coinbase(height), self.block_time)
self.block_time += 1
block102.vtx.extend([tx])
block102.hashMerkleRoot = block102.calc_merkle_root()
block102.rehash()
block102.solve()
self.blocks.append(block102)
self.tip = block102.sha256
self.block_time += 1
height += 1
# Bury the assumed valid block 2100 deep
for i in range(2100):
block = create_block(self.tip, create_coinbase(height), self.block_time)
block.nVersion = 4
block.solve()
self.blocks.append(block)
self.tip = block.sha256
self.block_time += 1
height += 1
# Start node1 and node2 with assumevalid so they accept a block with a bad signature.
self.nodes.append(start_node(1, self.options.tmpdir,
["-debug", "-assumevalid=" + hex(block102.sha256)]))
node1 = BaseNode() # connects to node1
connections.append(NodeConn('127.0.0.1', p2p_port(1), self.nodes[1], node1))
node1.add_connection(connections[1])
node1.wait_for_verack()
self.nodes.append(start_node(2, self.options.tmpdir,
["-debug", "-assumevalid=" + hex(block102.sha256)]))
node2 = BaseNode() # connects to node2
connections.append(NodeConn('127.0.0.1', p2p_port(2), self.nodes[2], node2))
node2.add_connection(connections[2])
node2.wait_for_verack()
# send header lists to all three nodes
node0.send_header_for_blocks(self.blocks[0:2000])
node0.send_header_for_blocks(self.blocks[2000:])
node1.send_header_for_blocks(self.blocks[0:2000])
node1.send_header_for_blocks(self.blocks[2000:])
node2.send_header_for_blocks(self.blocks[0:200])
# Send 102 blocks to node0. Block 102 will be rejected.
for i in range(101):
node0.send_message(msg_block(self.blocks[i]))
node0.sync_with_ping() # make sure the most recent block is synced
node0.send_message(msg_block(self.blocks[101]))
assert_equal(self.nodes[0].getblock(self.nodes[0].getbestblockhash())['height'], 101)
# Send 3102 blocks to node1. All blocks will be accepted.
for i in range(2202):
node1.send_message(msg_block(self.blocks[i]))
node1.sync_with_ping() # make sure the most recent block is synced
assert_equal(self.nodes[1].getblock(self.nodes[1].getbestblockhash())['height'], 2202)
# Send 102 blocks to node2. Block 102 will be rejected.
for i in range(101):
node2.send_message(msg_block(self.blocks[i]))
node2.sync_with_ping() # make sure the most recent block is synced
node2.send_message(msg_block(self.blocks[101]))
assert_equal(self.nodes[2].getblock(self.nodes[2].getbestblockhash())['height'], 101)
if __name__ == '__main__':
SendHeadersTest().main()
| mit |
nickhand/nbodykit | nbodykit/source/mesh/array.py | 2 | 1952 | from nbodykit.base.mesh import MeshSource
from nbodykit import CurrentMPIComm
from nbodykit.utils import attrs_to_dict
from pmesh.pm import RealField, ComplexField
import numpy
class ArrayMesh(MeshSource):
"""
A MeshSource initalized from an in-memory numpy array.
.. note::
The in-memory array must be fully hosted by the root rank.
Parameters
----------
array : numpy.ndarray
the numpy array holding the field data; this must be fully
hosted by the rank specified by ``root``
BoxSize : float, 3-vector
the size of the box
root : int, optional
the root rank holding the array data
**kwargs :
additional meta-data to store
"""
def __repr__(self):
return "ArrayMesh()"
@CurrentMPIComm.enable
def __init__(self, array, BoxSize, comm=None, root=0, **kwargs):
if comm.rank == root:
array = numpy.array(array)
if array.dtype.kind == 'c':
# transform to real for the correct shape
array = numpy.fft.irfftn(array)
array[...] *= numpy.prod(array.shape)
shape = array.shape
dtype = array.dtype
else:
array, dtype, shape = [None] * 3
dtype = comm.bcast(dtype, root=root)
shape = comm.bcast(shape, root=root)
assert len(shape) in (2, 3)
Nmesh = shape
empty = numpy.empty((0,), dtype)
MeshSource.__init__(self, comm, Nmesh, BoxSize, empty.real.dtype)
self.field = self.pm.create(type='real')
if comm.rank != root:
array = empty # ignore data from other ranks.
else:
array = array.ravel()
# fill the field with the array
self.field.unravel(array)
def to_real_field(self):
if isinstance(self.field, RealField):
return self.field.copy()
else:
return NotImplemented
| gpl-3.0 |
lloeki/python-dcpu_16 | test.py | 1 | 8924 | import unittest
import random
import dcpu_16
from dcpu_16 import CPU
class TestInstructions(unittest.TestCase):
"""Instruction set"""
def setUp(self):
pass
def test_SET(self):
dcpu_16.SET.opcode = (0x1,)
c = CPU()
c.a = 0x0
c.b = 0x42
dcpu_16.SET(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x42)
self.assertEqual(c.b, 0x42)
def test_ADD(self):
dcpu_16.SET.opcode = (0x2,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.ADD(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17+0x42)
self.assertEqual(c.b, 0x42)
self.assertEqual(c.o, 0x0)
def test_SUB(self):
dcpu_16.SET.opcode = (0x3,)
c = CPU()
c.a = 0x42
c.b = 0x17
dcpu_16.SUB(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x42-0x17)
self.assertEqual(c.b, 0x17)
self.assertEqual(c.o, 0x0)
def test_MUL(self):
dcpu_16.SET.opcode = (0x4,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.MUL(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17*0x42)
self.assertEqual(c.b, 0x42)
self.assertEqual(c.o, 0x0)
def test_DIV(self):
dcpu_16.SET.opcode = (0x5,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.DIV(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17/0x42)
self.assertEqual(c.b, 0x42)
self.assertEqual(c.o, ((0x17<<16)/0x42)&0xFFFF)
def test_MOD(self):
dcpu_16.SET.opcode = (0x6,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.MOD(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17%0x42)
self.assertEqual(c.b, 0x42)
self.assertEqual(c.o, 0x0)
def test_SHL(self):
dcpu_16.SET.opcode = (0x7,)
c = CPU()
c.a = 0x17
c.b = 0x4
dcpu_16.SHL(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17<<0x4 & dcpu_16.wmask)
self.assertEqual(c.b, 0x4)
self.assertEqual(c.o, 0x0)
def test_SHR(self):
dcpu_16.SET.opcode = (0x8,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.SHR(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17>>0x42)
self.assertEqual(c.b, 0x42)
self.assertEqual(c.o, 0x0)
def test_AND(self):
dcpu_16.SET.opcode = (0x9,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.AND(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17&0x42)
self.assertEqual(c.b, 0x42)
self.assertEqual(c.o, 0x0)
def test_BOR(self):
dcpu_16.SET.opcode = (0xA,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.BOR(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17|0x42)
self.assertEqual(c.b, 0x42)
self.assertEqual(c.o, 0x0)
def test_XOR(self):
dcpu_16.SET.opcode = (0xB,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.XOR(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.a, 0x17^0x42)
self.assertEqual(c.b, 0x42)
self.assertEqual(c.o, 0x0)
def test_IFE(self):
dcpu_16.SET.opcode = (0xC,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.IFE(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, True)
c.a = 0x42
c.b = 0x42
dcpu_16.IFE(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, False)
def test_IFN(self):
dcpu_16.SET.opcode = (0xD,)
c = CPU()
c.a = 0x17
c.b = 0x42
dcpu_16.IFN(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, False)
c.a = 0x42
c.b = 0x42
dcpu_16.IFN(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, True)
def test_IFG(self):
dcpu_16.SET.opcode = (0xE,)
c = CPU()
c.a = 0x41
c.b = 0x42
dcpu_16.IFG(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, True)
c.a = 0x42
c.b = 0x42
dcpu_16.IFG(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, True)
c.a = 0x42
c.b = 0x41
dcpu_16.IFG(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, False)
def test_IFB(self):
dcpu_16.SET.opcode = (0xF,)
c = CPU()
c.a = 0xF0F0
c.b = 0x0F0F
dcpu_16.IFB(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, True)
c.a = 0xF1F0
c.b = 0x0F0F
dcpu_16.IFB(c, c._pointer(0x0), c._pointer(0x1))
self.assertEqual(c.skip, False)
def test_JSR(self):
dcpu_16.JSR.opcode = (0x0, 0x1)
c = CPU()
c.a = 0xDEAD
c.pc = 0xBEEF
dcpu_16.JSR(c, c._pointer(0x0))
self.assertEqual(c.pc, 0xDEAD)
self.assertEqual(c.sp, 0xFFFF)
self.assertEqual(c.m[0xFFFF], 0xBEEF)
class TestCPU(unittest.TestCase):
"""CPU behavior"""
def setUp(self):
pass
def test_initial_state(self):
"""Initial state shall be all zero"""
c = CPU()
for r in c.r:
self.assertEqual(r, 0)
self.assertEqual(c.pc, 0)
self.assertEqual(c.o, 0)
self.assertEqual(c.sp, 0)
self.assertEqual(c.skip, False)
self.assertEqual(c.pc, 0)
for r in c.m:
self.assertEqual(r, 0)
def test_reset(self):
"""Reset shall bring CPU register state to initial"""
c = CPU()
for i in xrange(0x8):
c.r[i] = random.randrange(0x10000)
c.reset()
for r in c.r:
self.assertEqual(r, 0)
self.assertEqual(c.pc, 0)
self.assertEqual(c.o, 0)
self.assertEqual(c.sp, 0)
self.assertEqual(c.skip, False)
self.assertEqual(c.pc, 0)
def test_clear(self):
"""Clear shall zero memory"""
c = CPU()
for i in xrange(0x10000):
c.m[i] = random.randrange(0x10000)
c.clear()
for r in c.m:
self.assertEqual(r, 0)
class TestCPUWithPrograms(unittest.TestCase):
def setUP(self):
pass
def test_spec_demo(self):
c = CPU()
data = [
0x7c01, 0x0030, 0x7de1, 0x1000, 0x0020, 0x7803, 0x1000, 0xc00d,
0x7dc1, 0x001a, 0xa861, 0x7c01, 0x2000, 0x2161, 0x2000, 0x8463,
0x806d, 0x7dc1, 0x000d, 0x9031, 0x7c10, 0x0018, 0x7dc1, 0x001a,
0x9037, 0x61c1, 0x7dc1, 0x001a, 0x0000, 0x0000, 0x0000, 0x0000,
]
c.load_m(data=data)
self.assertEqual(c.pc, 0)
c.step() # SET A, 0x30
self.assertEqual(c.a, 0x30)
self.assertEqual(c.pc, 2)
c.step() # SET [0x1000], 0x20
self.assertEqual(c.m[0x1000], 0x20)
self.assertEqual(c.pc, 5)
c.step() # SUB A, [0x1000]
self.assertEqual(c.a, 0x10)
self.assertEqual(c.pc, 7)
c.step() # IFN A, 0x10
self.assertEqual(c.pc, 8)
self.assertEqual(c.skip, True)
c.step() # skip SET PC, crash
self.assertEqual(c.skip, False)
self.assertEqual(c.pc, 10)
c.step() # SET I, 10
self.assertEqual(c.i, 0x0A)
self.assertEqual(c.pc, 11)
c.step() # SET A, 0x2000
self.assertEqual(c.a, 0x2000)
for i in range(10, 0, -1):
self.assertEqual(c.pc, 13)
c.step() # SET [0x2000+I], [A]
self.assertEqual(c.m[0x2000+i], 0x0)
self.assertEqual(c.pc, 15)
c.step() # SUB I, 1
self.assertEqual(c.i, i-1)
self.assertEqual(c.pc, 16)
c.step() # IFN I, 0
self.assertEqual(c.skip, i-1==0)
self.assertEqual(c.pc, 17)
c.step() # SET PC, loop (with skip if c.i==0)
self.assertEqual(c.pc, 19)
c.step() # SET X, 0x4
self.assertEqual(c.x, 0x4)
self.assertEqual(c.pc, 20)
c.step() # JSR testsub
self.assertEqual(c.sp, 0xFFFF)
self.assertEqual(c.m[0xFFFF], 22)
self.assertEqual(c.pc, 24)
c.step() # SHL X, 4
self.assertEqual(c.x, 0x40)
self.assertEqual(c.pc, 25)
c.step() # SET PC, POP
self.assertEqual(c.pc, 22)
c.step() # SET PC, crash
self.assertEqual(c.pc, 26)
c.step() # SET PC, crash
self.assertEqual(c.pc, 26)
# endless loop
if __name__ == '__main__':
cases = [
'test.TestInstructions',
'test.TestCPU',
'test.TestCPUWithPrograms'
]
suite = unittest.TestLoader().loadTestsFromNames(cases)
unittest.TextTestRunner(verbosity=2).run(suite)
| bsd-3-clause |
zenodo/invenio | invenio/modules/formatter/manage.py | 13 | 10738 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2013, 2014 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
"""
Perform template migration operations.
Migrate output formats and output templates found in
``CFG_BIBFORMAT_OUTPUTS_PATH`` and ``CFG_BIBFORMAT_TEMPLATES_PATH``
respectively. It creates backup of each output format with name
``<FORMAT>_legacy.bfo`` and generates new Jinja2 templates in
``CFG_BIBFORMAT_JINJA_TEMPLATE_PATH``.
"""
from __future__ import print_function
import os
import re
import shutil
from six import iteritems
from invenio.ext.script import Manager
manager = Manager(usage="Perform template migration operations.")
@manager.option('--rewrite-existing-templates',
dest='rewrite_existing_templates',
action='store_true', default=False)
@manager.option('-t', '--template',
dest='only_template_re', default=None,
help="only templates matching regular expression")
@manager.option('--verbose', dest='verbose')
def bft2tpl(rewrite_existing_templates=False, only_template_re=None,
verbose=0):
"""Convert *bft* templates to Jinja2 *tpl* templates."""
# Import all invenio modules inside to avoid side-efects ouside
# Flask application context.
from invenio.modules.formatter.config import CFG_BIBFORMAT_OUTPUTS_PATH, \
CFG_BIBFORMAT_FORMAT_OUTPUT_EXTENSION, \
CFG_BIBFORMAT_FORMAT_TEMPLATE_EXTENSION, \
CFG_BIBFORMAT_FORMAT_JINJA_TEMPLATE_EXTENSION, \
CFG_BIBFORMAT_JINJA_TEMPLATE_PATH
from invenio.modules.formatter.engine import get_format_element, \
get_output_formats, \
pattern_function_params, \
pattern_tag, pattern_lang, \
translation_pattern, \
ln_pattern, get_format_templates
from invenio.legacy.bibformat.adminlib import \
update_output_format_rules
only_template = re.compile(only_template_re) \
if only_template_re is not None else None
def rename_template(template):
if template[-3:] == CFG_BIBFORMAT_FORMAT_TEMPLATE_EXTENSION and \
(only_template is None or only_template.match(template)):
return template[:-3] + \
CFG_BIBFORMAT_FORMAT_JINJA_TEMPLATE_EXTENSION
return template
def update_rule(rule):
rule['template'] = rename_template(rule['template'])
print(' ...', rule['template'], 'to', end=' ')
print(rename_template(rule['template']))
print(' ', rule)
return rule
def eval_format_template_elements(format_template, bfo, verbose=0):
def insert_element_code(match):
error = []
function_name = match.group("function_name")
try:
format_element = get_format_element(function_name, verbose)
except Exception:
error.append('Invalid function name %s' % (function_name, ))
params_str = []
if format_element is not None:
params = {}
# Look for function parameters given in format template code
all_params = match.group('params')
if all_params is not None:
function_params_iterator = pattern_function_params.\
finditer(all_params)
for param_match in function_params_iterator:
sep = param_match.group('sep')
name = param_match.group('param')
value = param_match.group('value')
params[name] = value
params_str.append(name + '=' + sep + value + sep)
# Replace element with function call with params.
result = '{{ bfe_%s(bfo, %s) }}' % (function_name.lower(),
', '.join(params_str))
return result
print('\n'.join(error))
# Substitute special tags in the format by our own text.
# Special tags have the form
# <BFE_format_element_name [param="value"]* />
format = pattern_tag.sub(insert_element_code, format_template)
return format
def translate(match):
"""Translate matching values."""
word = match.group("word")
translated_word = '{{ _("' + word + '") }}'
return translated_word
def filter_languages(format_template):
"""Filter languages in format template."""
def search_lang_tag(match):
"""Searche for the <lang>...</lang> tag."""
ln_tags = {}
def clean_language_tag(match):
"""Return tag text content.
It contains if statement block to match output language.
It is called by substitution in 'filter_languages(...)'.
@param match: a match object corresponding to the special tag
that must be interpreted
"""
ln_tags[match.group(1)] = match.group(2)
return '{% if g.ln == "' + match.group(1) + '" %}' + \
match.group(2) + '{% endif %}'
# End of clean_language_tag
lang_tag_content = match.group("langs")
return '{% lang %}' + lang_tag_content + '{% endlang %}'
cleaned_lang_tag = ln_pattern.sub(clean_language_tag,
lang_tag_content)
# FIXME no traslation for current language
# if len(ln_tags) > 0:
# cleaned_lang_tag += '{% if not g.ln in ["' + \
# '", "'.join(ln_tags.keys()) + '"] %}' + \
# ln_tags.get(CFG_SITE_LANG, '') + '{% endif %}'
return cleaned_lang_tag
# End of search_lang_tag
filtered_format_template = pattern_lang.sub(search_lang_tag,
format_template)
return filtered_format_template
skip_templates = lambda (name, key): name[-3:] != 'xsl'
format_templates = filter(skip_templates,
iteritems(get_format_templates(True)))
print('>>> Going to migrate %d format template(s) ...' % (
len(format_templates), ))
if not os.path.exists(CFG_BIBFORMAT_JINJA_TEMPLATE_PATH):
os.makedirs(CFG_BIBFORMAT_JINJA_TEMPLATE_PATH)
for name, template in format_templates:
if not (only_template is None or only_template.match(name)):
continue
new_name = os.path.join(CFG_BIBFORMAT_JINJA_TEMPLATE_PATH,
rename_template(name))
if os.path.exists(new_name):
print(' [!] File', new_name, 'already exists.', end=' ')
if not rewrite_existing_templates:
print('Skipped.')
continue
else:
shutil.copy2(new_name, new_name + '.backup')
print('Rewritten.')
print(' ... migrating', name, 'to', new_name)
with open(new_name, 'w+') as f:
code = template['code']
ln_tags_format = filter_languages(code)
localized_format = translation_pattern.sub(translate,
ln_tags_format)
evaled = eval_format_template_elements(localized_format, None)
f.write(evaled)
print()
skip_legacy = lambda (name, key): name[-11:] != '_legacy.' + \
CFG_BIBFORMAT_FORMAT_OUTPUT_EXTENSION
output_formats = filter(
skip_legacy, iteritems(get_output_formats(with_attributes=True)))
print('>>> Going to migrate %d output format(s) ...' % (
len(output_formats)))
for name, output_format in output_formats:
if not any(map(lambda rule: rule['template'][-3:] ==
CFG_BIBFORMAT_FORMAT_TEMPLATE_EXTENSION,
output_format['rules'])):
print(' [!]', name, 'does not contain any', end=' ')
print(CFG_BIBFORMAT_FORMAT_TEMPLATE_EXTENSION, 'template', end=' ')
if only_template is not None:
print('or does not match', only_template_re, end=' ')
print('.')
continue
new_name = name[:-4] + \
'_legacy.' + CFG_BIBFORMAT_FORMAT_OUTPUT_EXTENSION
if os.path.exists(os.path.join(CFG_BIBFORMAT_OUTPUTS_PATH, new_name)):
print(' [!] File', new_name, 'already exists. Skipped.')
continue
shutil.copy2(
os.path.join(CFG_BIBFORMAT_OUTPUTS_PATH, name),
os.path.join(CFG_BIBFORMAT_OUTPUTS_PATH, new_name))
# rename template names
print(' ... migrating', name, 'to', new_name)
update_output_format_rules(name,
map(update_rule, output_format['rules']),
rename_template(output_format['default']))
print()
print('>>> Please re-run `bibreformat` for all cached output formats.')
print(' $ bibreformat -oHB,HD -a')
@manager.option('-o', '--output-format', dest='output_format',
default="HB", help="Specify output format/s (default HB)")
def expunge(output_format="HB"):
"""Remove static output formats from cache."""
from invenio.ext.sqlalchemy import db
from invenio.modules.formatter.models import Bibfmt
# Make it uppercased as it is stored in database.
output_format = output_format.upper()
print(">>> Cleaning %s cache..." % (output_format, ))
# Prepare where expression.
filter_format = (
Bibfmt.format == output_format if ',' not in output_format else
Bibfmt.format.in_(map(lambda x: x.strip(), output_format.split(',')))
)
Bibfmt.query.filter(filter_format).delete(synchronize_session=False)
db.session.commit()
def main():
"""Run manager."""
from invenio.base.factory import create_app
app = create_app()
manager.app = app
manager.run()
if __name__ == '__main__':
main()
| gpl-2.0 |
RCAD/ringling-render-tools | src/rrt/maya/ui/submit.py | 1 | 13088 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '.\src\rrt\maya\ui\submit.ui'
#
# Created: Wed Oct 24 16:19:16 2012
# by: PyQt4 UI code generator 4.7.7
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_SubmitMainWindow(object):
def setupUi(self, SubmitMainWindow):
SubmitMainWindow.setObjectName(_fromUtf8("SubmitMainWindow"))
SubmitMainWindow.setEnabled(True)
SubmitMainWindow.resize(445, 283)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(SubmitMainWindow.sizePolicy().hasHeightForWidth())
SubmitMainWindow.setSizePolicy(sizePolicy)
SubmitMainWindow.setMinimumSize(QtCore.QSize(445, 283))
SubmitMainWindow.setWindowTitle(_fromUtf8("hpc-submit-maya"))
self.verticalLayout = QtGui.QVBoxLayout(SubmitMainWindow)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.formLayout = QtGui.QFormLayout()
self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.AllNonFixedFieldsGrow)
self.formLayout.setLabelAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.formLayout.setHorizontalSpacing(6)
self.formLayout.setVerticalSpacing(8)
self.formLayout.setObjectName(_fromUtf8("formLayout"))
self.head_node_label = QtGui.QLabel(SubmitMainWindow)
self.head_node_label.setObjectName(_fromUtf8("head_node_label"))
self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.head_node_label)
self.head_node_field = QtGui.QComboBox(SubmitMainWindow)
self.head_node_field.setObjectName(_fromUtf8("head_node_field"))
self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.head_node_field)
self.title_label = QtGui.QLabel(SubmitMainWindow)
self.title_label.setLayoutDirection(QtCore.Qt.LeftToRight)
self.title_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.title_label.setObjectName(_fromUtf8("title_label"))
self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.title_label)
self.project_label = QtGui.QLabel(SubmitMainWindow)
self.project_label.setMinimumSize(QtCore.QSize(0, 0))
self.project_label.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.project_label.setObjectName(_fromUtf8("project_label"))
self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.project_label)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setSpacing(6)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.project_field = QtGui.QLineEdit(SubmitMainWindow)
self.project_field.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.project_field.sizePolicy().hasHeightForWidth())
self.project_field.setSizePolicy(sizePolicy)
self.project_field.setMinimumSize(QtCore.QSize(161, 26))
self.project_field.setReadOnly(True)
self.project_field.setObjectName(_fromUtf8("project_field"))
self.horizontalLayout.addWidget(self.project_field)
self.browse_button = QtGui.QPushButton(SubmitMainWindow)
self.browse_button.setMinimumSize(QtCore.QSize(85, 27))
self.browse_button.setObjectName(_fromUtf8("browse_button"))
self.horizontalLayout.addWidget(self.browse_button)
self.formLayout.setLayout(2, QtGui.QFormLayout.FieldRole, self.horizontalLayout)
self.scene_label = QtGui.QLabel(SubmitMainWindow)
self.scene_label.setObjectName(_fromUtf8("scene_label"))
self.formLayout.setWidget(3, QtGui.QFormLayout.LabelRole, self.scene_label)
self.horizontalLayout1 = QtGui.QHBoxLayout()
self.horizontalLayout1.setSpacing(6)
self.horizontalLayout1.setObjectName(_fromUtf8("horizontalLayout1"))
self.scene_field = QtGui.QLineEdit(SubmitMainWindow)
self.scene_field.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scene_field.sizePolicy().hasHeightForWidth())
self.scene_field.setSizePolicy(sizePolicy)
self.scene_field.setMinimumSize(QtCore.QSize(161, 26))
self.scene_field.setReadOnly(True)
self.scene_field.setObjectName(_fromUtf8("scene_field"))
self.horizontalLayout1.addWidget(self.scene_field)
self.scene_button = QtGui.QPushButton(SubmitMainWindow)
self.scene_button.setMinimumSize(QtCore.QSize(85, 27))
self.scene_button.setObjectName(_fromUtf8("scene_button"))
self.horizontalLayout1.addWidget(self.scene_button)
self.formLayout.setLayout(3, QtGui.QFormLayout.FieldRole, self.horizontalLayout1)
self.start_label = QtGui.QLabel(SubmitMainWindow)
self.start_label.setObjectName(_fromUtf8("start_label"))
self.formLayout.setWidget(4, QtGui.QFormLayout.LabelRole, self.start_label)
self.start_field = QtGui.QSpinBox(SubmitMainWindow)
self.start_field.setMinimum(1)
self.start_field.setMaximum(999999999)
self.start_field.setObjectName(_fromUtf8("start_field"))
self.formLayout.setWidget(4, QtGui.QFormLayout.FieldRole, self.start_field)
self.end_label = QtGui.QLabel(SubmitMainWindow)
self.end_label.setObjectName(_fromUtf8("end_label"))
self.formLayout.setWidget(5, QtGui.QFormLayout.LabelRole, self.end_label)
self.end_field = QtGui.QSpinBox(SubmitMainWindow)
self.end_field.setMinimum(1)
self.end_field.setMaximum(999999999)
self.end_field.setObjectName(_fromUtf8("end_field"))
self.formLayout.setWidget(5, QtGui.QFormLayout.FieldRole, self.end_field)
self.step_label = QtGui.QLabel(SubmitMainWindow)
self.step_label.setObjectName(_fromUtf8("step_label"))
self.formLayout.setWidget(6, QtGui.QFormLayout.LabelRole, self.step_label)
self.horizontalLayout_11 = QtGui.QHBoxLayout()
self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11"))
self.step_field = QtGui.QSpinBox(SubmitMainWindow)
self.step_field.setMinimum(1)
self.step_field.setMaximum(999999999)
self.step_field.setObjectName(_fromUtf8("step_field"))
self.horizontalLayout_11.addWidget(self.step_field)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout_11.addItem(spacerItem)
spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout_11.addItem(spacerItem1)
spacerItem2 = QtGui.QSpacerItem(50, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout_11.addItem(spacerItem2)
self.render_label = QtGui.QLabel(SubmitMainWindow)
self.render_label.setObjectName(_fromUtf8("render_label"))
self.horizontalLayout_11.addWidget(self.render_label)
self.render_field = QtGui.QComboBox(SubmitMainWindow)
self.render_field.setObjectName(_fromUtf8("render_field"))
self.horizontalLayout_11.addWidget(self.render_field)
spacerItem3 = QtGui.QSpacerItem(10, 10, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.horizontalLayout_11.addItem(spacerItem3)
self.formLayout.setLayout(6, QtGui.QFormLayout.FieldRole, self.horizontalLayout_11)
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.rrt_debug = QtGui.QCheckBox(SubmitMainWindow)
self.rrt_debug.setLayoutDirection(QtCore.Qt.LeftToRight)
self.rrt_debug.setObjectName(_fromUtf8("rrt_debug"))
self.horizontalLayout_5.addWidget(self.rrt_debug)
self.pause = QtGui.QCheckBox(SubmitMainWindow)
self.pause.setLayoutDirection(QtCore.Qt.LeftToRight)
self.pause.setObjectName(_fromUtf8("pause"))
self.horizontalLayout_5.addWidget(self.pause)
self.formLayout.setLayout(7, QtGui.QFormLayout.FieldRole, self.horizontalLayout_5)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
self.title_field = QtGui.QLineEdit(SubmitMainWindow)
self.title_field.setObjectName(_fromUtf8("title_field"))
self.horizontalLayout_4.addWidget(self.title_field)
self.formLayout.setLayout(1, QtGui.QFormLayout.FieldRole, self.horizontalLayout_4)
self.verticalLayout.addLayout(self.formLayout)
self.line = QtGui.QFrame(SubmitMainWindow)
self.line.setFrameShape(QtGui.QFrame.HLine)
self.line.setFrameShadow(QtGui.QFrame.Sunken)
self.line.setObjectName(_fromUtf8("line"))
self.verticalLayout.addWidget(self.line)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setSpacing(6)
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
spacerItem4 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum)
self.horizontalLayout_2.addItem(spacerItem4)
self.submit_button = QtGui.QPushButton(SubmitMainWindow)
self.submit_button.setObjectName(_fromUtf8("submit_button"))
self.horizontalLayout_2.addWidget(self.submit_button)
self.cancel_button = QtGui.QPushButton(SubmitMainWindow)
self.cancel_button.setObjectName(_fromUtf8("cancel_button"))
self.horizontalLayout_2.addWidget(self.cancel_button)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.retranslateUi(SubmitMainWindow)
QtCore.QObject.connect(self.browse_button, QtCore.SIGNAL(_fromUtf8("clicked()")), SubmitMainWindow.browse)
QtCore.QObject.connect(self.cancel_button, QtCore.SIGNAL(_fromUtf8("clicked()")), SubmitMainWindow.quit)
QtCore.QObject.connect(self.submit_button, QtCore.SIGNAL(_fromUtf8("clicked()")), SubmitMainWindow.submit_job)
QtCore.QObject.connect(self.scene_button, QtCore.SIGNAL(_fromUtf8("clicked()")), SubmitMainWindow.scene)
QtCore.QMetaObject.connectSlotsByName(SubmitMainWindow)
def retranslateUi(self, SubmitMainWindow):
self.head_node_label.setToolTip(QtGui.QApplication.translate("SubmitMainWindow", "which cluster to use", None, QtGui.QApplication.UnicodeUTF8))
self.head_node_label.setText(QtGui.QApplication.translate("SubmitMainWindow", "Head Node", None, QtGui.QApplication.UnicodeUTF8))
self.head_node_field.setToolTip(QtGui.QApplication.translate("SubmitMainWindow", "Which cluster to submit to", None, QtGui.QApplication.UnicodeUTF8))
self.title_label.setText(QtGui.QApplication.translate("SubmitMainWindow", "Job Title", None, QtGui.QApplication.UnicodeUTF8))
self.project_label.setText(QtGui.QApplication.translate("SubmitMainWindow", "Project Folder", None, QtGui.QApplication.UnicodeUTF8))
self.browse_button.setText(QtGui.QApplication.translate("SubmitMainWindow", "Set", None, QtGui.QApplication.UnicodeUTF8))
self.scene_label.setText(QtGui.QApplication.translate("SubmitMainWindow", "Maya Scene File", None, QtGui.QApplication.UnicodeUTF8))
self.scene_button.setText(QtGui.QApplication.translate("SubmitMainWindow", "Browse", None, QtGui.QApplication.UnicodeUTF8))
self.start_label.setText(QtGui.QApplication.translate("SubmitMainWindow", "Start Frame", None, QtGui.QApplication.UnicodeUTF8))
self.end_label.setText(QtGui.QApplication.translate("SubmitMainWindow", "End Frame", None, QtGui.QApplication.UnicodeUTF8))
self.step_label.setText(QtGui.QApplication.translate("SubmitMainWindow", "Frame Step", None, QtGui.QApplication.UnicodeUTF8))
self.render_label.setText(QtGui.QApplication.translate("SubmitMainWindow", "Renderer", None, QtGui.QApplication.UnicodeUTF8))
self.rrt_debug.setText(QtGui.QApplication.translate("SubmitMainWindow", "Show Debug Messages", None, QtGui.QApplication.UnicodeUTF8))
self.pause.setText(QtGui.QApplication.translate("SubmitMainWindow", "Pause before exit", None, QtGui.QApplication.UnicodeUTF8))
self.submit_button.setText(QtGui.QApplication.translate("SubmitMainWindow", "Submit Job", None, QtGui.QApplication.UnicodeUTF8))
self.cancel_button.setText(QtGui.QApplication.translate("SubmitMainWindow", "Cancel", None, QtGui.QApplication.UnicodeUTF8))
| mit |
alekseyev/wheatleycms | docutils/parsers/rst/languages/en.py | 6 | 3219 | # $Id: en.py 6460 2010-10-29 22:18:44Z milde $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
# New language mappings are welcome. Before doing a new translation, please
# read <http://docutils.sf.net/docs/howto/i18n.html>. Two files must be
# translated for each language: one in docutils/languages, the other in
# docutils/parsers/rst/languages.
"""
English-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
# language-dependent: fixed
'attention': 'attention',
'caution': 'caution',
'danger': 'danger',
'error': 'error',
'hint': 'hint',
'important': 'important',
'note': 'note',
'tip': 'tip',
'warning': 'warning',
'admonition': 'admonition',
'sidebar': 'sidebar',
'topic': 'topic',
'line-block': 'line-block',
'parsed-literal': 'parsed-literal',
'rubric': 'rubric',
'epigraph': 'epigraph',
'highlights': 'highlights',
'pull-quote': 'pull-quote',
'compound': 'compound',
'container': 'container',
#'questions': 'questions',
'table': 'table',
'csv-table': 'csv-table',
'list-table': 'list-table',
#'qa': 'questions',
#'faq': 'questions',
'meta': 'meta',
'math': 'math',
#'imagemap': 'imagemap',
'image': 'image',
'figure': 'figure',
'include': 'include',
'raw': 'raw',
'replace': 'replace',
'unicode': 'unicode',
'date': 'date',
'class': 'class',
'role': 'role',
'default-role': 'default-role',
'title': 'title',
'contents': 'contents',
'sectnum': 'sectnum',
'section-numbering': 'sectnum',
'header': 'header',
'footer': 'footer',
#'footnotes': 'footnotes',
#'citations': 'citations',
'target-notes': 'target-notes',
'restructuredtext-test-directive': 'restructuredtext-test-directive'}
"""English name to registered (in directives/__init__.py) directive name
mapping."""
roles = {
# language-dependent: fixed
'abbreviation': 'abbreviation',
'ab': 'abbreviation',
'acronym': 'acronym',
'ac': 'acronym',
'index': 'index',
'i': 'index',
'subscript': 'subscript',
'sub': 'subscript',
'superscript': 'superscript',
'sup': 'superscript',
'title-reference': 'title-reference',
'title': 'title-reference',
't': 'title-reference',
'pep-reference': 'pep-reference',
'pep': 'pep-reference',
'rfc-reference': 'rfc-reference',
'rfc': 'rfc-reference',
'emphasis': 'emphasis',
'strong': 'strong',
'literal': 'literal',
'math': 'math',
'named-reference': 'named-reference',
'anonymous-reference': 'anonymous-reference',
'footnote-reference': 'footnote-reference',
'citation-reference': 'citation-reference',
'substitution-reference': 'substitution-reference',
'target': 'target',
'uri-reference': 'uri-reference',
'uri': 'uri-reference',
'url': 'uri-reference',
'raw': 'raw',}
"""Mapping of English role names to canonical role names for interpreted text.
"""
| bsd-3-clause |
riklaunim/django-custom-multisite | django/contrib/flatpages/views.py | 94 | 2859 | from django.contrib.flatpages.models import FlatPage
from django.template import loader, RequestContext
from django.shortcuts import get_object_or_404
from django.http import Http404, HttpResponse, HttpResponsePermanentRedirect
from django.conf import settings
from django.core.xheaders import populate_xheaders
from django.utils.safestring import mark_safe
from django.views.decorators.csrf import csrf_protect
DEFAULT_TEMPLATE = 'flatpages/default.html'
# This view is called from FlatpageFallbackMiddleware.process_response
# when a 404 is raised, which often means CsrfViewMiddleware.process_view
# has not been called even if CsrfViewMiddleware is installed. So we need
# to use @csrf_protect, in case the template needs {% csrf_token %}.
# However, we can't just wrap this view; if no matching flatpage exists,
# or a redirect is required for authentication, the 404 needs to be returned
# without any CSRF checks. Therefore, we only
# CSRF protect the internal implementation.
def flatpage(request, url):
"""
Public interface to the flat page view.
Models: `flatpages.flatpages`
Templates: Uses the template defined by the ``template_name`` field,
or `flatpages/default.html` if template_name is not defined.
Context:
flatpage
`flatpages.flatpages` object
"""
if not url.startswith('/'):
url = '/' + url
try:
f = get_object_or_404(FlatPage,
url__exact=url, sites__id__exact=settings.SITE_ID)
except Http404:
if not url.endswith('/') and settings.APPEND_SLASH:
url += '/'
f = get_object_or_404(FlatPage,
url__exact=url, sites__id__exact=settings.SITE_ID)
return HttpResponsePermanentRedirect('%s/' % request.path)
else:
raise
return render_flatpage(request, f)
@csrf_protect
def render_flatpage(request, f):
"""
Internal interface to the flat page view.
"""
# If registration is required for accessing this page, and the user isn't
# logged in, redirect to the login page.
if f.registration_required and not request.user.is_authenticated():
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(request.path)
if f.template_name:
t = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
else:
t = loader.get_template(DEFAULT_TEMPLATE)
# To avoid having to always use the "|safe" filter in flatpage templates,
# mark the title and content as already safe (since they are raw HTML
# content in the first place).
f.title = mark_safe(f.title)
f.content = mark_safe(f.content)
c = RequestContext(request, {
'flatpage': f,
})
response = HttpResponse(t.render(c))
populate_xheaders(request, response, FlatPage, f.id)
return response
| bsd-3-clause |
jeanlinux/calibre | src/calibre/gui2/actions/view.py | 14 | 12505 | #!/usr/bin/env python2
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
__license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os, time
from functools import partial
from PyQt5.Qt import Qt, QAction, pyqtSignal
from calibre.constants import isosx, iswindows
from calibre.gui2 import (
error_dialog, Dispatcher, question_dialog, config, open_local_file,
info_dialog, elided_text)
from calibre.gui2.dialogs.choose_format import ChooseFormatDialog
from calibre.utils.config import prefs, tweaks
from calibre.ptempfile import PersistentTemporaryFile
from calibre.gui2.actions import InterfaceAction
class HistoryAction(QAction):
view_historical = pyqtSignal(object)
def __init__(self, id_, title, parent):
QAction.__init__(self, title, parent)
self.id = id_
self.triggered.connect(self._triggered)
def _triggered(self):
self.view_historical.emit(self.id)
class ViewAction(InterfaceAction):
name = 'View'
action_spec = (_('View'), 'view.png', _('Read books'), _('V'))
action_type = 'current'
action_add_menu = True
action_menu_clone_qaction = True
def genesis(self):
self.persistent_files = []
self.qaction.triggered.connect(self.view_book)
self.view_action = self.menuless_qaction
self.view_menu = self.qaction.menu()
cm = partial(self.create_menu_action, self.view_menu)
self.view_specific_action = cm('specific', _('View specific format'),
shortcut='Alt+V', triggered=self.view_specific_format)
self.action_pick_random = cm('pick random', _('Read a random book'),
icon='random.png', triggered=self.view_random)
self.clear_sep1 = self.view_menu.addSeparator()
self.clear_sep2 = self.view_menu.addSeparator()
self.clear_history_action = cm('clear history',
_('Clear recently viewed list'), triggered=self.clear_history)
self.history_actions = [self.clear_sep1]
def initialization_complete(self):
self.build_menus(self.gui.current_db)
def build_menus(self, db):
for ac in self.history_actions:
self.view_menu.removeAction(ac)
self.history_actions = []
history = db.prefs.get('gui_view_history', [])
if history:
self.view_menu.insertAction(self.clear_sep2, self.clear_sep1)
self.history_actions.append(self.clear_sep1)
fm = self.gui.fontMetrics()
for id_, title in history:
ac = HistoryAction(id_, elided_text(title, font=fm, pos='right'), self.view_menu)
self.view_menu.insertAction(self.clear_sep2, ac)
ac.view_historical.connect(self.view_historical)
self.history_actions.append(ac)
def clear_history(self):
db = self.gui.current_db
db.new_api.set_pref('gui_view_history', [])
self.build_menus(db)
def view_historical(self, id_):
self._view_calibre_books([id_])
def library_changed(self, db):
self.build_menus(db)
def location_selected(self, loc):
enabled = loc == 'library'
for action in list(self.view_menu.actions())[1:]:
action.setEnabled(enabled)
def view_format(self, row, format):
id_ = self.gui.library_view.model().id(row)
self.view_format_by_id(id_, format)
def view_format_by_id(self, id_, format):
db = self.gui.current_db
fmt_path = db.format_abspath(id_, format,
index_is_id=True)
if fmt_path:
title = db.title(id_, index_is_id=True)
self._view_file(fmt_path)
self.update_history([(id_, title)])
def book_downloaded_for_viewing(self, job):
if job.failed:
self.gui.device_job_exception(job)
return
self._view_file(job.result)
def _launch_viewer(self, name=None, viewer='ebook-viewer', internal=True):
self.gui.setCursor(Qt.BusyCursor)
try:
if internal:
args = [viewer]
if isosx and 'ebook' in viewer:
args.append('--raise-window')
if name is not None:
args.append(name)
self.gui.job_manager.launch_gui_app(viewer,
kwargs=dict(args=args))
else:
if iswindows:
from calibre.utils.file_associations import file_assoc_windows
ext = name.rpartition('.')[-1]
if ext:
try:
prog = file_assoc_windows(ext)
except Exception:
prog = None
if prog and prog.lower().endswith('calibre.exe'):
name = os.path.basename(name)
return error_dialog(
self.gui, _('No associated program'), _(
'Windows will try to open %s with calibre itself'
' resulting in a duplicate in your calibre library. You'
' should install some program capable of viewing this'
' file format and tell windows to use that program to open'
' files of this type.') % name, show=True)
open_local_file(name)
time.sleep(2) # User feedback
finally:
self.gui.unsetCursor()
def _view_file(self, name):
ext = os.path.splitext(name)[1].upper().replace('.',
'').replace('ORIGINAL_', '')
viewer = 'lrfviewer' if ext == 'LRF' else 'ebook-viewer'
internal = ext in config['internally_viewed_formats']
self._launch_viewer(name, viewer, internal)
def view_specific_format(self, triggered):
rows = list(self.gui.library_view.selectionModel().selectedRows())
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Cannot view'), _('No book selected'))
d.exec_()
return
db = self.gui.library_view.model().db
rows = [r.row() for r in rows]
book_ids = [db.id(r) for r in rows]
formats = [[x.upper() for x in db.new_api.formats(book_id)] for book_id in book_ids]
all_fmts = set([])
for x in formats:
if x:
for f in x:
all_fmts.add(f)
if not all_fmts:
error_dialog(self.gui, _('Format unavailable'),
_('Selected books have no formats'), show=True)
return
d = ChooseFormatDialog(self.gui, _('Choose the format to view'),
list(sorted(all_fmts)), show_open_with=True)
self.gui.book_converted.connect(d.book_converted)
if d.exec_() == d.Accepted:
formats = [[x.upper() for x in db.new_api.formats(book_id)] for book_id in book_ids]
fmt = d.format()
orig_num = len(rows)
rows = [rows[i] for i in range(len(rows)) if formats[i] and fmt in
formats[i]]
if self._view_check(len(rows)):
for row in rows:
if d.open_with_format is None:
self.view_format(row, fmt)
else:
self.open_fmt_with(row, *d.open_with_format)
if len(rows) < orig_num:
info_dialog(self.gui, _('Format unavailable'),
_('Not all the selected books were available in'
' the %s format. You should convert'
' them first.')%fmt, show=True)
self.gui.book_converted.disconnect(d.book_converted)
def open_fmt_with(self, row, fmt, entry):
book_id = self.gui.library_view.model().id(row)
self.gui.book_details.open_fmt_with.emit(book_id, fmt, entry)
def _view_check(self, num, max_=3):
if num <= max_:
return True
return question_dialog(self.gui, _('Multiple Books Selected'),
_('You are attempting to open %d books. Opening too many '
'books at once can be slow and have a negative effect on the '
'responsiveness of your computer. Once started the process '
'cannot be stopped until complete. Do you wish to continue?'
) % num, show_copy_button=False)
def view_folder(self, *args):
rows = self.gui.current_view().selectionModel().selectedRows()
if not rows or len(rows) == 0:
d = error_dialog(self.gui, _('Cannot open folder'),
_('No book selected'))
d.exec_()
return
if not self._view_check(len(rows)):
return
for i, row in enumerate(rows):
path = self.gui.library_view.model().db.abspath(row.row())
open_local_file(path)
if isosx and i < len(rows) - 1:
time.sleep(0.1) # Finder cannot handle multiple folder opens
def view_folder_for_id(self, id_):
path = self.gui.library_view.model().db.abspath(id_, index_is_id=True)
open_local_file(path)
def view_book(self, triggered):
rows = self.gui.current_view().selectionModel().selectedRows()
self._view_books(rows)
def view_triggered(self, index):
self._view_books([index])
def view_specific_book(self, index):
self._view_books([index])
def view_random(self, *args):
self.gui.iactions['Pick Random Book'].pick_random()
self._view_books([self.gui.library_view.currentIndex()])
def _view_calibre_books(self, ids):
db = self.gui.current_db
views = []
for id_ in ids:
try:
formats = db.formats(id_, index_is_id=True)
except:
error_dialog(self.gui, _('Cannot view'),
_('This book no longer exists in your library'), show=True)
self.update_history([], remove=set([id_]))
continue
title = db.title(id_, index_is_id=True)
if not formats:
error_dialog(self.gui, _('Cannot view'),
_('%s has no available formats.')%(title,), show=True)
continue
formats = formats.upper().split(',')
fmt = formats[0]
for format in prefs['input_format_order']:
if format in formats:
fmt = format
break
views.append((id_, title))
self.view_format_by_id(id_, fmt)
self.update_history(views)
def update_history(self, views, remove=frozenset()):
db = self.gui.current_db
vh = tweaks['gui_view_history_size']
if views:
seen = set()
history = []
for id_, title in views + db.prefs.get('gui_view_history', []):
if title not in seen:
seen.add(title)
history.append((id_, title))
db.new_api.set_pref('gui_view_history', history[:vh])
self.build_menus(db)
if remove:
history = db.prefs.get('gui_view_history', [])
history = [x for x in history if x[0] not in remove]
db.new_api.set_pref('gui_view_history', history[:vh])
self.build_menus(db)
def view_device_book(self, path):
pt = PersistentTemporaryFile('_view_device_book'+
os.path.splitext(path)[1])
self.persistent_files.append(pt)
pt.close()
self.gui.device_manager.view_book(
Dispatcher(self.book_downloaded_for_viewing), path, pt.name)
def _view_books(self, rows):
if not rows or len(rows) == 0:
return error_dialog(self.gui, _('Cannot view'),
_('No books selected'), show=True)
if not self._view_check(len(rows)):
return
if self.gui.current_view() is self.gui.library_view:
ids = list(map(self.gui.library_view.model().id, rows))
self._view_calibre_books(ids)
else:
paths = self.gui.current_view().model().paths(rows)
for path in paths:
self.view_device_book(path)
| gpl-3.0 |
kunalarya/simple-sat-solver | satsolver/solver.py | 1 | 9011 | from __future__ import print_function
import argparse
import logging
from collections import namedtuple
import satsolver.parser as parser
from satsolver.util import Success, Failure
from satsolver.state import Instance
class Node(object):
def __init__(self, lit, asg, level):
assert lit > 0
self.lit = lit
self.asg = asg
self.level = level
def __repr__(self):
return '<x_{} = {} @ {}>'.format(
self.lit, self.asg, self.level)
class ImplicationGraph(object):
"""Implication Graph"""
def __init__(self):
self.nodes = set()
self.lits = set() # set of literals in nodes
# map lit -> nodes w/assignments
# dict[int, list[Node]]
self.nodes_by_lit = {}
self.fwd_edges = {}
# maps (x -> y) tuple edge to clause
self.edge_annot = {}
def add_node(self, node):
self.nodes.add(node)
self.lits.add(node.lit)
self.fwd_edges[node] = []
self.nodes_by_lit[node.lit] = node
def del_node(self, node):
self.lits.remove(node.lit)
self.nodes.remove(node)
del self.fwd_edges[node]
del self.nodes_by_lit[node.lit]
def add_edge(self, src, dst, reason):
self.fwd_edges[src].append(dst)
self.edge_annot[src, dst] = reason
Decision = namedtuple('Decision', ['level', 'lit', 'value'])
Implication = namedtuple('Implication', ['clause', 'lit', 'value'])
class Solver(object):
"""Main Solver"""
def __init__(self, instance, recipe=None):
self.instance = instance
# Pick variables in this order, if given.
self.recipe = recipe
self.recipe_index = 0
# def new_var(self):
# pass
# def add_clause(self, lits):
# pass
# def simplify_db(self):
# pass
def solve(self):
result = self.decide([], 1)
return result
def determine_next_var(self):
"""Choose the next variable to assign.
It will run the recipe if given, otherwise select a random unassigned
variable.
Returns:
tuple(variable, value)
"""
if self.recipe is not None:
if len(self.recipe) > 0:
next_var_and_value = self.recipe[0]
self.recipe = self.recipe[1:]
return next_var_and_value
# Otherwise, choose a variable randomly.
next_var = next(iter(self.instance.unasg_vars))
return next_var, 1
def bcp(self, decision_level, igraph):
"""Boolean Constrain Propagation
Returns:
Success | Failure
Success result:
{lit: Implication}
Failure means UNSAT
"""
any_unit = True
implications = {} # Keyed on int
while any_unit:
any_unit = False
for clause_index, clause in enumerate(self.instance.clauses):
r = self.instance.is_unit(clause)
if not r.success: return r
is_unit, implied = r.result
if is_unit:
lit = abs(implied)
if implied > 0:
r = self.instance.set_lit(lit, 1)
if not r.success: return r
implications[lit] = Implication(clause_index, lit, 1)
value = 1
else:
r = self.instance.set_lit(lit, 0)
if not r.success: return r
implications[lit] = Implication(clause_index, lit, 0)
value = 0
logging.debug('implied=%d -> %d', lit, value)
# Create a node in the ImplicationGraph if it doesn't yet exist.
if not lit in igraph.nodes_by_lit:
lit_node = Node(lit, value, decision_level)
igraph.add_node(lit_node)
# Create any edges
for implicating_lit in clause:
implicating_pair = self.instance.get_value(implicating_lit)
implicating_lit, implicating_value = implicating_pair
if implicating_lit != lit:
# create the implicating lit if needed
if implicating_lit not in igraph.lits:
inode = Node(implicating_lit, implicating_value,
decision_level)
igraph.add_node(inode)
else:
inode = igraph.nodes_by_lit[implicating_lit]
# create an edge for this node
lit_node = igraph.nodes_by_lit[lit]
igraph.add_edge(inode, lit_node, clause)
logging.debug('add edge %s->%s because of %s',
inode, lit_node, clause)
any_unit = True
return Success(implications)
def decide(self, decisions, level):
"""
Args:
decisions (list[Decision]):
level (int):
Returns:
Success | Failure
"""
# choose a variable to decide
print('.', end='')
logging.debug('______________________________')
logging.debug('[level: %d]', level)
# Choose a variable to set.
next_var, next_value = self.determine_next_var()
# Create a new copy of the decisions.
decisions = list(decisions)
decisions.append(Decision(level, next_var, next_value))
logging.debug('try_assignment(level=%d, %d->%d)', level, next_var,
next_value)
result = self.try_assignment(level, decisions, next_var, next_value)
if not result.success:
logging.debug('caused unsat: try_assignment(level=%d, %d->%d)',
level, next_var, next_value)
# try the other branch
inverted_value = 1 - next_value
# remove last decision
decisions = decisions[:-1]
# add new decision
decisions.append(Decision(level, next_var, inverted_value))
r = self.try_assignment(level, decisions, next_var, inverted_value)
# If we reached UNSAT here, then there's no solution here, so propagate
# this issue up.
if not r.success:
return r
else:
# If all variables have been assigned, store this as a solution.
if len(self.instance.unasg_vars) == 0:
if self.instance.verify():
self.instance.save_solution()
print('satisfied!')
else:
raise ValueError('All variables assigned, but UNSAT')
return Success()
def try_assignment(self, level, decisions, lit, value):
logging.debug('try_assignment: lit = %d -- setting to %d', lit, value)
# assign it True
r = self.instance.set_lit(lit, value)
if not r.success:
return r
igraph = ImplicationGraph()
# build the graph
for decision in decisions:
# create a node for each decision
node = Node(decision.lit, decision.value, decision.level)
igraph.add_node(node)
logging.debug('adding node %s', node)
logging.debug('running bcp...')
r = self.bcp(level, igraph)
if not r.success: # Meaning UNSAT:
logging.debug('decision led to UNSAT. unsetting')
self.instance.unset_lit(lit)
# If it's UNSAT, we need to backtrack
return Failure('Unsat!')
# Otherwise it was a Success
implications = r.result
if len(self.instance.unasg_vars) > 0:
# increase the decision level
r = self.decide(decisions, level+1)
self.instance.unset_lit(lit)
return r
# otherwise, return igraph
return Success(result=(igraph, None))
def solve(instance):
"""
Args:
instance (Instance): parsed SAT instance
Returns:
Success | Failure
"""
solver = Solver(instance)
result = solver.solve()
if not result.success:
print('Unsatisfiable')
return result
def main():
cmdline_parser = argparse.ArgumentParser()
cmdline_parser.add_argument('filename', action='store', type=str)
args = cmdline_parser.parse_args()
file_parser = parser.CNFFileParser(args.filename)
inst = Instance(var_count=file_parser.var_count, clauses=file_parser.clauses)
result = solve(inst)
if result.success:
# Print the solutions
print('Satisfying solutions:')
for solution in inst.solutions:
print(solution)
if __name__ == '__main__':
main()
| apache-2.0 |
luyijun/evennia_worldloader | worldloader/example_tutorial_world/worlddata/migrations/0001_initial.py | 1 | 5070 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='personal_objects',
fields=[
('key', models.CharField(max_length=255, serialize=False, primary_key=True)),
('name', models.CharField(max_length=255)),
('alias', models.CharField(max_length=255, blank=True)),
('typeclass', models.CharField(max_length=255)),
('desc', models.TextField(blank=True)),
('location', models.CharField(max_length=255, blank=True)),
('home', models.CharField(max_length=255, blank=True)),
('lock', models.CharField(max_length=255, blank=True)),
('attributes', models.TextField(blank=True)),
('tutorial_info', models.TextField(blank=True)),
('destination', models.CharField(max_length=255, blank=True)),
],
options={
'verbose_name': 'Personal Object List',
'verbose_name_plural': 'Personal Object List',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='world_details',
fields=[
('key', models.CharField(max_length=255, serialize=False, primary_key=True)),
('name', models.CharField(max_length=255)),
('desc', models.TextField(blank=True)),
('location', models.CharField(max_length=255, blank=True)),
],
options={
'verbose_name': 'World Detail List',
'verbose_name_plural': 'World Detail List',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='world_exits',
fields=[
('key', models.CharField(max_length=255, serialize=False, primary_key=True)),
('name', models.CharField(max_length=255)),
('alias', models.CharField(max_length=255, blank=True)),
('typeclass', models.CharField(max_length=255)),
('desc', models.TextField(blank=True)),
('location', models.CharField(max_length=255, blank=True)),
('home', models.CharField(max_length=255, blank=True)),
('lock', models.CharField(max_length=255, blank=True)),
('attributes', models.TextField(blank=True)),
('tutorial_info', models.TextField(blank=True)),
('destination', models.CharField(max_length=255, blank=True)),
],
options={
'verbose_name': 'World Exit List',
'verbose_name_plural': 'World Exit List',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='world_objects',
fields=[
('key', models.CharField(max_length=255, serialize=False, primary_key=True)),
('name', models.CharField(max_length=255)),
('alias', models.CharField(max_length=255, blank=True)),
('typeclass', models.CharField(max_length=255)),
('desc', models.TextField(blank=True)),
('location', models.CharField(max_length=255, blank=True)),
('home', models.CharField(max_length=255, blank=True)),
('lock', models.CharField(max_length=255, blank=True)),
('attributes', models.TextField(blank=True)),
('tutorial_info', models.TextField(blank=True)),
('destination', models.CharField(max_length=255, blank=True)),
],
options={
'verbose_name': 'World Object List',
'verbose_name_plural': 'World Object List',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='world_rooms',
fields=[
('key', models.CharField(max_length=255, serialize=False, primary_key=True)),
('name', models.CharField(max_length=255)),
('alias', models.CharField(max_length=255, blank=True)),
('typeclass', models.CharField(max_length=255)),
('desc', models.TextField(blank=True)),
('location', models.CharField(max_length=255, blank=True)),
('home', models.CharField(max_length=255, blank=True)),
('lock', models.CharField(max_length=255, blank=True)),
('attributes', models.TextField(blank=True)),
('tutorial_info', models.TextField(blank=True)),
('destination', models.CharField(max_length=255, blank=True)),
],
options={
'verbose_name': 'World Room List',
'verbose_name_plural': 'World Room List',
},
bases=(models.Model,),
),
]
| bsd-3-clause |
CMUSV-VisTrails/WorkflowRecommendation | vistrails/packages/analytics/__init__.py | 1 | 1938 | ###############################################################################
##
## Copyright (C) 2006-2011, University of Utah.
## All rights reserved.
## Contact: contact@vistrails.org
##
## This file is part of VisTrails.
##
## "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 University of Utah 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."
##
###############################################################################
name = "VisTrails Analytics"
identifier = "edu.utah.sci.vistrails.analytics"
version = "0.0.1"
| bsd-3-clause |
namecoin/namecore | test/functional/test_framework/bignum.py | 77 | 1230 | #!/usr/bin/env python3
#
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Big number routines.
This file is copied from python-bitcoinlib.
"""
import struct
# generic big endian MPI format
def bn_bytes(v, have_ext=False):
ext = 0
if have_ext:
ext = 1
return ((v.bit_length()+7)//8) + ext
def bn2bin(v):
s = bytearray()
i = bn_bytes(v)
while i > 0:
s.append((v >> ((i-1) * 8)) & 0xff)
i -= 1
return s
def bn2mpi(v):
have_ext = False
if v.bit_length() > 0:
have_ext = (v.bit_length() & 0x07) == 0
neg = False
if v < 0:
neg = True
v = -v
s = struct.pack(b">I", bn_bytes(v, have_ext))
ext = bytearray()
if have_ext:
ext.append(0)
v_bin = bn2bin(v)
if neg:
if have_ext:
ext[0] |= 0x80
else:
v_bin[0] |= 0x80
return s + ext + v_bin
# bitcoin-specific little endian format, with implicit size
def mpi2vch(s):
r = s[4:] # strip size
r = r[::-1] # reverse string, converting BE->LE
return r
def bn2vch(v):
return bytes(mpi2vch(bn2mpi(v)))
| mit |
zawzawzaw/offshore | node_modules/laravel-elixir/node_modules/gulp-sass/node_modules/node-sass/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py | 2779 | 1665 | # Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""gypsh output module
gypsh is a GYP shell. It's not really a generator per se. All it does is
fire up an interactive Python session with a few local variables set to the
variables passed to the generator. Like gypd, it's intended as a debugging
aid, to facilitate the exploration of .gyp structures after being processed
by the input module.
The expected usage is "gyp -f gypsh -D OS=desired_os".
"""
import code
import sys
# All of this stuff about generator variables was lovingly ripped from gypd.py.
# That module has a much better description of what's going on and why.
_generator_identity_variables = [
'EXECUTABLE_PREFIX',
'EXECUTABLE_SUFFIX',
'INTERMEDIATE_DIR',
'PRODUCT_DIR',
'RULE_INPUT_ROOT',
'RULE_INPUT_DIRNAME',
'RULE_INPUT_EXT',
'RULE_INPUT_NAME',
'RULE_INPUT_PATH',
'SHARED_INTERMEDIATE_DIR',
]
generator_default_variables = {
}
for v in _generator_identity_variables:
generator_default_variables[v] = '<(%s)' % v
def GenerateOutput(target_list, target_dicts, data, params):
locals = {
'target_list': target_list,
'target_dicts': target_dicts,
'data': data,
}
# Use a banner that looks like the stock Python one and like what
# code.interact uses by default, but tack on something to indicate what
# locals are available, and identify gypsh.
banner='Python %s on %s\nlocals.keys() = %s\ngypsh' % \
(sys.version, sys.platform, repr(sorted(locals.keys())))
code.interact(banner, local=locals)
| gpl-2.0 |
prodromou87/gem5 | src/mem/slicc/ast/FuncDeclAST.py | 18 | 3409 | # Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
# Copyright (c) 2009 The Hewlett-Packard Development Company
# 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 copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from slicc.ast.DeclAST import DeclAST
from slicc.symbols import Func, Type
class FuncDeclAST(DeclAST):
def __init__(self, slicc, return_type, ident, formals, pairs, statements):
super(FuncDeclAST, self).__init__(slicc, pairs)
self.return_type = return_type
self.ident = ident
self.formals = formals
self.statements = statements
def __repr__(self):
return "[FuncDecl: %s]" % self.ident
def files(self, parent=None):
return set()
def generate(self, parent = None):
types = []
params = []
void_type = self.symtab.find("void", Type)
# Generate definition code
self.symtab.pushFrame()
# Lookup return type
return_type = self.return_type.type
# Generate function header
for formal in self.formals:
# Lookup parameter types
type, ident = formal.generate()
types.append(type)
params.append(ident)
body = self.slicc.codeFormatter()
if self.statements is None:
self["external"] = "yes"
else:
rtype = self.statements.generate(body, return_type)
self.symtab.popFrame()
machine = self.state_machine
func = Func(self.symtab, self.ident, self.location, return_type,
types, params, str(body), self.pairs)
if parent is not None:
if not parent.addFunc(func):
self.error("Duplicate method: %s:%s()" % (parent, self.ident))
func.class_name = parent.c_ident
elif machine is not None:
machine.addFunc(func)
func.isInternalMachineFunc = True
func.class_name = "%s_Controller" % machine
else:
self.symtab.newSymbol(func)
| bsd-3-clause |
poryfly/scikit-learn | sklearn/manifold/spectral_embedding_.py | 128 | 19845 | """Spectral Embedding"""
# Author: Gael Varoquaux <gael.varoquaux@normalesup.org>
# Wei LI <kuantkid@gmail.com>
# License: BSD 3 clause
import warnings
import numpy as np
from scipy import sparse
from scipy.linalg import eigh
from scipy.sparse.linalg import lobpcg
from ..base import BaseEstimator
from ..externals import six
from ..utils import check_random_state, check_array, check_symmetric
from ..utils.extmath import _deterministic_vector_sign_flip
from ..utils.graph import graph_laplacian
from ..utils.sparsetools import connected_components
from ..utils.arpack import eigsh
from ..metrics.pairwise import rbf_kernel
from ..neighbors import kneighbors_graph
def _graph_connected_component(graph, node_id):
"""Find the largest graph connected components that contains one
given node
Parameters
----------
graph : array-like, shape: (n_samples, n_samples)
adjacency matrix of the graph, non-zero weight means an edge
between the nodes
node_id : int
The index of the query node of the graph
Returns
-------
connected_components_matrix : array-like, shape: (n_samples,)
An array of bool value indicating the indexes of the nodes
belonging to the largest connected components of the given query
node
"""
connected_components_matrix = np.zeros(
shape=(graph.shape[0]), dtype=np.bool)
connected_components_matrix[node_id] = True
n_node = graph.shape[0]
for i in range(n_node):
last_num_component = connected_components_matrix.sum()
_, node_to_add = np.where(graph[connected_components_matrix] != 0)
connected_components_matrix[node_to_add] = True
if last_num_component >= connected_components_matrix.sum():
break
return connected_components_matrix
def _graph_is_connected(graph):
""" Return whether the graph is connected (True) or Not (False)
Parameters
----------
graph : array-like or sparse matrix, shape: (n_samples, n_samples)
adjacency matrix of the graph, non-zero weight means an edge
between the nodes
Returns
-------
is_connected : bool
True means the graph is fully connected and False means not
"""
if sparse.isspmatrix(graph):
# sparse graph, find all the connected components
n_connected_components, _ = connected_components(graph)
return n_connected_components == 1
else:
# dense graph, find all connected components start from node 0
return _graph_connected_component(graph, 0).sum() == graph.shape[0]
def _set_diag(laplacian, value):
"""Set the diagonal of the laplacian matrix and convert it to a
sparse format well suited for eigenvalue decomposition
Parameters
----------
laplacian : array or sparse matrix
The graph laplacian
value : float
The value of the diagonal
Returns
-------
laplacian : array or sparse matrix
An array of matrix in a form that is well suited to fast
eigenvalue decomposition, depending on the band width of the
matrix.
"""
n_nodes = laplacian.shape[0]
# We need all entries in the diagonal to values
if not sparse.isspmatrix(laplacian):
laplacian.flat[::n_nodes + 1] = value
else:
laplacian = laplacian.tocoo()
diag_idx = (laplacian.row == laplacian.col)
laplacian.data[diag_idx] = value
# If the matrix has a small number of diagonals (as in the
# case of structured matrices coming from images), the
# dia format might be best suited for matvec products:
n_diags = np.unique(laplacian.row - laplacian.col).size
if n_diags <= 7:
# 3 or less outer diagonals on each side
laplacian = laplacian.todia()
else:
# csr has the fastest matvec and is thus best suited to
# arpack
laplacian = laplacian.tocsr()
return laplacian
def spectral_embedding(adjacency, n_components=8, eigen_solver=None,
random_state=None, eigen_tol=0.0,
norm_laplacian=True, drop_first=True):
"""Project the sample on the first eigenvectors of the graph Laplacian.
The adjacency matrix is used to compute a normalized graph Laplacian
whose spectrum (especially the eigenvectors associated to the
smallest eigenvalues) has an interpretation in terms of minimal
number of cuts necessary to split the graph into comparably sized
components.
This embedding can also 'work' even if the ``adjacency`` variable is
not strictly the adjacency matrix of a graph but more generally
an affinity or similarity matrix between samples (for instance the
heat kernel of a euclidean distance matrix or a k-NN matrix).
However care must taken to always make the affinity matrix symmetric
so that the eigenvector decomposition works as expected.
Read more in the :ref:`User Guide <spectral_embedding>`.
Parameters
----------
adjacency : array-like or sparse matrix, shape: (n_samples, n_samples)
The adjacency matrix of the graph to embed.
n_components : integer, optional, default 8
The dimension of the projection subspace.
eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}, default None
The eigenvalue decomposition strategy to use. AMG requires pyamg
to be installed. It can be faster on very large, sparse problems,
but may also lead to instabilities.
random_state : int seed, RandomState instance, or None (default)
A pseudo random number generator used for the initialization of the
lobpcg eigenvectors decomposition when eigen_solver == 'amg'.
By default, arpack is used.
eigen_tol : float, optional, default=0.0
Stopping criterion for eigendecomposition of the Laplacian matrix
when using arpack eigen_solver.
drop_first : bool, optional, default=True
Whether to drop the first eigenvector. For spectral embedding, this
should be True as the first eigenvector should be constant vector for
connected graph, but for spectral clustering, this should be kept as
False to retain the first eigenvector.
norm_laplacian : bool, optional, default=True
If True, then compute normalized Laplacian.
Returns
-------
embedding : array, shape=(n_samples, n_components)
The reduced samples.
Notes
-----
Spectral embedding is most useful when the graph has one connected
component. If there graph has many components, the first few eigenvectors
will simply uncover the connected components of the graph.
References
----------
* http://en.wikipedia.org/wiki/LOBPCG
* Toward the Optimal Preconditioned Eigensolver: Locally Optimal
Block Preconditioned Conjugate Gradient Method
Andrew V. Knyazev
http://dx.doi.org/10.1137%2FS1064827500366124
"""
adjacency = check_symmetric(adjacency)
try:
from pyamg import smoothed_aggregation_solver
except ImportError:
if eigen_solver == "amg":
raise ValueError("The eigen_solver was set to 'amg', but pyamg is "
"not available.")
if eigen_solver is None:
eigen_solver = 'arpack'
elif eigen_solver not in ('arpack', 'lobpcg', 'amg'):
raise ValueError("Unknown value for eigen_solver: '%s'."
"Should be 'amg', 'arpack', or 'lobpcg'"
% eigen_solver)
random_state = check_random_state(random_state)
n_nodes = adjacency.shape[0]
# Whether to drop the first eigenvector
if drop_first:
n_components = n_components + 1
if not _graph_is_connected(adjacency):
warnings.warn("Graph is not fully connected, spectral embedding"
" may not work as expected.")
laplacian, dd = graph_laplacian(adjacency,
normed=norm_laplacian, return_diag=True)
if (eigen_solver == 'arpack'
or eigen_solver != 'lobpcg' and
(not sparse.isspmatrix(laplacian)
or n_nodes < 5 * n_components)):
# lobpcg used with eigen_solver='amg' has bugs for low number of nodes
# for details see the source code in scipy:
# https://github.com/scipy/scipy/blob/v0.11.0/scipy/sparse/linalg/eigen
# /lobpcg/lobpcg.py#L237
# or matlab:
# http://www.mathworks.com/matlabcentral/fileexchange/48-lobpcg-m
laplacian = _set_diag(laplacian, 1)
# Here we'll use shift-invert mode for fast eigenvalues
# (see http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html
# for a short explanation of what this means)
# Because the normalized Laplacian has eigenvalues between 0 and 2,
# I - L has eigenvalues between -1 and 1. ARPACK is most efficient
# when finding eigenvalues of largest magnitude (keyword which='LM')
# and when these eigenvalues are very large compared to the rest.
# For very large, very sparse graphs, I - L can have many, many
# eigenvalues very near 1.0. This leads to slow convergence. So
# instead, we'll use ARPACK's shift-invert mode, asking for the
# eigenvalues near 1.0. This effectively spreads-out the spectrum
# near 1.0 and leads to much faster convergence: potentially an
# orders-of-magnitude speedup over simply using keyword which='LA'
# in standard mode.
try:
# We are computing the opposite of the laplacian inplace so as
# to spare a memory allocation of a possibly very large array
laplacian *= -1
lambdas, diffusion_map = eigsh(laplacian, k=n_components,
sigma=1.0, which='LM',
tol=eigen_tol)
embedding = diffusion_map.T[n_components::-1] * dd
except RuntimeError:
# When submatrices are exactly singular, an LU decomposition
# in arpack fails. We fallback to lobpcg
eigen_solver = "lobpcg"
# Revert the laplacian to its opposite to have lobpcg work
laplacian *= -1
if eigen_solver == 'amg':
# Use AMG to get a preconditioner and speed up the eigenvalue
# problem.
if not sparse.issparse(laplacian):
warnings.warn("AMG works better for sparse matrices")
# lobpcg needs double precision floats
laplacian = check_array(laplacian, dtype=np.float64,
accept_sparse=True)
laplacian = _set_diag(laplacian, 1)
ml = smoothed_aggregation_solver(check_array(laplacian, 'csr'))
M = ml.aspreconditioner()
X = random_state.rand(laplacian.shape[0], n_components + 1)
X[:, 0] = dd.ravel()
lambdas, diffusion_map = lobpcg(laplacian, X, M=M, tol=1.e-12,
largest=False)
embedding = diffusion_map.T * dd
if embedding.shape[0] == 1:
raise ValueError
elif eigen_solver == "lobpcg":
# lobpcg needs double precision floats
laplacian = check_array(laplacian, dtype=np.float64,
accept_sparse=True)
if n_nodes < 5 * n_components + 1:
# see note above under arpack why lobpcg has problems with small
# number of nodes
# lobpcg will fallback to eigh, so we short circuit it
if sparse.isspmatrix(laplacian):
laplacian = laplacian.toarray()
lambdas, diffusion_map = eigh(laplacian)
embedding = diffusion_map.T[:n_components] * dd
else:
laplacian = _set_diag(laplacian, 1)
# We increase the number of eigenvectors requested, as lobpcg
# doesn't behave well in low dimension
X = random_state.rand(laplacian.shape[0], n_components + 1)
X[:, 0] = dd.ravel()
lambdas, diffusion_map = lobpcg(laplacian, X, tol=1e-15,
largest=False, maxiter=2000)
embedding = diffusion_map.T[:n_components] * dd
if embedding.shape[0] == 1:
raise ValueError
embedding = _deterministic_vector_sign_flip(embedding)
if drop_first:
return embedding[1:n_components].T
else:
return embedding[:n_components].T
class SpectralEmbedding(BaseEstimator):
"""Spectral embedding for non-linear dimensionality reduction.
Forms an affinity matrix given by the specified function and
applies spectral decomposition to the corresponding graph laplacian.
The resulting transformation is given by the value of the
eigenvectors for each data point.
Read more in the :ref:`User Guide <spectral_embedding>`.
Parameters
-----------
n_components : integer, default: 2
The dimension of the projected subspace.
eigen_solver : {None, 'arpack', 'lobpcg', or 'amg'}
The eigenvalue decomposition strategy to use. AMG requires pyamg
to be installed. It can be faster on very large, sparse problems,
but may also lead to instabilities.
random_state : int seed, RandomState instance, or None, default : None
A pseudo random number generator used for the initialization of the
lobpcg eigenvectors decomposition when eigen_solver == 'amg'.
affinity : string or callable, default : "nearest_neighbors"
How to construct the affinity matrix.
- 'nearest_neighbors' : construct affinity matrix by knn graph
- 'rbf' : construct affinity matrix by rbf kernel
- 'precomputed' : interpret X as precomputed affinity matrix
- callable : use passed in function as affinity
the function takes in data matrix (n_samples, n_features)
and return affinity matrix (n_samples, n_samples).
gamma : float, optional, default : 1/n_features
Kernel coefficient for rbf kernel.
n_neighbors : int, default : max(n_samples/10 , 1)
Number of nearest neighbors for nearest_neighbors graph building.
Attributes
----------
embedding_ : array, shape = (n_samples, n_components)
Spectral embedding of the training matrix.
affinity_matrix_ : array, shape = (n_samples, n_samples)
Affinity_matrix constructed from samples or precomputed.
References
----------
- A Tutorial on Spectral Clustering, 2007
Ulrike von Luxburg
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.165.9323
- On Spectral Clustering: Analysis and an algorithm, 2011
Andrew Y. Ng, Michael I. Jordan, Yair Weiss
http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.19.8100
- Normalized cuts and image segmentation, 2000
Jianbo Shi, Jitendra Malik
http://citeseer.ist.psu.edu/viewdoc/summary?doi=10.1.1.160.2324
"""
def __init__(self, n_components=2, affinity="nearest_neighbors",
gamma=None, random_state=None, eigen_solver=None,
n_neighbors=None):
self.n_components = n_components
self.affinity = affinity
self.gamma = gamma
self.random_state = random_state
self.eigen_solver = eigen_solver
self.n_neighbors = n_neighbors
@property
def _pairwise(self):
return self.affinity == "precomputed"
def _get_affinity_matrix(self, X, Y=None):
"""Calculate the affinity matrix from data
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples
and n_features is the number of features.
If affinity is "precomputed"
X : array-like, shape (n_samples, n_samples),
Interpret X as precomputed adjacency graph computed from
samples.
Returns
-------
affinity_matrix, shape (n_samples, n_samples)
"""
if self.affinity == 'precomputed':
self.affinity_matrix_ = X
return self.affinity_matrix_
if self.affinity == 'nearest_neighbors':
if sparse.issparse(X):
warnings.warn("Nearest neighbors affinity currently does "
"not support sparse input, falling back to "
"rbf affinity")
self.affinity = "rbf"
else:
self.n_neighbors_ = (self.n_neighbors
if self.n_neighbors is not None
else max(int(X.shape[0] / 10), 1))
self.affinity_matrix_ = kneighbors_graph(X, self.n_neighbors_,
include_self=True)
# currently only symmetric affinity_matrix supported
self.affinity_matrix_ = 0.5 * (self.affinity_matrix_ +
self.affinity_matrix_.T)
return self.affinity_matrix_
if self.affinity == 'rbf':
self.gamma_ = (self.gamma
if self.gamma is not None else 1.0 / X.shape[1])
self.affinity_matrix_ = rbf_kernel(X, gamma=self.gamma_)
return self.affinity_matrix_
self.affinity_matrix_ = self.affinity(X)
return self.affinity_matrix_
def fit(self, X, y=None):
"""Fit the model from data in X.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples
and n_features is the number of features.
If affinity is "precomputed"
X : array-like, shape (n_samples, n_samples),
Interpret X as precomputed adjacency graph computed from
samples.
Returns
-------
self : object
Returns the instance itself.
"""
random_state = check_random_state(self.random_state)
if isinstance(self.affinity, six.string_types):
if self.affinity not in set(("nearest_neighbors", "rbf",
"precomputed")):
raise ValueError(("%s is not a valid affinity. Expected "
"'precomputed', 'rbf', 'nearest_neighbors' "
"or a callable.") % self.affinity)
elif not callable(self.affinity):
raise ValueError(("'affinity' is expected to be an an affinity "
"name or a callable. Got: %s") % self.affinity)
affinity_matrix = self._get_affinity_matrix(X)
self.embedding_ = spectral_embedding(affinity_matrix,
n_components=self.n_components,
eigen_solver=self.eigen_solver,
random_state=random_state)
return self
def fit_transform(self, X, y=None):
"""Fit the model from data in X and transform X.
Parameters
----------
X: array-like, shape (n_samples, n_features)
Training vector, where n_samples is the number of samples
and n_features is the number of features.
If affinity is "precomputed"
X : array-like, shape (n_samples, n_samples),
Interpret X as precomputed adjacency graph computed from
samples.
Returns
-------
X_new: array-like, shape (n_samples, n_components)
"""
self.fit(X)
return self.embedding_
| bsd-3-clause |
nanolearning/edx-platform | common/djangoapps/student/migrations/0001_initial.py | 188 | 8556 | # encoding: 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 'UserProfile'
db.create_table('auth_userprofile', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], unique=True)),
('name', self.gf('django.db.models.fields.TextField')(blank=True)),
('language', self.gf('django.db.models.fields.TextField')(blank=True)),
('location', self.gf('django.db.models.fields.TextField')(blank=True)),
('meta', self.gf('django.db.models.fields.TextField')(blank=True)),
('courseware', self.gf('django.db.models.fields.TextField')(default='course.xml', blank=True)),
))
db.send_create_signal('student', ['UserProfile'])
# Adding model 'Registration'
db.create_table('auth_registration', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], unique=True)),
('activation_key', self.gf('django.db.models.fields.CharField')(unique=True, max_length=32, db_index=True)),
))
db.send_create_signal('student', ['Registration'])
def backwards(self, orm):
# Deleting model 'UserProfile'
db.delete_table('auth_userprofile')
# Deleting model 'Registration'
db.delete_table('auth_registration')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'about': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'avatar_type': ('django.db.models.fields.CharField', [], {'default': "'n'", 'max_length': '1'}),
'bronze': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'consecutive_days_visit_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'blank': 'True'}),
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_of_birth': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'display_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'email_isvalid': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'email_key': ('django.db.models.fields.CharField', [], {'max_length': '32', 'null': 'True'}),
'email_tag_filter_strategy': ('django.db.models.fields.SmallIntegerField', [], {'default': '1'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'gold': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'gravatar': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ignored_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'interesting_tags': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'location': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'new_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'questions_per_page': ('django.db.models.fields.SmallIntegerField', [], {'default': '10'}),
'real_name': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'reputation': ('django.db.models.fields.PositiveIntegerField', [], {'default': '1'}),
'seen_response_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'show_country': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'silver': ('django.db.models.fields.SmallIntegerField', [], {'default': '0'}),
'status': ('django.db.models.fields.CharField', [], {'default': "'w'", 'max_length': '2'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'student.registration': {
'Meta': {'object_name': 'Registration', 'db_table': "'auth_registration'"},
'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'})
},
'student.userprofile': {
'Meta': {'object_name': 'UserProfile', 'db_table': "'auth_userprofile'"},
'courseware': ('django.db.models.fields.TextField', [], {'default': "'course.xml'", 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'location': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'meta': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'name': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'})
}
}
complete_apps = ['student']
| agpl-3.0 |
bennojoy/ansible | lib/ansible/plugins/filter/core.py | 10 | 10867 | # (c) 2012, Jeroen Hoekx <jeroen@hoekx.be>
#
# 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
import sys
import base64
import json
import os.path
import types
import pipes
import glob
import re
import crypt
import hashlib
import string
from functools import partial
import operator as py_operator
from random import SystemRandom, shuffle
import uuid
import yaml
from jinja2.filters import environmentfilter
from distutils.version import LooseVersion, StrictVersion
from ansible import errors
from ansible.parsing.yaml.dumper import AnsibleDumper
from ansible.utils.hashing import md5s, checksum_s
from ansible.utils.unicode import unicode_wrap, to_unicode
try:
import passlib.hash
HAS_PASSLIB = True
except:
HAS_PASSLIB = False
UUID_NAMESPACE_ANSIBLE = uuid.UUID('361E6D51-FAEC-444A-9079-341386DA8E2E')
def to_yaml(a, *args, **kw):
'''Make verbose, human readable yaml'''
transformed = yaml.dump(a, Dumper=AnsibleDumper, allow_unicode=True, **kw)
return to_unicode(transformed)
def to_nice_yaml(a, *args, **kw):
'''Make verbose, human readable yaml'''
transformed = yaml.dump(a, Dumper=AnsibleDumper, indent=4, allow_unicode=True, default_flow_style=False, **kw)
return to_unicode(transformed)
def to_json(a, *args, **kw):
''' Convert the value to JSON '''
return json.dumps(a, *args, **kw)
def to_nice_json(a, *args, **kw):
'''Make verbose, human readable JSON'''
# python-2.6's json encoder is buggy (can't encode hostvars)
if sys.version_info < (2, 7):
try:
import simplejson
except ImportError:
pass
else:
try:
major = int(simplejson.__version__.split('.')[0])
except:
pass
else:
if major >= 2:
return simplejson.dumps(a, indent=4, sort_keys=True, *args, **kw)
# Fallback to the to_json filter
return to_json(a, *args, **kw)
return json.dumps(a, indent=4, sort_keys=True, *args, **kw)
def failed(*a, **kw):
''' Test if task result yields failed '''
item = a[0]
if type(item) != dict:
raise errors.AnsibleFilterError("|failed expects a dictionary")
rc = item.get('rc',0)
failed = item.get('failed',False)
if rc != 0 or failed:
return True
else:
return False
def success(*a, **kw):
''' Test if task result yields success '''
return not failed(*a, **kw)
def changed(*a, **kw):
''' Test if task result yields changed '''
item = a[0]
if type(item) != dict:
raise errors.AnsibleFilterError("|changed expects a dictionary")
if not 'changed' in item:
changed = False
if ('results' in item # some modules return a 'results' key
and type(item['results']) == list
and type(item['results'][0]) == dict):
for result in item['results']:
changed = changed or result.get('changed', False)
else:
changed = item.get('changed', False)
return changed
def skipped(*a, **kw):
''' Test if task result yields skipped '''
item = a[0]
if type(item) != dict:
raise errors.AnsibleFilterError("|skipped expects a dictionary")
skipped = item.get('skipped', False)
return skipped
def mandatory(a):
''' Make a variable mandatory '''
try:
a
except NameError:
raise errors.AnsibleFilterError('Mandatory variable not defined.')
else:
return a
def bool(a):
''' return a bool for the arg '''
if a is None or type(a) == bool:
return a
if type(a) in types.StringTypes:
a = a.lower()
if a in ['yes', 'on', '1', 'true', 1]:
return True
else:
return False
def quote(a):
''' return its argument quoted for shell usage '''
return pipes.quote(a)
def fileglob(pathname):
''' return list of matched files for glob '''
return glob.glob(pathname)
def regex(value='', pattern='', ignorecase=False, match_type='search'):
''' Expose `re` as a boolean filter using the `search` method by default.
This is likely only useful for `search` and `match` which already
have their own filters.
'''
if ignorecase:
flags = re.I
else:
flags = 0
_re = re.compile(pattern, flags=flags)
_bool = __builtins__.get('bool')
return _bool(getattr(_re, match_type, 'search')(value))
def match(value, pattern='', ignorecase=False):
''' Perform a `re.match` returning a boolean '''
return regex(value, pattern, ignorecase, 'match')
def search(value, pattern='', ignorecase=False):
''' Perform a `re.search` returning a boolean '''
return regex(value, pattern, ignorecase, 'search')
def regex_replace(value='', pattern='', replacement='', ignorecase=False):
''' Perform a `re.sub` returning a string '''
if not isinstance(value, basestring):
value = str(value)
if ignorecase:
flags = re.I
else:
flags = 0
_re = re.compile(pattern, flags=flags)
return _re.sub(replacement, value)
def ternary(value, true_val, false_val):
''' value ? true_val : false_val '''
if value:
return true_val
else:
return false_val
def version_compare(value, version, operator='eq', strict=False):
''' Perform a version comparison on a value '''
op_map = {
'==': 'eq', '=': 'eq', 'eq': 'eq',
'<': 'lt', 'lt': 'lt',
'<=': 'le', 'le': 'le',
'>': 'gt', 'gt': 'gt',
'>=': 'ge', 'ge': 'ge',
'!=': 'ne', '<>': 'ne', 'ne': 'ne'
}
if strict:
Version = StrictVersion
else:
Version = LooseVersion
if operator in op_map:
operator = op_map[operator]
else:
raise errors.AnsibleFilterError('Invalid operator type')
try:
method = getattr(py_operator, operator)
return method(Version(str(value)), Version(str(version)))
except Exception, e:
raise errors.AnsibleFilterError('Version comparison: %s' % e)
@environmentfilter
def rand(environment, end, start=None, step=None):
r = SystemRandom()
if isinstance(end, (int, long)):
if not start:
start = 0
if not step:
step = 1
return r.randrange(start, end, step)
elif hasattr(end, '__iter__'):
if start or step:
raise errors.AnsibleFilterError('start and step can only be used with integer values')
return r.choice(end)
else:
raise errors.AnsibleFilterError('random can only be used on sequences and integers')
def randomize_list(mylist):
try:
mylist = list(mylist)
shuffle(mylist)
except:
pass
return mylist
def get_hash(data, hashtype='sha1'):
try: # see if hash is supported
h = hashlib.new(hashtype)
except:
return None
h.update(data)
return h.hexdigest()
def get_encrypted_password(password, hashtype='sha512', salt=None):
# TODO: find a way to construct dynamically from system
cryptmethod= {
'md5': '1',
'blowfish': '2a',
'sha256': '5',
'sha512': '6',
}
hastype = hashtype.lower()
if hashtype in cryptmethod:
if salt is None:
r = SystemRandom()
salt = ''.join([r.choice(string.ascii_letters + string.digits) for _ in range(16)])
if not HAS_PASSLIB:
if sys.platform.startswith('darwin'):
raise errors.AnsibleFilterError('|password_hash requires the passlib python module to generate password hashes on Mac OS X/Darwin')
saltstring = "$%s$%s" % (cryptmethod[hashtype],salt)
encrypted = crypt.crypt(password, saltstring)
else:
cls = getattr(passlib.hash, '%s_crypt' % hashtype)
encrypted = cls.encrypt(password, salt=salt)
return encrypted
return None
def to_uuid(string):
return str(uuid.uuid5(UUID_NAMESPACE_ANSIBLE, str(string)))
class FilterModule(object):
''' Ansible core jinja2 filters '''
def filters(self):
return {
# base 64
'b64decode': partial(unicode_wrap, base64.b64decode),
'b64encode': partial(unicode_wrap, base64.b64encode),
# uuid
'to_uuid': to_uuid,
# json
'to_json': to_json,
'to_nice_json': to_nice_json,
'from_json': json.loads,
# yaml
'to_yaml': to_yaml,
'to_nice_yaml': to_nice_yaml,
'from_yaml': yaml.safe_load,
# path
'basename': partial(unicode_wrap, os.path.basename),
'dirname': partial(unicode_wrap, os.path.dirname),
'expanduser': partial(unicode_wrap, os.path.expanduser),
'realpath': partial(unicode_wrap, os.path.realpath),
'relpath': partial(unicode_wrap, os.path.relpath),
# failure testing
'failed' : failed,
'success' : success,
# changed testing
'changed' : changed,
# skip testing
'skipped' : skipped,
# variable existence
'mandatory': mandatory,
# value as boolean
'bool': bool,
# quote string for shell usage
'quote': quote,
# hash filters
# md5 hex digest of string
'md5': md5s,
# sha1 hex digeset of string
'sha1': checksum_s,
# checksum of string as used by ansible for checksuming files
'checksum': checksum_s,
# generic hashing
'password_hash': get_encrypted_password,
'hash': get_hash,
# file glob
'fileglob': fileglob,
# regex
'match': match,
'search': search,
'regex': regex,
'regex_replace': regex_replace,
# ? : ;
'ternary': ternary,
# list
# version comparison
'version_compare': version_compare,
# random stuff
'random': rand,
'shuffle': randomize_list,
}
| gpl-3.0 |
M4sse/chromium.src | chrome/test/chromeos/utilities/vm_setup_state.py | 184 | 1114 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import pyauto_functional # has to be imported before pyauto
import pyauto
import sys
VM_CHROMEDRIVER_PORT = 4444
if __name__ == '__main__':
"""Script to prepare machine state for use as a WebDriver-controlled VM.
This script is intended to be run manually over ssh on a Chromium OS virtual
machine qcow2 image. Manually create a snapshot of the VM when prompted. The
resulting VM image will have ChromeDriver listening on port 4444.
"""
pyauto_suite = pyauto.PyUITestSuite(sys.argv)
pyuitest = pyauto.PyUITest()
pyuitest.setUp()
driver = pyuitest.NewWebDriver(port=VM_CHROMEDRIVER_PORT)
logging.info('WebDriver is listening on port %d.'
% VM_CHROMEDRIVER_PORT)
logging.info('Machine prepared for VM snapshot.')
raw_input('Please snapshot the VM and hit ENTER when done to '
'terminate this script.')
pyuitest.tearDown()
del pyuitest
del pyauto_suite
| bsd-3-clause |
HiroIshikawa/21playground | visualizer/_app_boilerplate/venv/lib/python3.5/site-packages/pip/_vendor/requests/packages/urllib3/connectionpool.py | 477 | 30319 | import errno
import logging
import sys
import warnings
from socket import error as SocketError, timeout as SocketTimeout
import socket
try: # Python 3
from queue import LifoQueue, Empty, Full
except ImportError:
from Queue import LifoQueue, Empty, Full
import Queue as _ # Platform-specific: Windows
from .exceptions import (
ClosedPoolError,
ProtocolError,
EmptyPoolError,
HostChangedError,
LocationValueError,
MaxRetryError,
ProxyError,
ReadTimeoutError,
SSLError,
TimeoutError,
InsecureRequestWarning,
)
from .packages.ssl_match_hostname import CertificateError
from .packages import six
from .connection import (
port_by_scheme,
DummyConnection,
HTTPConnection, HTTPSConnection, VerifiedHTTPSConnection,
HTTPException, BaseSSLError, ConnectionError
)
from .request import RequestMethods
from .response import HTTPResponse
from .util.connection import is_connection_dropped
from .util.retry import Retry
from .util.timeout import Timeout
from .util.url import get_host
xrange = six.moves.xrange
log = logging.getLogger(__name__)
_Default = object()
## Pool objects
class ConnectionPool(object):
"""
Base class for all connection pools, such as
:class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`.
"""
scheme = None
QueueCls = LifoQueue
def __init__(self, host, port=None):
if not host:
raise LocationValueError("No host specified.")
# httplib doesn't like it when we include brackets in ipv6 addresses
self.host = host.strip('[]')
self.port = port
def __str__(self):
return '%s(host=%r, port=%r)' % (type(self).__name__,
self.host, self.port)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
# Return False to re-raise any potential exceptions
return False
def close():
"""
Close all pooled connections and disable the pool.
"""
pass
# This is taken from http://hg.python.org/cpython/file/7aaba721ebc0/Lib/socket.py#l252
_blocking_errnos = set([errno.EAGAIN, errno.EWOULDBLOCK])
class HTTPConnectionPool(ConnectionPool, RequestMethods):
"""
Thread-safe connection pool for one host.
:param host:
Host used for this HTTP Connection (e.g. "localhost"), passed into
:class:`httplib.HTTPConnection`.
:param port:
Port used for this HTTP Connection (None is equivalent to 80), passed
into :class:`httplib.HTTPConnection`.
:param strict:
Causes BadStatusLine to be raised if the status line can't be parsed
as a valid HTTP/1.0 or 1.1 status line, passed into
:class:`httplib.HTTPConnection`.
.. note::
Only works in Python 2. This parameter is ignored in Python 3.
:param timeout:
Socket timeout in seconds for each individual connection. This can
be a float or integer, which sets the timeout for the HTTP request,
or an instance of :class:`urllib3.util.Timeout` which gives you more
fine-grained control over request timeouts. After the constructor has
been parsed, this is always a `urllib3.util.Timeout` object.
:param maxsize:
Number of connections to save that can be reused. More than 1 is useful
in multithreaded situations. If ``block`` is set to false, more
connections will be created but they will not be saved once they've
been used.
:param block:
If set to True, no more than ``maxsize`` connections will be used at
a time. When no free connections are available, the call will block
until a connection has been released. This is a useful side effect for
particular multithreaded situations where one does not want to use more
than maxsize connections per host to prevent flooding.
:param headers:
Headers to include with all requests, unless other headers are given
explicitly.
:param retries:
Retry configuration to use by default with requests in this pool.
:param _proxy:
Parsed proxy URL, should not be used directly, instead, see
:class:`urllib3.connectionpool.ProxyManager`"
:param _proxy_headers:
A dictionary with proxy headers, should not be used directly,
instead, see :class:`urllib3.connectionpool.ProxyManager`"
:param \**conn_kw:
Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`,
:class:`urllib3.connection.HTTPSConnection` instances.
"""
scheme = 'http'
ConnectionCls = HTTPConnection
def __init__(self, host, port=None, strict=False,
timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1, block=False,
headers=None, retries=None,
_proxy=None, _proxy_headers=None,
**conn_kw):
ConnectionPool.__init__(self, host, port)
RequestMethods.__init__(self, headers)
self.strict = strict
if not isinstance(timeout, Timeout):
timeout = Timeout.from_float(timeout)
if retries is None:
retries = Retry.DEFAULT
self.timeout = timeout
self.retries = retries
self.pool = self.QueueCls(maxsize)
self.block = block
self.proxy = _proxy
self.proxy_headers = _proxy_headers or {}
# Fill the queue up so that doing get() on it will block properly
for _ in xrange(maxsize):
self.pool.put(None)
# These are mostly for testing and debugging purposes.
self.num_connections = 0
self.num_requests = 0
self.conn_kw = conn_kw
if self.proxy:
# Enable Nagle's algorithm for proxies, to avoid packet fragmentation.
# We cannot know if the user has added default socket options, so we cannot replace the
# list.
self.conn_kw.setdefault('socket_options', [])
def _new_conn(self):
"""
Return a fresh :class:`HTTPConnection`.
"""
self.num_connections += 1
log.info("Starting new HTTP connection (%d): %s" %
(self.num_connections, self.host))
conn = self.ConnectionCls(host=self.host, port=self.port,
timeout=self.timeout.connect_timeout,
strict=self.strict, **self.conn_kw)
return conn
def _get_conn(self, timeout=None):
"""
Get a connection. Will return a pooled connection if one is available.
If no connections are available and :prop:`.block` is ``False``, then a
fresh connection is returned.
:param timeout:
Seconds to wait before giving up and raising
:class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and
:prop:`.block` is ``True``.
"""
conn = None
try:
conn = self.pool.get(block=self.block, timeout=timeout)
except AttributeError: # self.pool is None
raise ClosedPoolError(self, "Pool is closed.")
except Empty:
if self.block:
raise EmptyPoolError(self,
"Pool reached maximum size and no more "
"connections are allowed.")
pass # Oh well, we'll create a new connection then
# If this is a persistent connection, check if it got disconnected
if conn and is_connection_dropped(conn):
log.info("Resetting dropped connection: %s" % self.host)
conn.close()
if getattr(conn, 'auto_open', 1) == 0:
# This is a proxied connection that has been mutated by
# httplib._tunnel() and cannot be reused (since it would
# attempt to bypass the proxy)
conn = None
return conn or self._new_conn()
def _put_conn(self, conn):
"""
Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
because we exceeded maxsize. If connections are discarded frequently,
then maxsize should be increased.
If the pool is closed, then the connection will be closed and discarded.
"""
try:
self.pool.put(conn, block=False)
return # Everything is dandy, done.
except AttributeError:
# self.pool is None.
pass
except Full:
# This should never happen if self.block == True
log.warning(
"Connection pool is full, discarding connection: %s" %
self.host)
# Connection never got put back into the pool, close it.
if conn:
conn.close()
def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
pass
def _prepare_proxy(self, conn):
# Nothing to do for HTTP connections.
pass
def _get_timeout(self, timeout):
""" Helper that always returns a :class:`urllib3.util.Timeout` """
if timeout is _Default:
return self.timeout.clone()
if isinstance(timeout, Timeout):
return timeout.clone()
else:
# User passed us an int/float. This is for backwards compatibility,
# can be removed later
return Timeout.from_float(timeout)
def _raise_timeout(self, err, url, timeout_value):
"""Is the error actually a timeout? Will raise a ReadTimeout or pass"""
if isinstance(err, SocketTimeout):
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
# See the above comment about EAGAIN in Python 3. In Python 2 we have
# to specifically catch it and throw the timeout error
if hasattr(err, 'errno') and err.errno in _blocking_errnos:
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
# Catch possible read timeouts thrown as SSL errors. If not the
# case, rethrow the original. We need to do this because of:
# http://bugs.python.org/issue10272
if 'timed out' in str(err) or 'did not complete (read)' in str(err): # Python 2.6
raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value)
def _make_request(self, conn, method, url, timeout=_Default,
**httplib_request_kw):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our connection pools
:param timeout:
Socket timeout in seconds for the request. This can be a
float or integer, which will set the same timeout value for
the socket connect and the socket read, or an instance of
:class:`urllib3.util.Timeout`, which gives you more fine-grained
control over your timeouts.
"""
self.num_requests += 1
timeout_obj = self._get_timeout(timeout)
timeout_obj.start_connect()
conn.timeout = timeout_obj.connect_timeout
# Trigger any extra validation we need to do.
try:
self._validate_conn(conn)
except (SocketTimeout, BaseSSLError) as e:
# Py2 raises this as a BaseSSLError, Py3 raises it as socket timeout.
self._raise_timeout(err=e, url=url, timeout_value=conn.timeout)
raise
# conn.request() calls httplib.*.request, not the method in
# urllib3.request. It also calls makefile (recv) on the socket.
conn.request(method, url, **httplib_request_kw)
# Reset the timeout for the recv() on the socket
read_timeout = timeout_obj.read_timeout
# App Engine doesn't have a sock attr
if getattr(conn, 'sock', None):
# In Python 3 socket.py will catch EAGAIN and return None when you
# try and read into the file pointer created by http.client, which
# instead raises a BadStatusLine exception. Instead of catching
# the exception and assuming all BadStatusLine exceptions are read
# timeouts, check for a zero timeout before making the request.
if read_timeout == 0:
raise ReadTimeoutError(
self, url, "Read timed out. (read timeout=%s)" % read_timeout)
if read_timeout is Timeout.DEFAULT_TIMEOUT:
conn.sock.settimeout(socket.getdefaulttimeout())
else: # None or a value
conn.sock.settimeout(read_timeout)
# Receive the response from the server
try:
try: # Python 2.7, use buffering of HTTP responses
httplib_response = conn.getresponse(buffering=True)
except TypeError: # Python 2.6 and older
httplib_response = conn.getresponse()
except (SocketTimeout, BaseSSLError, SocketError) as e:
self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
raise
# AppEngine doesn't have a version attr.
http_version = getattr(conn, '_http_vsn_str', 'HTTP/?')
log.debug("\"%s %s %s\" %s %s" % (method, url, http_version,
httplib_response.status,
httplib_response.length))
return httplib_response
def close(self):
"""
Close all pooled connections and disable the pool.
"""
# Disable access to the pool
old_pool, self.pool = self.pool, None
try:
while True:
conn = old_pool.get(block=False)
if conn:
conn.close()
except Empty:
pass # Done.
def is_same_host(self, url):
"""
Check if the given ``url`` is a member of the same host as this
connection pool.
"""
if url.startswith('/'):
return True
# TODO: Add optional support for socket.gethostbyname checking.
scheme, host, port = get_host(url)
# Use explicit default port for comparison when none is given
if self.port and not port:
port = port_by_scheme.get(scheme)
elif not self.port and port == port_by_scheme.get(scheme):
port = None
return (scheme, host, port) == (self.scheme, self.host, self.port)
def urlopen(self, method, url, body=None, headers=None, retries=None,
redirect=True, assert_same_host=True, timeout=_Default,
pool_timeout=None, release_conn=None, **response_kw):
"""
Get a connection from the pool and perform an HTTP request. This is the
lowest level call for making a request, so you'll need to specify all
the raw details.
.. note::
More commonly, it's appropriate to use a convenience method provided
by :class:`.RequestMethods`, such as :meth:`request`.
.. note::
`release_conn` will only behave as expected if
`preload_content=False` because we want to make
`preload_content=False` the default behaviour someday soon without
breaking backwards compatibility.
:param method:
HTTP request method (such as GET, POST, PUT, etc.)
:param body:
Data to send in the request body (useful for creating
POST requests, see HTTPConnectionPool.post_url for
more convenience).
:param headers:
Dictionary of custom headers to send, such as User-Agent,
If-None-Match, etc. If None, pool headers are used. If provided,
these headers completely replace any pool-specific headers.
:param retries:
Configure the number of retries to allow before raising a
:class:`~urllib3.exceptions.MaxRetryError` exception.
Pass ``None`` to retry until you receive a response. Pass a
:class:`~urllib3.util.retry.Retry` object for fine-grained control
over different types of retries.
Pass an integer number to retry connection errors that many times,
but no other types of errors. Pass zero to never retry.
If ``False``, then retries are disabled and any exception is raised
immediately. Also, instead of raising a MaxRetryError on redirects,
the redirect response will be returned.
:type retries: :class:`~urllib3.util.retry.Retry`, False, or an int.
:param redirect:
If True, automatically handle redirects (status codes 301, 302,
303, 307, 308). Each redirect counts as a retry. Disabling retries
will disable redirect, too.
:param assert_same_host:
If ``True``, will make sure that the host of the pool requests is
consistent else will raise HostChangedError. When False, you can
use the pool on an HTTP proxy and request foreign hosts.
:param timeout:
If specified, overrides the default timeout for this one
request. It may be a float (in seconds) or an instance of
:class:`urllib3.util.Timeout`.
:param pool_timeout:
If set and the pool is set to block=True, then this method will
block for ``pool_timeout`` seconds and raise EmptyPoolError if no
connection is available within the time period.
:param release_conn:
If False, then the urlopen call will not release the connection
back into the pool once a response is received (but will release if
you read the entire contents of the response such as when
`preload_content=True`). This is useful if you're not preloading
the response's content immediately. You will need to call
``r.release_conn()`` on the response ``r`` to return the connection
back into the pool. If None, it takes the value of
``response_kw.get('preload_content', True)``.
:param \**response_kw:
Additional parameters are passed to
:meth:`urllib3.response.HTTPResponse.from_httplib`
"""
if headers is None:
headers = self.headers
if not isinstance(retries, Retry):
retries = Retry.from_int(retries, redirect=redirect, default=self.retries)
if release_conn is None:
release_conn = response_kw.get('preload_content', True)
# Check host
if assert_same_host and not self.is_same_host(url):
raise HostChangedError(self, url, retries)
conn = None
# Merge the proxy headers. Only do this in HTTP. We have to copy the
# headers dict so we can safely change it without those changes being
# reflected in anyone else's copy.
if self.scheme == 'http':
headers = headers.copy()
headers.update(self.proxy_headers)
# Must keep the exception bound to a separate variable or else Python 3
# complains about UnboundLocalError.
err = None
try:
# Request a connection from the queue.
timeout_obj = self._get_timeout(timeout)
conn = self._get_conn(timeout=pool_timeout)
conn.timeout = timeout_obj.connect_timeout
is_new_proxy_conn = self.proxy is not None and not getattr(conn, 'sock', None)
if is_new_proxy_conn:
self._prepare_proxy(conn)
# Make the request on the httplib connection object.
httplib_response = self._make_request(conn, method, url,
timeout=timeout_obj,
body=body, headers=headers)
# If we're going to release the connection in ``finally:``, then
# the request doesn't need to know about the connection. Otherwise
# it will also try to release it and we'll have a double-release
# mess.
response_conn = not release_conn and conn
# Import httplib's response into our own wrapper object
response = HTTPResponse.from_httplib(httplib_response,
pool=self,
connection=response_conn,
**response_kw)
# else:
# The connection will be put back into the pool when
# ``response.release_conn()`` is called (implicitly by
# ``response.read()``)
except Empty:
# Timed out by queue.
raise EmptyPoolError(self, "No pool connections are available.")
except (BaseSSLError, CertificateError) as e:
# Close the connection. If a connection is reused on which there
# was a Certificate error, the next request will certainly raise
# another Certificate error.
if conn:
conn.close()
conn = None
raise SSLError(e)
except SSLError:
# Treat SSLError separately from BaseSSLError to preserve
# traceback.
if conn:
conn.close()
conn = None
raise
except (TimeoutError, HTTPException, SocketError, ConnectionError) as e:
if conn:
# Discard the connection for these exceptions. It will be
# be replaced during the next _get_conn() call.
conn.close()
conn = None
if isinstance(e, SocketError) and self.proxy:
e = ProxyError('Cannot connect to proxy.', e)
elif isinstance(e, (SocketError, HTTPException)):
e = ProtocolError('Connection aborted.', e)
retries = retries.increment(method, url, error=e, _pool=self,
_stacktrace=sys.exc_info()[2])
retries.sleep()
# Keep track of the error for the retry warning.
err = e
finally:
if release_conn:
# Put the connection back to be reused. If the connection is
# expired then it will be None, which will get replaced with a
# fresh connection during _get_conn.
self._put_conn(conn)
if not conn:
# Try again
log.warning("Retrying (%r) after connection "
"broken by '%r': %s" % (retries, err, url))
return self.urlopen(method, url, body, headers, retries,
redirect, assert_same_host,
timeout=timeout, pool_timeout=pool_timeout,
release_conn=release_conn, **response_kw)
# Handle redirect?
redirect_location = redirect and response.get_redirect_location()
if redirect_location:
if response.status == 303:
method = 'GET'
try:
retries = retries.increment(method, url, response=response, _pool=self)
except MaxRetryError:
if retries.raise_on_redirect:
raise
return response
log.info("Redirecting %s -> %s" % (url, redirect_location))
return self.urlopen(method, redirect_location, body, headers,
retries=retries, redirect=redirect,
assert_same_host=assert_same_host,
timeout=timeout, pool_timeout=pool_timeout,
release_conn=release_conn, **response_kw)
# Check if we should retry the HTTP response.
if retries.is_forced_retry(method, status_code=response.status):
retries = retries.increment(method, url, response=response, _pool=self)
retries.sleep()
log.info("Forced retry: %s" % url)
return self.urlopen(method, url, body, headers,
retries=retries, redirect=redirect,
assert_same_host=assert_same_host,
timeout=timeout, pool_timeout=pool_timeout,
release_conn=release_conn, **response_kw)
return response
class HTTPSConnectionPool(HTTPConnectionPool):
"""
Same as :class:`.HTTPConnectionPool`, but HTTPS.
When Python is compiled with the :mod:`ssl` module, then
:class:`.VerifiedHTTPSConnection` is used, which *can* verify certificates,
instead of :class:`.HTTPSConnection`.
:class:`.VerifiedHTTPSConnection` uses one of ``assert_fingerprint``,
``assert_hostname`` and ``host`` in this order to verify connections.
If ``assert_hostname`` is False, no verification is done.
The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs`` and
``ssl_version`` are only used if :mod:`ssl` is available and are fed into
:meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket
into an SSL socket.
"""
scheme = 'https'
ConnectionCls = HTTPSConnection
def __init__(self, host, port=None,
strict=False, timeout=Timeout.DEFAULT_TIMEOUT, maxsize=1,
block=False, headers=None, retries=None,
_proxy=None, _proxy_headers=None,
key_file=None, cert_file=None, cert_reqs=None,
ca_certs=None, ssl_version=None,
assert_hostname=None, assert_fingerprint=None,
**conn_kw):
HTTPConnectionPool.__init__(self, host, port, strict, timeout, maxsize,
block, headers, retries, _proxy, _proxy_headers,
**conn_kw)
self.key_file = key_file
self.cert_file = cert_file
self.cert_reqs = cert_reqs
self.ca_certs = ca_certs
self.ssl_version = ssl_version
self.assert_hostname = assert_hostname
self.assert_fingerprint = assert_fingerprint
def _prepare_conn(self, conn):
"""
Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`
and establish the tunnel if proxy is used.
"""
if isinstance(conn, VerifiedHTTPSConnection):
conn.set_cert(key_file=self.key_file,
cert_file=self.cert_file,
cert_reqs=self.cert_reqs,
ca_certs=self.ca_certs,
assert_hostname=self.assert_hostname,
assert_fingerprint=self.assert_fingerprint)
conn.ssl_version = self.ssl_version
return conn
def _prepare_proxy(self, conn):
"""
Establish tunnel connection early, because otherwise httplib
would improperly set Host: header to proxy's IP:port.
"""
# Python 2.7+
try:
set_tunnel = conn.set_tunnel
except AttributeError: # Platform-specific: Python 2.6
set_tunnel = conn._set_tunnel
if sys.version_info <= (2, 6, 4) and not self.proxy_headers: # Python 2.6.4 and older
set_tunnel(self.host, self.port)
else:
set_tunnel(self.host, self.port, self.proxy_headers)
conn.connect()
def _new_conn(self):
"""
Return a fresh :class:`httplib.HTTPSConnection`.
"""
self.num_connections += 1
log.info("Starting new HTTPS connection (%d): %s"
% (self.num_connections, self.host))
if not self.ConnectionCls or self.ConnectionCls is DummyConnection:
raise SSLError("Can't connect to HTTPS URL because the SSL "
"module is not available.")
actual_host = self.host
actual_port = self.port
if self.proxy is not None:
actual_host = self.proxy.host
actual_port = self.proxy.port
conn = self.ConnectionCls(host=actual_host, port=actual_port,
timeout=self.timeout.connect_timeout,
strict=self.strict, **self.conn_kw)
return self._prepare_conn(conn)
def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
super(HTTPSConnectionPool, self)._validate_conn(conn)
# Force connect early to allow us to validate the connection.
if not getattr(conn, 'sock', None): # AppEngine might not have `.sock`
conn.connect()
if not conn.is_verified:
warnings.warn((
'Unverified HTTPS request is being made. '
'Adding certificate verification is strongly advised. See: '
'https://urllib3.readthedocs.org/en/latest/security.html'),
InsecureRequestWarning)
def connection_from_url(url, **kw):
"""
Given a url, return an :class:`.ConnectionPool` instance of its host.
This is a shortcut for not having to parse out the scheme, host, and port
of the url before creating an :class:`.ConnectionPool` instance.
:param url:
Absolute URL string that must include the scheme. Port is optional.
:param \**kw:
Passes additional parameters to the constructor of the appropriate
:class:`.ConnectionPool`. Useful for specifying things like
timeout, maxsize, headers, etc.
Example::
>>> conn = connection_from_url('http://google.com/')
>>> r = conn.request('GET', '/')
"""
scheme, host, port = get_host(url)
if scheme == 'https':
return HTTPSConnectionPool(host, port=port, **kw)
else:
return HTTPConnectionPool(host, port=port, **kw)
| mit |
toshywoshy/ansible | test/lib/ansible_test/_internal/git.py | 56 | 4379 | """Wrapper around git command-line tools."""
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import re
from . import types as t
from .util import (
SubprocessError,
raw_command,
)
class Git:
"""Wrapper around git command-line tools."""
def __init__(self, root=None): # type: (t.Optional[str]) -> None
self.git = 'git'
self.root = root
def get_diff(self, args, git_options=None):
"""
:type args: list[str]
:type git_options: list[str] | None
:rtype: list[str]
"""
cmd = ['diff'] + args
if git_options is None:
git_options = ['-c', 'core.quotePath=']
return self.run_git_split(git_options + cmd, '\n', str_errors='replace')
def get_diff_names(self, args):
"""
:type args: list[str]
:rtype: list[str]
"""
cmd = ['diff', '--name-only', '--no-renames', '-z'] + args
return self.run_git_split(cmd, '\0')
def get_submodule_paths(self): # type: () -> t.List[str]
"""Return a list of submodule paths recursively."""
cmd = ['submodule', 'status', '--recursive']
output = self.run_git_split(cmd, '\n')
submodule_paths = [re.search(r'^.[0-9a-f]+ (?P<path>[^ ]+)', line).group('path') for line in output]
# status is returned for all submodules in the current git repository relative to the current directory
# when the current directory is not the root of the git repository this can yield relative paths which are not below the current directory
# this can occur when multiple collections are in a git repo and some collections are submodules when others are not
# specifying "." as the path to enumerate would limit results to the current directory, but can cause the git command to fail with the error:
# error: pathspec '.' did not match any file(s) known to git
# this can occur when the current directory contains no files tracked by git
# instead we'll filter out the relative paths, since we're only interested in those at or below the current directory
submodule_paths = [path for path in submodule_paths if not path.startswith('../')]
return submodule_paths
def get_file_names(self, args):
"""
:type args: list[str]
:rtype: list[str]
"""
cmd = ['ls-files', '-z'] + args
return self.run_git_split(cmd, '\0')
def get_branches(self):
"""
:rtype: list[str]
"""
cmd = ['for-each-ref', 'refs/heads/', '--format', '%(refname:strip=2)']
return self.run_git_split(cmd)
def get_branch(self):
"""
:rtype: str
"""
cmd = ['symbolic-ref', '--short', 'HEAD']
return self.run_git(cmd).strip()
def get_rev_list(self, commits=None, max_count=None):
"""
:type commits: list[str] | None
:type max_count: int | None
:rtype: list[str]
"""
cmd = ['rev-list']
if commits:
cmd += commits
else:
cmd += ['HEAD']
if max_count:
cmd += ['--max-count', '%s' % max_count]
return self.run_git_split(cmd)
def get_branch_fork_point(self, branch):
"""
:type branch: str
:rtype: str
"""
cmd = ['merge-base', '--fork-point', branch]
return self.run_git(cmd).strip()
def is_valid_ref(self, ref):
"""
:type ref: str
:rtype: bool
"""
cmd = ['show', ref]
try:
self.run_git(cmd, str_errors='replace')
return True
except SubprocessError:
return False
def run_git_split(self, cmd, separator=None, str_errors='strict'):
"""
:type cmd: list[str]
:type separator: str | None
:type str_errors: str
:rtype: list[str]
"""
output = self.run_git(cmd, str_errors=str_errors).strip(separator)
if not output:
return []
return output.split(separator)
def run_git(self, cmd, str_errors='strict'):
"""
:type cmd: list[str]
:type str_errors: str
:rtype: str
"""
return raw_command([self.git] + cmd, cwd=self.root, capture=True, str_errors=str_errors)[0]
| gpl-3.0 |
ProfessorX/Config | .PyCharm30/system/python_stubs/-1247971765/PyQt4/QtGui/QAbstractSpinBox.py | 1 | 9176 | # encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python3/dist-packages/PyQt4/QtGui.cpython-34m-x86_64-linux-gnu.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
from .QWidget import QWidget
class QAbstractSpinBox(QWidget):
""" QAbstractSpinBox(QWidget parent=None) """
def alignment(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.alignment() -> Qt.Alignment """
pass
def buttonSymbols(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.buttonSymbols() -> QAbstractSpinBox.ButtonSymbols """
pass
def changeEvent(self, QEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.changeEvent(QEvent) """
pass
def clear(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.clear() """
pass
def closeEvent(self, QCloseEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.closeEvent(QCloseEvent) """
pass
def contextMenuEvent(self, QContextMenuEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.contextMenuEvent(QContextMenuEvent) """
pass
def correctionMode(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.correctionMode() -> QAbstractSpinBox.CorrectionMode """
pass
def editingFinished(self, *args, **kwargs): # real signature unknown
""" QAbstractSpinBox.editingFinished [signal] """
pass
def event(self, QEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.event(QEvent) -> bool """
return False
def fixup(self, p_str): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.fixup(str) -> str """
return ""
def focusInEvent(self, QFocusEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.focusInEvent(QFocusEvent) """
pass
def focusOutEvent(self, QFocusEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.focusOutEvent(QFocusEvent) """
pass
def hasAcceptableInput(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.hasAcceptableInput() -> bool """
return False
def hasFrame(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.hasFrame() -> bool """
return False
def hideEvent(self, QHideEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.hideEvent(QHideEvent) """
pass
def initStyleOption(self, QStyleOptionSpinBox): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.initStyleOption(QStyleOptionSpinBox) """
pass
def inputMethodQuery(self, Qt_InputMethodQuery): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.inputMethodQuery(Qt.InputMethodQuery) -> object """
return object()
def interpretText(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.interpretText() """
pass
def isAccelerated(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.isAccelerated() -> bool """
return False
def isReadOnly(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.isReadOnly() -> bool """
return False
def keyboardTracking(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.keyboardTracking() -> bool """
return False
def keyPressEvent(self, QKeyEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.keyPressEvent(QKeyEvent) """
pass
def keyReleaseEvent(self, QKeyEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.keyReleaseEvent(QKeyEvent) """
pass
def lineEdit(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.lineEdit() -> QLineEdit """
return QLineEdit
def minimumSizeHint(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.minimumSizeHint() -> QSize """
pass
def mouseMoveEvent(self, QMouseEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.mouseMoveEvent(QMouseEvent) """
pass
def mousePressEvent(self, QMouseEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.mousePressEvent(QMouseEvent) """
pass
def mouseReleaseEvent(self, QMouseEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.mouseReleaseEvent(QMouseEvent) """
pass
def paintEvent(self, QPaintEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.paintEvent(QPaintEvent) """
pass
def resizeEvent(self, QResizeEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.resizeEvent(QResizeEvent) """
pass
def selectAll(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.selectAll() """
pass
def setAccelerated(self, bool): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setAccelerated(bool) """
pass
def setAlignment(self, Qt_Alignment): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setAlignment(Qt.Alignment) """
pass
def setButtonSymbols(self, QAbstractSpinBox_ButtonSymbols): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setButtonSymbols(QAbstractSpinBox.ButtonSymbols) """
pass
def setCorrectionMode(self, QAbstractSpinBox_CorrectionMode): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setCorrectionMode(QAbstractSpinBox.CorrectionMode) """
pass
def setFrame(self, bool): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setFrame(bool) """
pass
def setKeyboardTracking(self, bool): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setKeyboardTracking(bool) """
pass
def setLineEdit(self, QLineEdit): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setLineEdit(QLineEdit) """
pass
def setReadOnly(self, bool): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setReadOnly(bool) """
pass
def setSpecialValueText(self, p_str): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setSpecialValueText(str) """
pass
def setWrapping(self, bool): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.setWrapping(bool) """
pass
def showEvent(self, QShowEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.showEvent(QShowEvent) """
pass
def sizeHint(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.sizeHint() -> QSize """
pass
def specialValueText(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.specialValueText() -> str """
return ""
def stepBy(self, p_int): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.stepBy(int) """
pass
def stepDown(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.stepDown() """
pass
def stepEnabled(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.stepEnabled() -> QAbstractSpinBox.StepEnabled """
pass
def stepUp(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.stepUp() """
pass
def text(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.text() -> str """
return ""
def timerEvent(self, QTimerEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.timerEvent(QTimerEvent) """
pass
def validate(self, p_str, p_int): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.validate(str, int) -> (QValidator.State, str, int) """
pass
def wheelEvent(self, QWheelEvent): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.wheelEvent(QWheelEvent) """
pass
def wrapping(self): # real signature unknown; restored from __doc__
""" QAbstractSpinBox.wrapping() -> bool """
return False
def __init__(self, QWidget_parent=None): # real signature unknown; restored from __doc__
pass
ButtonSymbols = None # (!) real value is ''
CorrectionMode = None # (!) real value is ''
CorrectToNearestValue = 1
CorrectToPreviousValue = 0
NoButtons = 2
PlusMinus = 1
StepDownEnabled = 2
StepEnabled = None # (!) real value is ''
StepEnabledFlag = None # (!) real value is ''
StepNone = 0
StepUpEnabled = 1
UpDownArrows = 0
| gpl-2.0 |
broferek/ansible | lib/ansible/modules/network/aci/aci_l3out.py | 8 | 11082 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# 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': 'certified'}
DOCUMENTATION = r'''
---
module: aci_l3out
short_description: Manage Layer 3 Outside (L3Out) objects (l3ext:Out)
description:
- Manage Layer 3 Outside (L3Out) on Cisco ACI fabrics.
version_added: '2.6'
options:
tenant:
description:
- Name of an existing tenant.
type: str
required: yes
aliases: [ tenant_name ]
l3out:
description:
- Name of L3Out being created.
type: str
required: yes
aliases: [ l3out_name, name ]
vrf:
description:
- Name of the VRF being associated with the L3Out.
type: str
required: yes
aliases: [ vrf_name ]
domain:
description:
- Name of the external L3 domain being associated with the L3Out.
type: str
required: yes
aliases: [ ext_routed_domain_name, routed_domain ]
dscp:
description:
- The target Differentiated Service (DSCP) value.
- The APIC defaults to C(unspecified) when unset during creation.
type: str
choices: [ AF11, AF12, AF13, AF21, AF22, AF23, AF31, AF32, AF33, AF41, AF42, AF43, CS0, CS1, CS2, CS3, CS4, CS5, CS6, CS7, EF, VA, unspecified ]
aliases: [ target ]
route_control:
description:
- Route Control enforcement direction. The only allowed values are export or import,export.
type: list
choices: [ export, import ]
aliases: [ route_control_enforcement ]
l3protocol:
description:
- Routing protocol for the L3Out
type: list
choices: [ bgp, eigrp, ospf, pim, static ]
asn:
description:
- The AS number for the L3Out.
- Only applicable when using 'eigrp' as the l3protocol
type: int
aliases: [ as_number ]
version_added: '2.8'
description:
description:
- Description for the L3Out.
type: str
aliases: [ descr ]
state:
description:
- Use C(present) or C(absent) for adding or removing.
- Use C(query) for listing an object or multiple objects.
type: str
choices: [ absent, present, query ]
default: present
extends_documentation_fragment: aci
notes:
- The C(tenant) and C(domain) and C(vrf) used must exist before using this module in your playbook.
The M(aci_tenant) and M(aci_domain) and M(aci_vrf) modules can be used for this.
seealso:
- module: aci_tenant
- module: aci_domain
- module: aci_vrf
- name: APIC Management Information Model reference
description: More information about the internal APIC class B(l3ext:Out).
link: https://developer.cisco.com/docs/apic-mim-ref/
author:
- Rostyslav Davydenko (@rost-d)
'''
EXAMPLES = r'''
- name: Add a new L3Out
aci_l3out:
host: apic
username: admin
password: SomeSecretPassword
tenant: production
name: prod_l3out
description: L3Out for Production tenant
domain: l3dom_prod
vrf: prod
l3protocol: ospf
state: present
delegate_to: localhost
- name: Delete L3Out
aci_l3out:
host: apic
username: admin
password: SomeSecretPassword
tenant: production
name: prod_l3out
state: absent
delegate_to: localhost
- name: Query L3Out information
aci_l3out:
host: apic
username: admin
password: SomeSecretPassword
tenant: production
name: prod_l3out
state: query
delegate_to: localhost
register: query_result
'''
RETURN = r'''
current:
description: The existing configuration from the APIC after the module has finished
returned: success
type: list
sample:
[
{
"fvTenant": {
"attributes": {
"descr": "Production environment",
"dn": "uni/tn-production",
"name": "production",
"nameAlias": "",
"ownerKey": "",
"ownerTag": ""
}
}
}
]
error:
description: The error information as returned from the APIC
returned: failure
type: dict
sample:
{
"code": "122",
"text": "unknown managed object class foo"
}
raw:
description: The raw output returned by the APIC REST API (xml or json)
returned: parse error
type: str
sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>'
sent:
description: The actual/minimal configuration pushed to the APIC
returned: info
type: list
sample:
{
"fvTenant": {
"attributes": {
"descr": "Production environment"
}
}
}
previous:
description: The original configuration from the APIC before the module has started
returned: info
type: list
sample:
[
{
"fvTenant": {
"attributes": {
"descr": "Production",
"dn": "uni/tn-production",
"name": "production",
"nameAlias": "",
"ownerKey": "",
"ownerTag": ""
}
}
}
]
proposed:
description: The assembled configuration from the user-provided parameters
returned: info
type: dict
sample:
{
"fvTenant": {
"attributes": {
"descr": "Production environment",
"name": "production"
}
}
}
filter_string:
description: The filter string used for the request
returned: failure or debug
type: str
sample: ?rsp-prop-include=config-only
method:
description: The HTTP method used for the request to the APIC
returned: failure or debug
type: str
sample: POST
response:
description: The HTTP response from the APIC
returned: failure or debug
type: str
sample: OK (30 bytes)
status:
description: The HTTP status from the APIC
returned: failure or debug
type: int
sample: 200
url:
description: The HTTP url used for the request to the APIC
returned: failure or debug
type: str
sample: https://10.11.12.13/api/mo/uni/tn-production.json
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.aci.aci import ACIModule, aci_argument_spec
def main():
argument_spec = aci_argument_spec()
argument_spec.update(
tenant=dict(type='str', aliases=['tenant_name']), # Not required for querying all objects
l3out=dict(type='str', aliases=['l3out_name', 'name']), # Not required for querying all objects
domain=dict(type='str', aliases=['ext_routed_domain_name', 'routed_domain']),
vrf=dict(type='str', aliases=['vrf_name']),
description=dict(type='str', aliases=['descr']),
route_control=dict(type='list', choices=['export', 'import'], aliases=['route_control_enforcement']),
dscp=dict(type='str',
choices=['AF11', 'AF12', 'AF13', 'AF21', 'AF22', 'AF23', 'AF31', 'AF32', 'AF33', 'AF41', 'AF42',
'AF43', 'CS0', 'CS1', 'CS2', 'CS3', 'CS4', 'CS5', 'CS6', 'CS7', 'EF', 'VA', 'unspecified'],
aliases=['target']),
l3protocol=dict(type='list', choices=['bgp', 'eigrp', 'ospf', 'pim', 'static']),
asn=dict(type='int', aliases=['as_number']),
state=dict(type='str', default='present', choices=['absent', 'present', 'query'])
)
module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True,
required_if=[
['state', 'absent', ['l3out', 'tenant']],
['state', 'present', ['l3out', 'tenant', 'domain', 'vrf']],
],
)
aci = ACIModule(module)
l3out = module.params.get('l3out')
domain = module.params.get('domain')
dscp = module.params.get('dscp')
description = module.params.get('description')
enforceRtctrl = module.params.get('route_control')
vrf = module.params.get('vrf')
l3protocol = module.params.get('l3protocol')
asn = module.params.get('asn')
state = module.params.get('state')
tenant = module.params.get('tenant')
if l3protocol:
if 'eigrp' in l3protocol and asn is None:
module.fail_json(msg="Parameter 'asn' is required when l3protocol is 'eigrp'")
if 'eigrp' not in l3protocol and asn is not None:
module.warn("Parameter 'asn' is only applicable when l3protocol is 'eigrp'. The ASN will be ignored")
enforce_ctrl = ''
if enforceRtctrl is not None:
if len(enforceRtctrl) == 1 and enforceRtctrl[0] == 'import':
aci.fail_json(
"The route_control parameter is invalid: allowed options are export or import,export only")
elif len(enforceRtctrl) == 1 and enforceRtctrl[0] == 'export':
enforce_ctrl = 'export'
else:
enforce_ctrl = 'export,import'
child_classes = ['l3extRsL3DomAtt', 'l3extRsEctx', 'bgpExtP', 'ospfExtP', 'eigrpExtP', 'pimExtP']
aci.construct_url(
root_class=dict(
aci_class='fvTenant',
aci_rn='tn-{0}'.format(tenant),
module_object=tenant,
target_filter={'name': tenant},
),
subclass_1=dict(
aci_class='l3extOut',
aci_rn='out-{0}'.format(l3out),
module_object=l3out,
target_filter={'name': l3out},
),
child_classes=child_classes,
)
aci.get_existing()
child_configs = [
dict(l3extRsL3DomAtt=dict(attributes=dict(
tDn='uni/l3dom-{0}'.format(domain)))),
dict(l3extRsEctx=dict(attributes=dict(tnFvCtxName=vrf))),
]
if l3protocol is not None:
for protocol in l3protocol:
if protocol == 'bgp':
child_configs.append(
dict(bgpExtP=dict(attributes=dict(descr='', nameAlias=''))))
elif protocol == 'eigrp':
child_configs.append(
dict(eigrpExtP=dict(attributes=dict(descr='', nameAlias='', asn=asn))))
elif protocol == 'ospf':
child_configs.append(
dict(ospfExtP=dict(attributes=dict(descr='', nameAlias=''))))
elif protocol == 'pim':
child_configs.append(
dict(pimExtP=dict(attributes=dict(descr='', nameAlias=''))))
if state == 'present':
aci.payload(
aci_class='l3extOut',
class_config=dict(
name=l3out,
descr=description,
dn='uni/tn-{0}/out-{1}'.format(tenant, l3out),
enforceRtctrl=enforce_ctrl,
targetDscp=dscp
),
child_configs=child_configs,
)
aci.get_diff(aci_class='l3extOut')
aci.post_config()
elif state == 'absent':
aci.delete_config()
aci.exit_json()
if __name__ == "__main__":
main()
| gpl-3.0 |
wiso/dask | dask/store/core.py | 15 | 2780 | from collections import defaultdict, MutableMapping
from operator import getitem, add
from datetime import datetime
from time import time
from ..core import istask, ishashable
class Store(MutableMapping):
""" Store - A storage of data and computation
Example
-------
Store data like a dictionary
>>> import dask.store as ds
>>> s = ds.Store()
>>> s['x'] = 10
>>> s['x']
10
Also store computation on that data
>>> s['y'] = (add, 'x', 5)
Accessing these keys results in computations. Results may be cached for
reuse.
>>> s['y']
15
Design
------
A Store maintains the following state
dsk: dict
A dask to define all computation
cache: dict-like
Stores both ground data and cached intermediate values
data: set
The keys in the cache that can not be removed for correctness.
compute_time: dict:: {key: float}
dict mapping the time it took to compute each key
access_times: dict:: {key: [datetimes]}
The times at which a key was accessed
"""
def __init__(self, cache=None):
self.dsk = dict()
if cache is None:
cache = dict()
self.cache = cache
self.data = set()
self.compute_time = dict()
self.access_times = defaultdict(list)
def __setitem__(self, key, value):
if key in self.dsk:
if (self.dsk[key] == value or
self.dsk[key] == (getitem, self.cache, key) and
self.cache[key] == value):
return
else:
raise KeyError("Can not overwrite data")
if istask(value):
self.dsk[key] = value
else:
self.cache[key] = value
self.dsk[key] = (getitem, self.cache, key)
self.data.add(key)
def __getitem__(self, key):
if isinstance(key, list):
return (self[item] for item in key)
if not ishashable(key):
return key
if key not in self.dsk:
return key
self.access_times[key].append(datetime.now())
if key in self.cache:
return self.cache[key]
task = self.dsk[key]
func, args = task[0], task[1:]
if func == getitem and args[0] is self.cache:
return self.cache[args[1]]
args = [self[arg] for arg in args]
start = time()
result = func(*args)
end = time()
self.cache[key] = result
self.compute_time[key] = end - start
return result
def __len__(self):
return len(self.dsk)
def __iter__(self):
return iter(self.dsk)
def __delitem__(self, key):
raise ValueError("Dask Store does not support deletion")
| bsd-3-clause |
liqi328/rjrepaircompany | django/contrib/sessions/backends/cache.py | 268 | 1881 | from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.cache import cache
class SessionStore(SessionBase):
"""
A cache-based session store.
"""
def __init__(self, session_key=None):
self._cache = cache
super(SessionStore, self).__init__(session_key)
def load(self):
session_data = self._cache.get(self.session_key)
if session_data is not None:
return session_data
self.create()
return {}
def create(self):
# Because a cache can fail silently (e.g. memcache), we don't know if
# we are failing to create a new session because of a key collision or
# because the cache is missing. So we try for a (large) number of times
# and then raise an exception. That's the risk you shoulder if using
# cache backing.
for i in xrange(10000):
self.session_key = self._get_new_session_key()
try:
self.save(must_create=True)
except CreateError:
continue
self.modified = True
return
raise RuntimeError("Unable to create a new session key.")
def save(self, must_create=False):
if must_create:
func = self._cache.add
else:
func = self._cache.set
result = func(self.session_key, self._get_session(no_load=must_create),
self.get_expiry_age())
if must_create and not result:
raise CreateError
def exists(self, session_key):
if self._cache.has_key(session_key):
return True
return False
def delete(self, session_key=None):
if session_key is None:
if self._session_key is None:
return
session_key = self._session_key
self._cache.delete(session_key)
| bsd-3-clause |
zxsted/scipy | scipy/sparse/linalg/isolve/iterative/test.py | 110 | 4126 | from __future__ import division, print_function, absolute_import
from scipy import *
from iterative import *
def test_fun(alpha, x, beta, y, A, n):
# compute z = alpha*A*x + beta*y
xx = x[:n]
yy = y[:n]
w = dot(A,xx)
z = alpha*w+beta*yy
y[:n] = z
return
def test_fun_t(alpha, x, beta, y, A, n):
# compute z = alpha*A*x + beta*y
xx = x[:n]
yy = y[:n]
AA = conj(transpose(A))
w = dot(AA,xx)
z = alpha*w+beta*yy
y[:n] = z
return
def test_psolve(x,b,n):
x[:n] = b[:n]
return
def test_psolve_t(x,b,n):
x[:n] = b[:n]
return
def test_psolveq(x,b,which,n):
x[:n] = b[:n]
return
def test_psolveq_t(x,b,which,n):
x[:n] = b[:n]
return
n = 5
dA = 1.0*array([[2, -1, 0, 0, 0],
[-1, 2, -1, 0, 0],
[0, -1, 2, -1, 0],
[0, 0, -1, 2, -1],
[0, 0, 0, 1, 2]])
db = 1.0*array([0,1,1,0,0])
##zA = (1.0+0j)*array([[ 2, -1+0.1j, 0, 0, 0],
## [-1+0.1j, 2, -1-0.1j, 0, 0],
## [ 0, -1-0.1j, 2, -1+0.1j, 0],
## [ 0, 0, -1+0.1j, 2, -1-0.1j],
## [ 0, 0, 0, -1, 2-0.1j]])
zA = (1.0+0j)*array([[2, -1 + 1j, 0, 0, 0],
[-1+0.1j, 2, -1-0.1j, 0, 0],
[0, -1 - 1j, 2, -1+0.1j, 0],
[0, 0, -1+0.1j, 2, -1-0.1j],
[0, 0, 0, -1, 2-0.1j]])
zb = (1.0+0j)*array([0,1,1,0,0])
dx = 0*db.copy()
zx = 0*zb.copy()
diter = 1000
dresid = 1e-6
ziter = 1000
zresid = 1e-6
drestrt = n
zrestrt = n
############### BiCG #######################
dx,diter,dresid,dinfor = dbicg(db,dx,diter,dresid,test_fun,test_fun_t,test_psolve,test_psolve_t,(dA,n),(dA,n),(n,),(n,))
zx,ziter,zresid,zinfor = zbicg(zb,zx,ziter,zresid,test_fun,test_fun_t,test_psolve,test_psolve_t,(zA,n),(zA,n),(n,),(n,))
############### BiCGSTAB ###################
#dx,diter,dresid,dinfor = dbicgstab(db,dx,diter,dresid,test_fun,test_psolve,(dA,n),(n,))
#zx,ziter,zresid,zinfor = zbicgstab(zb,zx,ziter,zresid,test_fun,test_psolve,(zA,n),(n,))
############### CG #########################
##dA = 1.0*array([[ 2, -1, 0, 0, 0],
## [-1, 2, -1, 0, 0],
## [ 0, -1, 2, -1, 0],
## [ 0, 0, -1, 2, -1],
## [ 0, 0, 0, -1, 2]])
##dx = db.copy()
##zA = (1.0+0j)*array([[ 2, -1+0.1j, 0, 0, 0],
## [-1+0.1j, 2, -1-0.1j, 0, 0],
## [ 0, -1-0.1j, 2, -1+0.1j, 0],
## [ 0, 0, -1+0.1j, 2, -1-0.1j],
## [ 0, 0, 0, -1, 2-0.1j]])
##zx = zb.copy()
##dx,diter,dresid,dinfor = dcg(db,dx,diter,dresid,test_fun,test_psolve,(dA,n),(n,))
##zx,ziter,zresid,zinfor = zcg(zb,zx,ziter,zresid,test_fun,test_psolve,(zA,n),(n,))
############### CGS ########################
#dx,diter,dresid,dinfor = dcgs(db,dx,diter,dresid,test_fun,test_psolve,(dA,n),(n,))
#zx,ziter,zresid,zinfor = zcgs(zb,zx,ziter,zresid,test_fun,test_psolve,(zA,n),(n,))
############### GMRES ######################
#dx,diter,dresid,dinfor = dgmres(db,dx,drestrt,diter,dresid,test_fun,test_psolve,(dA,n),(n,))
#zx,ziter,zresid,zinfor = zgmres(zb,zx,zrestrt,ziter,zresid,test_fun,test_psolve,(zA,n),(n,))
############### QMR ########################
#dx,diter,dresid,dinfor = dqmr(db,dx,diter,dresid,test_fun,test_fun_t,test_psolveq,test_psolveq_t,(dA,n),(dA,n),(n,),(n,))
#zx,ziter,zresid,zinfor = zqmr(zb,zx,ziter,zresid,test_fun,test_fun_t,test_psolveq,test_psolveq_t,(zA,n),(zA,n),(n,),(n,))
print()
print('**************** double *****************')
print('iter:',diter, 'resid:', dresid, 'info:',dinfor)
print('x=',dx)
print('*****************************************')
print()
print()
print('**************** complex ****************')
print('iter:',ziter, 'resid:',zresid, 'info:',zinfor)
print('x=',zx)
print('*****************************************')
print()
| bsd-3-clause |
spencerpomme/coconuts-on-fire | person.py | 1 | 1237 | from classtools import AttrDisplay
class Person(AttrDisplay):
'''
Create and process person records
'''
def __init__(self, name, job=None, pay=0):
self.name = name
self.job = job
self.pay = pay
def lastName(self):
return self.name.split()[-1]
def giveRaise(self, percent):
self.pay = int(self.pay *(1 + percent))
class Manager(Person):
def __init__(self, name, pay):
Person.__init__(self, name, 'mgr', pay)
def giveRaise(self, percent, bonus=.10):
Person.giveRaise(self, percent+bonus)
class Department:
def __init__(self, *args):
self.members = list(args)
def addMember(self, person):
self.members.append(person)
def giveRaise(self, percent):
for person in self.members:
person.giveRaise(percent)
def showAll(self):
for person in self.members:
print(person)
if __name__ == '__main__':
bob = Person('Bob Smith')
sue = Person('Sue Jones', job='dev', pay=100000)
tom = Manager('Tom Jones', pay=50000)
development = Department(bob, sue)
development.addMember(tom)
development.giveRaise(.10)
development.showAll()
| apache-2.0 |
jnerin/ansible | lib/ansible/modules/network/nxos/nxos_snmp_user.py | 7 | 9187 | #!/usr/bin/python
#
# 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': 'network'}
DOCUMENTATION = '''
---
module: nxos_snmp_user
extends_documentation_fragment: nxos
version_added: "2.2"
short_description: Manages SNMP users for monitoring.
description:
- Manages SNMP user configuration.
author:
- Jason Edelman (@jedelman8)
notes:
- Tested against NXOSv 7.3.(0)D1(1) on VIRL
- Authentication parameters not idempotent.
options:
user:
description:
- Name of the user.
required: true
group:
description:
- Group to which the user will belong to.
required: true
authentication:
description:
- Authentication parameters for the user.
required: false
default: null
choices: ['md5', 'sha']
pwd:
description:
- Authentication password when using md5 or sha.
required: false
default: null
privacy:
description:
- Privacy password for the user.
required: false
default: null
encrypt:
description:
- Enables AES-128 bit encryption when using privacy password.
required: false
default: null
choices: ['true','false']
state:
description:
- Manage the state of the resource.
required: false
default: present
choices: ['present','absent']
'''
EXAMPLES = '''
- nxos_snmp_user:
user: ntc
group: network-operator
authentication: md5
pwd: test_password
'''
RETURN = '''
commands:
description: commands sent to the device
returned: always
type: list
sample: ["snmp-server user ntc network-operator auth md5 test_password"]
'''
from ansible.module_utils.network.nxos.nxos import load_config, run_commands
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args
from ansible.module_utils.basic import AnsibleModule
def execute_show_command(command, module, text=False):
command = {
'command': command,
'output': 'json',
}
if text:
command['output'] = 'text'
return run_commands(module, command)
def flatten_list(command_lists):
flat_command_list = []
for command in command_lists:
if isinstance(command, list):
flat_command_list.extend(command)
else:
flat_command_list.append(command)
return flat_command_list
def get_snmp_groups(module):
data = execute_show_command('show snmp group', module)[0]
group_list = []
try:
group_table = data['TABLE_role']['ROW_role']
for group in group_table:
group_list.append(group['role_name'])
except (KeyError, AttributeError):
return group_list
return group_list
def get_snmp_user(user, module):
command = 'show snmp user {0}'.format(user)
body = execute_show_command(command, module, text=True)
if 'No such entry' not in body[0]:
body = execute_show_command(command, module)
resource = {}
try:
# The TABLE and ROW keys differ between NXOS platforms.
if body[0].get('TABLE_snmp_user'):
tablekey = 'TABLE_snmp_user'
rowkey = 'ROW_snmp_user'
tablegrpkey = 'TABLE_snmp_group_names'
rowgrpkey = 'ROW_snmp_group_names'
authkey = 'auth_protocol'
privkey = 'priv_protocol'
grpkey = 'group_names'
elif body[0].get('TABLE_snmp_users'):
tablekey = 'TABLE_snmp_users'
rowkey = 'ROW_snmp_users'
tablegrpkey = 'TABLE_groups'
rowgrpkey = 'ROW_groups'
authkey = 'auth'
privkey = 'priv'
grpkey = 'group'
resource_table = body[0][tablekey][rowkey]
resource['user'] = str(resource_table['user'])
resource['authentication'] = str(resource_table[authkey]).strip()
encrypt = str(resource_table[privkey]).strip()
if encrypt.startswith('aes'):
resource['encrypt'] = 'aes-128'
else:
resource['encrypt'] = 'none'
group_table = resource_table[tablegrpkey][rowgrpkey]
groups = []
try:
for group in group_table:
groups.append(str(group[grpkey]).strip())
except TypeError:
groups.append(str(group_table[grpkey]).strip())
resource['group'] = groups
except (KeyError, AttributeError, IndexError, TypeError):
return resource
return resource
def remove_snmp_user(user):
return ['no snmp-server user {0}'.format(user)]
def config_snmp_user(proposed, user, reset, new):
if reset and not new:
commands = remove_snmp_user(user)
else:
commands = []
group = proposed.get('group', None)
cmd = ''
if group:
cmd = 'snmp-server user {0} {group}'.format(user, **proposed)
auth = proposed.get('authentication', None)
pwd = proposed.get('pwd', None)
if auth and pwd:
cmd += ' auth {authentication} {pwd}'.format(**proposed)
encrypt = proposed.get('encrypt', None)
privacy = proposed.get('privacy', None)
if encrypt and privacy:
cmd += ' priv {encrypt} {privacy}'.format(**proposed)
elif privacy:
cmd += ' priv {privacy}'.format(**proposed)
if cmd:
commands.append(cmd)
return commands
def main():
argument_spec = dict(
user=dict(required=True, type='str'),
group=dict(type='str', required=True),
pwd=dict(type='str'),
privacy=dict(type='str'),
authentication=dict(choices=['md5', 'sha']),
encrypt=dict(type='bool'),
state=dict(choices=['absent', 'present'], default='present'),
)
argument_spec.update(nxos_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
required_together=[['authentication', 'pwd'],
['encrypt', 'privacy']],
supports_check_mode=True)
warnings = list()
check_args(module, warnings)
results = {'changed': False, 'commands': [], 'warnings': warnings}
user = module.params['user']
group = module.params['group']
pwd = module.params['pwd']
privacy = module.params['privacy']
encrypt = module.params['encrypt']
authentication = module.params['authentication']
state = module.params['state']
if privacy and encrypt:
if not pwd and authentication:
module.fail_json(msg='pwd and authentication must be provided '
'when using privacy and encrypt')
if group and group not in get_snmp_groups(module):
module.fail_json(msg='group not configured yet on switch.')
existing = get_snmp_user(user, module)
if existing:
if group not in existing['group']:
existing['group'] = None
else:
existing['group'] = group
commands = []
if state == 'absent' and existing:
commands.append(remove_snmp_user(user))
elif state == 'present':
new = False
reset = False
args = dict(user=user, pwd=pwd, group=group, privacy=privacy,
encrypt=encrypt, authentication=authentication)
proposed = dict((k, v) for k, v in args.items() if v is not None)
if not existing:
if encrypt:
proposed['encrypt'] = 'aes-128'
commands.append(config_snmp_user(proposed, user, reset, new))
elif existing:
if encrypt and not existing['encrypt'].startswith('aes'):
reset = True
proposed['encrypt'] = 'aes-128'
delta = dict(set(proposed.items()).difference(existing.items()))
if delta.get('pwd'):
delta['authentication'] = authentication
if delta:
delta['group'] = group
if delta and encrypt:
delta['encrypt'] = 'aes-128'
command = config_snmp_user(delta, user, reset, new)
commands.append(command)
cmds = flatten_list(commands)
if cmds:
results['changed'] = True
if not module.check_mode:
load_config(module, cmds)
if 'configure' in cmds:
cmds.pop(0)
results['commands'] = cmds
module.exit_json(**results)
if __name__ == '__main__':
main()
| gpl-3.0 |
cloudbase/neutron-virtualbox | neutron/plugins/sriovnicagent/sriov_nic_agent.py | 2 | 14544 | # Copyright 2014 Mellanox Technologies, Ltd
#
# 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.
import socket
import sys
import time
import eventlet
eventlet.monkey_patch()
from oslo_config import cfg
import oslo_messaging
from neutron.agent import rpc as agent_rpc
from neutron.agent import securitygroups_rpc as sg_rpc
from neutron.common import config as common_config
from neutron.common import constants as q_constants
from neutron.common import topics
from neutron.common import utils as q_utils
from neutron import context
from neutron.i18n import _LE, _LI
from neutron.openstack.common import log as logging
from neutron.openstack.common import loopingcall
from neutron.plugins.sriovnicagent.common import config # noqa
from neutron.plugins.sriovnicagent.common import exceptions as exc
from neutron.plugins.sriovnicagent import eswitch_manager as esm
LOG = logging.getLogger(__name__)
class SriovNicSwitchRpcCallbacks(sg_rpc.SecurityGroupAgentRpcCallbackMixin):
# Set RPC API version to 1.0 by default.
# history
# 1.1 Support Security Group RPC
target = oslo_messaging.Target(version='1.1')
def __init__(self, context, agent, sg_agent):
super(SriovNicSwitchRpcCallbacks, self).__init__()
self.context = context
self.agent = agent
self.sg_agent = sg_agent
def port_update(self, context, **kwargs):
LOG.debug("port_update received")
port = kwargs.get('port')
# Put the port mac address in the updated_devices set.
# Do not store port details, as if they're used for processing
# notifications there is no guarantee the notifications are
# processed in the same order as the relevant API requests.
self.agent.updated_devices.add(port['mac_address'])
LOG.debug("port_update RPC received for port: %s", port['id'])
class SriovNicSwitchAgent(object):
def __init__(self, physical_devices_mappings, exclude_devices,
polling_interval):
self.polling_interval = polling_interval
self.setup_eswitch_mgr(physical_devices_mappings,
exclude_devices)
configurations = {'device_mappings': physical_devices_mappings}
self.agent_state = {
'binary': 'neutron-sriov-nic-agent',
'host': cfg.CONF.host,
'topic': q_constants.L2_AGENT_TOPIC,
'configurations': configurations,
'agent_type': q_constants.AGENT_TYPE_NIC_SWITCH,
'start_flag': True}
# Stores port update notifications for processing in the main loop
self.updated_devices = set()
self.context = context.get_admin_context_without_session()
self.plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN)
self.sg_plugin_rpc = sg_rpc.SecurityGroupServerRpcApi(topics.PLUGIN)
self.sg_agent = sg_rpc.SecurityGroupAgentRpc(self.context,
self.sg_plugin_rpc)
self._setup_rpc()
# Initialize iteration counter
self.iter_num = 0
def _setup_rpc(self):
self.agent_id = 'nic-switch-agent.%s' % socket.gethostname()
LOG.info(_LI("RPC agent_id: %s"), self.agent_id)
self.topic = topics.AGENT
self.state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN)
# RPC network init
# Handle updates from service
self.endpoints = [SriovNicSwitchRpcCallbacks(self.context, self,
self.sg_agent)]
# Define the listening consumers for the agent
consumers = [[topics.PORT, topics.UPDATE],
[topics.NETWORK, topics.DELETE],
[topics.SECURITY_GROUP, topics.UPDATE]]
self.connection = agent_rpc.create_consumers(self.endpoints,
self.topic,
consumers)
report_interval = cfg.CONF.AGENT.report_interval
if report_interval:
heartbeat = loopingcall.FixedIntervalLoopingCall(
self._report_state)
heartbeat.start(interval=report_interval)
def _report_state(self):
try:
devices = len(self.eswitch_mgr.get_assigned_devices())
self.agent_state.get('configurations')['devices'] = devices
self.state_rpc.report_state(self.context,
self.agent_state)
self.agent_state.pop('start_flag', None)
except Exception:
LOG.exception(_LE("Failed reporting state!"))
def setup_eswitch_mgr(self, device_mappings, exclude_devices={}):
self.eswitch_mgr = esm.ESwitchManager(device_mappings, exclude_devices)
def scan_devices(self, registered_devices, updated_devices):
curr_devices = self.eswitch_mgr.get_assigned_devices()
device_info = {}
device_info['current'] = curr_devices
device_info['added'] = curr_devices - registered_devices
# we don't want to process updates for devices that don't exist
device_info['updated'] = updated_devices & curr_devices
# we need to clean up after devices are removed
device_info['removed'] = registered_devices - curr_devices
return device_info
def _device_info_has_changes(self, device_info):
return (device_info.get('added')
or device_info.get('updated')
or device_info.get('removed'))
def process_network_devices(self, device_info):
resync_a = False
resync_b = False
self.sg_agent.prepare_devices_filter(device_info.get('added'))
if device_info.get('updated'):
self.sg_agent.refresh_firewall()
# Updated devices are processed the same as new ones, as their
# admin_state_up may have changed. The set union prevents duplicating
# work when a device is new and updated in the same polling iteration.
devices_added_updated = (set(device_info.get('added'))
| set(device_info.get('updated')))
if devices_added_updated:
resync_a = self.treat_devices_added_updated(devices_added_updated)
if device_info.get('removed'):
resync_b = self.treat_devices_removed(device_info['removed'])
# If one of the above operations fails => resync with plugin
return (resync_a | resync_b)
def treat_device(self, device, pci_slot, admin_state_up):
if self.eswitch_mgr.device_exists(device, pci_slot):
try:
self.eswitch_mgr.set_device_state(device, pci_slot,
admin_state_up)
except exc.SriovNicError:
LOG.exception(_LE("Failed to set device %s state"), device)
return
if admin_state_up:
# update plugin about port status
self.plugin_rpc.update_device_up(self.context,
device,
self.agent_id,
cfg.CONF.host)
else:
self.plugin_rpc.update_device_down(self.context,
device,
self.agent_id,
cfg.CONF.host)
else:
LOG.info(_LI("No device with MAC %s defined on agent."), device)
def treat_devices_added_updated(self, devices):
try:
devices_details_list = self.plugin_rpc.get_devices_details_list(
self.context, devices, self.agent_id)
except Exception as e:
LOG.debug("Unable to get port details for devices "
"with MAC address %(devices)s: %(e)s",
{'devices': devices, 'e': e})
# resync is needed
return True
for device_details in devices_details_list:
device = device_details['device']
LOG.debug("Port with MAC address %s is added", device)
if 'port_id' in device_details:
LOG.info(_LI("Port %(device)s updated. Details: %(details)s"),
{'device': device, 'details': device_details})
profile = device_details['profile']
self.treat_device(device_details['device'],
profile.get('pci_slot'),
device_details['admin_state_up'])
else:
LOG.info(_LI("Device with MAC %s not defined on plugin"),
device)
return False
def treat_devices_removed(self, devices):
resync = False
for device in devices:
LOG.info(_LI("Removing device with mac_address %s"), device)
try:
dev_details = self.plugin_rpc.update_device_down(self.context,
device,
self.agent_id,
cfg.CONF.host)
except Exception as e:
LOG.debug("Removing port failed for device %(device)s "
"due to %(exc)s", {'device': device, 'exc': e})
resync = True
continue
if dev_details['exists']:
LOG.info(_LI("Port %s updated."), device)
else:
LOG.debug("Device %s not defined on plugin", device)
return resync
def daemon_loop(self):
sync = True
devices = set()
LOG.info(_LI("SRIOV NIC Agent RPC Daemon Started!"))
while True:
start = time.time()
LOG.debug("Agent rpc_loop - iteration:%d started",
self.iter_num)
if sync:
LOG.info(_LI("Agent out of sync with plugin!"))
devices.clear()
sync = False
device_info = {}
# Save updated devices dict to perform rollback in case
# resync would be needed, and then clear self.updated_devices.
# As the greenthread should not yield between these
# two statements, this will should be thread-safe.
updated_devices_copy = self.updated_devices
self.updated_devices = set()
try:
device_info = self.scan_devices(devices, updated_devices_copy)
if self._device_info_has_changes(device_info):
LOG.debug("Agent loop found changes! %s", device_info)
# If treat devices fails - indicates must resync with
# plugin
sync = self.process_network_devices(device_info)
devices = device_info['current']
except Exception:
LOG.exception(_LE("Error in agent loop. Devices info: %s"),
device_info)
sync = True
# Restore devices that were removed from this set earlier
# without overwriting ones that may have arrived since.
self.updated_devices |= updated_devices_copy
# sleep till end of polling interval
elapsed = (time.time() - start)
if (elapsed < self.polling_interval):
time.sleep(self.polling_interval - elapsed)
else:
LOG.debug("Loop iteration exceeded interval "
"(%(polling_interval)s vs. %(elapsed)s)!",
{'polling_interval': self.polling_interval,
'elapsed': elapsed})
self.iter_num = self.iter_num + 1
class SriovNicAgentConfigParser(object):
def __init__(self):
self.device_mappings = {}
self.exclude_devices = {}
def parse(self):
"""Parses device_mappings and exclude_devices.
Parse and validate the consistency in both mappings
"""
self.device_mappings = q_utils.parse_mappings(
cfg.CONF.SRIOV_NIC.physical_device_mappings)
self.exclude_devices = config.parse_exclude_devices(
cfg.CONF.SRIOV_NIC.exclude_devices)
self._validate()
def _validate(self):
"""Validate configuration.
Validate that network_device in excluded_device
exists in device mappings
"""
dev_net_set = set(self.device_mappings.itervalues())
for dev_name in self.exclude_devices.iterkeys():
if dev_name not in dev_net_set:
raise ValueError(_("Device name %(dev_name)s is missing from "
"physical_device_mappings") % {'dev_name':
dev_name})
def main():
common_config.init(sys.argv[1:])
common_config.setup_logging()
try:
config_parser = SriovNicAgentConfigParser()
config_parser.parse()
device_mappings = config_parser.device_mappings
exclude_devices = config_parser.exclude_devices
except ValueError:
LOG.exception(_LE("Failed on Agent configuration parse. "
"Agent terminated!"))
raise SystemExit(1)
LOG.info(_LI("Physical Devices mappings: %s"), device_mappings)
LOG.info(_LI("Exclude Devices: %s"), exclude_devices)
polling_interval = cfg.CONF.AGENT.polling_interval
try:
agent = SriovNicSwitchAgent(device_mappings,
exclude_devices,
polling_interval)
except exc.SriovNicError:
LOG.exception(_LE("Agent Initialization Failed"))
raise SystemExit(1)
# Start everything.
LOG.info(_LI("Agent initialized successfully, now running... "))
agent.daemon_loop()
if __name__ == '__main__':
main()
| apache-2.0 |
jeffrey4l/nova | nova/tests/functional/v3/test_admin_actions.py | 24 | 2623 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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 oslo_config import cfg
from nova.tests.functional.v3 import test_servers
CONF = cfg.CONF
CONF.import_opt('osapi_compute_extension',
'nova.api.openstack.compute.extensions')
class AdminActionsSamplesJsonTest(test_servers.ServersSampleBase):
extension_name = "os-admin-actions"
# TODO(gmann): Overriding '_api_version' till all functional tests
# are merged between v2 and v2.1. After that base class variable
# itself can be changed to 'v2'
_api_version = 'v2'
extra_extensions_to_load = ["os-access-ips"]
def _get_flags(self):
f = super(AdminActionsSamplesJsonTest, self)._get_flags()
f['osapi_compute_extension'] = CONF.osapi_compute_extension[:]
f['osapi_compute_extension'].append(
'nova.api.openstack.compute.contrib.admin_actions.Admin_actions')
return f
def setUp(self):
"""setUp Method for AdminActions api samples extension
This method creates the server that will be used in each tests
"""
super(AdminActionsSamplesJsonTest, self).setUp()
self.uuid = self._post_server()
def test_post_reset_network(self):
# Get api samples to reset server network request.
response = self._do_post('servers/%s/action' % self.uuid,
'admin-actions-reset-network', {})
self.assertEqual(response.status_code, 202)
def test_post_inject_network_info(self):
# Get api samples to inject network info request.
response = self._do_post('servers/%s/action' % self.uuid,
'admin-actions-inject-network-info', {})
self.assertEqual(response.status_code, 202)
def test_post_reset_state(self):
# get api samples to server reset state request.
response = self._do_post('servers/%s/action' % self.uuid,
'admin-actions-reset-server-state', {})
self.assertEqual(response.status_code, 202)
| apache-2.0 |
isyippee/nova | nova/tests/unit/api/openstack/compute/test_floating_ips.py | 14 | 38097 | # Copyright (c) 2011 X.commerce, a business unit of eBay Inc.
# Copyright 2011 Eldar Nugaev
# 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.
import contextlib
import uuid
import mock
import six
import webob
from nova.api.openstack.compute import floating_ips as fips_v21
from nova.api.openstack.compute.legacy_v2.contrib import floating_ips \
as fips_v2
from nova.api.openstack import extensions
from nova import compute
from nova.compute import utils as compute_utils
from nova import context
from nova import db
from nova import exception
from nova import network
from nova import objects
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_network
FAKE_UUID = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'
TEST_INST = 1
WRONG_INST = 9999
def network_api_get_floating_ip(self, context, id):
return {'id': 1, 'address': '10.10.10.10', 'pool': 'nova',
'fixed_ip_id': None}
def network_api_get_floating_ip_by_address(self, context, address):
return {'id': 1, 'address': '10.10.10.10', 'pool': 'nova',
'fixed_ip_id': 10}
def network_api_get_floating_ips_by_project(self, context):
return [{'id': 1,
'address': '10.10.10.10',
'pool': 'nova',
'fixed_ip': {'address': '10.0.0.1',
'instance_uuid': FAKE_UUID,
'instance': objects.Instance(
**{'uuid': FAKE_UUID})}},
{'id': 2,
'pool': 'nova', 'interface': 'eth0',
'address': '10.10.10.11',
'fixed_ip': None}]
def compute_api_get(self, context, instance_id, expected_attrs=None,
want_objects=False):
return objects.Instance(uuid=FAKE_UUID, id=instance_id,
instance_type_id=1, host='bob')
def network_api_allocate(self, context):
return '10.10.10.10'
def network_api_release(self, context, address):
pass
def compute_api_associate(self, context, instance_id, address):
pass
def network_api_associate(self, context, floating_address, fixed_address):
pass
def network_api_disassociate(self, context, instance, floating_address):
pass
def fake_instance_get(context, instance_id):
return objects.Instance(**{
"id": 1,
"uuid": uuid.uuid4(),
"name": 'fake',
"user_id": 'fakeuser',
"project_id": '123'})
def stub_nw_info(stubs):
def get_nw_info_for_instance(instance):
return fake_network.fake_get_instance_nw_info(stubs)
return get_nw_info_for_instance
def get_instance_by_floating_ip_addr(self, context, address):
return None
class FloatingIpTestNeutronV21(test.NoDBTestCase):
floating_ips = fips_v21
def setUp(self):
super(FloatingIpTestNeutronV21, self).setUp()
self.flags(network_api_class='nova.network.neutronv2.api.API')
self.controller = self.floating_ips.FloatingIPController()
def test_floatingip_delete(self):
req = fakes.HTTPRequest.blank('')
fip_val = {'address': '1.1.1.1', 'fixed_ip_id': '192.168.1.2'}
with contextlib.nested(
mock.patch.object(self.controller.network_api,
'disassociate_floating_ip'),
mock.patch.object(self.controller.network_api,
'disassociate_and_release_floating_ip'),
mock.patch.object(self.controller.network_api,
'release_floating_ip'),
mock.patch.object(self.controller.network_api,
'get_instance_id_by_floating_address',
return_value=None),
mock.patch.object(self.controller.network_api,
'get_floating_ip',
return_value=fip_val)) as (
disoc_fip, dis_and_del, rel_fip, _, _):
self.controller.delete(req, 1)
self.assertFalse(disoc_fip.called)
self.assertFalse(rel_fip.called)
# Only disassociate_and_release_floating_ip is
# called if using neutron
self.assertTrue(dis_and_del.called)
def _test_floatingip_delete_not_found(self, ex,
expect_ex=webob.exc.HTTPNotFound):
req = fakes.HTTPRequest.blank('')
with contextlib.nested(
mock.patch.object(self.controller.network_api,
'get_floating_ip',
side_effect=ex)
):
self.assertRaises(expect_ex,
self.controller.delete, req, 1)
def test_floatingip_delete_not_found_ip(self):
ex = exception.FloatingIpNotFound(id=1)
self._test_floatingip_delete_not_found(ex)
def test_floatingip_delete_not_found(self):
ex = exception.NotFound
self._test_floatingip_delete_not_found(ex)
def test_floatingip_delete_invalid_id(self):
ex = exception.InvalidID(id=1)
self._test_floatingip_delete_not_found(ex, webob.exc.HTTPBadRequest)
class FloatingIpTestNeutronV2(FloatingIpTestNeutronV21):
floating_ips = fips_v2
def test_floatingip_delete_invalid_id(self):
ex = exception.InvalidID(id=1)
self._test_floatingip_delete_not_found(ex, webob.exc.HTTPNotFound)
class FloatingIpTestV21(test.TestCase):
floating_ip = "10.10.10.10"
floating_ip_2 = "10.10.10.11"
floating_ips = fips_v21
validation_error = exception.ValidationError
def _create_floating_ips(self, floating_ips=None):
"""Create a floating ip object."""
if floating_ips is None:
floating_ips = [self.floating_ip]
elif not isinstance(floating_ips, (list, tuple)):
floating_ips = [floating_ips]
def make_ip_dict(ip):
"""Shortcut for creating floating ip dict."""
return
dict_ = {'pool': 'nova', 'host': 'fake_host'}
return db.floating_ip_bulk_create(
self.context, [dict(address=ip, **dict_) for ip in floating_ips],
)
def _delete_floating_ip(self):
db.floating_ip_destroy(self.context, self.floating_ip)
def setUp(self):
super(FloatingIpTestV21, self).setUp()
self.stubs.Set(compute.api.API, "get",
compute_api_get)
self.stubs.Set(network.api.API, "get_floating_ip",
network_api_get_floating_ip)
self.stubs.Set(network.api.API, "get_floating_ip_by_address",
network_api_get_floating_ip_by_address)
self.stubs.Set(network.api.API, "get_floating_ips_by_project",
network_api_get_floating_ips_by_project)
self.stubs.Set(network.api.API, "release_floating_ip",
network_api_release)
self.stubs.Set(network.api.API, "disassociate_floating_ip",
network_api_disassociate)
self.stubs.Set(network.api.API, "get_instance_id_by_floating_address",
get_instance_by_floating_ip_addr)
self.stubs.Set(compute_utils, "get_nw_info_for_instance",
stub_nw_info(self.stubs))
fake_network.stub_out_nw_api_get_instance_nw_info(self.stubs)
self.stubs.Set(db, 'instance_get',
fake_instance_get)
self.context = context.get_admin_context()
self._create_floating_ips()
self.ext_mgr = extensions.ExtensionManager()
self.ext_mgr.extensions = {}
self.controller = self.floating_ips.FloatingIPController()
self.manager = self.floating_ips.\
FloatingIPActionController(self.ext_mgr)
self.fake_req = fakes.HTTPRequest.blank('')
def tearDown(self):
self._delete_floating_ip()
super(FloatingIpTestV21, self).tearDown()
def test_floatingip_delete(self):
fip_val = {'address': '1.1.1.1', 'fixed_ip_id': '192.168.1.2'}
with contextlib.nested(
mock.patch.object(self.controller.network_api,
'disassociate_floating_ip'),
mock.patch.object(self.controller.network_api,
'release_floating_ip'),
mock.patch.object(self.controller.network_api,
'get_instance_id_by_floating_address',
return_value=None),
mock.patch.object(self.controller.network_api,
'get_floating_ip',
return_value=fip_val)) as (
disoc_fip, rel_fip, _, _):
self.controller.delete(self.fake_req, 1)
self.assertTrue(disoc_fip.called)
self.assertTrue(rel_fip.called)
def _test_floatingip_delete_not_found(self, ex,
expect_ex=webob.exc.HTTPNotFound):
with contextlib.nested(
mock.patch.object(self.controller.network_api,
'get_floating_ip',
side_effect=ex)
):
self.assertRaises(expect_ex,
self.controller.delete, self.fake_req, 1)
def test_floatingip_delete_not_found_ip(self):
ex = exception.FloatingIpNotFound(id=1)
self._test_floatingip_delete_not_found(ex)
def test_floatingip_delete_not_found(self):
ex = exception.NotFound
self._test_floatingip_delete_not_found(ex)
def test_floatingip_delete_invalid_id(self):
ex = exception.InvalidID(id=1)
self._test_floatingip_delete_not_found(ex, webob.exc.HTTPBadRequest)
def test_translate_floating_ip_view(self):
floating_ip_address = self.floating_ip
floating_ip = db.floating_ip_get_by_address(self.context,
floating_ip_address)
# NOTE(vish): network_get uses the id not the address
floating_ip = db.floating_ip_get(self.context, floating_ip['id'])
view = self.floating_ips._translate_floating_ip_view(floating_ip)
self.assertIn('floating_ip', view)
self.assertTrue(view['floating_ip']['id'])
self.assertEqual(view['floating_ip']['ip'], self.floating_ip)
self.assertIsNone(view['floating_ip']['fixed_ip'])
self.assertIsNone(view['floating_ip']['instance_id'])
def test_translate_floating_ip_view_dict(self):
floating_ip = {'id': 0, 'address': '10.0.0.10', 'pool': 'nova',
'fixed_ip': None}
view = self.floating_ips._translate_floating_ip_view(floating_ip)
self.assertIn('floating_ip', view)
def test_floating_ips_list(self):
res_dict = self.controller.index(self.fake_req)
response = {'floating_ips': [{'instance_id': FAKE_UUID,
'ip': '10.10.10.10',
'pool': 'nova',
'fixed_ip': '10.0.0.1',
'id': 1},
{'instance_id': None,
'ip': '10.10.10.11',
'pool': 'nova',
'fixed_ip': None,
'id': 2}]}
self.assertEqual(res_dict, response)
def test_floating_ip_release_nonexisting(self):
def fake_get_floating_ip(*args, **kwargs):
raise exception.FloatingIpNotFound(id=id)
self.stubs.Set(network.api.API, "get_floating_ip",
fake_get_floating_ip)
ex = self.assertRaises(webob.exc.HTTPNotFound,
self.controller.delete, self.fake_req, '9876')
self.assertIn("Floating ip not found for id 9876", ex.explanation)
def test_floating_ip_release_race_cond(self):
def fake_get_floating_ip(*args, **kwargs):
return {'fixed_ip_id': 1, 'address': self.floating_ip}
def fake_get_instance_by_floating_ip_addr(*args, **kwargs):
return 'test-inst'
def fake_disassociate_floating_ip(*args, **kwargs):
raise exception.FloatingIpNotAssociated(args[3])
self.stubs.Set(network.api.API, "get_floating_ip",
fake_get_floating_ip)
self.stubs.Set(self.floating_ips, "get_instance_by_floating_ip_addr",
fake_get_instance_by_floating_ip_addr)
self.stubs.Set(self.floating_ips, "disassociate_floating_ip",
fake_disassociate_floating_ip)
res = self.controller.delete(self.fake_req, '9876')
# NOTE: on v2.1, http status code is set as wsgi_code of API
# method instead of status_int in a response object.
if isinstance(self.controller,
fips_v21.FloatingIPController):
status_int = self.controller.delete.wsgi_code
else:
status_int = res.status_int
self.assertEqual(status_int, 202)
def test_floating_ip_show(self):
res_dict = self.controller.show(self.fake_req, 1)
self.assertEqual(res_dict['floating_ip']['id'], 1)
self.assertEqual(res_dict['floating_ip']['ip'], '10.10.10.10')
self.assertIsNone(res_dict['floating_ip']['instance_id'])
def test_floating_ip_show_not_found(self):
def fake_get_floating_ip(*args, **kwargs):
raise exception.FloatingIpNotFound(id='fake')
self.stubs.Set(network.api.API, "get_floating_ip",
fake_get_floating_ip)
ex = self.assertRaises(webob.exc.HTTPNotFound,
self.controller.show, self.fake_req, '9876')
self.assertIn("Floating ip not found for id 9876", ex.explanation)
def test_show_associated_floating_ip(self):
def get_floating_ip(self, context, id):
return {'id': 1, 'address': '10.10.10.10', 'pool': 'nova',
'fixed_ip': {'address': '10.0.0.1',
'instance_uuid': FAKE_UUID,
'instance': {'uuid': FAKE_UUID}}}
self.stubs.Set(network.api.API, "get_floating_ip", get_floating_ip)
res_dict = self.controller.show(self.fake_req, 1)
self.assertEqual(res_dict['floating_ip']['id'], 1)
self.assertEqual(res_dict['floating_ip']['ip'], '10.10.10.10')
self.assertEqual(res_dict['floating_ip']['fixed_ip'], '10.0.0.1')
self.assertEqual(res_dict['floating_ip']['instance_id'], FAKE_UUID)
def test_recreation_of_floating_ip(self):
self._delete_floating_ip()
self._create_floating_ips()
def test_floating_ip_in_bulk_creation(self):
self._delete_floating_ip()
self._create_floating_ips([self.floating_ip, self.floating_ip_2])
all_ips = db.floating_ip_get_all(self.context)
ip_list = [ip['address'] for ip in all_ips]
self.assertIn(self.floating_ip, ip_list)
self.assertIn(self.floating_ip_2, ip_list)
def test_fail_floating_ip_in_bulk_creation(self):
self.assertRaises(exception.FloatingIpExists,
self._create_floating_ips,
[self.floating_ip, self.floating_ip_2])
all_ips = db.floating_ip_get_all(self.context)
ip_list = [ip['address'] for ip in all_ips]
self.assertIn(self.floating_ip, ip_list)
self.assertNotIn(self.floating_ip_2, ip_list)
def test_floating_ip_allocate_no_free_ips(self):
def fake_allocate(*args, **kwargs):
raise exception.NoMoreFloatingIps()
self.stubs.Set(network.api.API, "allocate_floating_ip", fake_allocate)
ex = self.assertRaises(webob.exc.HTTPNotFound,
self.controller.create, self.fake_req)
self.assertIn('No more floating ips', ex.explanation)
def test_floating_ip_allocate_no_free_ips_pool(self):
def fake_allocate(*args, **kwargs):
raise exception.NoMoreFloatingIps()
self.stubs.Set(network.api.API, "allocate_floating_ip", fake_allocate)
ex = self.assertRaises(webob.exc.HTTPNotFound,
self.controller.create, self.fake_req,
{'pool': 'non_existent_pool'})
self.assertIn('No more floating ips in pool non_existent_pool',
ex.explanation)
@mock.patch.object(network.api.API, 'allocate_floating_ip',
side_effect=exception.FloatingIpBadRequest(
'Bad floatingip request: Network '
'c8f0e88f-ae41-47cb-be6c-d8256ba80576 does not contain any '
'IPv4 subnet'))
def test_floating_ip_allocate_no_ipv4_subnet(self, allocate_mock):
ex = self.assertRaises(webob.exc.HTTPBadRequest,
self.controller.create, self.fake_req,
{'pool': 'non_existent_pool'})
self.assertIn("does not contain any IPv4 subnet",
six.text_type(ex))
@mock.patch('nova.network.api.API.allocate_floating_ip',
side_effect=exception.FloatingIpLimitExceeded())
def test_floating_ip_allocate_over_quota(self, allocate_mock):
ex = self.assertRaises(webob.exc.HTTPForbidden,
self.controller.create, self.fake_req)
self.assertIn('IP allocation over quota', ex.explanation)
@mock.patch('nova.network.api.API.allocate_floating_ip',
side_effect=exception.FloatingIpLimitExceeded())
def test_floating_ip_allocate_quota_exceed_in_pool(self, allocate_mock):
ex = self.assertRaises(webob.exc.HTTPForbidden,
self.controller.create, self.fake_req,
{'pool': 'non_existent_pool'})
self.assertIn('IP allocation over quota in pool non_existent_pool.',
ex.explanation)
@mock.patch('nova.network.api.API.allocate_floating_ip',
side_effect=exception.FloatingIpPoolNotFound())
def test_floating_ip_create_with_unknown_pool(self, allocate_mock):
ex = self.assertRaises(webob.exc.HTTPNotFound,
self.controller.create, self.fake_req,
{'pool': 'non_existent_pool'})
self.assertIn('Floating ip pool not found.', ex.explanation)
def test_floating_ip_allocate(self):
def fake1(*args, **kwargs):
pass
def fake2(*args, **kwargs):
return {'id': 1, 'address': '10.10.10.10', 'pool': 'nova'}
self.stubs.Set(network.api.API, "allocate_floating_ip",
fake1)
self.stubs.Set(network.api.API, "get_floating_ip_by_address",
fake2)
res_dict = self.controller.create(self.fake_req)
ip = res_dict['floating_ip']
expected = {
"id": 1,
"instance_id": None,
"ip": "10.10.10.10",
"fixed_ip": None,
"pool": 'nova'}
self.assertEqual(ip, expected)
def test_floating_ip_release(self):
self.controller.delete(self.fake_req, 1)
def _test_floating_ip_associate(self, fixed_address):
def fake_associate_floating_ip(*args, **kwargs):
self.assertEqual(fixed_address, kwargs['fixed_address'])
self.stubs.Set(network.api.API, "associate_floating_ip",
fake_associate_floating_ip)
body = dict(addFloatingIp=dict(address=self.floating_ip))
rsp = self.manager._add_floating_ip(self.fake_req, TEST_INST,
body=body)
self.assertEqual(202, rsp.status_int)
def test_floating_ip_associate(self):
self._test_floating_ip_associate(fixed_address='192.168.1.100')
@mock.patch.object(network.model.NetworkInfo, 'fixed_ips')
def test_associate_floating_ip_v4v6_fixed_ip(self, fixed_ips_mock):
fixed_address = '192.168.1.100'
fixed_ips_mock.return_value = [{'address': 'fc00:2001:db8::100'},
{'address': fixed_address}]
self._test_floating_ip_associate(fixed_address=fixed_address)
@mock.patch.object(network.model.NetworkInfo, 'fixed_ips',
return_value=[{'address': 'fc00:2001:db8::100'}])
def test_associate_floating_ip_v6_fixed_ip(self, fixed_ips_mock):
body = dict(addFloatingIp=dict(address=self.floating_ip))
self.assertRaises(webob.exc.HTTPBadRequest,
self.manager._add_floating_ip, self.fake_req,
TEST_INST, body=body)
def test_floating_ip_associate_invalid_instance(self):
def fake_get(self, context, id, expected_attrs=None,
want_objects=False):
raise exception.InstanceNotFound(instance_id=id)
self.stubs.Set(compute.api.API, "get", fake_get)
body = dict(addFloatingIp=dict(address=self.floating_ip))
self.assertRaises(webob.exc.HTTPNotFound,
self.manager._add_floating_ip, self.fake_req,
'test_inst', body=body)
def test_associate_not_allocated_floating_ip_to_instance(self):
def fake_associate_floating_ip(self, context, instance,
floating_address, fixed_address,
affect_auto_assigned=False):
raise exception.FloatingIpNotFoundForAddress(
address=floating_address)
self.stubs.Set(network.api.API, "associate_floating_ip",
fake_associate_floating_ip)
floating_ip = '10.10.10.11'
body = dict(addFloatingIp=dict(address=floating_ip))
ex = self.assertRaises(webob.exc.HTTPNotFound,
self.manager._add_floating_ip,
self.fake_req, TEST_INST, body=body)
self.assertIn("floating ip not found", ex.explanation)
@mock.patch.object(network.api.API, 'associate_floating_ip',
side_effect=exception.Forbidden)
def test_associate_floating_ip_forbidden(self, associate_mock):
body = dict(addFloatingIp=dict(address='10.10.10.11'))
self.assertRaises(webob.exc.HTTPForbidden,
self.manager._add_floating_ip, self.fake_req,
TEST_INST, body=body)
def test_associate_floating_ip_bad_address_key(self):
body = dict(addFloatingIp=dict(bad_address='10.10.10.11'))
req = fakes.HTTPRequest.blank('/v2/fake/servers/test_inst/action')
self.assertRaises(self.validation_error,
self.manager._add_floating_ip, req, 'test_inst',
body=body)
def test_associate_floating_ip_bad_addfloatingip_key(self):
body = dict(bad_addFloatingIp=dict(address='10.10.10.11'))
req = fakes.HTTPRequest.blank('/v2/fake/servers/test_inst/action')
self.assertRaises(self.validation_error,
self.manager._add_floating_ip, req, 'test_inst',
body=body)
def test_floating_ip_disassociate(self):
def get_instance_by_floating_ip_addr(self, context, address):
if address == '10.10.10.10':
return TEST_INST
self.stubs.Set(network.api.API, "get_instance_id_by_floating_address",
get_instance_by_floating_ip_addr)
body = dict(removeFloatingIp=dict(address='10.10.10.10'))
rsp = self.manager._remove_floating_ip(self.fake_req, TEST_INST,
body=body)
self.assertEqual(202, rsp.status_int)
def test_floating_ip_disassociate_missing(self):
body = dict(removeFloatingIp=dict(address='10.10.10.10'))
self.assertRaises(webob.exc.HTTPConflict,
self.manager._remove_floating_ip,
self.fake_req, 'test_inst', body=body)
def test_floating_ip_associate_non_existent_ip(self):
def fake_network_api_associate(self, context, instance,
floating_address=None,
fixed_address=None):
floating_ips = ["10.10.10.10", "10.10.10.11"]
if floating_address not in floating_ips:
raise exception.FloatingIpNotFoundForAddress(
address=floating_address)
self.stubs.Set(network.api.API, "associate_floating_ip",
fake_network_api_associate)
body = dict(addFloatingIp=dict(address='1.1.1.1'))
self.assertRaises(webob.exc.HTTPNotFound,
self.manager._add_floating_ip,
self.fake_req, TEST_INST, body=body)
def test_floating_ip_disassociate_non_existent_ip(self):
def network_api_get_floating_ip_by_address(self, context,
floating_address):
floating_ips = ["10.10.10.10", "10.10.10.11"]
if floating_address not in floating_ips:
raise exception.FloatingIpNotFoundForAddress(
address=floating_address)
self.stubs.Set(network.api.API, "get_floating_ip_by_address",
network_api_get_floating_ip_by_address)
body = dict(removeFloatingIp=dict(address='1.1.1.1'))
self.assertRaises(webob.exc.HTTPNotFound,
self.manager._remove_floating_ip,
self.fake_req, TEST_INST, body=body)
def test_floating_ip_disassociate_wrong_instance_uuid(self):
def get_instance_by_floating_ip_addr(self, context, address):
if address == '10.10.10.10':
return TEST_INST
self.stubs.Set(network.api.API, "get_instance_id_by_floating_address",
get_instance_by_floating_ip_addr)
wrong_uuid = 'aaaaaaaa-ffff-ffff-ffff-aaaaaaaaaaaa'
body = dict(removeFloatingIp=dict(address='10.10.10.10'))
self.assertRaises(webob.exc.HTTPConflict,
self.manager._remove_floating_ip,
self.fake_req, wrong_uuid, body=body)
def test_floating_ip_disassociate_wrong_instance_id(self):
def get_instance_by_floating_ip_addr(self, context, address):
if address == '10.10.10.10':
return WRONG_INST
self.stubs.Set(network.api.API, "get_instance_id_by_floating_address",
get_instance_by_floating_ip_addr)
body = dict(removeFloatingIp=dict(address='10.10.10.10'))
self.assertRaises(webob.exc.HTTPConflict,
self.manager._remove_floating_ip,
self.fake_req, TEST_INST, body=body)
def test_floating_ip_disassociate_auto_assigned(self):
def fake_get_floating_ip_addr_auto_assigned(self, context, address):
return {'id': 1, 'address': '10.10.10.10', 'pool': 'nova',
'fixed_ip_id': 10, 'auto_assigned': 1}
def get_instance_by_floating_ip_addr(self, context, address):
if address == '10.10.10.10':
return TEST_INST
def network_api_disassociate(self, context, instance,
floating_address):
raise exception.CannotDisassociateAutoAssignedFloatingIP()
self.stubs.Set(network.api.API, "get_floating_ip_by_address",
fake_get_floating_ip_addr_auto_assigned)
self.stubs.Set(network.api.API, "get_instance_id_by_floating_address",
get_instance_by_floating_ip_addr)
self.stubs.Set(network.api.API, "disassociate_floating_ip",
network_api_disassociate)
body = dict(removeFloatingIp=dict(address='10.10.10.10'))
self.assertRaises(webob.exc.HTTPForbidden,
self.manager._remove_floating_ip,
self.fake_req, TEST_INST, body=body)
def test_floating_ip_disassociate_map_authorization_exc(self):
def fake_get_floating_ip_addr_auto_assigned(self, context, address):
return {'id': 1, 'address': '10.10.10.10', 'pool': 'nova',
'fixed_ip_id': 10, 'auto_assigned': 1}
def get_instance_by_floating_ip_addr(self, context, address):
if address == '10.10.10.10':
return TEST_INST
def network_api_disassociate(self, context, instance, address):
raise exception.Forbidden()
self.stubs.Set(network.api.API, "get_floating_ip_by_address",
fake_get_floating_ip_addr_auto_assigned)
self.stubs.Set(network.api.API, "get_instance_id_by_floating_address",
get_instance_by_floating_ip_addr)
self.stubs.Set(network.api.API, "disassociate_floating_ip",
network_api_disassociate)
body = dict(removeFloatingIp=dict(address='10.10.10.10'))
self.assertRaises(webob.exc.HTTPForbidden,
self.manager._remove_floating_ip,
self.fake_req, TEST_INST, body=body)
# these are a few bad param tests
def test_bad_address_param_in_remove_floating_ip(self):
body = dict(removeFloatingIp=dict(badparam='11.0.0.1'))
self.assertRaises(self.validation_error,
self.manager._remove_floating_ip, self.fake_req,
TEST_INST, body=body)
def test_missing_dict_param_in_remove_floating_ip(self):
body = dict(removeFloatingIp='11.0.0.1')
self.assertRaises(self.validation_error,
self.manager._remove_floating_ip, self.fake_req,
TEST_INST, body=body)
def test_missing_dict_param_in_add_floating_ip(self):
body = dict(addFloatingIp='11.0.0.1')
self.assertRaises(self.validation_error,
self.manager._add_floating_ip, self.fake_req,
TEST_INST, body=body)
class FloatingIpTestV2(FloatingIpTestV21):
floating_ips = fips_v2
validation_error = webob.exc.HTTPBadRequest
def test_not_extended_floating_ip_associate_fixed(self):
# Check that fixed_address is ignored if os-extended-floating-ips
# is not loaded
fixed_address_requested = '192.168.1.101'
fixed_address_allocated = '192.168.1.100'
def fake_associate_floating_ip(*args, **kwargs):
self.assertEqual(fixed_address_allocated,
kwargs['fixed_address'])
self.stubs.Set(network.api.API, "associate_floating_ip",
fake_associate_floating_ip)
body = dict(addFloatingIp=dict(address=self.floating_ip,
fixed_address=fixed_address_requested))
rsp = self.manager._add_floating_ip(self.fake_req, TEST_INST, body)
self.assertEqual(202, rsp.status_int)
def test_floatingip_delete_invalid_id(self):
ex = exception.InvalidID(id=1)
self._test_floatingip_delete_not_found(ex, webob.exc.HTTPNotFound)
class ExtendedFloatingIpTestV21(test.TestCase):
floating_ip = "10.10.10.10"
floating_ip_2 = "10.10.10.11"
floating_ips = fips_v21
def _create_floating_ips(self, floating_ips=None):
"""Create a floating ip object."""
if floating_ips is None:
floating_ips = [self.floating_ip]
elif not isinstance(floating_ips, (list, tuple)):
floating_ips = [floating_ips]
dict_ = {'pool': 'nova', 'host': 'fake_host'}
return db.floating_ip_bulk_create(
self.context, [dict(address=ip, **dict_) for ip in floating_ips],
)
def _delete_floating_ip(self):
db.floating_ip_destroy(self.context, self.floating_ip)
def setUp(self):
super(ExtendedFloatingIpTestV21, self).setUp()
self.stubs.Set(compute.api.API, "get",
compute_api_get)
self.stubs.Set(network.api.API, "get_floating_ip",
network_api_get_floating_ip)
self.stubs.Set(network.api.API, "get_floating_ip_by_address",
network_api_get_floating_ip_by_address)
self.stubs.Set(network.api.API, "get_floating_ips_by_project",
network_api_get_floating_ips_by_project)
self.stubs.Set(network.api.API, "release_floating_ip",
network_api_release)
self.stubs.Set(network.api.API, "disassociate_floating_ip",
network_api_disassociate)
self.stubs.Set(network.api.API, "get_instance_id_by_floating_address",
get_instance_by_floating_ip_addr)
self.stubs.Set(compute_utils, "get_nw_info_for_instance",
stub_nw_info(self.stubs))
fake_network.stub_out_nw_api_get_instance_nw_info(self.stubs)
self.stubs.Set(db, 'instance_get',
fake_instance_get)
self.context = context.get_admin_context()
self._create_floating_ips()
self.ext_mgr = extensions.ExtensionManager()
self.ext_mgr.extensions = {}
self.ext_mgr.extensions['os-floating-ips'] = True
self.ext_mgr.extensions['os-extended-floating-ips'] = True
self.controller = self.floating_ips.FloatingIPController()
self.manager = self.floating_ips.\
FloatingIPActionController(self.ext_mgr)
self.fake_req = fakes.HTTPRequest.blank('')
def tearDown(self):
self._delete_floating_ip()
super(ExtendedFloatingIpTestV21, self).tearDown()
def test_extended_floating_ip_associate_fixed(self):
fixed_address = '192.168.1.101'
def fake_associate_floating_ip(*args, **kwargs):
self.assertEqual(fixed_address, kwargs['fixed_address'])
self.stubs.Set(network.api.API, "associate_floating_ip",
fake_associate_floating_ip)
body = dict(addFloatingIp=dict(address=self.floating_ip,
fixed_address=fixed_address))
rsp = self.manager._add_floating_ip(self.fake_req, TEST_INST,
body=body)
self.assertEqual(202, rsp.status_int)
def test_extended_floating_ip_associate_fixed_not_allocated(self):
def fake_associate_floating_ip(*args, **kwargs):
pass
self.stubs.Set(network.api.API, "associate_floating_ip",
fake_associate_floating_ip)
body = dict(addFloatingIp=dict(address=self.floating_ip,
fixed_address='11.11.11.11'))
ex = self.assertRaises(webob.exc.HTTPBadRequest,
self.manager._add_floating_ip,
self.fake_req, TEST_INST, body=body)
self.assertIn("Specified fixed address not assigned to instance",
ex.explanation)
class ExtendedFloatingIpTestV2(ExtendedFloatingIpTestV21):
floating_ips = fips_v2
class FloatingIPPolicyEnforcementV21(test.NoDBTestCase):
def setUp(self):
super(FloatingIPPolicyEnforcementV21, self).setUp()
self.controller = fips_v21.FloatingIPController()
self.req = fakes.HTTPRequest.blank('')
def _common_policy_check(self, func, *arg, **kwarg):
rule_name = "os_compute_api:os-floating-ips"
rule = {rule_name: "project:non_fake"}
self.policy.set_rules(rule)
exc = self.assertRaises(
exception.PolicyNotAuthorized, func, *arg, **kwarg)
self.assertEqual(
"Policy doesn't allow %s to be performed." % rule_name,
exc.format_message())
def test_index_policy_failed(self):
self._common_policy_check(self.controller.index, self.req)
def test_show_policy_failed(self):
self._common_policy_check(self.controller.show, self.req, FAKE_UUID)
def test_create_policy_failed(self):
self._common_policy_check(self.controller.create, self.req)
def test_delete_policy_failed(self):
self._common_policy_check(self.controller.delete, self.req, FAKE_UUID)
class FloatingIPActionPolicyEnforcementV21(test.NoDBTestCase):
def setUp(self):
super(FloatingIPActionPolicyEnforcementV21, self).setUp()
self.controller = fips_v21.FloatingIPActionController()
self.req = fakes.HTTPRequest.blank('')
def _common_policy_check(self, func, *arg, **kwarg):
rule_name = "os_compute_api:os-floating-ips"
rule = {rule_name: "project:non_fake"}
self.policy.set_rules(rule)
exc = self.assertRaises(
exception.PolicyNotAuthorized, func, *arg, **kwarg)
self.assertEqual(
"Policy doesn't allow %s to be performed." % rule_name,
exc.format_message())
def test_add_policy_failed(self):
body = dict(addFloatingIp=dict(address='10.10.10.11'))
self._common_policy_check(
self.controller._add_floating_ip, self.req, FAKE_UUID, body=body)
def test_remove_policy_failed(self):
body = dict(removeFloatingIp=dict(address='10.10.10.10'))
self._common_policy_check(
self.controller._remove_floating_ip, self.req,
FAKE_UUID, body=body)
| apache-2.0 |
chugunovyar/factoryForBuild | env/lib/python2.7/site-packages/scipy/linalg/blas.py | 37 | 6855 | """
Low-level BLAS functions (:mod:`scipy.linalg.blas`)
===================================================
This module contains low-level functions from the BLAS library.
.. versionadded:: 0.12.0
.. warning::
These functions do little to no error checking.
It is possible to cause crashes by mis-using them,
so prefer using the higher-level routines in `scipy.linalg`.
Finding functions
-----------------
.. autosummary::
:toctree: generated/
get_blas_funcs
find_best_blas_type
BLAS Level 1 functions
----------------------
.. autosummary::
:toctree: generated/
caxpy
ccopy
cdotc
cdotu
crotg
cscal
csrot
csscal
cswap
dasum
daxpy
dcopy
ddot
dnrm2
drot
drotg
drotm
drotmg
dscal
dswap
dzasum
dznrm2
icamax
idamax
isamax
izamax
sasum
saxpy
scasum
scnrm2
scopy
sdot
snrm2
srot
srotg
srotm
srotmg
sscal
sswap
zaxpy
zcopy
zdotc
zdotu
zdrot
zdscal
zrotg
zscal
zswap
BLAS Level 2 functions
----------------------
.. autosummary::
:toctree: generated/
cgemv
cgerc
cgeru
chemv
ctrmv
csyr
cher
cher2
dgemv
dger
dsymv
dtrmv
dsyr
dsyr2
sgemv
sger
ssymv
strmv
ssyr
ssyr2
zgemv
zgerc
zgeru
zhemv
ztrmv
zsyr
zher
zher2
BLAS Level 3 functions
----------------------
.. autosummary::
:toctree: generated/
cgemm
chemm
cherk
cher2k
csymm
csyrk
csyr2k
dgemm
dsymm
dsyrk
dsyr2k
sgemm
ssymm
ssyrk
ssyr2k
zgemm
zhemm
zherk
zher2k
zsymm
zsyrk
zsyr2k
"""
#
# Author: Pearu Peterson, March 2002
# refactoring by Fabian Pedregosa, March 2010
#
from __future__ import division, print_function, absolute_import
__all__ = ['get_blas_funcs', 'find_best_blas_type']
import numpy as _np
from scipy.linalg import _fblas
try:
from scipy.linalg import _cblas
except ImportError:
_cblas = None
# Expose all functions (only fblas --- cblas is an implementation detail)
empty_module = None
from scipy.linalg._fblas import *
del empty_module
# 'd' will be default for 'i',..
_type_conv = {'f': 's', 'd': 'd', 'F': 'c', 'D': 'z', 'G': 'z'}
# some convenience alias for complex functions
_blas_alias = {'cnrm2': 'scnrm2', 'znrm2': 'dznrm2',
'cdot': 'cdotc', 'zdot': 'zdotc',
'cger': 'cgerc', 'zger': 'zgerc',
'sdotc': 'sdot', 'sdotu': 'sdot',
'ddotc': 'ddot', 'ddotu': 'ddot'}
def find_best_blas_type(arrays=(), dtype=None):
"""Find best-matching BLAS/LAPACK type.
Arrays are used to determine the optimal prefix of BLAS routines.
Parameters
----------
arrays : sequence of ndarrays, optional
Arrays can be given to determine optimal prefix of BLAS
routines. If not given, double-precision routines will be
used, otherwise the most generic type in arrays will be used.
dtype : str or dtype, optional
Data-type specifier. Not used if `arrays` is non-empty.
Returns
-------
prefix : str
BLAS/LAPACK prefix character.
dtype : dtype
Inferred Numpy data type.
prefer_fortran : bool
Whether to prefer Fortran order routines over C order.
"""
dtype = _np.dtype(dtype)
prefer_fortran = False
if arrays:
# use the most generic type in arrays
dtypes = [ar.dtype for ar in arrays]
dtype = _np.find_common_type(dtypes, ())
try:
index = dtypes.index(dtype)
except ValueError:
index = 0
if arrays[index].flags['FORTRAN']:
# prefer Fortran for leading array with column major order
prefer_fortran = True
prefix = _type_conv.get(dtype.char, 'd')
if dtype.char == 'G':
# complex256 -> complex128 (i.e., C long double -> C double)
dtype = _np.dtype('D')
elif dtype.char not in 'fdFD':
dtype = _np.dtype('d')
return prefix, dtype, prefer_fortran
def _get_funcs(names, arrays, dtype,
lib_name, fmodule, cmodule,
fmodule_name, cmodule_name, alias):
"""
Return available BLAS/LAPACK functions.
Used also in lapack.py. See get_blas_funcs for docstring.
"""
funcs = []
unpack = False
dtype = _np.dtype(dtype)
module1 = (cmodule, cmodule_name)
module2 = (fmodule, fmodule_name)
if isinstance(names, str):
names = (names,)
unpack = True
prefix, dtype, prefer_fortran = find_best_blas_type(arrays, dtype)
if prefer_fortran:
module1, module2 = module2, module1
for i, name in enumerate(names):
func_name = prefix + name
func_name = alias.get(func_name, func_name)
func = getattr(module1[0], func_name, None)
module_name = module1[1]
if func is None:
func = getattr(module2[0], func_name, None)
module_name = module2[1]
if func is None:
raise ValueError(
'%s function %s could not be found' % (lib_name, func_name))
func.module_name, func.typecode = module_name, prefix
func.dtype = dtype
func.prefix = prefix # Backward compatibility
funcs.append(func)
if unpack:
return funcs[0]
else:
return funcs
def get_blas_funcs(names, arrays=(), dtype=None):
"""Return available BLAS function objects from names.
Arrays are used to determine the optimal prefix of BLAS routines.
Parameters
----------
names : str or sequence of str
Name(s) of BLAS functions without type prefix.
arrays : sequence of ndarrays, optional
Arrays can be given to determine optimal prefix of BLAS
routines. If not given, double-precision routines will be
used, otherwise the most generic type in arrays will be used.
dtype : str or dtype, optional
Data-type specifier. Not used if `arrays` is non-empty.
Returns
-------
funcs : list
List containing the found function(s).
Notes
-----
This routine automatically chooses between Fortran/C
interfaces. Fortran code is used whenever possible for arrays with
column major order. In all other cases, C code is preferred.
In BLAS, the naming convention is that all functions start with a
type prefix, which depends on the type of the principal
matrix. These can be one of {'s', 'd', 'c', 'z'} for the numpy
types {float32, float64, complex64, complex128} respectively.
The code and the dtype are stored in attributes `typecode` and `dtype`
of the returned functions.
"""
return _get_funcs(names, arrays, dtype,
"BLAS", _fblas, _cblas, "fblas", "cblas",
_blas_alias)
| gpl-3.0 |
j4/horizon | openstack_dashboard/dashboards/project/routers/tables.py | 38 | 8661 | # Copyright 2012, Nachi Ueno, NTT MCL, 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.
import logging
from django.core.urlresolvers import reverse
from django.template import defaultfilters as filters
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ungettext_lazy
from neutronclient.common import exceptions as q_ext
from horizon import exceptions
from horizon import messages
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard import policy
from openstack_dashboard.usage import quotas
LOG = logging.getLogger(__name__)
class DeleteRouter(policy.PolicyTargetMixin, tables.DeleteAction):
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Delete Router",
u"Delete Routers",
count
)
@staticmethod
def action_past(count):
return ungettext_lazy(
u"Deleted Router",
u"Deleted Routers",
count
)
redirect_url = "horizon:project:routers:index"
policy_rules = (("network", "delete_router"),)
def delete(self, request, obj_id):
try:
# detach all interfaces before attempting to delete the router
search_opts = {'device_owner': 'network:router_interface',
'device_id': obj_id}
ports = api.neutron.port_list(request, **search_opts)
for port in ports:
api.neutron.router_remove_interface(request, obj_id,
port_id=port.id)
api.neutron.router_delete(request, obj_id)
except q_ext.NeutronClientException as e:
msg = _('Unable to delete router "%s"') % e
LOG.info(msg)
messages.error(request, msg)
redirect = reverse(self.redirect_url)
raise exceptions.Http302(redirect, message=msg)
except Exception:
obj = self.table.get_object_by_id(obj_id)
name = self.table.get_object_display(obj)
msg = _('Unable to delete router "%s"') % name
LOG.info(msg)
exceptions.handle(request, msg)
def allowed(self, request, router=None):
return True
class CreateRouter(tables.LinkAction):
name = "create"
verbose_name = _("Create Router")
url = "horizon:project:routers:create"
classes = ("ajax-modal",)
icon = "plus"
policy_rules = (("network", "create_router"),)
def allowed(self, request, datum=None):
usages = quotas.tenant_quota_usages(request)
if usages['routers']['available'] <= 0:
if "disabled" not in self.classes:
self.classes = [c for c in self.classes] + ["disabled"]
self.verbose_name = _("Create Router (Quota exceeded)")
else:
self.verbose_name = _("Create Router")
self.classes = [c for c in self.classes if c != "disabled"]
return True
class EditRouter(policy.PolicyTargetMixin, tables.LinkAction):
name = "update"
verbose_name = _("Edit Router")
url = "horizon:project:routers:update"
classes = ("ajax-modal",)
icon = "pencil"
policy_rules = (("network", "update_router"),)
class SetGateway(policy.PolicyTargetMixin, tables.LinkAction):
name = "setgateway"
verbose_name = _("Set Gateway")
url = "horizon:project:routers:setgateway"
classes = ("ajax-modal",)
icon = "camera"
policy_rules = (("network", "update_router"),)
def allowed(self, request, datum=None):
if datum.external_gateway_info:
return False
return True
class ClearGateway(policy.PolicyTargetMixin, tables.BatchAction):
help_text = _("You may reset the gateway later by using the"
" set gateway action, but the gateway IP may change.")
@staticmethod
def action_present(count):
return ungettext_lazy(
u"Clear Gateway",
u"Clear Gateways",
count
)
@staticmethod
def action_past(count):
return ungettext_lazy(
u"Cleared Gateway",
u"Cleared Gateways",
count
)
name = "cleargateway"
classes = ('btn-danger', 'btn-cleargateway')
redirect_url = "horizon:project:routers:index"
policy_rules = (("network", "update_router"),)
def action(self, request, obj_id):
obj = self.table.get_object_by_id(obj_id)
name = self.table.get_object_display(obj)
try:
api.neutron.router_remove_gateway(request, obj_id)
except Exception as e:
msg = (_('Unable to clear gateway for router '
'"%(name)s": "%(msg)s"')
% {"name": name, "msg": e})
LOG.info(msg)
redirect = reverse(self.redirect_url)
exceptions.handle(request, msg, redirect=redirect)
def get_success_url(self, request):
return reverse(self.redirect_url)
def allowed(self, request, datum=None):
if datum.external_gateway_info:
return True
return False
class UpdateRow(tables.Row):
ajax = True
def get_data(self, request, router_id):
router = api.neutron.router_get(request, router_id)
return router
def get_external_network(router):
if router.external_gateway_info:
return router.external_gateway_info['network']
else:
return _("-")
class RoutersFilterAction(tables.FilterAction):
def filter(self, table, routers, filter_string):
"""Naive case-insensitive search."""
query = filter_string.lower()
return [router for router in routers
if query in router.name.lower()]
class RoutersTable(tables.DataTable):
STATUS_DISPLAY_CHOICES = (
("active", pgettext_lazy("current status of router", u"Active")),
("error", pgettext_lazy("current status of router", u"Error")),
)
ADMIN_STATE_DISPLAY_CHOICES = (
("UP", pgettext_lazy("Admin state of a Router", u"UP")),
("DOWN", pgettext_lazy("Admin state of a Router", u"DOWN")),
)
name = tables.Column("name",
verbose_name=_("Name"),
link="horizon:project:routers:detail")
status = tables.Column("status",
verbose_name=_("Status"),
status=True,
display_choices=STATUS_DISPLAY_CHOICES)
distributed = tables.Column("distributed",
filters=(filters.yesno, filters.capfirst),
verbose_name=_("Distributed"))
ha = tables.Column("ha",
filters=(filters.yesno, filters.capfirst),
# Translators: High Availability mode of Neutron router
verbose_name=_("HA mode"))
ext_net = tables.Column(get_external_network,
verbose_name=_("External Network"))
admin_state = tables.Column("admin_state",
verbose_name=_("Admin State"),
display_choices=ADMIN_STATE_DISPLAY_CHOICES)
def __init__(self, request, data=None, needs_form_wrapper=None, **kwargs):
super(RoutersTable, self).__init__(
request,
data=data,
needs_form_wrapper=needs_form_wrapper,
**kwargs)
if not api.neutron.get_feature_permission(request, "dvr", "get"):
del self.columns["distributed"]
if not api.neutron.get_feature_permission(request, "l3-ha", "get"):
del self.columns["ha"]
def get_object_display(self, obj):
return obj.name
class Meta(object):
name = "Routers"
verbose_name = _("Routers")
status_columns = ["status"]
row_class = UpdateRow
table_actions = (CreateRouter, DeleteRouter,
RoutersFilterAction)
row_actions = (SetGateway, ClearGateway, EditRouter, DeleteRouter)
| apache-2.0 |
mauzeh/formation-flight | runs/singlehub/z/run.py | 1 | 1259 | #!/usr/bin/env python
"""Simulation bootstrapper"""
from formation_flight.formation import handlers as formation_handlers
from formation_flight.aircraft import handlers as aircraft_handlers
from formation_flight.aircraft import generators
from formation_flight.hub import builders
from formation_flight.hub import allocators
from lib import sim, debug, sink
from lib.debug import print_line as p
from formation_flight import statistics
import config
import os
import numpy as np
config.sink_dir = '%s/sink' % os.path.dirname(__file__)
def init():
sink.init(config.sink_dir)
def execute():
init()
for z in np.linspace(0, 1, 250):
config.Z = z
single_run()
def single_run():
sim.init()
aircraft_handlers.init()
formation_handlers.init()
statistics.init()
# Construct flight list
planes = generators.get_via_stdin()
# Find hubs
config.hubs = builders.build_hubs(planes, config.count_hubs, config.Z)
# Allocate hubs to flights
allocators.allocate(planes, config.hubs)
for flight in planes:
sim.events.append(sim.Event('aircraft-init', flight, 0))
sim.run()
sink.push(statistics.vars)
debug.print_dictionary(statistics.vars)
| mit |
adoosii/edx-platform | lms/djangoapps/courseware/migrations/0011_add_model_StudentFieldOverride.py | 94 | 11581 | # -*- coding: utf-8 -*-
# pylint: disable=invalid-name, missing-docstring, unused-argument, unused-import, line-too-long
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 'StudentFieldOverride'
db.create_table('courseware_studentfieldoverride', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('course_id', self.gf('xmodule_django.models.CourseKeyField')(max_length=255, db_index=True)),
('location', self.gf('xmodule_django.models.LocationKeyField')(max_length=255, db_index=True)),
('student', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])),
('field', self.gf('django.db.models.fields.CharField')(max_length=255)),
('value', self.gf('django.db.models.fields.TextField')(default='null')),
))
db.send_create_signal('courseware', ['StudentFieldOverride'])
def backwards(self, orm):
# Deleting model 'StudentFieldOverride'
db.delete_table('courseware_studentfieldoverride')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'courseware.offlinecomputedgrade': {
'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'OfflineComputedGrade'},
'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),
'gradeset': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'courseware.offlinecomputedgradelog': {
'Meta': {'ordering': "['-created']", 'object_name': 'OfflineComputedGradeLog'},
'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nstudents': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'seconds': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'courseware.studentfieldoverride': {
'Meta': {'unique_together': "(('course_id', 'location', 'student'),)", 'object_name': 'StudentFieldOverride'},
'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'field': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'location': ('xmodule_django.models.LocationKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'student': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'value': ('django.db.models.fields.TextField', [], {'default': "'null'"})
},
'courseware.studentmodule': {
'Meta': {'unique_together': "(('student', 'module_state_key', 'course_id'),)", 'object_name': 'StudentModule'},
'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'done': ('django.db.models.fields.CharField', [], {'default': "'na'", 'max_length': '8', 'db_index': 'True'}),
'grade': ('django.db.models.fields.FloatField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'max_grade': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'module_state_key': ('xmodule_django.models.LocationKeyField', [], {'max_length': '255', 'db_column': "'module_id'", 'db_index': 'True'}),
'module_type': ('django.db.models.fields.CharField', [], {'default': "'problem'", 'max_length': '32', 'db_index': 'True'}),
'state': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'student': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'courseware.studentmodulehistory': {
'Meta': {'object_name': 'StudentModuleHistory'},
'created': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),
'grade': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'max_grade': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'state': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'student_module': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['courseware.StudentModule']"}),
'version': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'courseware.xmodulestudentinfofield': {
'Meta': {'unique_together': "(('student', 'field_name'),)", 'object_name': 'XModuleStudentInfoField'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'field_name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'student': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'value': ('django.db.models.fields.TextField', [], {'default': "'null'"})
},
'courseware.xmodulestudentprefsfield': {
'Meta': {'unique_together': "(('student', 'module_type', 'field_name'),)", 'object_name': 'XModuleStudentPrefsField'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'field_name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'module_type': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_index': 'True'}),
'student': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}),
'value': ('django.db.models.fields.TextField', [], {'default': "'null'"})
},
'courseware.xmoduleuserstatesummaryfield': {
'Meta': {'unique_together': "(('usage_id', 'field_name'),)", 'object_name': 'XModuleUserStateSummaryField'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'field_name': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'usage_id': ('xmodule_django.models.LocationKeyField', [], {'max_length': '255', 'db_index': 'True'}),
'value': ('django.db.models.fields.TextField', [], {'default': "'null'"})
}
}
complete_apps = ['courseware']
| agpl-3.0 |
octopicorn/cloudbrain | cloudbrain/connectors/MockConnector.py | 1 | 1165 | import time
import random
from cloudbrain.connectors.ConnectorInterface import Connector
from cloudbrain.utils.metadata_info import get_num_channels
class MockConnector(Connector):
def __init__(self, publishers, buffer_size, device_name, device_port='mock_port', device_mac=None):
"""
:return:
"""
super(MockConnector, self).__init__(publishers, buffer_size, device_name, device_port, device_mac)
self.data_generators = [self.data_generator_factory(metric, get_num_channels(self.device_name, metric)) for metric in self.metrics]
def connect_device(self):
"""
Mock connector so actually, don't do anything there :-)
:return:
"""
pass
def start(self):
while 1:
for data_generator in self.data_generators:
data_generator()
time.sleep(1)
def data_generator_factory(self, metric_name, num_channels):
def data_generator():
message = {"channel_%s" % i: random.random() * 10 for i in xrange(num_channels)}
message['timestamp'] = int(time.time() * 1000000) # micro seconds
print message
self.buffers[metric_name].write(message)
return data_generator
| agpl-3.0 |
insequent/quark | quark/cache/security_groups_client.py | 1 | 8108 | # Copyright 2014 Openstack Foundation
# 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
#
import json
import netaddr
from oslo_log import log as logging
from quark.cache import redis_base
from quark import exceptions as q_exc
from quark import protocols
from quark import utils
LOG = logging.getLogger(__name__)
SECURITY_GROUP_RULE_KEY = "rules"
SECURITY_GROUP_HASH_ATTR = "security group rules"
SECURITY_GROUP_ACK = "security group ack"
ALL_V4 = netaddr.IPNetwork("::ffff:0.0.0.0/96")
ALL_V6 = netaddr.IPNetwork("::/0")
class SecurityGroupsClient(redis_base.ClientBase):
def _convert_remote_network(self, remote_ip_prefix):
# NOTE(mdietz): RM11364 - While a /0 is valid and should be supported,
# it breaks OVS to apply a /0 as the source or
# destination network.
net = netaddr.IPNetwork(remote_ip_prefix).ipv6()
if net.cidr == ALL_V4 or net.cidr == ALL_V6:
return ''
return str(net)
def serialize_rules(self, rules):
"""Creates a payload for the redis server."""
# TODO(mdietz): If/when we support other rule types, this comment
# will have to be revised.
# Action and direction are static, for now. The implementation may
# support 'deny' and 'egress' respectively in the future. We allow
# the direction to be set to something else, technically, but current
# plugin level call actually raises. It's supported here for unit
# test purposes at this time
serialized = []
for rule in rules:
direction = rule["direction"]
source = ''
destination = ''
if rule.get("remote_ip_prefix"):
prefix = rule["remote_ip_prefix"]
if direction == "ingress":
source = self._convert_remote_network(prefix)
else:
destination = self._convert_remote_network(prefix)
optional_fields = {}
# NOTE(mdietz): this will expand as we add more protocols
protocol_map = protocols.PROTOCOL_MAP[rule["ethertype"]]
if rule["protocol"] == protocol_map["icmp"]:
optional_fields["icmp type"] = rule["port_range_min"]
optional_fields["icmp code"] = rule["port_range_max"]
else:
optional_fields["port start"] = rule["port_range_min"]
optional_fields["port end"] = rule["port_range_max"]
payload = {"ethertype": rule["ethertype"],
"protocol": rule["protocol"],
"source network": source,
"destination network": destination,
"action": "allow",
"direction": direction}
payload.update(optional_fields)
serialized.append(payload)
return serialized
def serialize_groups(self, groups):
"""Creates a payload for the redis server
The rule schema is the following:
REDIS KEY - port_device_id.port_mac_address/sg
REDIS VALUE - A JSON dump of the following:
port_mac_address must be lower-cased and stripped of non-alphanumeric
characters
{"id": "<arbitrary uuid>",
"rules": [
{"ethertype": <hexademical integer>,
"protocol": <integer>,
"port start": <integer>, # optional
"port end": <integer>, # optional
"icmp type": <integer>, # optional
"icmp code": <integer>, # optional
"source network": <string>,
"destination network": <string>,
"action": <string>,
"direction": <string>},
],
"security groups ack": <boolean>
}
Example:
{"id": "004c6369-9f3d-4d33-b8f5-9416bf3567dd",
"rules": [
{"ethertype": 0x800,
"protocol": "tcp",
"port start": 1000,
"port end": 1999,
"source network": "10.10.10.0/24",
"destination network": "",
"action": "allow",
"direction": "ingress"},
],
"security groups ack": "true"
}
port start/end and icmp type/code are mutually exclusive pairs.
"""
rules = []
for group in groups:
rules.extend(self.serialize_rules(group.rules))
return rules
def get_rules_for_port(self, device_id, mac_address):
rules = self.get_field(
self.vif_key(device_id, mac_address), SECURITY_GROUP_HASH_ATTR)
if rules:
return json.loads(rules)
def apply_rules(self, device_id, mac_address, rules):
"""Writes a series of security group rules to a redis server."""
LOG.info("Applying security group rules for device %s with MAC %s" %
(device_id, mac_address))
if not self._use_master:
raise q_exc.RedisSlaveWritesForbidden()
rule_dict = {SECURITY_GROUP_RULE_KEY: rules}
redis_key = self.vif_key(device_id, mac_address)
# TODO(mdietz): Pipeline these. Requires some rewriting
self.set_field(redis_key, SECURITY_GROUP_HASH_ATTR, rule_dict)
self.set_field_raw(redis_key, SECURITY_GROUP_ACK, False)
def delete_vif_rules(self, device_id, mac_address):
# Redis HDEL command will ignore key safely if it doesn't exist
self.delete_field(self.vif_key(device_id, mac_address),
SECURITY_GROUP_HASH_ATTR)
self.delete_field(self.vif_key(device_id, mac_address),
SECURITY_GROUP_ACK)
def delete_vif(self, device_id, mac_address):
# Redis DEL command will ignore key safely if it doesn't exist
self.delete_key(self.vif_key(device_id, mac_address))
@utils.retry_loop(3)
def get_security_group_states(self, interfaces):
"""Gets security groups for interfaces from Redis
Returns a dictionary of xapi.VIFs with values of the current
acknowledged status in Redis.
States not explicitly handled:
* ack key, no rules - This is the same as just tagging the VIF,
the instance will be inaccessible
* rules key, no ack - Nothing will happen, the VIF will
not be tagged.
"""
LOG.debug("Getting security groups from Redis for {0}".format(
interfaces))
interfaces = tuple(interfaces)
vif_keys = [self.vif_key(vif.device_id, vif.mac_address)
for vif in interfaces]
security_groups = self.get_fields(vif_keys, SECURITY_GROUP_ACK)
ret = {}
for vif, security_group_ack in zip(interfaces, security_groups):
if security_group_ack:
security_group_ack = security_group_ack.lower()
if "true" in security_group_ack:
ret[vif] = True
elif "false" in security_group_ack:
ret[vif] = False
else:
LOG.debug("Skipping bad ack value %s" % security_group_ack)
return ret
@utils.retry_loop(3)
def update_group_states_for_vifs(self, vifs, ack):
"""Updates security groups by setting the ack field"""
if not self._use_master:
raise q_exc.RedisSlaveWritesForbidden()
vif_keys = [self.vif_key(vif.device_id, vif.mac_address)
for vif in vifs]
self.set_fields(vif_keys, SECURITY_GROUP_ACK, ack)
| apache-2.0 |
klim-iv/phantomjs-qt5 | src/webkit/Tools/Scripts/webkitpy/tool/steps/applypatch.py | 128 | 2041 | # Copyright (C) 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.
import logging
from webkitpy.tool.steps.abstractstep import AbstractStep
from webkitpy.tool.steps.options import Options
_log = logging.getLogger(__name__)
class ApplyPatch(AbstractStep):
@classmethod
def options(cls):
return AbstractStep.options() + [
Options.non_interactive,
]
def run(self, state):
_log.info("Processing patch %s from bug %s." % (state["patch"].id(), state["patch"].bug_id()))
self._tool.checkout().apply_patch(state["patch"])
| bsd-3-clause |
github-account-because-they-want-it/django | tests/bash_completion/tests.py | 327 | 3888 | """
A series of tests to establish that the command-line bash completion works.
"""
import os
import sys
import unittest
from django.apps import apps
from django.core.management import ManagementUtility
from django.test.utils import captured_stdout
class BashCompletionTests(unittest.TestCase):
"""
Testing the Python level bash completion code.
This requires setting up the environment as if we got passed data
from bash.
"""
def setUp(self):
self.old_DJANGO_AUTO_COMPLETE = os.environ.get('DJANGO_AUTO_COMPLETE')
os.environ['DJANGO_AUTO_COMPLETE'] = '1'
def tearDown(self):
if self.old_DJANGO_AUTO_COMPLETE:
os.environ['DJANGO_AUTO_COMPLETE'] = self.old_DJANGO_AUTO_COMPLETE
else:
del os.environ['DJANGO_AUTO_COMPLETE']
def _user_input(self, input_str):
"""
Set the environment and the list of command line arguments.
This sets the bash variables $COMP_WORDS and $COMP_CWORD. The former is
an array consisting of the individual words in the current command
line, the latter is the index of the current cursor position, so in
case a word is completed and the cursor is placed after a whitespace,
$COMP_CWORD must be incremented by 1:
* 'django-admin start' -> COMP_CWORD=1
* 'django-admin startproject' -> COMP_CWORD=1
* 'django-admin startproject ' -> COMP_CWORD=2
"""
os.environ['COMP_WORDS'] = input_str
idx = len(input_str.split(' ')) - 1 # Index of the last word
comp_cword = idx + 1 if input_str.endswith(' ') else idx
os.environ['COMP_CWORD'] = str(comp_cword)
sys.argv = input_str.split()
def _run_autocomplete(self):
util = ManagementUtility(argv=sys.argv)
with captured_stdout() as stdout:
try:
util.autocomplete()
except SystemExit:
pass
return stdout.getvalue().strip().split('\n')
def test_django_admin_py(self):
"django_admin.py will autocomplete option flags"
self._user_input('django-admin sqlmigrate --verb')
output = self._run_autocomplete()
self.assertEqual(output, ['--verbosity='])
def test_manage_py(self):
"manage.py will autocomplete option flags"
self._user_input('manage.py sqlmigrate --verb')
output = self._run_autocomplete()
self.assertEqual(output, ['--verbosity='])
def test_custom_command(self):
"A custom command can autocomplete option flags"
self._user_input('django-admin test_command --l')
output = self._run_autocomplete()
self.assertEqual(output, ['--list'])
def test_subcommands(self):
"Subcommands can be autocompleted"
self._user_input('django-admin sql')
output = self._run_autocomplete()
self.assertEqual(output, ['sqlflush sqlmigrate sqlsequencereset'])
def test_completed_subcommand(self):
"Show option flags in case a subcommand is completed"
self._user_input('django-admin startproject ') # Trailing whitespace
output = self._run_autocomplete()
for item in output:
self.assertTrue(item.startswith('--'))
def test_help(self):
"No errors, just an empty list if there are no autocomplete options"
self._user_input('django-admin help --')
output = self._run_autocomplete()
self.assertEqual(output, [''])
def test_app_completion(self):
"Application names will be autocompleted for an AppCommand"
self._user_input('django-admin sqlmigrate a')
output = self._run_autocomplete()
a_labels = sorted(app_config.label
for app_config in apps.get_app_configs()
if app_config.label.startswith('a'))
self.assertEqual(output, a_labels)
| bsd-3-clause |
netsamir/dotfiles | files/vim/bundle/YouCompleteMe/python/ycm/setup.py | 9 | 1867 | # Copyright (C) 2016 YouCompleteMe contributors
#
# 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/>.
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
# No imports from `future` because when this is loaded, sys.path hasn't been set
# up yet!
import sys
import os
# Can't import these from paths.py because that uses `future` imports
DIR_OF_CURRENT_SCRIPT = os.path.dirname( os.path.abspath( __file__ ) )
DIR_OF_YCMD = os.path.join( DIR_OF_CURRENT_SCRIPT, '..', '..', 'third_party',
'ycmd' )
def SetUpSystemPaths():
sys.path.insert( 0, os.path.join( DIR_OF_YCMD ) )
from ycmd import server_utils as su
su.AddNearestThirdPartyFoldersToSysPath( DIR_OF_CURRENT_SCRIPT )
# We need to import ycmd's third_party folders as well since we import and
# use ycmd code in the client.
su.AddNearestThirdPartyFoldersToSysPath( su.__file__ )
def SetUpYCM():
from ycm import base
from ycmd import user_options_store
from ycm.youcompleteme import YouCompleteMe
base.LoadJsonDefaultsIntoVim()
user_options_store.SetAll( base.BuildServerConf() )
return YouCompleteMe( user_options_store.GetAll() )
| unlicense |
thebestgirl123/CloudBot | plugins/name_generator.py | 28 | 2056 | """
name_generator.py
Generates fun names using the textgen module.
Created By:
- Luke Rogers <https://github.com/lukeroge>
License:
GPL v3
"""
import json
import codecs
import os
from cloudbot import hook
from cloudbot.util import formatting, textgen
def get_generator(_json):
data = json.loads(_json)
return textgen.TextGenerator(data["templates"],
data["parts"], default_templates=data["default_templates"])
@hook.command(autohelp=False)
def namegen(text, bot, notice):
"""[generator|list] - generates some names using the chosen generator, or lists all generators if 'list' is specified
:type bot: cloudbot.bot.CloudBot
"""
# clean up the input
inp = text.strip().lower()
# get a list of available name generators
files = os.listdir(os.path.join(bot.data_dir, "name_files"))
all_modules = [os.path.splitext(i)[0] for i in files if os.path.splitext(i)[1] == ".json"]
all_modules.sort()
# command to return a list of all available generators
if inp == "list":
message = "Available generators: "
message += formatting.get_text_list(all_modules, 'and')
notice(message)
return
if inp:
selected_module = inp.split()[0]
else:
# make some generic fantasy names
selected_module = "fantasy"
# check if the selected module is valid
if selected_module not in all_modules:
return "{} is not a valid name generator.".format(inp)
# load the name generator
path = os.path.join(bot.data_dir, "name_files", "{}.json".format(selected_module))
with codecs.open(path, encoding="utf-8") as f:
try:
generator = get_generator(f.read())
except ValueError as error:
return "Unable to read name file: {}".format(error)
# time to generate some names
name_list = generator.generate_strings(10)
# and finally return the final message :D
return "Some names to ponder: {}.".format(formatting.get_text_list(name_list, 'and'))
| gpl-3.0 |
harisbal/pandas | pandas/tests/test_panel.py | 1 | 95658 | # -*- coding: utf-8 -*-
# pylint: disable=W0612,E1101
from warnings import catch_warnings, simplefilter
from datetime import datetime
import operator
import pytest
import numpy as np
from pandas.core.dtypes.common import is_float_dtype
from pandas import (Series, DataFrame, Index, date_range, isna, notna,
MultiIndex)
from pandas.core.nanops import nanall, nanany
from pandas.core.panel import Panel
from pandas.io.formats.printing import pprint_thing
from pandas import compat
from pandas.compat import range, lrange, StringIO, OrderedDict, signature
from pandas.tseries.offsets import BDay, MonthEnd
from pandas.util.testing import (assert_panel_equal, assert_frame_equal,
assert_series_equal, assert_almost_equal,
ensure_clean, makeMixedDataFrame,
makeCustomDataframe as mkdf)
import pandas.core.panel as panelm
import pandas.util.testing as tm
import pandas.util._test_decorators as td
def make_test_panel():
with catch_warnings(record=True):
simplefilter("ignore", FutureWarning)
_panel = tm.makePanel()
tm.add_nans(_panel)
_panel = _panel.copy()
return _panel
@pytest.mark.filterwarnings("ignore:\\nPanel:FutureWarning")
class PanelTests(object):
panel = None
def test_pickle(self):
unpickled = tm.round_trip_pickle(self.panel)
assert_frame_equal(unpickled['ItemA'], self.panel['ItemA'])
def test_rank(self):
pytest.raises(NotImplementedError, lambda: self.panel.rank())
def test_cumsum(self):
cumsum = self.panel.cumsum()
assert_frame_equal(cumsum['ItemA'], self.panel['ItemA'].cumsum())
def not_hashable(self):
c_empty = Panel()
c = Panel(Panel([[[1]]]))
pytest.raises(TypeError, hash, c_empty)
pytest.raises(TypeError, hash, c)
@pytest.mark.filterwarnings("ignore:\\nPanel:FutureWarning")
class SafeForLongAndSparse(object):
def test_repr(self):
repr(self.panel)
def test_copy_names(self):
for attr in ('major_axis', 'minor_axis'):
getattr(self.panel, attr).name = None
cp = self.panel.copy()
getattr(cp, attr).name = 'foo'
assert getattr(self.panel, attr).name is None
def test_iter(self):
tm.equalContents(list(self.panel), self.panel.items)
def test_count(self):
f = lambda s: notna(s).sum()
self._check_stat_op('count', f, obj=self.panel, has_skipna=False)
def test_sum(self):
self._check_stat_op('sum', np.sum, skipna_alternative=np.nansum)
def test_mean(self):
self._check_stat_op('mean', np.mean)
@td.skip_if_no("numpy", min_version="1.10.0")
def test_prod(self):
self._check_stat_op('prod', np.prod, skipna_alternative=np.nanprod)
@pytest.mark.filterwarnings("ignore:Invalid value:RuntimeWarning")
@pytest.mark.filterwarnings("ignore:All-NaN:RuntimeWarning")
def test_median(self):
def wrapper(x):
if isna(x).any():
return np.nan
return np.median(x)
self._check_stat_op('median', wrapper)
@pytest.mark.filterwarnings("ignore:Invalid value:RuntimeWarning")
def test_min(self):
self._check_stat_op('min', np.min)
@pytest.mark.filterwarnings("ignore:Invalid value:RuntimeWarning")
def test_max(self):
self._check_stat_op('max', np.max)
@td.skip_if_no_scipy
def test_skew(self):
from scipy.stats import skew
def this_skew(x):
if len(x) < 3:
return np.nan
return skew(x, bias=False)
self._check_stat_op('skew', this_skew)
def test_var(self):
def alt(x):
if len(x) < 2:
return np.nan
return np.var(x, ddof=1)
self._check_stat_op('var', alt)
def test_std(self):
def alt(x):
if len(x) < 2:
return np.nan
return np.std(x, ddof=1)
self._check_stat_op('std', alt)
def test_sem(self):
def alt(x):
if len(x) < 2:
return np.nan
return np.std(x, ddof=1) / np.sqrt(len(x))
self._check_stat_op('sem', alt)
def _check_stat_op(self, name, alternative, obj=None, has_skipna=True,
skipna_alternative=None):
if obj is None:
obj = self.panel
# # set some NAs
# obj.loc[5:10] = np.nan
# obj.loc[15:20, -2:] = np.nan
f = getattr(obj, name)
if has_skipna:
skipna_wrapper = tm._make_skipna_wrapper(alternative,
skipna_alternative)
def wrapper(x):
return alternative(np.asarray(x))
for i in range(obj.ndim):
result = f(axis=i, skipna=False)
assert_frame_equal(result, obj.apply(wrapper, axis=i))
else:
skipna_wrapper = alternative
wrapper = alternative
for i in range(obj.ndim):
result = f(axis=i)
if name in ['sum', 'prod']:
assert_frame_equal(result, obj.apply(skipna_wrapper, axis=i))
pytest.raises(Exception, f, axis=obj.ndim)
# Unimplemented numeric_only parameter.
if 'numeric_only' in signature(f).args:
tm.assert_raises_regex(NotImplementedError, name, f,
numeric_only=True)
@pytest.mark.filterwarnings("ignore:\\nPanel:FutureWarning")
class SafeForSparse(object):
def test_get_axis(self):
assert (self.panel._get_axis(0) is self.panel.items)
assert (self.panel._get_axis(1) is self.panel.major_axis)
assert (self.panel._get_axis(2) is self.panel.minor_axis)
def test_set_axis(self):
new_items = Index(np.arange(len(self.panel.items)))
new_major = Index(np.arange(len(self.panel.major_axis)))
new_minor = Index(np.arange(len(self.panel.minor_axis)))
# ensure propagate to potentially prior-cached items too
item = self.panel['ItemA']
self.panel.items = new_items
if hasattr(self.panel, '_item_cache'):
assert 'ItemA' not in self.panel._item_cache
assert self.panel.items is new_items
# TODO: unused?
item = self.panel[0] # noqa
self.panel.major_axis = new_major
assert self.panel[0].index is new_major
assert self.panel.major_axis is new_major
# TODO: unused?
item = self.panel[0] # noqa
self.panel.minor_axis = new_minor
assert self.panel[0].columns is new_minor
assert self.panel.minor_axis is new_minor
def test_get_axis_number(self):
assert self.panel._get_axis_number('items') == 0
assert self.panel._get_axis_number('major') == 1
assert self.panel._get_axis_number('minor') == 2
with tm.assert_raises_regex(ValueError, "No axis named foo"):
self.panel._get_axis_number('foo')
with tm.assert_raises_regex(ValueError, "No axis named foo"):
self.panel.__ge__(self.panel, axis='foo')
def test_get_axis_name(self):
assert self.panel._get_axis_name(0) == 'items'
assert self.panel._get_axis_name(1) == 'major_axis'
assert self.panel._get_axis_name(2) == 'minor_axis'
def test_get_plane_axes(self):
# what to do here?
index, columns = self.panel._get_plane_axes('items')
index, columns = self.panel._get_plane_axes('major_axis')
index, columns = self.panel._get_plane_axes('minor_axis')
index, columns = self.panel._get_plane_axes(0)
def test_truncate(self):
dates = self.panel.major_axis
start, end = dates[1], dates[5]
trunced = self.panel.truncate(start, end, axis='major')
expected = self.panel['ItemA'].truncate(start, end)
assert_frame_equal(trunced['ItemA'], expected)
trunced = self.panel.truncate(before=start, axis='major')
expected = self.panel['ItemA'].truncate(before=start)
assert_frame_equal(trunced['ItemA'], expected)
trunced = self.panel.truncate(after=end, axis='major')
expected = self.panel['ItemA'].truncate(after=end)
assert_frame_equal(trunced['ItemA'], expected)
def test_arith(self):
self._test_op(self.panel, operator.add)
self._test_op(self.panel, operator.sub)
self._test_op(self.panel, operator.mul)
self._test_op(self.panel, operator.truediv)
self._test_op(self.panel, operator.floordiv)
self._test_op(self.panel, operator.pow)
self._test_op(self.panel, lambda x, y: y + x)
self._test_op(self.panel, lambda x, y: y - x)
self._test_op(self.panel, lambda x, y: y * x)
self._test_op(self.panel, lambda x, y: y / x)
self._test_op(self.panel, lambda x, y: y ** x)
self._test_op(self.panel, lambda x, y: x + y) # panel + 1
self._test_op(self.panel, lambda x, y: x - y) # panel - 1
self._test_op(self.panel, lambda x, y: x * y) # panel * 1
self._test_op(self.panel, lambda x, y: x / y) # panel / 1
self._test_op(self.panel, lambda x, y: x ** y) # panel ** 1
pytest.raises(Exception, self.panel.__add__,
self.panel['ItemA'])
@staticmethod
def _test_op(panel, op):
result = op(panel, 1)
assert_frame_equal(result['ItemA'], op(panel['ItemA'], 1))
def test_keys(self):
tm.equalContents(list(self.panel.keys()), self.panel.items)
def test_iteritems(self):
# Test panel.iteritems(), aka panel.iteritems()
# just test that it works
for k, v in self.panel.iteritems():
pass
assert len(list(self.panel.iteritems())) == len(self.panel.items)
def test_combineFrame(self):
def check_op(op, name):
# items
df = self.panel['ItemA']
func = getattr(self.panel, name)
result = func(df, axis='items')
assert_frame_equal(
result['ItemB'], op(self.panel['ItemB'], df))
# major
xs = self.panel.major_xs(self.panel.major_axis[0])
result = func(xs, axis='major')
idx = self.panel.major_axis[1]
assert_frame_equal(result.major_xs(idx),
op(self.panel.major_xs(idx), xs))
# minor
xs = self.panel.minor_xs(self.panel.minor_axis[0])
result = func(xs, axis='minor')
idx = self.panel.minor_axis[1]
assert_frame_equal(result.minor_xs(idx),
op(self.panel.minor_xs(idx), xs))
ops = ['add', 'sub', 'mul', 'truediv', 'floordiv', 'pow', 'mod']
if not compat.PY3:
ops.append('div')
for op in ops:
try:
check_op(getattr(operator, op), op)
except:
pprint_thing("Failing operation: %r" % op)
raise
if compat.PY3:
try:
check_op(operator.truediv, 'div')
except:
pprint_thing("Failing operation: %r" % 'div')
raise
def test_combinePanel(self):
result = self.panel.add(self.panel)
assert_panel_equal(result, self.panel * 2)
def test_neg(self):
assert_panel_equal(-self.panel, self.panel * -1)
# issue 7692
def test_raise_when_not_implemented(self):
p = Panel(np.arange(3 * 4 * 5).reshape(3, 4, 5),
items=['ItemA', 'ItemB', 'ItemC'],
major_axis=date_range('20130101', periods=4),
minor_axis=list('ABCDE'))
d = p.sum(axis=1).iloc[0]
ops = ['add', 'sub', 'mul', 'truediv',
'floordiv', 'div', 'mod', 'pow']
for op in ops:
with pytest.raises(NotImplementedError):
getattr(p, op)(d, axis=0)
def test_select(self):
p = self.panel
# select items
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = p.select(lambda x: x in ('ItemA', 'ItemC'), axis='items')
expected = p.reindex(items=['ItemA', 'ItemC'])
assert_panel_equal(result, expected)
# select major_axis
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = p.select(lambda x: x >= datetime(
2000, 1, 15), axis='major')
new_major = p.major_axis[p.major_axis >= datetime(2000, 1, 15)]
expected = p.reindex(major=new_major)
assert_panel_equal(result, expected)
# select minor_axis
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = p.select(lambda x: x in ('D', 'A'), axis=2)
expected = p.reindex(minor=['A', 'D'])
assert_panel_equal(result, expected)
# corner case, empty thing
with tm.assert_produces_warning(FutureWarning, check_stacklevel=False):
result = p.select(lambda x: x in ('foo', ), axis='items')
assert_panel_equal(result, p.reindex(items=[]))
def test_get_value(self):
for item in self.panel.items:
for mjr in self.panel.major_axis[::2]:
for mnr in self.panel.minor_axis:
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
result = self.panel.get_value(item, mjr, mnr)
expected = self.panel[item][mnr][mjr]
assert_almost_equal(result, expected)
def test_abs(self):
result = self.panel.abs()
result2 = abs(self.panel)
expected = np.abs(self.panel)
assert_panel_equal(result, expected)
assert_panel_equal(result2, expected)
df = self.panel['ItemA']
result = df.abs()
result2 = abs(df)
expected = np.abs(df)
assert_frame_equal(result, expected)
assert_frame_equal(result2, expected)
s = df['A']
result = s.abs()
result2 = abs(s)
expected = np.abs(s)
assert_series_equal(result, expected)
assert_series_equal(result2, expected)
assert result.name == 'A'
assert result2.name == 'A'
@pytest.mark.filterwarnings("ignore:\\nPanel:FutureWarning")
class CheckIndexing(object):
def test_getitem(self):
pytest.raises(Exception, self.panel.__getitem__, 'ItemQ')
def test_delitem_and_pop(self):
expected = self.panel['ItemA']
result = self.panel.pop('ItemA')
assert_frame_equal(expected, result)
assert 'ItemA' not in self.panel.items
del self.panel['ItemB']
assert 'ItemB' not in self.panel.items
pytest.raises(Exception, self.panel.__delitem__, 'ItemB')
values = np.empty((3, 3, 3))
values[0] = 0
values[1] = 1
values[2] = 2
panel = Panel(values, lrange(3), lrange(3), lrange(3))
# did we delete the right row?
panelc = panel.copy()
del panelc[0]
tm.assert_frame_equal(panelc[1], panel[1])
tm.assert_frame_equal(panelc[2], panel[2])
panelc = panel.copy()
del panelc[1]
tm.assert_frame_equal(panelc[0], panel[0])
tm.assert_frame_equal(panelc[2], panel[2])
panelc = panel.copy()
del panelc[2]
tm.assert_frame_equal(panelc[1], panel[1])
tm.assert_frame_equal(panelc[0], panel[0])
def test_setitem(self):
lp = self.panel.filter(['ItemA', 'ItemB']).to_frame()
with pytest.raises(ValueError):
self.panel['ItemE'] = lp
# DataFrame
df = self.panel['ItemA'][2:].filter(items=['A', 'B'])
self.panel['ItemF'] = df
self.panel['ItemE'] = df
df2 = self.panel['ItemF']
assert_frame_equal(df, df2.reindex(
index=df.index, columns=df.columns))
# scalar
self.panel['ItemG'] = 1
self.panel['ItemE'] = True
assert self.panel['ItemG'].values.dtype == np.int64
assert self.panel['ItemE'].values.dtype == np.bool_
# object dtype
self.panel['ItemQ'] = 'foo'
assert self.panel['ItemQ'].values.dtype == np.object_
# boolean dtype
self.panel['ItemP'] = self.panel['ItemA'] > 0
assert self.panel['ItemP'].values.dtype == np.bool_
pytest.raises(TypeError, self.panel.__setitem__, 'foo',
self.panel.loc[['ItemP']])
# bad shape
p = Panel(np.random.randn(4, 3, 2))
with tm.assert_raises_regex(ValueError,
r"shape of value must be "
r"\(3, 2\), shape of given "
r"object was \(4, 2\)"):
p[0] = np.random.randn(4, 2)
def test_setitem_ndarray(self):
timeidx = date_range(start=datetime(2009, 1, 1),
end=datetime(2009, 12, 31),
freq=MonthEnd())
lons_coarse = np.linspace(-177.5, 177.5, 72)
lats_coarse = np.linspace(-87.5, 87.5, 36)
P = Panel(items=timeidx, major_axis=lons_coarse,
minor_axis=lats_coarse)
data = np.random.randn(72 * 36).reshape((72, 36))
key = datetime(2009, 2, 28)
P[key] = data
assert_almost_equal(P[key].values, data)
def test_set_minor_major(self):
# GH 11014
df1 = DataFrame(['a', 'a', 'a', np.nan, 'a', np.nan])
df2 = DataFrame([1.0, np.nan, 1.0, np.nan, 1.0, 1.0])
panel = Panel({'Item1': df1, 'Item2': df2})
newminor = notna(panel.iloc[:, :, 0])
panel.loc[:, :, 'NewMinor'] = newminor
assert_frame_equal(panel.loc[:, :, 'NewMinor'],
newminor.astype(object))
newmajor = notna(panel.iloc[:, 0, :])
panel.loc[:, 'NewMajor', :] = newmajor
assert_frame_equal(panel.loc[:, 'NewMajor', :],
newmajor.astype(object))
def test_major_xs(self):
ref = self.panel['ItemA']
idx = self.panel.major_axis[5]
xs = self.panel.major_xs(idx)
result = xs['ItemA']
assert_series_equal(result, ref.xs(idx), check_names=False)
assert result.name == 'ItemA'
# not contained
idx = self.panel.major_axis[0] - BDay()
pytest.raises(Exception, self.panel.major_xs, idx)
def test_major_xs_mixed(self):
self.panel['ItemD'] = 'foo'
xs = self.panel.major_xs(self.panel.major_axis[0])
assert xs['ItemA'].dtype == np.float64
assert xs['ItemD'].dtype == np.object_
def test_minor_xs(self):
ref = self.panel['ItemA']
idx = self.panel.minor_axis[1]
xs = self.panel.minor_xs(idx)
assert_series_equal(xs['ItemA'], ref[idx], check_names=False)
# not contained
pytest.raises(Exception, self.panel.minor_xs, 'E')
def test_minor_xs_mixed(self):
self.panel['ItemD'] = 'foo'
xs = self.panel.minor_xs('D')
assert xs['ItemA'].dtype == np.float64
assert xs['ItemD'].dtype == np.object_
def test_xs(self):
itemA = self.panel.xs('ItemA', axis=0)
expected = self.panel['ItemA']
tm.assert_frame_equal(itemA, expected)
# Get a view by default.
itemA_view = self.panel.xs('ItemA', axis=0)
itemA_view.values[:] = np.nan
assert np.isnan(self.panel['ItemA'].values).all()
# Mixed-type yields a copy.
self.panel['strings'] = 'foo'
result = self.panel.xs('D', axis=2)
assert result._is_copy is not None
def test_getitem_fancy_labels(self):
p = self.panel
items = p.items[[1, 0]]
dates = p.major_axis[::2]
cols = ['D', 'C', 'F']
# all 3 specified
with catch_warnings():
simplefilter("ignore", FutureWarning)
# XXX: warning in _validate_read_indexer
assert_panel_equal(p.loc[items, dates, cols],
p.reindex(items=items, major=dates, minor=cols))
# 2 specified
assert_panel_equal(p.loc[:, dates, cols],
p.reindex(major=dates, minor=cols))
assert_panel_equal(p.loc[items, :, cols],
p.reindex(items=items, minor=cols))
assert_panel_equal(p.loc[items, dates, :],
p.reindex(items=items, major=dates))
# only 1
assert_panel_equal(p.loc[items, :, :], p.reindex(items=items))
assert_panel_equal(p.loc[:, dates, :], p.reindex(major=dates))
assert_panel_equal(p.loc[:, :, cols], p.reindex(minor=cols))
def test_getitem_fancy_slice(self):
pass
def test_getitem_fancy_ints(self):
p = self.panel
# #1603
result = p.iloc[:, -1, :]
expected = p.loc[:, p.major_axis[-1], :]
assert_frame_equal(result, expected)
def test_getitem_fancy_xs(self):
p = self.panel
item = 'ItemB'
date = p.major_axis[5]
col = 'C'
# get DataFrame
# item
assert_frame_equal(p.loc[item], p[item])
assert_frame_equal(p.loc[item, :], p[item])
assert_frame_equal(p.loc[item, :, :], p[item])
# major axis, axis=1
assert_frame_equal(p.loc[:, date], p.major_xs(date))
assert_frame_equal(p.loc[:, date, :], p.major_xs(date))
# minor axis, axis=2
assert_frame_equal(p.loc[:, :, 'C'], p.minor_xs('C'))
# get Series
assert_series_equal(p.loc[item, date], p[item].loc[date])
assert_series_equal(p.loc[item, date, :], p[item].loc[date])
assert_series_equal(p.loc[item, :, col], p[item][col])
assert_series_equal(p.loc[:, date, col], p.major_xs(date).loc[col])
def test_getitem_fancy_xs_check_view(self):
item = 'ItemB'
date = self.panel.major_axis[5]
# make sure it's always a view
NS = slice(None, None)
# DataFrames
comp = assert_frame_equal
self._check_view(item, comp)
self._check_view((item, NS), comp)
self._check_view((item, NS, NS), comp)
self._check_view((NS, date), comp)
self._check_view((NS, date, NS), comp)
self._check_view((NS, NS, 'C'), comp)
# Series
comp = assert_series_equal
self._check_view((item, date), comp)
self._check_view((item, date, NS), comp)
self._check_view((item, NS, 'C'), comp)
self._check_view((NS, date, 'C'), comp)
def test_getitem_callable(self):
p = self.panel
# GH 12533
assert_frame_equal(p[lambda x: 'ItemB'], p.loc['ItemB'])
assert_panel_equal(p[lambda x: ['ItemB', 'ItemC']],
p.loc[['ItemB', 'ItemC']])
def test_ix_setitem_slice_dataframe(self):
a = Panel(items=[1, 2, 3], major_axis=[11, 22, 33],
minor_axis=[111, 222, 333])
b = DataFrame(np.random.randn(2, 3), index=[111, 333],
columns=[1, 2, 3])
a.loc[:, 22, [111, 333]] = b
assert_frame_equal(a.loc[:, 22, [111, 333]], b)
def test_ix_align(self):
from pandas import Series
b = Series(np.random.randn(10), name=0)
b.sort_values()
df_orig = Panel(np.random.randn(3, 10, 2))
df = df_orig.copy()
df.loc[0, :, 0] = b
assert_series_equal(df.loc[0, :, 0].reindex(b.index), b)
df = df_orig.swapaxes(0, 1)
df.loc[:, 0, 0] = b
assert_series_equal(df.loc[:, 0, 0].reindex(b.index), b)
df = df_orig.swapaxes(1, 2)
df.loc[0, 0, :] = b
assert_series_equal(df.loc[0, 0, :].reindex(b.index), b)
def test_ix_frame_align(self):
p_orig = tm.makePanel()
df = p_orig.iloc[0].copy()
assert_frame_equal(p_orig['ItemA'], df)
p = p_orig.copy()
p.iloc[0, :, :] = df
assert_panel_equal(p, p_orig)
p = p_orig.copy()
p.iloc[0] = df
assert_panel_equal(p, p_orig)
p = p_orig.copy()
p.iloc[0, :, :] = df
assert_panel_equal(p, p_orig)
p = p_orig.copy()
p.iloc[0] = df
assert_panel_equal(p, p_orig)
p = p_orig.copy()
p.loc['ItemA'] = df
assert_panel_equal(p, p_orig)
p = p_orig.copy()
p.loc['ItemA', :, :] = df
assert_panel_equal(p, p_orig)
p = p_orig.copy()
p['ItemA'] = df
assert_panel_equal(p, p_orig)
p = p_orig.copy()
p.iloc[0, [0, 1, 3, 5], -2:] = df
out = p.iloc[0, [0, 1, 3, 5], -2:]
assert_frame_equal(out, df.iloc[[0, 1, 3, 5], [2, 3]])
# GH3830, panel assignent by values/frame
for dtype in ['float64', 'int64']:
panel = Panel(np.arange(40).reshape((2, 4, 5)),
items=['a1', 'a2'], dtype=dtype)
df1 = panel.iloc[0]
df2 = panel.iloc[1]
tm.assert_frame_equal(panel.loc['a1'], df1)
tm.assert_frame_equal(panel.loc['a2'], df2)
# Assignment by Value Passes for 'a2'
panel.loc['a2'] = df1.values
tm.assert_frame_equal(panel.loc['a1'], df1)
tm.assert_frame_equal(panel.loc['a2'], df1)
# Assignment by DataFrame Ok w/o loc 'a2'
panel['a2'] = df2
tm.assert_frame_equal(panel.loc['a1'], df1)
tm.assert_frame_equal(panel.loc['a2'], df2)
# Assignment by DataFrame Fails for 'a2'
panel.loc['a2'] = df2
tm.assert_frame_equal(panel.loc['a1'], df1)
tm.assert_frame_equal(panel.loc['a2'], df2)
def _check_view(self, indexer, comp):
cp = self.panel.copy()
obj = cp.loc[indexer]
obj.values[:] = 0
assert (obj.values == 0).all()
comp(cp.loc[indexer].reindex_like(obj), obj)
def test_logical_with_nas(self):
d = Panel({'ItemA': {'a': [np.nan, False]},
'ItemB': {'a': [True, True]}})
result = d['ItemA'] | d['ItemB']
expected = DataFrame({'a': [np.nan, True]})
assert_frame_equal(result, expected)
# this is autodowncasted here
result = d['ItemA'].fillna(False) | d['ItemB']
expected = DataFrame({'a': [True, True]})
assert_frame_equal(result, expected)
def test_neg(self):
assert_panel_equal(-self.panel, -1 * self.panel)
def test_invert(self):
assert_panel_equal(-(self.panel < 0), ~(self.panel < 0))
def test_comparisons(self):
p1 = tm.makePanel()
p2 = tm.makePanel()
tp = p1.reindex(items=p1.items + ['foo'])
df = p1[p1.items[0]]
def test_comp(func):
# versus same index
result = func(p1, p2)
tm.assert_numpy_array_equal(result.values,
func(p1.values, p2.values))
# versus non-indexed same objs
pytest.raises(Exception, func, p1, tp)
# versus different objs
pytest.raises(Exception, func, p1, df)
# versus scalar
result3 = func(self.panel, 0)
tm.assert_numpy_array_equal(result3.values,
func(self.panel.values, 0))
with np.errstate(invalid='ignore'):
test_comp(operator.eq)
test_comp(operator.ne)
test_comp(operator.lt)
test_comp(operator.gt)
test_comp(operator.ge)
test_comp(operator.le)
def test_get_value(self):
for item in self.panel.items:
for mjr in self.panel.major_axis[::2]:
for mnr in self.panel.minor_axis:
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
result = self.panel.get_value(item, mjr, mnr)
expected = self.panel[item][mnr][mjr]
assert_almost_equal(result, expected)
with catch_warnings():
simplefilter("ignore", FutureWarning)
with tm.assert_raises_regex(TypeError,
"There must be an argument "
"for each axis"):
self.panel.get_value('a')
def test_set_value(self):
for item in self.panel.items:
for mjr in self.panel.major_axis[::2]:
for mnr in self.panel.minor_axis:
with tm.assert_produces_warning(FutureWarning,
check_stacklevel=False):
self.panel.set_value(item, mjr, mnr, 1.)
tm.assert_almost_equal(self.panel[item][mnr][mjr], 1.)
# resize
with catch_warnings():
simplefilter("ignore", FutureWarning)
res = self.panel.set_value('ItemE', 'foo', 'bar', 1.5)
assert isinstance(res, Panel)
assert res is not self.panel
assert res.get_value('ItemE', 'foo', 'bar') == 1.5
res3 = self.panel.set_value('ItemE', 'foobar', 'baz', 5)
assert is_float_dtype(res3['ItemE'].values)
msg = ("There must be an argument for each "
"axis plus the value provided")
with tm.assert_raises_regex(TypeError, msg):
self.panel.set_value('a')
@pytest.mark.filterwarnings("ignore:\\nPanel:FutureWarning")
class TestPanel(PanelTests, CheckIndexing, SafeForLongAndSparse,
SafeForSparse):
def setup_method(self, method):
self.panel = make_test_panel()
self.panel.major_axis.name = None
self.panel.minor_axis.name = None
self.panel.items.name = None
def test_constructor(self):
# with BlockManager
wp = Panel(self.panel._data)
assert wp._data is self.panel._data
wp = Panel(self.panel._data, copy=True)
assert wp._data is not self.panel._data
tm.assert_panel_equal(wp, self.panel)
# strings handled prop
wp = Panel([[['foo', 'foo', 'foo', ], ['foo', 'foo', 'foo']]])
assert wp.values.dtype == np.object_
vals = self.panel.values
# no copy
wp = Panel(vals)
assert wp.values is vals
# copy
wp = Panel(vals, copy=True)
assert wp.values is not vals
# GH #8285, test when scalar data is used to construct a Panel
# if dtype is not passed, it should be inferred
value_and_dtype = [(1, 'int64'), (3.14, 'float64'),
('foo', np.object_)]
for (val, dtype) in value_and_dtype:
wp = Panel(val, items=range(2), major_axis=range(3),
minor_axis=range(4))
vals = np.empty((2, 3, 4), dtype=dtype)
vals.fill(val)
tm.assert_panel_equal(wp, Panel(vals, dtype=dtype))
# test the case when dtype is passed
wp = Panel(1, items=range(2), major_axis=range(3),
minor_axis=range(4),
dtype='float32')
vals = np.empty((2, 3, 4), dtype='float32')
vals.fill(1)
tm.assert_panel_equal(wp, Panel(vals, dtype='float32'))
def test_constructor_cast(self):
zero_filled = self.panel.fillna(0)
casted = Panel(zero_filled._data, dtype=int)
casted2 = Panel(zero_filled.values, dtype=int)
exp_values = zero_filled.values.astype(int)
assert_almost_equal(casted.values, exp_values)
assert_almost_equal(casted2.values, exp_values)
casted = Panel(zero_filled._data, dtype=np.int32)
casted2 = Panel(zero_filled.values, dtype=np.int32)
exp_values = zero_filled.values.astype(np.int32)
assert_almost_equal(casted.values, exp_values)
assert_almost_equal(casted2.values, exp_values)
# can't cast
data = [[['foo', 'bar', 'baz']]]
pytest.raises(ValueError, Panel, data, dtype=float)
def test_constructor_empty_panel(self):
empty = Panel()
assert len(empty.items) == 0
assert len(empty.major_axis) == 0
assert len(empty.minor_axis) == 0
def test_constructor_observe_dtype(self):
# GH #411
panel = Panel(items=lrange(3), major_axis=lrange(3),
minor_axis=lrange(3), dtype='O')
assert panel.values.dtype == np.object_
def test_constructor_dtypes(self):
# GH #797
def _check_dtype(panel, dtype):
for i in panel.items:
assert panel[i].values.dtype.name == dtype
# only nan holding types allowed here
for dtype in ['float64', 'float32', 'object']:
panel = Panel(items=lrange(2), major_axis=lrange(10),
minor_axis=lrange(5), dtype=dtype)
_check_dtype(panel, dtype)
for dtype in ['float64', 'float32', 'int64', 'int32', 'object']:
panel = Panel(np.array(np.random.randn(2, 10, 5), dtype=dtype),
items=lrange(2),
major_axis=lrange(10),
minor_axis=lrange(5), dtype=dtype)
_check_dtype(panel, dtype)
for dtype in ['float64', 'float32', 'int64', 'int32', 'object']:
panel = Panel(np.array(np.random.randn(2, 10, 5), dtype='O'),
items=lrange(2),
major_axis=lrange(10),
minor_axis=lrange(5), dtype=dtype)
_check_dtype(panel, dtype)
for dtype in ['float64', 'float32', 'int64', 'int32', 'object']:
panel = Panel(
np.random.randn(2, 10, 5),
items=lrange(2), major_axis=lrange(10),
minor_axis=lrange(5),
dtype=dtype)
_check_dtype(panel, dtype)
for dtype in ['float64', 'float32', 'int64', 'int32', 'object']:
df1 = DataFrame(np.random.randn(2, 5),
index=lrange(2), columns=lrange(5))
df2 = DataFrame(np.random.randn(2, 5),
index=lrange(2), columns=lrange(5))
panel = Panel.from_dict({'a': df1, 'b': df2}, dtype=dtype)
_check_dtype(panel, dtype)
def test_constructor_fails_with_not_3d_input(self):
with tm.assert_raises_regex(ValueError, "The number of dimensions required is 3"): # noqa
Panel(np.random.randn(10, 2))
def test_consolidate(self):
assert self.panel._data.is_consolidated()
self.panel['foo'] = 1.
assert not self.panel._data.is_consolidated()
panel = self.panel._consolidate()
assert panel._data.is_consolidated()
def test_ctor_dict(self):
itema = self.panel['ItemA']
itemb = self.panel['ItemB']
d = {'A': itema, 'B': itemb[5:]}
d2 = {'A': itema._series, 'B': itemb[5:]._series}
d3 = {'A': None,
'B': DataFrame(itemb[5:]._series),
'C': DataFrame(itema._series)}
wp = Panel.from_dict(d)
wp2 = Panel.from_dict(d2) # nested Dict
# TODO: unused?
wp3 = Panel.from_dict(d3) # noqa
tm.assert_index_equal(wp.major_axis, self.panel.major_axis)
assert_panel_equal(wp, wp2)
# intersect
wp = Panel.from_dict(d, intersect=True)
tm.assert_index_equal(wp.major_axis, itemb.index[5:])
# use constructor
assert_panel_equal(Panel(d), Panel.from_dict(d))
assert_panel_equal(Panel(d2), Panel.from_dict(d2))
assert_panel_equal(Panel(d3), Panel.from_dict(d3))
# a pathological case
d4 = {'A': None, 'B': None}
# TODO: unused?
wp4 = Panel.from_dict(d4) # noqa
assert_panel_equal(Panel(d4), Panel(items=['A', 'B']))
# cast
dcasted = {k: v.reindex(wp.major_axis).fillna(0)
for k, v in compat.iteritems(d)}
result = Panel(dcasted, dtype=int)
expected = Panel({k: v.astype(int)
for k, v in compat.iteritems(dcasted)})
assert_panel_equal(result, expected)
result = Panel(dcasted, dtype=np.int32)
expected = Panel({k: v.astype(np.int32)
for k, v in compat.iteritems(dcasted)})
assert_panel_equal(result, expected)
def test_constructor_dict_mixed(self):
data = {k: v.values for k, v in self.panel.iteritems()}
result = Panel(data)
exp_major = Index(np.arange(len(self.panel.major_axis)))
tm.assert_index_equal(result.major_axis, exp_major)
result = Panel(data, items=self.panel.items,
major_axis=self.panel.major_axis,
minor_axis=self.panel.minor_axis)
assert_panel_equal(result, self.panel)
data['ItemC'] = self.panel['ItemC']
result = Panel(data)
assert_panel_equal(result, self.panel)
# corner, blow up
data['ItemB'] = data['ItemB'][:-1]
pytest.raises(Exception, Panel, data)
data['ItemB'] = self.panel['ItemB'].values[:, :-1]
pytest.raises(Exception, Panel, data)
def test_ctor_orderedDict(self):
keys = list(set(np.random.randint(0, 5000, 100)))[
:50] # unique random int keys
d = OrderedDict([(k, mkdf(10, 5)) for k in keys])
p = Panel(d)
assert list(p.items) == keys
p = Panel.from_dict(d)
assert list(p.items) == keys
def test_constructor_resize(self):
data = self.panel._data
items = self.panel.items[:-1]
major = self.panel.major_axis[:-1]
minor = self.panel.minor_axis[:-1]
result = Panel(data, items=items,
major_axis=major, minor_axis=minor)
expected = self.panel.reindex(
items=items, major=major, minor=minor)
assert_panel_equal(result, expected)
result = Panel(data, items=items, major_axis=major)
expected = self.panel.reindex(items=items, major=major)
assert_panel_equal(result, expected)
result = Panel(data, items=items)
expected = self.panel.reindex(items=items)
assert_panel_equal(result, expected)
result = Panel(data, minor_axis=minor)
expected = self.panel.reindex(minor=minor)
assert_panel_equal(result, expected)
def test_from_dict_mixed_orient(self):
df = tm.makeDataFrame()
df['foo'] = 'bar'
data = {'k1': df, 'k2': df}
panel = Panel.from_dict(data, orient='minor')
assert panel['foo'].values.dtype == np.object_
assert panel['A'].values.dtype == np.float64
def test_constructor_error_msgs(self):
def testit():
Panel(np.random.randn(3, 4, 5),
lrange(4), lrange(5), lrange(5))
tm.assert_raises_regex(ValueError,
r"Shape of passed values is "
r"\(3, 4, 5\), indices imply "
r"\(4, 5, 5\)",
testit)
def testit():
Panel(np.random.randn(3, 4, 5),
lrange(5), lrange(4), lrange(5))
tm.assert_raises_regex(ValueError,
r"Shape of passed values is "
r"\(3, 4, 5\), indices imply "
r"\(5, 4, 5\)",
testit)
def testit():
Panel(np.random.randn(3, 4, 5),
lrange(5), lrange(5), lrange(4))
tm.assert_raises_regex(ValueError,
r"Shape of passed values is "
r"\(3, 4, 5\), indices imply "
r"\(5, 5, 4\)",
testit)
def test_conform(self):
df = self.panel['ItemA'][:-5].filter(items=['A', 'B'])
conformed = self.panel.conform(df)
tm.assert_index_equal(conformed.index, self.panel.major_axis)
tm.assert_index_equal(conformed.columns, self.panel.minor_axis)
def test_convert_objects(self):
# GH 4937
p = Panel(dict(A=dict(a=['1', '1.0'])))
expected = Panel(dict(A=dict(a=[1, 1.0])))
result = p._convert(numeric=True, coerce=True)
assert_panel_equal(result, expected)
def test_dtypes(self):
result = self.panel.dtypes
expected = Series(np.dtype('float64'), index=self.panel.items)
assert_series_equal(result, expected)
def test_astype(self):
# GH7271
data = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
panel = Panel(data, ['a', 'b'], ['c', 'd'], ['e', 'f'])
str_data = np.array([[['1', '2'], ['3', '4']],
[['5', '6'], ['7', '8']]])
expected = Panel(str_data, ['a', 'b'], ['c', 'd'], ['e', 'f'])
assert_panel_equal(panel.astype(str), expected)
pytest.raises(NotImplementedError, panel.astype, {0: str})
def test_apply(self):
# GH1148
# ufunc
applied = self.panel.apply(np.sqrt)
with np.errstate(invalid='ignore'):
expected = np.sqrt(self.panel.values)
assert_almost_equal(applied.values, expected)
# ufunc same shape
result = self.panel.apply(lambda x: x * 2, axis='items')
expected = self.panel * 2
assert_panel_equal(result, expected)
result = self.panel.apply(lambda x: x * 2, axis='major_axis')
expected = self.panel * 2
assert_panel_equal(result, expected)
result = self.panel.apply(lambda x: x * 2, axis='minor_axis')
expected = self.panel * 2
assert_panel_equal(result, expected)
# reduction to DataFrame
result = self.panel.apply(lambda x: x.dtype, axis='items')
expected = DataFrame(np.dtype('float64'),
index=self.panel.major_axis,
columns=self.panel.minor_axis)
assert_frame_equal(result, expected)
result = self.panel.apply(lambda x: x.dtype, axis='major_axis')
expected = DataFrame(np.dtype('float64'),
index=self.panel.minor_axis,
columns=self.panel.items)
assert_frame_equal(result, expected)
result = self.panel.apply(lambda x: x.dtype, axis='minor_axis')
expected = DataFrame(np.dtype('float64'),
index=self.panel.major_axis,
columns=self.panel.items)
assert_frame_equal(result, expected)
# reductions via other dims
expected = self.panel.sum(0)
result = self.panel.apply(lambda x: x.sum(), axis='items')
assert_frame_equal(result, expected)
expected = self.panel.sum(1)
result = self.panel.apply(lambda x: x.sum(), axis='major_axis')
assert_frame_equal(result, expected)
expected = self.panel.sum(2)
result = self.panel.apply(lambda x: x.sum(), axis='minor_axis')
assert_frame_equal(result, expected)
# pass kwargs
result = self.panel.apply(
lambda x, y: x.sum() + y, axis='items', y=5)
expected = self.panel.sum(0) + 5
assert_frame_equal(result, expected)
def test_apply_slabs(self):
# same shape as original
result = self.panel.apply(lambda x: x * 2,
axis=['items', 'major_axis'])
expected = (self.panel * 2).transpose('minor_axis', 'major_axis',
'items')
assert_panel_equal(result, expected)
result = self.panel.apply(lambda x: x * 2,
axis=['major_axis', 'items'])
assert_panel_equal(result, expected)
result = self.panel.apply(lambda x: x * 2,
axis=['items', 'minor_axis'])
expected = (self.panel * 2).transpose('major_axis', 'minor_axis',
'items')
assert_panel_equal(result, expected)
result = self.panel.apply(lambda x: x * 2,
axis=['minor_axis', 'items'])
assert_panel_equal(result, expected)
result = self.panel.apply(lambda x: x * 2,
axis=['major_axis', 'minor_axis'])
expected = self.panel * 2
assert_panel_equal(result, expected)
result = self.panel.apply(lambda x: x * 2,
axis=['minor_axis', 'major_axis'])
assert_panel_equal(result, expected)
# reductions
result = self.panel.apply(lambda x: x.sum(0), axis=[
'items', 'major_axis'
])
expected = self.panel.sum(1).T
assert_frame_equal(result, expected)
result = self.panel.apply(lambda x: x.sum(1), axis=[
'items', 'major_axis'
])
expected = self.panel.sum(0)
assert_frame_equal(result, expected)
# transforms
f = lambda x: ((x.T - x.mean(1)) / x.std(1)).T
# make sure that we don't trigger any warnings
result = self.panel.apply(f, axis=['items', 'major_axis'])
expected = Panel({ax: f(self.panel.loc[:, :, ax])
for ax in self.panel.minor_axis})
assert_panel_equal(result, expected)
result = self.panel.apply(f, axis=['major_axis', 'minor_axis'])
expected = Panel({ax: f(self.panel.loc[ax])
for ax in self.panel.items})
assert_panel_equal(result, expected)
result = self.panel.apply(f, axis=['minor_axis', 'items'])
expected = Panel({ax: f(self.panel.loc[:, ax])
for ax in self.panel.major_axis})
assert_panel_equal(result, expected)
# with multi-indexes
# GH7469
index = MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), (
'two', 'a'), ('two', 'b')])
dfa = DataFrame(np.array(np.arange(12, dtype='int64')).reshape(
4, 3), columns=list("ABC"), index=index)
dfb = DataFrame(np.array(np.arange(10, 22, dtype='int64')).reshape(
4, 3), columns=list("ABC"), index=index)
p = Panel({'f': dfa, 'g': dfb})
result = p.apply(lambda x: x.sum(), axis=0)
# on windows this will be in32
result = result.astype('int64')
expected = p.sum(0)
assert_frame_equal(result, expected)
def test_apply_no_or_zero_ndim(self):
# GH10332
self.panel = Panel(np.random.rand(5, 5, 5))
result_int = self.panel.apply(lambda df: 0, axis=[1, 2])
result_float = self.panel.apply(lambda df: 0.0, axis=[1, 2])
result_int64 = self.panel.apply(
lambda df: np.int64(0), axis=[1, 2])
result_float64 = self.panel.apply(lambda df: np.float64(0.0),
axis=[1, 2])
expected_int = expected_int64 = Series([0] * 5)
expected_float = expected_float64 = Series([0.0] * 5)
assert_series_equal(result_int, expected_int)
assert_series_equal(result_int64, expected_int64)
assert_series_equal(result_float, expected_float)
assert_series_equal(result_float64, expected_float64)
def test_reindex(self):
ref = self.panel['ItemB']
# items
result = self.panel.reindex(items=['ItemA', 'ItemB'])
assert_frame_equal(result['ItemB'], ref)
# major
new_major = list(self.panel.major_axis[:10])
result = self.panel.reindex(major=new_major)
assert_frame_equal(result['ItemB'], ref.reindex(index=new_major))
# raise exception put both major and major_axis
pytest.raises(Exception, self.panel.reindex,
major_axis=new_major,
major=new_major)
# minor
new_minor = list(self.panel.minor_axis[:2])
result = self.panel.reindex(minor=new_minor)
assert_frame_equal(result['ItemB'], ref.reindex(columns=new_minor))
# raise exception put both major and major_axis
pytest.raises(Exception, self.panel.reindex,
minor_axis=new_minor,
minor=new_minor)
# this ok
result = self.panel.reindex()
assert_panel_equal(result, self.panel)
assert result is not self.panel
# with filling
smaller_major = self.panel.major_axis[::5]
smaller = self.panel.reindex(major=smaller_major)
larger = smaller.reindex(major=self.panel.major_axis, method='pad')
assert_frame_equal(larger.major_xs(self.panel.major_axis[1]),
smaller.major_xs(smaller_major[0]))
# don't necessarily copy
result = self.panel.reindex(
major=self.panel.major_axis, copy=False)
assert_panel_equal(result, self.panel)
assert result is self.panel
def test_reindex_axis_style(self):
panel = Panel(np.random.rand(5, 5, 5))
expected0 = Panel(panel.values).iloc[[0, 1]]
expected1 = Panel(panel.values).iloc[:, [0, 1]]
expected2 = Panel(panel.values).iloc[:, :, [0, 1]]
result = panel.reindex([0, 1], axis=0)
assert_panel_equal(result, expected0)
result = panel.reindex([0, 1], axis=1)
assert_panel_equal(result, expected1)
result = panel.reindex([0, 1], axis=2)
assert_panel_equal(result, expected2)
result = panel.reindex([0, 1], axis=2)
assert_panel_equal(result, expected2)
def test_reindex_multi(self):
# with and without copy full reindexing
result = self.panel.reindex(
items=self.panel.items,
major=self.panel.major_axis,
minor=self.panel.minor_axis, copy=False)
assert result.items is self.panel.items
assert result.major_axis is self.panel.major_axis
assert result.minor_axis is self.panel.minor_axis
result = self.panel.reindex(
items=self.panel.items,
major=self.panel.major_axis,
minor=self.panel.minor_axis, copy=False)
assert_panel_equal(result, self.panel)
# multi-axis indexing consistency
# GH 5900
df = DataFrame(np.random.randn(4, 3))
p = Panel({'Item1': df})
expected = Panel({'Item1': df})
expected['Item2'] = np.nan
items = ['Item1', 'Item2']
major_axis = np.arange(4)
minor_axis = np.arange(3)
results = []
results.append(p.reindex(items=items, major_axis=major_axis,
copy=True))
results.append(p.reindex(items=items, major_axis=major_axis,
copy=False))
results.append(p.reindex(items=items, minor_axis=minor_axis,
copy=True))
results.append(p.reindex(items=items, minor_axis=minor_axis,
copy=False))
results.append(p.reindex(items=items, major_axis=major_axis,
minor_axis=minor_axis, copy=True))
results.append(p.reindex(items=items, major_axis=major_axis,
minor_axis=minor_axis, copy=False))
for i, r in enumerate(results):
assert_panel_equal(expected, r)
def test_reindex_like(self):
# reindex_like
smaller = self.panel.reindex(items=self.panel.items[:-1],
major=self.panel.major_axis[:-1],
minor=self.panel.minor_axis[:-1])
smaller_like = self.panel.reindex_like(smaller)
assert_panel_equal(smaller, smaller_like)
def test_take(self):
# axis == 0
result = self.panel.take([2, 0, 1], axis=0)
expected = self.panel.reindex(items=['ItemC', 'ItemA', 'ItemB'])
assert_panel_equal(result, expected)
# axis >= 1
result = self.panel.take([3, 0, 1, 2], axis=2)
expected = self.panel.reindex(minor=['D', 'A', 'B', 'C'])
assert_panel_equal(result, expected)
# neg indices ok
expected = self.panel.reindex(minor=['D', 'D', 'B', 'C'])
result = self.panel.take([3, -1, 1, 2], axis=2)
assert_panel_equal(result, expected)
pytest.raises(Exception, self.panel.take, [4, 0, 1, 2], axis=2)
def test_sort_index(self):
import random
ritems = list(self.panel.items)
rmajor = list(self.panel.major_axis)
rminor = list(self.panel.minor_axis)
random.shuffle(ritems)
random.shuffle(rmajor)
random.shuffle(rminor)
random_order = self.panel.reindex(items=ritems)
sorted_panel = random_order.sort_index(axis=0)
assert_panel_equal(sorted_panel, self.panel)
# descending
random_order = self.panel.reindex(items=ritems)
sorted_panel = random_order.sort_index(axis=0, ascending=False)
assert_panel_equal(
sorted_panel,
self.panel.reindex(items=self.panel.items[::-1]))
random_order = self.panel.reindex(major=rmajor)
sorted_panel = random_order.sort_index(axis=1)
assert_panel_equal(sorted_panel, self.panel)
random_order = self.panel.reindex(minor=rminor)
sorted_panel = random_order.sort_index(axis=2)
assert_panel_equal(sorted_panel, self.panel)
def test_fillna(self):
filled = self.panel.fillna(0)
assert np.isfinite(filled.values).all()
filled = self.panel.fillna(method='backfill')
assert_frame_equal(filled['ItemA'],
self.panel['ItemA'].fillna(method='backfill'))
panel = self.panel.copy()
panel['str'] = 'foo'
filled = panel.fillna(method='backfill')
assert_frame_equal(filled['ItemA'],
panel['ItemA'].fillna(method='backfill'))
empty = self.panel.reindex(items=[])
filled = empty.fillna(0)
assert_panel_equal(filled, empty)
pytest.raises(ValueError, self.panel.fillna)
pytest.raises(ValueError, self.panel.fillna, 5, method='ffill')
pytest.raises(TypeError, self.panel.fillna, [1, 2])
pytest.raises(TypeError, self.panel.fillna, (1, 2))
# limit not implemented when only value is specified
p = Panel(np.random.randn(3, 4, 5))
p.iloc[0:2, 0:2, 0:2] = np.nan
pytest.raises(NotImplementedError,
lambda: p.fillna(999, limit=1))
# Test in place fillNA
# Expected result
expected = Panel([[[0, 1], [2, 1]], [[10, 11], [12, 11]]],
items=['a', 'b'], minor_axis=['x', 'y'],
dtype=np.float64)
# method='ffill'
p1 = Panel([[[0, 1], [2, np.nan]], [[10, 11], [12, np.nan]]],
items=['a', 'b'], minor_axis=['x', 'y'],
dtype=np.float64)
p1.fillna(method='ffill', inplace=True)
assert_panel_equal(p1, expected)
# method='bfill'
p2 = Panel([[[0, np.nan], [2, 1]], [[10, np.nan], [12, 11]]],
items=['a', 'b'], minor_axis=['x', 'y'],
dtype=np.float64)
p2.fillna(method='bfill', inplace=True)
assert_panel_equal(p2, expected)
def test_ffill_bfill(self):
assert_panel_equal(self.panel.ffill(),
self.panel.fillna(method='ffill'))
assert_panel_equal(self.panel.bfill(),
self.panel.fillna(method='bfill'))
def test_truncate_fillna_bug(self):
# #1823
result = self.panel.truncate(before=None, after=None, axis='items')
# it works!
result.fillna(value=0.0)
def test_swapaxes(self):
result = self.panel.swapaxes('items', 'minor')
assert result.items is self.panel.minor_axis
result = self.panel.swapaxes('items', 'major')
assert result.items is self.panel.major_axis
result = self.panel.swapaxes('major', 'minor')
assert result.major_axis is self.panel.minor_axis
panel = self.panel.copy()
result = panel.swapaxes('major', 'minor')
panel.values[0, 0, 1] = np.nan
expected = panel.swapaxes('major', 'minor')
assert_panel_equal(result, expected)
# this should also work
result = self.panel.swapaxes(0, 1)
assert result.items is self.panel.major_axis
# this works, but return a copy
result = self.panel.swapaxes('items', 'items')
assert_panel_equal(self.panel, result)
assert id(self.panel) != id(result)
def test_transpose(self):
result = self.panel.transpose('minor', 'major', 'items')
expected = self.panel.swapaxes('items', 'minor')
assert_panel_equal(result, expected)
# test kwargs
result = self.panel.transpose(items='minor', major='major',
minor='items')
expected = self.panel.swapaxes('items', 'minor')
assert_panel_equal(result, expected)
# text mixture of args
result = self.panel.transpose(
'minor', major='major', minor='items')
expected = self.panel.swapaxes('items', 'minor')
assert_panel_equal(result, expected)
result = self.panel.transpose('minor',
'major',
minor='items')
expected = self.panel.swapaxes('items', 'minor')
assert_panel_equal(result, expected)
# duplicate axes
with tm.assert_raises_regex(TypeError,
'not enough/duplicate arguments'):
self.panel.transpose('minor', maj='major', minor='items')
with tm.assert_raises_regex(ValueError,
'repeated axis in transpose'):
self.panel.transpose('minor', 'major', major='minor',
minor='items')
result = self.panel.transpose(2, 1, 0)
assert_panel_equal(result, expected)
result = self.panel.transpose('minor', 'items', 'major')
expected = self.panel.swapaxes('items', 'minor')
expected = expected.swapaxes('major', 'minor')
assert_panel_equal(result, expected)
result = self.panel.transpose(2, 0, 1)
assert_panel_equal(result, expected)
pytest.raises(ValueError, self.panel.transpose, 0, 0, 1)
def test_transpose_copy(self):
panel = self.panel.copy()
result = panel.transpose(2, 0, 1, copy=True)
expected = panel.swapaxes('items', 'minor')
expected = expected.swapaxes('major', 'minor')
assert_panel_equal(result, expected)
panel.values[0, 1, 1] = np.nan
assert notna(result.values[1, 0, 1])
def test_to_frame(self):
# filtered
filtered = self.panel.to_frame()
expected = self.panel.to_frame().dropna(how='any')
assert_frame_equal(filtered, expected)
# unfiltered
unfiltered = self.panel.to_frame(filter_observations=False)
assert_panel_equal(unfiltered.to_panel(), self.panel)
# names
assert unfiltered.index.names == ('major', 'minor')
# unsorted, round trip
df = self.panel.to_frame(filter_observations=False)
unsorted = df.take(np.random.permutation(len(df)))
pan = unsorted.to_panel()
assert_panel_equal(pan, self.panel)
# preserve original index names
df = DataFrame(np.random.randn(6, 2),
index=[['a', 'a', 'b', 'b', 'c', 'c'],
[0, 1, 0, 1, 0, 1]],
columns=['one', 'two'])
df.index.names = ['foo', 'bar']
df.columns.name = 'baz'
rdf = df.to_panel().to_frame()
assert rdf.index.names == df.index.names
assert rdf.columns.names == df.columns.names
def test_to_frame_mixed(self):
panel = self.panel.fillna(0)
panel['str'] = 'foo'
panel['bool'] = panel['ItemA'] > 0
lp = panel.to_frame()
wp = lp.to_panel()
assert wp['bool'].values.dtype == np.bool_
# Previously, this was mutating the underlying
# index and changing its name
assert_frame_equal(wp['bool'], panel['bool'], check_names=False)
# GH 8704
# with categorical
df = panel.to_frame()
df['category'] = df['str'].astype('category')
# to_panel
# TODO: this converts back to object
p = df.to_panel()
expected = panel.copy()
expected['category'] = 'foo'
assert_panel_equal(p, expected)
def test_to_frame_multi_major(self):
idx = MultiIndex.from_tuples(
[(1, 'one'), (1, 'two'), (2, 'one'), (2, 'two')])
df = DataFrame([[1, 'a', 1], [2, 'b', 1],
[3, 'c', 1], [4, 'd', 1]],
columns=['A', 'B', 'C'], index=idx)
wp = Panel({'i1': df, 'i2': df})
expected_idx = MultiIndex.from_tuples(
[
(1, 'one', 'A'), (1, 'one', 'B'),
(1, 'one', 'C'), (1, 'two', 'A'),
(1, 'two', 'B'), (1, 'two', 'C'),
(2, 'one', 'A'), (2, 'one', 'B'),
(2, 'one', 'C'), (2, 'two', 'A'),
(2, 'two', 'B'), (2, 'two', 'C')
],
names=[None, None, 'minor'])
expected = DataFrame({'i1': [1, 'a', 1, 2, 'b', 1, 3,
'c', 1, 4, 'd', 1],
'i2': [1, 'a', 1, 2, 'b',
1, 3, 'c', 1, 4, 'd', 1]},
index=expected_idx)
result = wp.to_frame()
assert_frame_equal(result, expected)
wp.iloc[0, 0].iloc[0] = np.nan # BUG on setting. GH #5773
result = wp.to_frame()
assert_frame_equal(result, expected[1:])
idx = MultiIndex.from_tuples(
[(1, 'two'), (1, 'one'), (2, 'one'), (np.nan, 'two')])
df = DataFrame([[1, 'a', 1], [2, 'b', 1],
[3, 'c', 1], [4, 'd', 1]],
columns=['A', 'B', 'C'], index=idx)
wp = Panel({'i1': df, 'i2': df})
ex_idx = MultiIndex.from_tuples([(1, 'two', 'A'), (1, 'two', 'B'),
(1, 'two', 'C'),
(1, 'one', 'A'),
(1, 'one', 'B'),
(1, 'one', 'C'),
(2, 'one', 'A'),
(2, 'one', 'B'),
(2, 'one', 'C'),
(np.nan, 'two', 'A'),
(np.nan, 'two', 'B'),
(np.nan, 'two', 'C')],
names=[None, None, 'minor'])
expected.index = ex_idx
result = wp.to_frame()
assert_frame_equal(result, expected)
def test_to_frame_multi_major_minor(self):
cols = MultiIndex(levels=[['C_A', 'C_B'], ['C_1', 'C_2']],
labels=[[0, 0, 1, 1], [0, 1, 0, 1]])
idx = MultiIndex.from_tuples([(1, 'one'), (1, 'two'), (2, 'one'), (
2, 'two'), (3, 'three'), (4, 'four')])
df = DataFrame([[1, 2, 11, 12], [3, 4, 13, 14],
['a', 'b', 'w', 'x'],
['c', 'd', 'y', 'z'], [-1, -2, -3, -4],
[-5, -6, -7, -8]], columns=cols, index=idx)
wp = Panel({'i1': df, 'i2': df})
exp_idx = MultiIndex.from_tuples(
[(1, 'one', 'C_A', 'C_1'), (1, 'one', 'C_A', 'C_2'),
(1, 'one', 'C_B', 'C_1'), (1, 'one', 'C_B', 'C_2'),
(1, 'two', 'C_A', 'C_1'), (1, 'two', 'C_A', 'C_2'),
(1, 'two', 'C_B', 'C_1'), (1, 'two', 'C_B', 'C_2'),
(2, 'one', 'C_A', 'C_1'), (2, 'one', 'C_A', 'C_2'),
(2, 'one', 'C_B', 'C_1'), (2, 'one', 'C_B', 'C_2'),
(2, 'two', 'C_A', 'C_1'), (2, 'two', 'C_A', 'C_2'),
(2, 'two', 'C_B', 'C_1'), (2, 'two', 'C_B', 'C_2'),
(3, 'three', 'C_A', 'C_1'), (3, 'three', 'C_A', 'C_2'),
(3, 'three', 'C_B', 'C_1'), (3, 'three', 'C_B', 'C_2'),
(4, 'four', 'C_A', 'C_1'), (4, 'four', 'C_A', 'C_2'),
(4, 'four', 'C_B', 'C_1'), (4, 'four', 'C_B', 'C_2')],
names=[None, None, None, None])
exp_val = [[1, 1], [2, 2], [11, 11], [12, 12],
[3, 3], [4, 4],
[13, 13], [14, 14], ['a', 'a'],
['b', 'b'], ['w', 'w'],
['x', 'x'], ['c', 'c'], ['d', 'd'], [
'y', 'y'], ['z', 'z'],
[-1, -1], [-2, -2], [-3, -3], [-4, -4],
[-5, -5], [-6, -6],
[-7, -7], [-8, -8]]
result = wp.to_frame()
expected = DataFrame(exp_val, columns=['i1', 'i2'], index=exp_idx)
assert_frame_equal(result, expected)
def test_to_frame_multi_drop_level(self):
idx = MultiIndex.from_tuples([(1, 'one'), (2, 'one'), (2, 'two')])
df = DataFrame({'A': [np.nan, 1, 2]}, index=idx)
wp = Panel({'i1': df, 'i2': df})
result = wp.to_frame()
exp_idx = MultiIndex.from_tuples(
[(2, 'one', 'A'), (2, 'two', 'A')],
names=[None, None, 'minor'])
expected = DataFrame({'i1': [1., 2], 'i2': [1., 2]}, index=exp_idx)
assert_frame_equal(result, expected)
def test_to_panel_na_handling(self):
df = DataFrame(np.random.randint(0, 10, size=20).reshape((10, 2)),
index=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 1, 2, 3, 4, 5, 2, 3, 4, 5]])
panel = df.to_panel()
assert isna(panel[0].loc[1, [0, 1]]).all()
def test_to_panel_duplicates(self):
# #2441
df = DataFrame({'a': [0, 0, 1], 'b': [1, 1, 1], 'c': [1, 2, 3]})
idf = df.set_index(['a', 'b'])
tm.assert_raises_regex(
ValueError, 'non-uniquely indexed', idf.to_panel)
def test_panel_dups(self):
# GH 4960
# duplicates in an index
# items
data = np.random.randn(5, 100, 5)
no_dup_panel = Panel(data, items=list("ABCDE"))
panel = Panel(data, items=list("AACDE"))
expected = no_dup_panel['A']
result = panel.iloc[0]
assert_frame_equal(result, expected)
expected = no_dup_panel['E']
result = panel.loc['E']
assert_frame_equal(result, expected)
expected = no_dup_panel.loc[['A', 'B']]
expected.items = ['A', 'A']
result = panel.loc['A']
assert_panel_equal(result, expected)
# major
data = np.random.randn(5, 5, 5)
no_dup_panel = Panel(data, major_axis=list("ABCDE"))
panel = Panel(data, major_axis=list("AACDE"))
expected = no_dup_panel.loc[:, 'A']
result = panel.iloc[:, 0]
assert_frame_equal(result, expected)
expected = no_dup_panel.loc[:, 'E']
result = panel.loc[:, 'E']
assert_frame_equal(result, expected)
expected = no_dup_panel.loc[:, ['A', 'B']]
expected.major_axis = ['A', 'A']
result = panel.loc[:, 'A']
assert_panel_equal(result, expected)
# minor
data = np.random.randn(5, 100, 5)
no_dup_panel = Panel(data, minor_axis=list("ABCDE"))
panel = Panel(data, minor_axis=list("AACDE"))
expected = no_dup_panel.loc[:, :, 'A']
result = panel.iloc[:, :, 0]
assert_frame_equal(result, expected)
expected = no_dup_panel.loc[:, :, 'E']
result = panel.loc[:, :, 'E']
assert_frame_equal(result, expected)
expected = no_dup_panel.loc[:, :, ['A', 'B']]
expected.minor_axis = ['A', 'A']
result = panel.loc[:, :, 'A']
assert_panel_equal(result, expected)
def test_filter(self):
pass
def test_compound(self):
compounded = self.panel.compound()
assert_series_equal(compounded['ItemA'],
(1 + self.panel['ItemA']).product(0) - 1,
check_names=False)
def test_shift(self):
# major
idx = self.panel.major_axis[0]
idx_lag = self.panel.major_axis[1]
shifted = self.panel.shift(1)
assert_frame_equal(self.panel.major_xs(idx),
shifted.major_xs(idx_lag))
# minor
idx = self.panel.minor_axis[0]
idx_lag = self.panel.minor_axis[1]
shifted = self.panel.shift(1, axis='minor')
assert_frame_equal(self.panel.minor_xs(idx),
shifted.minor_xs(idx_lag))
# items
idx = self.panel.items[0]
idx_lag = self.panel.items[1]
shifted = self.panel.shift(1, axis='items')
assert_frame_equal(self.panel[idx], shifted[idx_lag])
# negative numbers, #2164
result = self.panel.shift(-1)
expected = Panel({i: f.shift(-1)[:-1]
for i, f in self.panel.iteritems()})
assert_panel_equal(result, expected)
# mixed dtypes #6959
data = [('item ' + ch, makeMixedDataFrame())
for ch in list('abcde')]
data = dict(data)
mixed_panel = Panel.from_dict(data, orient='minor')
shifted = mixed_panel.shift(1)
assert_series_equal(mixed_panel.dtypes, shifted.dtypes)
def test_tshift(self):
# PeriodIndex
ps = tm.makePeriodPanel()
shifted = ps.tshift(1)
unshifted = shifted.tshift(-1)
assert_panel_equal(unshifted, ps)
shifted2 = ps.tshift(freq='B')
assert_panel_equal(shifted, shifted2)
shifted3 = ps.tshift(freq=BDay())
assert_panel_equal(shifted, shifted3)
tm.assert_raises_regex(ValueError, 'does not match',
ps.tshift, freq='M')
# DatetimeIndex
panel = make_test_panel()
shifted = panel.tshift(1)
unshifted = shifted.tshift(-1)
assert_panel_equal(panel, unshifted)
shifted2 = panel.tshift(freq=panel.major_axis.freq)
assert_panel_equal(shifted, shifted2)
inferred_ts = Panel(panel.values, items=panel.items,
major_axis=Index(np.asarray(panel.major_axis)),
minor_axis=panel.minor_axis)
shifted = inferred_ts.tshift(1)
unshifted = shifted.tshift(-1)
assert_panel_equal(shifted, panel.tshift(1))
assert_panel_equal(unshifted, inferred_ts)
no_freq = panel.iloc[:, [0, 5, 7], :]
pytest.raises(ValueError, no_freq.tshift)
def test_pct_change(self):
df1 = DataFrame({'c1': [1, 2, 5], 'c2': [3, 4, 6]})
df2 = df1 + 1
df3 = DataFrame({'c1': [3, 4, 7], 'c2': [5, 6, 8]})
wp = Panel({'i1': df1, 'i2': df2, 'i3': df3})
# major, 1
result = wp.pct_change() # axis='major'
expected = Panel({'i1': df1.pct_change(),
'i2': df2.pct_change(),
'i3': df3.pct_change()})
assert_panel_equal(result, expected)
result = wp.pct_change(axis=1)
assert_panel_equal(result, expected)
# major, 2
result = wp.pct_change(periods=2)
expected = Panel({'i1': df1.pct_change(2),
'i2': df2.pct_change(2),
'i3': df3.pct_change(2)})
assert_panel_equal(result, expected)
# minor, 1
result = wp.pct_change(axis='minor')
expected = Panel({'i1': df1.pct_change(axis=1),
'i2': df2.pct_change(axis=1),
'i3': df3.pct_change(axis=1)})
assert_panel_equal(result, expected)
result = wp.pct_change(axis=2)
assert_panel_equal(result, expected)
# minor, 2
result = wp.pct_change(periods=2, axis='minor')
expected = Panel({'i1': df1.pct_change(periods=2, axis=1),
'i2': df2.pct_change(periods=2, axis=1),
'i3': df3.pct_change(periods=2, axis=1)})
assert_panel_equal(result, expected)
# items, 1
result = wp.pct_change(axis='items')
expected = Panel(
{'i1': DataFrame({'c1': [np.nan, np.nan, np.nan],
'c2': [np.nan, np.nan, np.nan]}),
'i2': DataFrame({'c1': [1, 0.5, .2],
'c2': [1. / 3, 0.25, 1. / 6]}),
'i3': DataFrame({'c1': [.5, 1. / 3, 1. / 6],
'c2': [.25, .2, 1. / 7]})})
assert_panel_equal(result, expected)
result = wp.pct_change(axis=0)
assert_panel_equal(result, expected)
# items, 2
result = wp.pct_change(periods=2, axis='items')
expected = Panel(
{'i1': DataFrame({'c1': [np.nan, np.nan, np.nan],
'c2': [np.nan, np.nan, np.nan]}),
'i2': DataFrame({'c1': [np.nan, np.nan, np.nan],
'c2': [np.nan, np.nan, np.nan]}),
'i3': DataFrame({'c1': [2, 1, .4],
'c2': [2. / 3, .5, 1. / 3]})})
assert_panel_equal(result, expected)
def test_round(self):
values = [[[-3.2, 2.2], [0, -4.8213], [3.123, 123.12],
[-1566.213, 88.88], [-12, 94.5]],
[[-5.82, 3.5], [6.21, -73.272], [-9.087, 23.12],
[272.212, -99.99], [23, -76.5]]]
evalues = [[[float(np.around(i)) for i in j] for j in k]
for k in values]
p = Panel(values, items=['Item1', 'Item2'],
major_axis=date_range('1/1/2000', periods=5),
minor_axis=['A', 'B'])
expected = Panel(evalues, items=['Item1', 'Item2'],
major_axis=date_range('1/1/2000', periods=5),
minor_axis=['A', 'B'])
result = p.round()
assert_panel_equal(expected, result)
def test_numpy_round(self):
values = [[[-3.2, 2.2], [0, -4.8213], [3.123, 123.12],
[-1566.213, 88.88], [-12, 94.5]],
[[-5.82, 3.5], [6.21, -73.272], [-9.087, 23.12],
[272.212, -99.99], [23, -76.5]]]
evalues = [[[float(np.around(i)) for i in j] for j in k]
for k in values]
p = Panel(values, items=['Item1', 'Item2'],
major_axis=date_range('1/1/2000', periods=5),
minor_axis=['A', 'B'])
expected = Panel(evalues, items=['Item1', 'Item2'],
major_axis=date_range('1/1/2000', periods=5),
minor_axis=['A', 'B'])
result = np.round(p)
assert_panel_equal(expected, result)
msg = "the 'out' parameter is not supported"
tm.assert_raises_regex(ValueError, msg, np.round, p, out=p)
# removing Panel before NumPy enforces, so just ignore
@pytest.mark.filterwarnings("ignore:Using a non-tuple:FutureWarning")
def test_multiindex_get(self):
ind = MultiIndex.from_tuples(
[('a', 1), ('a', 2), ('b', 1), ('b', 2)],
names=['first', 'second'])
wp = Panel(np.random.random((4, 5, 5)),
items=ind,
major_axis=np.arange(5),
minor_axis=np.arange(5))
f1 = wp['a']
f2 = wp.loc['a']
assert_panel_equal(f1, f2)
assert (f1.items == [1, 2]).all()
assert (f2.items == [1, 2]).all()
MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1)],
names=['first', 'second'])
@pytest.mark.filterwarnings("ignore:Using a non-tuple:FutureWarning")
def test_multiindex_blocks(self):
ind = MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1)],
names=['first', 'second'])
wp = Panel(self.panel._data)
wp.items = ind
f1 = wp['a']
assert (f1.items == [1, 2]).all()
f1 = wp[('b', 1)]
assert (f1.columns == ['A', 'B', 'C', 'D']).all()
def test_repr_empty(self):
empty = Panel()
repr(empty)
# ignore warning from us, because removing panel
@pytest.mark.filterwarnings("ignore:Using:FutureWarning")
def test_rename(self):
mapper = {'ItemA': 'foo', 'ItemB': 'bar', 'ItemC': 'baz'}
renamed = self.panel.rename(items=mapper)
exp = Index(['foo', 'bar', 'baz'])
tm.assert_index_equal(renamed.items, exp)
renamed = self.panel.rename(minor_axis=str.lower)
exp = Index(['a', 'b', 'c', 'd'])
tm.assert_index_equal(renamed.minor_axis, exp)
# don't copy
renamed_nocopy = self.panel.rename(items=mapper, copy=False)
renamed_nocopy['foo'] = 3.
assert (self.panel['ItemA'].values == 3).all()
def test_get_attr(self):
assert_frame_equal(self.panel['ItemA'], self.panel.ItemA)
# specific cases from #3440
self.panel['a'] = self.panel['ItemA']
assert_frame_equal(self.panel['a'], self.panel.a)
self.panel['i'] = self.panel['ItemA']
assert_frame_equal(self.panel['i'], self.panel.i)
def test_from_frame_level1_unsorted(self):
tuples = [('MSFT', 3), ('MSFT', 2), ('AAPL', 2), ('AAPL', 1),
('MSFT', 1)]
midx = MultiIndex.from_tuples(tuples)
df = DataFrame(np.random.rand(5, 4), index=midx)
p = df.to_panel()
assert_frame_equal(p.minor_xs(2), df.xs(2, level=1).sort_index())
def test_to_excel(self):
try:
import xlwt # noqa
import xlrd # noqa
import openpyxl # noqa
from pandas.io.excel import ExcelFile
except ImportError:
pytest.skip("need xlwt xlrd openpyxl")
for ext in ['xls', 'xlsx']:
with ensure_clean('__tmp__.' + ext) as path:
self.panel.to_excel(path)
try:
reader = ExcelFile(path)
except ImportError:
pytest.skip("need xlwt xlrd openpyxl")
for item, df in self.panel.iteritems():
recdf = reader.parse(str(item), index_col=0)
assert_frame_equal(df, recdf)
def test_to_excel_xlsxwriter(self):
try:
import xlrd # noqa
import xlsxwriter # noqa
from pandas.io.excel import ExcelFile
except ImportError:
pytest.skip("Requires xlrd and xlsxwriter. Skipping test.")
with ensure_clean('__tmp__.xlsx') as path:
self.panel.to_excel(path, engine='xlsxwriter')
try:
reader = ExcelFile(path)
except ImportError as e:
pytest.skip("cannot write excel file: %s" % e)
for item, df in self.panel.iteritems():
recdf = reader.parse(str(item), index_col=0)
assert_frame_equal(df, recdf)
@pytest.mark.filterwarnings("ignore:'.reindex:FutureWarning")
def test_dropna(self):
p = Panel(np.random.randn(4, 5, 6), major_axis=list('abcde'))
p.loc[:, ['b', 'd'], 0] = np.nan
result = p.dropna(axis=1)
exp = p.loc[:, ['a', 'c', 'e'], :]
assert_panel_equal(result, exp)
inp = p.copy()
inp.dropna(axis=1, inplace=True)
assert_panel_equal(inp, exp)
result = p.dropna(axis=1, how='all')
assert_panel_equal(result, p)
p.loc[:, ['b', 'd'], :] = np.nan
result = p.dropna(axis=1, how='all')
exp = p.loc[:, ['a', 'c', 'e'], :]
assert_panel_equal(result, exp)
p = Panel(np.random.randn(4, 5, 6), items=list('abcd'))
p.loc[['b'], :, 0] = np.nan
result = p.dropna()
exp = p.loc[['a', 'c', 'd']]
assert_panel_equal(result, exp)
result = p.dropna(how='all')
assert_panel_equal(result, p)
p.loc['b'] = np.nan
result = p.dropna(how='all')
exp = p.loc[['a', 'c', 'd']]
assert_panel_equal(result, exp)
def test_drop(self):
df = DataFrame({"A": [1, 2], "B": [3, 4]})
panel = Panel({"One": df, "Two": df})
def check_drop(drop_val, axis_number, aliases, expected):
try:
actual = panel.drop(drop_val, axis=axis_number)
assert_panel_equal(actual, expected)
for alias in aliases:
actual = panel.drop(drop_val, axis=alias)
assert_panel_equal(actual, expected)
except AssertionError:
pprint_thing("Failed with axis_number %d and aliases: %s" %
(axis_number, aliases))
raise
# Items
expected = Panel({"One": df})
check_drop('Two', 0, ['items'], expected)
pytest.raises(KeyError, panel.drop, 'Three')
# errors = 'ignore'
dropped = panel.drop('Three', errors='ignore')
assert_panel_equal(dropped, panel)
dropped = panel.drop(['Two', 'Three'], errors='ignore')
expected = Panel({"One": df})
assert_panel_equal(dropped, expected)
# Major
exp_df = DataFrame({"A": [2], "B": [4]}, index=[1])
expected = Panel({"One": exp_df, "Two": exp_df})
check_drop(0, 1, ['major_axis', 'major'], expected)
exp_df = DataFrame({"A": [1], "B": [3]}, index=[0])
expected = Panel({"One": exp_df, "Two": exp_df})
check_drop([1], 1, ['major_axis', 'major'], expected)
# Minor
exp_df = df[['B']]
expected = Panel({"One": exp_df, "Two": exp_df})
check_drop(["A"], 2, ['minor_axis', 'minor'], expected)
exp_df = df[['A']]
expected = Panel({"One": exp_df, "Two": exp_df})
check_drop("B", 2, ['minor_axis', 'minor'], expected)
def test_update(self):
pan = Panel([[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]],
[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]]])
other = Panel(
[[[3.6, 2., np.nan], [np.nan, np.nan, 7]]], items=[1])
pan.update(other)
expected = Panel([[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.], [1.5, np.nan, 3.]],
[[3.6, 2., 3], [1.5, np.nan, 7],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]]])
assert_panel_equal(pan, expected)
def test_update_from_dict(self):
pan = Panel({'one': DataFrame([[1.5, np.nan, 3],
[1.5, np.nan, 3],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]]),
'two': DataFrame([[1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]])})
other = {'two': DataFrame(
[[3.6, 2., np.nan], [np.nan, np.nan, 7]])}
pan.update(other)
expected = Panel(
{'one': DataFrame([[1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]]),
'two': DataFrame([[3.6, 2., 3],
[1.5, np.nan, 7],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]])
}
)
assert_panel_equal(pan, expected)
def test_update_nooverwrite(self):
pan = Panel([[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]],
[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]]])
other = Panel(
[[[3.6, 2., np.nan], [np.nan, np.nan, 7]]], items=[1])
pan.update(other, overwrite=False)
expected = Panel([[[1.5, np.nan, 3], [1.5, np.nan, 3],
[1.5, np.nan, 3.], [1.5, np.nan, 3.]],
[[1.5, 2., 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]]])
assert_panel_equal(pan, expected)
def test_update_filtered(self):
pan = Panel([[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]],
[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]]])
other = Panel(
[[[3.6, 2., np.nan], [np.nan, np.nan, 7]]], items=[1])
pan.update(other, filter_func=lambda x: x > 2)
expected = Panel([[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.], [1.5, np.nan, 3.]],
[[1.5, np.nan, 3], [1.5, np.nan, 7],
[1.5, np.nan, 3.], [1.5, np.nan, 3.]]])
assert_panel_equal(pan, expected)
def test_update_raise(self):
pan = Panel([[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]],
[[1.5, np.nan, 3.], [1.5, np.nan, 3.],
[1.5, np.nan, 3.],
[1.5, np.nan, 3.]]])
pytest.raises(Exception, pan.update, *(pan, ),
**{'raise_conflict': True})
def test_all_any(self):
assert (self.panel.all(axis=0).values == nanall(
self.panel, axis=0)).all()
assert (self.panel.all(axis=1).values == nanall(
self.panel, axis=1).T).all()
assert (self.panel.all(axis=2).values == nanall(
self.panel, axis=2).T).all()
assert (self.panel.any(axis=0).values == nanany(
self.panel, axis=0)).all()
assert (self.panel.any(axis=1).values == nanany(
self.panel, axis=1).T).all()
assert (self.panel.any(axis=2).values == nanany(
self.panel, axis=2).T).all()
def test_all_any_unhandled(self):
pytest.raises(NotImplementedError, self.panel.all, bool_only=True)
pytest.raises(NotImplementedError, self.panel.any, bool_only=True)
# GH issue 15960
def test_sort_values(self):
pytest.raises(NotImplementedError, self.panel.sort_values)
pytest.raises(NotImplementedError, self.panel.sort_values, 'ItemA')
@pytest.mark.filterwarnings("ignore:\\nPanel:FutureWarning")
class TestPanelFrame(object):
"""
Check that conversions to and from Panel to DataFrame work.
"""
def setup_method(self, method):
panel = make_test_panel()
self.panel = panel.to_frame()
self.unfiltered_panel = panel.to_frame(filter_observations=False)
def test_ops_differently_indexed(self):
# trying to set non-identically indexed panel
wp = self.panel.to_panel()
wp2 = wp.reindex(major=wp.major_axis[:-1])
lp2 = wp2.to_frame()
result = self.panel + lp2
assert_frame_equal(result.reindex(lp2.index), lp2 * 2)
# careful, mutation
self.panel['foo'] = lp2['ItemA']
assert_series_equal(self.panel['foo'].reindex(lp2.index),
lp2['ItemA'],
check_names=False)
def test_ops_scalar(self):
result = self.panel.mul(2)
expected = DataFrame.__mul__(self.panel, 2)
assert_frame_equal(result, expected)
def test_combineFrame(self):
wp = self.panel.to_panel()
result = self.panel.add(wp['ItemA'].stack(), axis=0)
assert_frame_equal(result.to_panel()['ItemA'], wp['ItemA'] * 2)
def test_combinePanel(self):
wp = self.panel.to_panel()
result = self.panel.add(self.panel)
wide_result = result.to_panel()
assert_frame_equal(wp['ItemA'] * 2, wide_result['ItemA'])
# one item
result = self.panel.add(self.panel.filter(['ItemA']))
def test_combine_scalar(self):
result = self.panel.mul(2)
expected = DataFrame(self.panel._data) * 2
assert_frame_equal(result, expected)
def test_combine_series(self):
s = self.panel['ItemA'][:10]
result = self.panel.add(s, axis=0)
expected = DataFrame.add(self.panel, s, axis=0)
assert_frame_equal(result, expected)
s = self.panel.iloc[5]
result = self.panel + s
expected = DataFrame.add(self.panel, s, axis=1)
assert_frame_equal(result, expected)
def test_operators(self):
wp = self.panel.to_panel()
result = (self.panel + 1).to_panel()
assert_frame_equal(wp['ItemA'] + 1, result['ItemA'])
def test_arith_flex_panel(self):
ops = ['add', 'sub', 'mul', 'div',
'truediv', 'pow', 'floordiv', 'mod']
if not compat.PY3:
aliases = {}
else:
aliases = {'div': 'truediv'}
self.panel = self.panel.to_panel()
for n in [np.random.randint(-50, -1), np.random.randint(1, 50), 0]:
for op in ops:
alias = aliases.get(op, op)
f = getattr(operator, alias)
exp = f(self.panel, n)
result = getattr(self.panel, op)(n)
assert_panel_equal(result, exp, check_panel_type=True)
# rops
r_f = lambda x, y: f(y, x)
exp = r_f(self.panel, n)
result = getattr(self.panel, 'r' + op)(n)
assert_panel_equal(result, exp)
def test_sort(self):
def is_sorted(arr):
return (arr[1:] > arr[:-1]).any()
sorted_minor = self.panel.sort_index(level=1)
assert is_sorted(sorted_minor.index.labels[1])
sorted_major = sorted_minor.sort_index(level=0)
assert is_sorted(sorted_major.index.labels[0])
def test_to_string(self):
buf = StringIO()
self.panel.to_string(buf)
def test_to_sparse(self):
if isinstance(self.panel, Panel):
msg = 'sparsifying is not supported'
tm.assert_raises_regex(NotImplementedError, msg,
self.panel.to_sparse)
def test_truncate(self):
dates = self.panel.index.levels[0]
start, end = dates[1], dates[5]
trunced = self.panel.truncate(start, end).to_panel()
expected = self.panel.to_panel()['ItemA'].truncate(start, end)
# TODO truncate drops index.names
assert_frame_equal(trunced['ItemA'], expected, check_names=False)
trunced = self.panel.truncate(before=start).to_panel()
expected = self.panel.to_panel()['ItemA'].truncate(before=start)
# TODO truncate drops index.names
assert_frame_equal(trunced['ItemA'], expected, check_names=False)
trunced = self.panel.truncate(after=end).to_panel()
expected = self.panel.to_panel()['ItemA'].truncate(after=end)
# TODO truncate drops index.names
assert_frame_equal(trunced['ItemA'], expected, check_names=False)
# truncate on dates that aren't in there
wp = self.panel.to_panel()
new_index = wp.major_axis[::5]
wp2 = wp.reindex(major=new_index)
lp2 = wp2.to_frame()
lp_trunc = lp2.truncate(wp.major_axis[2], wp.major_axis[-2])
wp_trunc = wp2.truncate(wp.major_axis[2], wp.major_axis[-2])
assert_panel_equal(wp_trunc, lp_trunc.to_panel())
# throw proper exception
pytest.raises(Exception, lp2.truncate, wp.major_axis[-2],
wp.major_axis[2])
def test_axis_dummies(self):
from pandas.core.reshape.reshape import make_axis_dummies
minor_dummies = make_axis_dummies(self.panel, 'minor').astype(np.uint8)
assert len(minor_dummies.columns) == len(self.panel.index.levels[1])
major_dummies = make_axis_dummies(self.panel, 'major').astype(np.uint8)
assert len(major_dummies.columns) == len(self.panel.index.levels[0])
mapping = {'A': 'one', 'B': 'one', 'C': 'two', 'D': 'two'}
transformed = make_axis_dummies(self.panel, 'minor',
transform=mapping.get).astype(np.uint8)
assert len(transformed.columns) == 2
tm.assert_index_equal(transformed.columns, Index(['one', 'two']))
# TODO: test correctness
def test_get_dummies(self):
from pandas.core.reshape.reshape import get_dummies, make_axis_dummies
self.panel['Label'] = self.panel.index.labels[1]
minor_dummies = make_axis_dummies(self.panel, 'minor').astype(np.uint8)
dummies = get_dummies(self.panel['Label'])
tm.assert_numpy_array_equal(dummies.values, minor_dummies.values)
def test_mean(self):
means = self.panel.mean(level='minor')
# test versus Panel version
wide_means = self.panel.to_panel().mean('major')
assert_frame_equal(means, wide_means)
def test_sum(self):
sums = self.panel.sum(level='minor')
# test versus Panel version
wide_sums = self.panel.to_panel().sum('major')
assert_frame_equal(sums, wide_sums)
def test_count(self):
index = self.panel.index
major_count = self.panel.count(level=0)['ItemA']
labels = index.labels[0]
for i, idx in enumerate(index.levels[0]):
assert major_count[i] == (labels == i).sum()
minor_count = self.panel.count(level=1)['ItemA']
labels = index.labels[1]
for i, idx in enumerate(index.levels[1]):
assert minor_count[i] == (labels == i).sum()
def test_join(self):
lp1 = self.panel.filter(['ItemA', 'ItemB'])
lp2 = self.panel.filter(['ItemC'])
joined = lp1.join(lp2)
assert len(joined.columns) == 3
pytest.raises(Exception, lp1.join,
self.panel.filter(['ItemB', 'ItemC']))
def test_panel_index():
index = panelm.panel_index([1, 2, 3, 4], [1, 2, 3])
expected = MultiIndex.from_arrays([np.tile([1, 2, 3, 4], 3),
np.repeat([1, 2, 3], 4)],
names=['time', 'panel'])
tm.assert_index_equal(index, expected)
@pytest.mark.filterwarnings("ignore:\\nPanel:FutureWarning")
def test_panel_np_all():
wp = Panel({"A": DataFrame({'b': [1, 2]})})
result = np.all(wp)
assert result == np.bool_(True)
| bsd-3-clause |
dongjoon-hyun/tensorflow | tensorflow/python/ops/linalg/linear_operator_block_diag.py | 23 | 14165 | # Copyright 2018 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.
# ==============================================================================
"""Create a Block Diagonal operator from one or more `LinearOperators`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import common_shapes
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops.linalg import linear_operator
from tensorflow.python.ops.linalg import linear_operator_util
from tensorflow.python.util.tf_export import tf_export
__all__ = [
"LinearOperatorBlockDiag",
]
@tf_export("linalg.LinearOperatorBlockDiag")
class LinearOperatorBlockDiag(linear_operator.LinearOperator):
"""Combines one or more `LinearOperators` in to a Block Diagonal matrix.
This operator combines one or more linear operators `[op1,...,opJ]`,
building a new `LinearOperator`, whose underlying matrix representation is
square and has each operator `opi` on the main diagonal, and zero's elsewhere.
#### Shape compatibility
If `opj` acts like a [batch] square matrix `Aj`, then `op_combined` acts like
the [batch] square matrix formed by having each matrix `Aj` on the main
diagonal.
Each `opj` is required to represent a square matrix, and hence will have
shape `batch_shape_j + [M_j, M_j]`.
If `opj` has shape `batch_shape_j + [M_j, M_j]`, then the combined operator
has shape `broadcast_batch_shape + [sum M_j, sum M_j]`, where
`broadcast_batch_shape` is the mutual broadcast of `batch_shape_j`,
`j = 1,...,J`, assuming the intermediate batch shapes broadcast.
Even if the combined shape is well defined, the combined operator's
methods may fail due to lack of broadcasting ability in the defining
operators' methods.
```python
# Create a 4 x 4 linear operator combined of two 2 x 2 operators.
operator_1 = LinearOperatorFullMatrix([[1., 2.], [3., 4.]])
operator_2 = LinearOperatorFullMatrix([[1., 0.], [0., 1.]])
operator = LinearOperatorBlockDiag([operator_1, operator_2])
operator.to_dense()
==> [[1., 2., 0., 0.],
[3., 4., 0., 0.],
[0., 0., 1., 0.],
[0., 0., 0., 1.]]
operator.shape
==> [4, 4]
operator.log_abs_determinant()
==> scalar Tensor
x1 = ... # Shape [2, 2] Tensor
x2 = ... # Shape [2, 2] Tensor
x = tf.concat([x1, x2], 0) # Shape [2, 4] Tensor
operator.matmul(x)
==> tf.concat([operator_1.matmul(x1), operator_2.matmul(x2)])
# Create a [2, 3] batch of 4 x 4 linear operators.
matrix_44 = tf.random_normal(shape=[2, 3, 4, 4])
operator_44 = LinearOperatorFullMatrix(matrix)
# Create a [1, 3] batch of 5 x 5 linear operators.
matrix_55 = tf.random_normal(shape=[1, 3, 5, 5])
operator_55 = LinearOperatorFullMatrix(matrix_55)
# Combine to create a [2, 3] batch of 9 x 9 operators.
operator_99 = LinearOperatorBlockDiag([operator_44, operator_55])
# Create a shape [2, 3, 9] vector.
x = tf.random_normal(shape=[2, 3, 9])
operator_99.matmul(x)
==> Shape [2, 3, 9] Tensor
```
#### Performance
The performance of `LinearOperatorBlockDiag` on any operation is equal to
the sum of the individual operators' operations.
#### Matrix property hints
This `LinearOperator` is initialized with boolean flags of the form `is_X`,
for `X = non_singular, self_adjoint, positive_definite, square`.
These have the following meaning:
* If `is_X == True`, callers should expect the operator to have the
property `X`. This is a promise that should be fulfilled, but is *not* a
runtime assert. For example, finite floating point precision may result
in these promises being violated.
* If `is_X == False`, callers should expect the operator to not have `X`.
* If `is_X == None` (the default), callers should have no expectation either
way.
"""
def __init__(self,
operators,
is_non_singular=None,
is_self_adjoint=None,
is_positive_definite=None,
is_square=True,
name=None):
r"""Initialize a `LinearOperatorBlockDiag`.
`LinearOperatorBlockDiag` is initialized with a list of operators
`[op_1,...,op_J]`.
Args:
operators: Iterable of `LinearOperator` objects, each with
the same `dtype` and composable shape.
is_non_singular: Expect that this operator is non-singular.
is_self_adjoint: Expect that this operator is equal to its hermitian
transpose.
is_positive_definite: Expect that this operator is positive definite,
meaning the quadratic form `x^H A x` has positive real part for all
nonzero `x`. Note that we do not require the operator to be
self-adjoint to be positive-definite. See:
https://en.wikipedia.org/wiki/Positive-definite_matrix#Extension_for_non-symmetric_matrices
is_square: Expect that this operator acts like square [batch] matrices.
This is true by default, and will raise a `ValueError` otherwise.
name: A name for this `LinearOperator`. Default is the individual
operators names joined with `_o_`.
Raises:
TypeError: If all operators do not have the same `dtype`.
ValueError: If `operators` is empty or are non-square.
"""
# Validate operators.
check_ops.assert_proper_iterable(operators)
operators = list(operators)
if not operators:
raise ValueError(
"Expected a non-empty list of operators. Found: %s" % operators)
self._operators = operators
# Validate dtype.
dtype = operators[0].dtype
for operator in operators:
if operator.dtype != dtype:
name_type = (str((o.name, o.dtype)) for o in operators)
raise TypeError(
"Expected all operators to have the same dtype. Found %s"
% " ".join(name_type))
# Auto-set and check hints.
if all(operator.is_non_singular for operator in operators):
if is_non_singular is False:
raise ValueError(
"The direct sum of non-singular operators is always non-singular.")
is_non_singular = True
if all(operator.is_self_adjoint for operator in operators):
if is_self_adjoint is False:
raise ValueError(
"The direct sum of self-adjoint operators is always self-adjoint.")
is_self_adjoint = True
if all(operator.is_positive_definite for operator in operators):
if is_positive_definite is False:
raise ValueError(
"The direct sum of positive definite operators is always "
"positive definite.")
is_positive_definite = True
if not (is_square and all(operator.is_square for operator in operators)):
raise ValueError(
"Can only represent a block diagonal of square matrices.")
# Initialization.
graph_parents = []
for operator in operators:
graph_parents.extend(operator.graph_parents)
if name is None:
# Using ds to mean direct sum.
name = "_ds_".join(operator.name for operator in operators)
with ops.name_scope(name, values=graph_parents):
super(LinearOperatorBlockDiag, self).__init__(
dtype=dtype,
graph_parents=graph_parents,
is_non_singular=is_non_singular,
is_self_adjoint=is_self_adjoint,
is_positive_definite=is_positive_definite,
is_square=True,
name=name)
@property
def operators(self):
return self._operators
def _shape(self):
# Get final matrix shape.
domain_dimension = self.operators[0].domain_dimension
range_dimension = self.operators[0].range_dimension
for operator in self.operators[1:]:
domain_dimension += operator.domain_dimension
range_dimension += operator.range_dimension
matrix_shape = tensor_shape.TensorShape([domain_dimension, range_dimension])
# Get broadcast batch shape.
# broadcast_shape checks for compatibility.
batch_shape = self.operators[0].batch_shape
for operator in self.operators[1:]:
batch_shape = common_shapes.broadcast_shape(
batch_shape, operator.batch_shape)
return batch_shape.concatenate(matrix_shape)
def _shape_tensor(self):
# Avoid messy broadcasting if possible.
if self.shape.is_fully_defined():
return ops.convert_to_tensor(
self.shape.as_list(), dtype=dtypes.int32, name="shape")
domain_dimension = self.operators[0].domain_dimension_tensor()
range_dimension = self.operators[0].range_dimension_tensor()
for operator in self.operators[1:]:
domain_dimension += operator.domain_dimension_tensor()
range_dimension += operator.range_dimension_tensor()
matrix_shape = array_ops.stack([domain_dimension, range_dimension])
# Dummy Tensor of zeros. Will never be materialized.
zeros = array_ops.zeros(shape=self.operators[0].batch_shape_tensor())
for operator in self.operators[1:]:
zeros += array_ops.zeros(shape=operator.batch_shape_tensor())
batch_shape = array_ops.shape(zeros)
return array_ops.concat((batch_shape, matrix_shape), 0)
def _matmul(self, x, adjoint=False, adjoint_arg=False):
split_dim = -1 if adjoint_arg else -2
# Split input by rows normally, and otherwise columns.
split_x = self._split_input_into_blocks(x, axis=split_dim)
result_list = []
for index, operator in enumerate(self.operators):
result_list += [operator.matmul(
split_x[index], adjoint=adjoint, adjoint_arg=adjoint_arg)]
result_list = linear_operator_util.broadcast_matrix_batch_dims(
result_list)
return array_ops.concat(result_list, axis=-2)
def _determinant(self):
result = self.operators[0].determinant()
for operator in self.operators[1:]:
result *= operator.determinant()
return result
def _log_abs_determinant(self):
result = self.operators[0].log_abs_determinant()
for operator in self.operators[1:]:
result += operator.log_abs_determinant()
return result
def _solve(self, rhs, adjoint=False, adjoint_arg=False):
split_dim = -1 if adjoint_arg else -2
# Split input by rows normally, and otherwise columns.
split_rhs = self._split_input_into_blocks(rhs, axis=split_dim)
solution_list = []
for index, operator in enumerate(self.operators):
solution_list += [operator.solve(
split_rhs[index], adjoint=adjoint, adjoint_arg=adjoint_arg)]
solution_list = linear_operator_util.broadcast_matrix_batch_dims(
solution_list)
return array_ops.concat(solution_list, axis=-2)
def _diag_part(self):
diag_list = []
for operator in self.operators:
# Extend the axis for broadcasting.
diag_list += [operator.diag_part()[..., array_ops.newaxis]]
diag_list = linear_operator_util.broadcast_matrix_batch_dims(diag_list)
diagonal = array_ops.concat(diag_list, axis=-2)
return array_ops.squeeze(diagonal, axis=-1)
def _trace(self):
result = self.operators[0].trace()
for operator in self.operators[1:]:
result += operator.trace()
return result
def _to_dense(self):
num_cols = 0
rows = []
broadcasted_blocks = [operator.to_dense() for operator in self.operators]
broadcasted_blocks = linear_operator_util.broadcast_matrix_batch_dims(
broadcasted_blocks)
for block in broadcasted_blocks:
batch_row_shape = array_ops.shape(block)[:-1]
zeros_to_pad_before_shape = array_ops.concat(
[batch_row_shape, [num_cols]], axis=-1)
zeros_to_pad_before = array_ops.zeros(
shape=zeros_to_pad_before_shape, dtype=block.dtype)
num_cols += array_ops.shape(block)[-1]
zeros_to_pad_after_shape = array_ops.concat(
[batch_row_shape,
[self.domain_dimension_tensor() - num_cols]], axis=-1)
zeros_to_pad_after = array_ops.zeros(
shape=zeros_to_pad_after_shape, dtype=block.dtype)
rows.append(array_ops.concat(
[zeros_to_pad_before, block, zeros_to_pad_after], axis=-1))
mat = array_ops.concat(rows, axis=-2)
mat.set_shape(self.shape)
return mat
def _assert_non_singular(self):
return control_flow_ops.group([
operator.assert_non_singular() for operator in self.operators])
def _assert_self_adjoint(self):
return control_flow_ops.group([
operator.assert_self_adjoint() for operator in self.operators])
def _assert_positive_definite(self):
return control_flow_ops.group([
operator.assert_positive_definite() for operator in self.operators])
def _split_input_into_blocks(self, x, axis=-1):
"""Split `x` into blocks matching `operators`'s `domain_dimension`.
Specifically, if we have a block diagonal matrix, with block sizes
`[M_j, M_j] j = 1..J`, this method splits `x` on `axis` into `J`
tensors, whose shape at `axis` is `M_j`.
Args:
x: `Tensor`. `x` is split into `J` tensors.
axis: Python `Integer` representing the axis to split `x` on.
Returns:
A list of `Tensor`s.
"""
block_sizes = []
if self.shape.is_fully_defined():
for operator in self.operators:
block_sizes += [operator.domain_dimension.value]
else:
for operator in self.operators:
block_sizes += [operator.domain_dimension_tensor()]
return array_ops.split(x, block_sizes, axis=axis)
| apache-2.0 |
alvations/Paddle | demo/recommendation/prediction.py | 2 | 1973 | #!/bin/env python2
# Copyright (c) 2016 Baidu, 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.
from py_paddle import swig_paddle, DataProviderConverter
from common_utils import *
from paddle.trainer.config_parser import parse_config
try:
import cPickle as pickle
except ImportError:
import pickle
import sys
if __name__ == '__main__':
model_path = sys.argv[1]
swig_paddle.initPaddle('--use_gpu=0')
conf = parse_config("trainer_config.py", "is_predict=1")
network = swig_paddle.GradientMachine.createFromConfigProto(
conf.model_config)
assert isinstance(network, swig_paddle.GradientMachine)
network.loadParameters(model_path)
with open('./data/meta.bin', 'rb') as f:
meta = pickle.load(f)
headers = list(meta_to_header(meta, 'movie'))
headers.extend(list(meta_to_header(meta, 'user')))
cvt = DataProviderConverter(headers)
while True:
movie_id = int(raw_input("Input movie_id: "))
user_id = int(raw_input("Input user_id: "))
movie_meta = meta['movie'][movie_id] # Query Data From Meta.
user_meta = meta['user'][user_id]
data = [movie_id - 1]
data.extend(movie_meta)
data.append(user_id - 1)
data.extend(user_meta)
print "Prediction Score is %.2f" % (
(network.forwardTest(cvt.convert([data]))[0]['value'][0][0] + 5)
/ 2)
| apache-2.0 |
maaaks/andreas | andreas/db/model.py | 1 | 3293 | from typing import Dict, List, Optional, Tuple, Type
from playhouse import signals
from andreas.db.database import db
class Model(signals.Model):
class Meta:
database = db
schema = 'andreas'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._models_to_save_after_myself: List[Tuple[Model,Dict]] = []
@classmethod
def table(cls) -> str:
return f'{cls._meta.schema}.{cls._meta.table_name}'
@classmethod
def triggers(cls) -> Optional[Dict[str,str]]:
return None
@classmethod
def create_table(cls, fail_silently=False):
"""
Creates a table for given model and creates/recreates all the triggers on it.
"""
super().create_table(fail_silently=fail_silently)
if cls.triggers():
# Remove the old triggers
for event in 'insert', 'update', 'delete', 'truncate':
for when in 'before', 'after', 'instead_of':
db.execute_sql(f'drop trigger if exists {when}_{event} on {cls.table()}')
db.execute_sql(f'drop function if exists on_{cls.table()}_{when}_{event}()')
# Create new triggers
for when, code in cls.triggers().items():
trigger_name = when.replace(' ', '_')
code = code.rstrip('; \t\n\t')
db.execute_sql(
f'create or replace function {cls.table()}_{trigger_name}() returns trigger '
f'as $$ begin {code}; end $$ language plpgsql')
db.execute_sql(
f'create trigger {trigger_name} {when} on {cls.table()} '
f'for each row execute procedure {cls.table()}_{trigger_name}()')
def reload(self):
"""
Updates all the fields from the database.
"""
newer_self = self.get(self._pk_expr())
for field_name in self._meta.fields.keys():
val = getattr(newer_self, field_name)
setattr(self, field_name, val)
self._dirty.clear()
def save_after(self, dependency: 'Model', **kwargs) -> None:
"""
Registers handler that will automatically save this model right as soon as `dependency` will be saved.
This handler works only once and unregisters itself after finishing its work.
"""
dependency._models_to_save_after_myself.append((self, kwargs))
@classmethod
def create_after(cls, dependency: 'Model', **kwargs) -> 'Model':
"""
Creates instance and registers handler that will automatically save it as soon as `dependency` will be saved.
This handler works only once and unregisters itself after finishing its work.
"""
instance = cls(**kwargs)
dependency._models_to_save_after_myself.append((instance, {}))
return instance
@signals.post_save()
def post_save(model_class: Type[Model], instance: Model, created: bool):
"""
After an object is saved, all other models that waited for it will be automatically saved, too.
"""
for model, kwargs in instance._models_to_save_after_myself:
model.save(**kwargs)
instance._models_to_save_after_myself = [] | mit |
avoinsystems/odoo | addons/account/res_currency.py | 340 | 2267 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2010 OpenERP s.a. (<http://www.openerp.com>).
#
# 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 osv
"""Inherit res.currency to handle accounting date values when converting currencies"""
class res_currency_account(osv.osv):
_inherit = "res.currency"
def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
if context is None:
context = {}
rate = super(res_currency_account, self)._get_conversion_rate(cr, uid, from_currency, to_currency, context=context)
#process the case where the account doesn't work with an outgoing currency rate method 'at date' but 'average'
account = context.get('res.currency.compute.account')
account_invert = context.get('res.currency.compute.account_invert')
if account and account.currency_mode == 'average' and account.currency_id:
query = self.pool.get('account.move.line')._query_get(cr, uid, context=context)
cr.execute('select sum(debit-credit),sum(amount_currency) from account_move_line l ' \
'where l.currency_id=%s and l.account_id=%s and '+query, (account.currency_id.id,account.id,))
tot1,tot2 = cr.fetchone()
if tot2 and not account_invert:
rate = float(tot1)/float(tot2)
elif tot1 and account_invert:
rate = float(tot2)/float(tot1)
return rate
| agpl-3.0 |
richardcs/ansible | lib/ansible/modules/cloud/azure/azure_rm_containerinstance_facts.py | 33 | 9452 | #!/usr/bin/python
#
# Copyright (c) 2017 Zim Kalinowski, <zikalino@microsoft.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: azure_rm_containerinstance_facts
version_added: "2.8"
short_description: Get Azure Container Instance facts.
description:
- Get facts of Container Instance.
options:
resource_group:
description:
- The name of the resource group.
required: True
name:
description:
- The name of the container instance.
tags:
description:
- Limit results by providing a list of tags. Format tags as 'key' or 'key:value'.
extends_documentation_fragment:
- azure
author:
- "Zim Kalinowski (@zikalino)"
'''
EXAMPLES = '''
- name: Get specific Container Instance facts
azure_rm_containerinstance_facts:
resource_group: resource_group_name
name: container_group_name
- name: List Container Instances in a specified resource group name
azure_rm_containerinstance_facts:
resource_group: resource_group_name
'''
RETURN = '''
container_groups:
description: A list of Container Instance dictionaries.
returned: always
type: complex
contains:
id:
description:
- The resource id.
returned: always
type: str
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/my
containers"
resource_group:
description:
- Resource group where the container exists.
returned: always
type: str
sample: testrg
name:
description:
- The resource name.
returned: always
type: str
sample: mycontainers
location:
description:
- The resource location.
returned: always
type: str
sample: westus
os_type:
description:
- The OS type of containers.
returned: always
type: str
sample: linux
ip_address:
description:
- IP address of the container instance.
returned: always
type: str
sample: 173.15.18.1
ports:
description:
- List of ports exposed by the container instance.
returned: always
type: list
sample: [ 80, 81 ]
containers:
description:
- The containers within the container group.
returned: always
type: complex
sample: containers
contains:
name:
description:
- The name of the container instance.
returned: always
type: str
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/my
containers"
image:
description:
- The container image name.
returned: always
type: str
sample: "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/demo/providers/Microsoft.ContainerInstance/containerGroups/my
containers"
memory:
description:
- The required memory of the containers in GB.
returned: always
type: float
sample: 1.5
cpu:
description:
- The required number of CPU cores of the containers.
returned: always
type: int
sample: 1
ports:
description:
- List of ports exposed within the container group.
returned: always
type: list
sample: [ 80, 81 ]
tags:
description: Tags assigned to the resource. Dictionary of string:string pairs.
type: dict
sample: { "tag1": "abc" }
'''
from ansible.module_utils.azure_rm_common import AzureRMModuleBase
try:
from msrestazure.azure_exceptions import CloudError
from msrestazure.azure_operation import AzureOperationPoller
from azure.mgmt.containerinstance import ContainerInstanceManagementClient
from msrest.serialization import Model
except ImportError:
# This is handled in azure_rm_common
pass
class AzureRMContainerInstanceFacts(AzureRMModuleBase):
def __init__(self):
# define user inputs into argument
self.module_arg_spec = dict(
resource_group=dict(
type='str',
required=True
),
name=dict(
type='str'
),
tags=dict(
type='list'
)
)
# store the results of the module operation
self.results = dict(
changed=False,
ansible_facts=dict()
)
self.resource_group = None
self.name = None
super(AzureRMContainerInstanceFacts, self).__init__(self.module_arg_spec, supports_tags=False)
def exec_module(self, **kwargs):
for key in self.module_arg_spec:
setattr(self, key, kwargs[key])
if (self.name is not None):
self.results['containerinstances'] = self.get()
elif (self.resource_group is not None):
self.results['containerinstances'] = self.list_by_resource_group()
else:
self.results['containerinstances'] = self.list_all()
return self.results
def get(self):
response = None
results = []
try:
response = self.containerinstance_client.container_groups.get(resource_group_name=self.resource_group,
container_group_name=self.name)
self.log("Response : {0}".format(response))
except CloudError as e:
self.log('Could not get facts for Container Instances.')
if response is not None and self.has_tags(response.tags, self.tags):
results.append(self.format_item(response))
return results
def list_by_resource_group(self):
response = None
results = []
try:
response = self.containerinstance_client.container_groups.list_by_resource_group(resource_group_name=self.resource_group)
self.log("Response : {0}".format(response))
except CloudError as e:
self.fail('Could not list facts for Container Instances.')
if response is not None:
for item in response:
if self.has_tags(item.tags, self.tags):
results.append(self.format_item(item))
return results
def list_all(self):
response = None
results = []
try:
response = self.containerinstance_client.container_groups.list()
self.log("Response : {0}".format(response))
except CloudError as e:
self.fail('Could not list facts for Container Instances.')
if response is not None:
for item in response:
if self.has_tags(item.tags, self.tags):
results.append(self.format_item(item))
return results
def format_item(self, item):
d = item.as_dict()
containers = d['containers']
ports = d['ip_address']['ports']
resource_group = d['id'].split('resourceGroups/')[1].split('/')[0]
for port_index in range(len(ports)):
ports[port_index] = ports[port_index]['port']
for container_index in range(len(containers)):
old_container = containers[container_index]
new_container = {
'name': old_container['name'],
'image': old_container['image'],
'memory': old_container['resources']['requests']['memory_in_gb'],
'cpu': old_container['resources']['requests']['cpu'],
'ports': []
}
for port_index in range(len(old_container['ports'])):
new_container['ports'].append(old_container['ports'][port_index]['port'])
containers[container_index] = new_container
d = {
'id': d['id'],
'resource_group': resource_group,
'name': d['name'],
'os_type': d['os_type'],
'ip_address': 'public' if d['ip_address']['type'] == 'Public' else 'none',
'ports': ports,
'location': d['location'],
'containers': containers,
'tags': d.get('tags', None)
}
return d
def main():
AzureRMContainerInstanceFacts()
if __name__ == '__main__':
main()
| gpl-3.0 |
yongshengwang/hue | build/env/lib/python2.7/site-packages/Mako-0.8.1-py2.7.egg/mako/exceptions.py | 38 | 12536 | # mako/exceptions.py
# Copyright (C) 2006-2012 the Mako authors and contributors <see AUTHORS file>
#
# This module is part of Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""exception classes"""
import traceback
import sys
import re
from mako import util, compat
class MakoException(Exception):
pass
class RuntimeException(MakoException):
pass
def _format_filepos(lineno, pos, filename):
if filename is None:
return " at line: %d char: %d" % (lineno, pos)
else:
return " in file '%s' at line: %d char: %d" % (filename, lineno, pos)
class CompileException(MakoException):
def __init__(self, message, source, lineno, pos, filename):
MakoException.__init__(self,
message + _format_filepos(lineno, pos, filename))
self.lineno =lineno
self.pos = pos
self.filename = filename
self.source = source
class SyntaxException(MakoException):
def __init__(self, message, source, lineno, pos, filename):
MakoException.__init__(self,
message + _format_filepos(lineno, pos, filename))
self.lineno =lineno
self.pos = pos
self.filename = filename
self.source = source
class UnsupportedError(MakoException):
"""raised when a retired feature is used."""
class NameConflictError(MakoException):
"""raised when a reserved word is used inappropriately"""
class TemplateLookupException(MakoException):
pass
class TopLevelLookupException(TemplateLookupException):
pass
class RichTraceback(object):
"""Pull the current exception from the ``sys`` traceback and extracts
Mako-specific template information.
See the usage examples in :ref:`handling_exceptions`.
"""
def __init__(self, error=None, traceback=None):
self.source, self.lineno = "", 0
if error is None or traceback is None:
t, value, tback = sys.exc_info()
if error is None:
error = value or t
if traceback is None:
traceback = tback
self.error = error
self.records = self._init(traceback)
if isinstance(self.error, (CompileException, SyntaxException)):
import mako.template
self.source = self.error.source
self.lineno = self.error.lineno
self._has_source = True
self._init_message()
@property
def errorname(self):
return compat.exception_name(self.error)
def _init_message(self):
"""Find a unicode representation of self.error"""
try:
self.message = compat.text_type(self.error)
except UnicodeError:
try:
self.message = str(self.error)
except UnicodeEncodeError:
# Fallback to args as neither unicode nor
# str(Exception(u'\xe6')) work in Python < 2.6
self.message = self.error.args[0]
if not isinstance(self.message, compat.text_type):
self.message = compat.text_type(self.message, 'ascii', 'replace')
def _get_reformatted_records(self, records):
for rec in records:
if rec[6] is not None:
yield (rec[4], rec[5], rec[2], rec[6])
else:
yield tuple(rec[0:4])
@property
def traceback(self):
"""Return a list of 4-tuple traceback records (i.e. normal python
format) with template-corresponding lines remapped to the originating
template.
"""
return list(self._get_reformatted_records(self.records))
@property
def reverse_records(self):
return reversed(self.records)
@property
def reverse_traceback(self):
"""Return the same data as traceback, except in reverse order.
"""
return list(self._get_reformatted_records(self.reverse_records))
def _init(self, trcback):
"""format a traceback from sys.exc_info() into 7-item tuples,
containing the regular four traceback tuple items, plus the original
template filename, the line number adjusted relative to the template
source, and code line from that line number of the template."""
import mako.template
mods = {}
rawrecords = traceback.extract_tb(trcback)
new_trcback = []
for filename, lineno, function, line in rawrecords:
if not line:
line = ''
try:
(line_map, template_lines) = mods[filename]
except KeyError:
try:
info = mako.template._get_module_info(filename)
module_source = info.code
template_source = info.source
template_filename = info.template_filename or filename
except KeyError:
# A normal .py file (not a Template)
if not compat.py3k:
try:
fp = open(filename, 'rb')
encoding = util.parse_encoding(fp)
fp.close()
except IOError:
encoding = None
if encoding:
line = line.decode(encoding)
else:
line = line.decode('ascii', 'replace')
new_trcback.append((filename, lineno, function, line,
None, None, None, None))
continue
template_ln = module_ln = 1
line_map = {}
for line in module_source.split("\n"):
match = re.match(r'\s*# SOURCE LINE (\d+)', line)
if match:
template_ln = int(match.group(1))
module_ln += 1
line_map[module_ln] = template_ln
template_lines = [line for line in
template_source.split("\n")]
mods[filename] = (line_map, template_lines)
template_ln = line_map[lineno]
if template_ln <= len(template_lines):
template_line = template_lines[template_ln - 1]
else:
template_line = None
new_trcback.append((filename, lineno, function,
line, template_filename, template_ln,
template_line, template_source))
if not self.source:
for l in range(len(new_trcback)-1, 0, -1):
if new_trcback[l][5]:
self.source = new_trcback[l][7]
self.lineno = new_trcback[l][5]
break
else:
if new_trcback:
try:
# A normal .py file (not a Template)
fp = open(new_trcback[-1][0], 'rb')
encoding = util.parse_encoding(fp)
fp.seek(0)
self.source = fp.read()
fp.close()
if encoding:
self.source = self.source.decode(encoding)
except IOError:
self.source = ''
self.lineno = new_trcback[-1][1]
return new_trcback
def text_error_template(lookup=None):
"""Provides a template that renders a stack trace in a similar format to
the Python interpreter, substituting source template filenames, line
numbers and code for that of the originating source template, as
applicable.
"""
import mako.template
return mako.template.Template(r"""
<%page args="error=None, traceback=None"/>
<%!
from mako.exceptions import RichTraceback
%>\
<%
tback = RichTraceback(error=error, traceback=traceback)
%>\
Traceback (most recent call last):
% for (filename, lineno, function, line) in tback.traceback:
File "${filename}", line ${lineno}, in ${function or '?'}
${line | trim}
% endfor
${tback.errorname}: ${tback.message}
""")
def _install_pygments():
global syntax_highlight, pygments_html_formatter
from mako.ext.pygmentplugin import syntax_highlight,\
pygments_html_formatter
def _install_fallback():
global syntax_highlight, pygments_html_formatter
from mako.filters import html_escape
pygments_html_formatter = None
def syntax_highlight(filename='', language=None):
return html_escape
def _install_highlighting():
try:
_install_pygments()
except ImportError:
_install_fallback()
_install_highlighting()
def html_error_template():
"""Provides a template that renders a stack trace in an HTML format,
providing an excerpt of code as well as substituting source template
filenames, line numbers and code for that of the originating source
template, as applicable.
The template's default ``encoding_errors`` value is ``'htmlentityreplace'``. The
template has two options. With the ``full`` option disabled, only a section of
an HTML document is returned. With the ``css`` option disabled, the default
stylesheet won't be included.
"""
import mako.template
return mako.template.Template(r"""
<%!
from mako.exceptions import RichTraceback, syntax_highlight,\
pygments_html_formatter
%>
<%page args="full=True, css=True, error=None, traceback=None"/>
% if full:
<html>
<head>
<title>Mako Runtime Error</title>
% endif
% if css:
<style>
body { font-family:verdana; margin:10px 30px 10px 30px;}
.stacktrace { margin:5px 5px 5px 5px; }
.highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; }
.nonhighlight { padding:0px; background-color:#DFDFDF; }
.sample { padding:10px; margin:10px 10px 10px 10px;
font-family:monospace; }
.sampleline { padding:0px 10px 0px 10px; }
.sourceline { margin:5px 5px 10px 5px; font-family:monospace;}
.location { font-size:80%; }
.highlight { white-space:pre; }
.sampleline { white-space:pre; }
% if pygments_html_formatter:
${pygments_html_formatter.get_style_defs()}
.linenos { min-width: 2.5em; text-align: right; }
pre { margin: 0; }
.syntax-highlighted { padding: 0 10px; }
.syntax-highlightedtable { border-spacing: 1px; }
.nonhighlight { border-top: 1px solid #DFDFDF;
border-bottom: 1px solid #DFDFDF; }
.stacktrace .nonhighlight { margin: 5px 15px 10px; }
.sourceline { margin: 0 0; font-family:monospace; }
.code { background-color: #F8F8F8; width: 100%; }
.error .code { background-color: #FFBDBD; }
.error .syntax-highlighted { background-color: #FFBDBD; }
% endif
</style>
% endif
% if full:
</head>
<body>
% endif
<h2>Error !</h2>
<%
tback = RichTraceback(error=error, traceback=traceback)
src = tback.source
line = tback.lineno
if src:
lines = src.split('\n')
else:
lines = None
%>
<h3>${tback.errorname}: ${tback.message|h}</h3>
% if lines:
<div class="sample">
<div class="nonhighlight">
% for index in range(max(0, line-4),min(len(lines), line+5)):
<%
if pygments_html_formatter:
pygments_html_formatter.linenostart = index + 1
%>
% if index + 1 == line:
<%
if pygments_html_formatter:
old_cssclass = pygments_html_formatter.cssclass
pygments_html_formatter.cssclass = 'error ' + old_cssclass
%>
${lines[index] | syntax_highlight(language='mako')}
<%
if pygments_html_formatter:
pygments_html_formatter.cssclass = old_cssclass
%>
% else:
${lines[index] | syntax_highlight(language='mako')}
% endif
% endfor
</div>
</div>
% endif
<div class="stacktrace">
% for (filename, lineno, function, line) in tback.reverse_traceback:
<div class="location">${filename}, line ${lineno}:</div>
<div class="nonhighlight">
<%
if pygments_html_formatter:
pygments_html_formatter.linenostart = lineno
%>
<div class="sourceline">${line | syntax_highlight(filename)}</div>
</div>
% endfor
</div>
% if full:
</body>
</html>
% endif
""", output_encoding=sys.getdefaultencoding(),
encoding_errors='htmlentityreplace')
| apache-2.0 |
malkoto1/just_cook | SQLAlchemy-1.0.4/lib/sqlalchemy/orm/descriptor_props.py | 60 | 25141 | # orm/descriptor_props.py
# Copyright (C) 2005-2015 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Descriptor properties are more "auxiliary" properties
that exist as configurational elements, but don't participate
as actively in the load/persist ORM loop.
"""
from .interfaces import MapperProperty, PropComparator
from .util import _none_set
from . import attributes
from .. import util, sql, exc as sa_exc, event, schema
from ..sql import expression
from . import properties
from . import query
class DescriptorProperty(MapperProperty):
""":class:`.MapperProperty` which proxies access to a
user-defined descriptor."""
doc = None
def instrument_class(self, mapper):
prop = self
class _ProxyImpl(object):
accepts_scalar_loader = False
expire_missing = True
collection = False
def __init__(self, key):
self.key = key
if hasattr(prop, 'get_history'):
def get_history(self, state, dict_,
passive=attributes.PASSIVE_OFF):
return prop.get_history(state, dict_, passive)
if self.descriptor is None:
desc = getattr(mapper.class_, self.key, None)
if mapper._is_userland_descriptor(desc):
self.descriptor = desc
if self.descriptor is None:
def fset(obj, value):
setattr(obj, self.name, value)
def fdel(obj):
delattr(obj, self.name)
def fget(obj):
return getattr(obj, self.name)
self.descriptor = property(
fget=fget,
fset=fset,
fdel=fdel,
)
proxy_attr = attributes.create_proxied_attribute(
self.descriptor)(
self.parent.class_,
self.key,
self.descriptor,
lambda: self._comparator_factory(mapper),
doc=self.doc,
original_property=self
)
proxy_attr.impl = _ProxyImpl(self.key)
mapper.class_manager.instrument_attribute(self.key, proxy_attr)
@util.langhelpers.dependency_for("sqlalchemy.orm.properties")
class CompositeProperty(DescriptorProperty):
"""Defines a "composite" mapped attribute, representing a collection
of columns as one attribute.
:class:`.CompositeProperty` is constructed using the :func:`.composite`
function.
.. seealso::
:ref:`mapper_composite`
"""
def __init__(self, class_, *attrs, **kwargs):
"""Return a composite column-based property for use with a Mapper.
See the mapping documentation section :ref:`mapper_composite` for a
full usage example.
The :class:`.MapperProperty` returned by :func:`.composite`
is the :class:`.CompositeProperty`.
:param class\_:
The "composite type" class.
:param \*cols:
List of Column objects to be mapped.
:param active_history=False:
When ``True``, indicates that the "previous" value for a
scalar attribute should be loaded when replaced, if not
already loaded. See the same flag on :func:`.column_property`.
.. versionchanged:: 0.7
This flag specifically becomes meaningful
- previously it was a placeholder.
:param group:
A group name for this property when marked as deferred.
:param deferred:
When True, the column property is "deferred", meaning that it does
not load immediately, and is instead loaded when the attribute is
first accessed on an instance. See also
:func:`~sqlalchemy.orm.deferred`.
:param comparator_factory: a class which extends
:class:`.CompositeProperty.Comparator` which provides custom SQL
clause generation for comparison operations.
:param doc:
optional string that will be applied as the doc on the
class-bound descriptor.
:param info: Optional data dictionary which will be populated into the
:attr:`.MapperProperty.info` attribute of this object.
.. versionadded:: 0.8
:param extension:
an :class:`.AttributeExtension` instance,
or list of extensions, which will be prepended to the list of
attribute listeners for the resulting descriptor placed on the
class. **Deprecated.** Please see :class:`.AttributeEvents`.
"""
super(CompositeProperty, self).__init__()
self.attrs = attrs
self.composite_class = class_
self.active_history = kwargs.get('active_history', False)
self.deferred = kwargs.get('deferred', False)
self.group = kwargs.get('group', None)
self.comparator_factory = kwargs.pop('comparator_factory',
self.__class__.Comparator)
if 'info' in kwargs:
self.info = kwargs.pop('info')
util.set_creation_order(self)
self._create_descriptor()
def instrument_class(self, mapper):
super(CompositeProperty, self).instrument_class(mapper)
self._setup_event_handlers()
def do_init(self):
"""Initialization which occurs after the :class:`.CompositeProperty`
has been associated with its parent mapper.
"""
self._setup_arguments_on_columns()
def _create_descriptor(self):
"""Create the Python descriptor that will serve as
the access point on instances of the mapped class.
"""
def fget(instance):
dict_ = attributes.instance_dict(instance)
state = attributes.instance_state(instance)
if self.key not in dict_:
# key not present. Iterate through related
# attributes, retrieve their values. This
# ensures they all load.
values = [
getattr(instance, key)
for key in self._attribute_keys
]
# current expected behavior here is that the composite is
# created on access if the object is persistent or if
# col attributes have non-None. This would be better
# if the composite were created unconditionally,
# but that would be a behavioral change.
if self.key not in dict_ and (
state.key is not None or
not _none_set.issuperset(values)
):
dict_[self.key] = self.composite_class(*values)
state.manager.dispatch.refresh(state, None, [self.key])
return dict_.get(self.key, None)
def fset(instance, value):
dict_ = attributes.instance_dict(instance)
state = attributes.instance_state(instance)
attr = state.manager[self.key]
previous = dict_.get(self.key, attributes.NO_VALUE)
for fn in attr.dispatch.set:
value = fn(state, value, previous, attr.impl)
dict_[self.key] = value
if value is None:
for key in self._attribute_keys:
setattr(instance, key, None)
else:
for key, value in zip(
self._attribute_keys,
value.__composite_values__()):
setattr(instance, key, value)
def fdel(instance):
state = attributes.instance_state(instance)
dict_ = attributes.instance_dict(instance)
previous = dict_.pop(self.key, attributes.NO_VALUE)
attr = state.manager[self.key]
attr.dispatch.remove(state, previous, attr.impl)
for key in self._attribute_keys:
setattr(instance, key, None)
self.descriptor = property(fget, fset, fdel)
@util.memoized_property
def _comparable_elements(self):
return [
getattr(self.parent.class_, prop.key)
for prop in self.props
]
@util.memoized_property
def props(self):
props = []
for attr in self.attrs:
if isinstance(attr, str):
prop = self.parent.get_property(
attr, _configure_mappers=False)
elif isinstance(attr, schema.Column):
prop = self.parent._columntoproperty[attr]
elif isinstance(attr, attributes.InstrumentedAttribute):
prop = attr.property
else:
raise sa_exc.ArgumentError(
"Composite expects Column objects or mapped "
"attributes/attribute names as arguments, got: %r"
% (attr,))
props.append(prop)
return props
@property
def columns(self):
return [a for a in self.attrs if isinstance(a, schema.Column)]
def _setup_arguments_on_columns(self):
"""Propagate configuration arguments made on this composite
to the target columns, for those that apply.
"""
for prop in self.props:
prop.active_history = self.active_history
if self.deferred:
prop.deferred = self.deferred
prop.strategy_class = prop._strategy_lookup(
("deferred", True),
("instrument", True))
prop.group = self.group
def _setup_event_handlers(self):
"""Establish events that populate/expire the composite attribute."""
def load_handler(state, *args):
dict_ = state.dict
if self.key in dict_:
return
# if column elements aren't loaded, skip.
# __get__() will initiate a load for those
# columns
for k in self._attribute_keys:
if k not in dict_:
return
# assert self.key not in dict_
dict_[self.key] = self.composite_class(
*[state.dict[key] for key in
self._attribute_keys]
)
def expire_handler(state, keys):
if keys is None or set(self._attribute_keys).intersection(keys):
state.dict.pop(self.key, None)
def insert_update_handler(mapper, connection, state):
"""After an insert or update, some columns may be expired due
to server side defaults, or re-populated due to client side
defaults. Pop out the composite value here so that it
recreates.
"""
state.dict.pop(self.key, None)
event.listen(self.parent, 'after_insert',
insert_update_handler, raw=True)
event.listen(self.parent, 'after_update',
insert_update_handler, raw=True)
event.listen(self.parent, 'load',
load_handler, raw=True, propagate=True)
event.listen(self.parent, 'refresh',
load_handler, raw=True, propagate=True)
event.listen(self.parent, 'expire',
expire_handler, raw=True, propagate=True)
# TODO: need a deserialize hook here
@util.memoized_property
def _attribute_keys(self):
return [
prop.key for prop in self.props
]
def get_history(self, state, dict_, passive=attributes.PASSIVE_OFF):
"""Provided for userland code that uses attributes.get_history()."""
added = []
deleted = []
has_history = False
for prop in self.props:
key = prop.key
hist = state.manager[key].impl.get_history(state, dict_)
if hist.has_changes():
has_history = True
non_deleted = hist.non_deleted()
if non_deleted:
added.extend(non_deleted)
else:
added.append(None)
if hist.deleted:
deleted.extend(hist.deleted)
else:
deleted.append(None)
if has_history:
return attributes.History(
[self.composite_class(*added)],
(),
[self.composite_class(*deleted)]
)
else:
return attributes.History(
(), [self.composite_class(*added)], ()
)
def _comparator_factory(self, mapper):
return self.comparator_factory(self, mapper)
class CompositeBundle(query.Bundle):
def __init__(self, property, expr):
self.property = property
super(CompositeProperty.CompositeBundle, self).__init__(
property.key, *expr)
def create_row_processor(self, query, procs, labels):
def proc(row):
return self.property.composite_class(
*[proc(row) for proc in procs])
return proc
class Comparator(PropComparator):
"""Produce boolean, comparison, and other operators for
:class:`.CompositeProperty` attributes.
See the example in :ref:`composite_operations` for an overview
of usage , as well as the documentation for :class:`.PropComparator`.
See also:
:class:`.PropComparator`
:class:`.ColumnOperators`
:ref:`types_operators`
:attr:`.TypeEngine.comparator_factory`
"""
__hash__ = None
@property
def clauses(self):
return self.__clause_element__()
def __clause_element__(self):
return expression.ClauseList(
group=False, *self._comparable_elements)
def _query_clause_element(self):
return CompositeProperty.CompositeBundle(
self.prop, self.__clause_element__())
@util.memoized_property
def _comparable_elements(self):
if self._adapt_to_entity:
return [
getattr(
self._adapt_to_entity.entity,
prop.key
) for prop in self.prop._comparable_elements
]
else:
return self.prop._comparable_elements
def __eq__(self, other):
if other is None:
values = [None] * len(self.prop._comparable_elements)
else:
values = other.__composite_values__()
comparisons = [
a == b
for a, b in zip(self.prop._comparable_elements, values)
]
if self._adapt_to_entity:
comparisons = [self.adapter(x) for x in comparisons]
return sql.and_(*comparisons)
def __ne__(self, other):
return sql.not_(self.__eq__(other))
def __str__(self):
return str(self.parent.class_.__name__) + "." + self.key
@util.langhelpers.dependency_for("sqlalchemy.orm.properties")
class ConcreteInheritedProperty(DescriptorProperty):
"""A 'do nothing' :class:`.MapperProperty` that disables
an attribute on a concrete subclass that is only present
on the inherited mapper, not the concrete classes' mapper.
Cases where this occurs include:
* When the superclass mapper is mapped against a
"polymorphic union", which includes all attributes from
all subclasses.
* When a relationship() is configured on an inherited mapper,
but not on the subclass mapper. Concrete mappers require
that relationship() is configured explicitly on each
subclass.
"""
def _comparator_factory(self, mapper):
comparator_callable = None
for m in self.parent.iterate_to_root():
p = m._props[self.key]
if not isinstance(p, ConcreteInheritedProperty):
comparator_callable = p.comparator_factory
break
return comparator_callable
def __init__(self):
super(ConcreteInheritedProperty, self).__init__()
def warn():
raise AttributeError("Concrete %s does not implement "
"attribute %r at the instance level. Add "
"this property explicitly to %s." %
(self.parent, self.key, self.parent))
class NoninheritedConcreteProp(object):
def __set__(s, obj, value):
warn()
def __delete__(s, obj):
warn()
def __get__(s, obj, owner):
if obj is None:
return self.descriptor
warn()
self.descriptor = NoninheritedConcreteProp()
@util.langhelpers.dependency_for("sqlalchemy.orm.properties")
class SynonymProperty(DescriptorProperty):
def __init__(self, name, map_column=None,
descriptor=None, comparator_factory=None,
doc=None, info=None):
"""Denote an attribute name as a synonym to a mapped property,
in that the attribute will mirror the value and expression behavior
of another attribute.
:param name: the name of the existing mapped property. This
can refer to the string name of any :class:`.MapperProperty`
configured on the class, including column-bound attributes
and relationships.
:param descriptor: a Python :term:`descriptor` that will be used
as a getter (and potentially a setter) when this attribute is
accessed at the instance level.
:param map_column: if ``True``, the :func:`.synonym` construct will
locate the existing named :class:`.MapperProperty` based on the
attribute name of this :func:`.synonym`, and assign it to a new
attribute linked to the name of this :func:`.synonym`.
That is, given a mapping like::
class MyClass(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
job_status = Column(String(50))
job_status = synonym("_job_status", map_column=True)
The above class ``MyClass`` will now have the ``job_status``
:class:`.Column` object mapped to the attribute named
``_job_status``, and the attribute named ``job_status`` will refer
to the synonym itself. This feature is typically used in
conjunction with the ``descriptor`` argument in order to link a
user-defined descriptor as a "wrapper" for an existing column.
:param info: Optional data dictionary which will be populated into the
:attr:`.InspectionAttr.info` attribute of this object.
.. versionadded:: 1.0.0
:param comparator_factory: A subclass of :class:`.PropComparator`
that will provide custom comparison behavior at the SQL expression
level.
.. note::
For the use case of providing an attribute which redefines both
Python-level and SQL-expression level behavior of an attribute,
please refer to the Hybrid attribute introduced at
:ref:`mapper_hybrids` for a more effective technique.
.. seealso::
:ref:`synonyms` - examples of functionality.
:ref:`mapper_hybrids` - Hybrids provide a better approach for
more complicated attribute-wrapping schemes than synonyms.
"""
super(SynonymProperty, self).__init__()
self.name = name
self.map_column = map_column
self.descriptor = descriptor
self.comparator_factory = comparator_factory
self.doc = doc or (descriptor and descriptor.__doc__) or None
if info:
self.info = info
util.set_creation_order(self)
# TODO: when initialized, check _proxied_property,
# emit a warning if its not a column-based property
@util.memoized_property
def _proxied_property(self):
return getattr(self.parent.class_, self.name).property
def _comparator_factory(self, mapper):
prop = self._proxied_property
if self.comparator_factory:
comp = self.comparator_factory(prop, mapper)
else:
comp = prop.comparator_factory(prop, mapper)
return comp
def set_parent(self, parent, init):
if self.map_column:
# implement the 'map_column' option.
if self.key not in parent.mapped_table.c:
raise sa_exc.ArgumentError(
"Can't compile synonym '%s': no column on table "
"'%s' named '%s'"
% (self.name, parent.mapped_table.description, self.key))
elif parent.mapped_table.c[self.key] in \
parent._columntoproperty and \
parent._columntoproperty[
parent.mapped_table.c[self.key]
].key == self.name:
raise sa_exc.ArgumentError(
"Can't call map_column=True for synonym %r=%r, "
"a ColumnProperty already exists keyed to the name "
"%r for column %r" %
(self.key, self.name, self.name, self.key)
)
p = properties.ColumnProperty(parent.mapped_table.c[self.key])
parent._configure_property(
self.name, p,
init=init,
setparent=True)
p._mapped_by_synonym = self.key
self.parent = parent
@util.langhelpers.dependency_for("sqlalchemy.orm.properties")
class ComparableProperty(DescriptorProperty):
"""Instruments a Python property for use in query expressions."""
def __init__(
self, comparator_factory, descriptor=None, doc=None, info=None):
"""Provides a method of applying a :class:`.PropComparator`
to any Python descriptor attribute.
.. versionchanged:: 0.7
:func:`.comparable_property` is superseded by
the :mod:`~sqlalchemy.ext.hybrid` extension. See the example
at :ref:`hybrid_custom_comparators`.
Allows any Python descriptor to behave like a SQL-enabled
attribute when used at the class level in queries, allowing
redefinition of expression operator behavior.
In the example below we redefine :meth:`.PropComparator.operate`
to wrap both sides of an expression in ``func.lower()`` to produce
case-insensitive comparison::
from sqlalchemy.orm import comparable_property
from sqlalchemy.orm.interfaces import PropComparator
from sqlalchemy.sql import func
from sqlalchemy import Integer, String, Column
from sqlalchemy.ext.declarative import declarative_base
class CaseInsensitiveComparator(PropComparator):
def __clause_element__(self):
return self.prop
def operate(self, op, other):
return op(
func.lower(self.__clause_element__()),
func.lower(other)
)
Base = declarative_base()
class SearchWord(Base):
__tablename__ = 'search_word'
id = Column(Integer, primary_key=True)
word = Column(String)
word_insensitive = comparable_property(lambda prop, mapper:
CaseInsensitiveComparator(
mapper.c.word, mapper)
)
A mapping like the above allows the ``word_insensitive`` attribute
to render an expression like::
>>> print SearchWord.word_insensitive == "Trucks"
lower(search_word.word) = lower(:lower_1)
:param comparator_factory:
A PropComparator subclass or factory that defines operator behavior
for this property.
:param descriptor:
Optional when used in a ``properties={}`` declaration. The Python
descriptor or property to layer comparison behavior on top of.
The like-named descriptor will be automatically retrieved from the
mapped class if left blank in a ``properties`` declaration.
:param info: Optional data dictionary which will be populated into the
:attr:`.InspectionAttr.info` attribute of this object.
.. versionadded:: 1.0.0
"""
super(ComparableProperty, self).__init__()
self.descriptor = descriptor
self.comparator_factory = comparator_factory
self.doc = doc or (descriptor and descriptor.__doc__) or None
if info:
self.info = info
util.set_creation_order(self)
def _comparator_factory(self, mapper):
return self.comparator_factory(self, mapper)
| gpl-2.0 |
enavarro222/bblamp | webserver.py | 1 | 5293 | #!/usr/bin/python
#-*- coding:utf-8 -*-
import os
import sys
import json
# Make sure your gevent version is >= 1.0
import gevent
from gevent.wsgi import WSGIServer
from gevent.queue import Queue
from flask import Flask, Response
from flask import render_template, jsonify
from utils import ServerSentEvent
from api import lapps
from api import get_lapp_status
from errors import BBLampException
#TODO: hardware ?
from simulate import simu
import config
# the Flask app
bblamp_app = Flask(__name__)
bblamp_app.debug = True
# app API
bblamp_app.register_blueprint(lapps, url_prefix="/v1")
# lamp simulation API
bblamp_app.register_blueprint(simu, url_prefix="/simu/v1")
# app shared state variables
subscriptions = []
#-------------------------------------------------------------------------------
@bblamp_app.errorhandler(BBLampException)
def handle_invalid_lapp_name(error):
""" BBLampException handler
"""
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
#-------------------------------------------------------------------------------
# lapp log API (push)
@bblamp_app.route("/log/debug")
def log_debug():
return "Currently %d subscriptions" % len(subscriptions)
@bblamp_app.route("/log/subscribe")
def log_subscribe():
def gen():
q = Queue()
subscriptions.append(q)
try:
while True:
result = q.get()
ev = ServerSentEvent(str(result))
yield ev.encode()
except GeneratorExit: # Or maybe use flask signals
subscriptions.remove(q)
return Response(gen(), mimetype="text/event-stream")
def send_data(dtype, data):
""" Send data to the clients
"""
output = {
"dtype": dtype,
"data": data
}
for sub in subscriptions[:]:
print("%s : %s" % (dtype, data))
sub.put(json.dumps(output))
def new_lapp_output(msg):
send_data("output", msg)
def new_lapp_logmsg(msg):
send_data("log", msg)
def new_lapp_status():
send_data("status", get_lapp_status())
def monitor_logging_file(filename, output_fct):
""" pseudo therad (gevent) that monitor a log file
"""
while True:
try:
with open(filename, "r") as in_file:
#seek to the end
# in order to not send all already in the file lines
in_file.seek(0, os.SEEK_END)
while True:
# check the file still exist
# cf: http://stackoverflow.com/a/12690767
if os.fstat(in_file.fileno()).st_nlink == 0:
break # try to reopen it if it has been deleted
# try to read next line
log_line = in_file.readline()
if log_line != "":
# Search if next lines are for the same log "line"
## wait short time to be sure to not miss next "same log line"
gevent.sleep(2e-3)
last_pos = in_file.tell()
nextline = in_file.readline()
while not (nextline == "" or nextline.startswith("LampApp")): # = not a new log line
log_line += nextline
# wait short time to be sure to not miss next "same log line"
gevent.sleep(2e-3)
last_pos = in_file.tell()
nextline = in_file.readline()
# push log_line
output_fct(log_line)
# and seek back to the next log line (seek to the same position)
in_file.seek(last_pos)
gevent.sleep(0.1)
except IOError as error:
# file doesn't exist or not
if error.errno == 2:
#TODO: add logging
gevent.sleep(1)
else:
raise
def monitor_lapp_logfile():
monitor_logging_file(config.LAPP_LOGFILE, new_lapp_logmsg)
def monitor_lapp_outfile():
monitor_logging_file(config.LAPP_OUTFILE, new_lapp_output)
def monitor_lapp_status():
while True:
last_status = get_lapp_status()
while last_status["hash"] == get_lapp_status()["hash"]:
gevent.sleep(0.4)
new_lapp_status()
gevent.sleep(0.4)
#-------------------------------------------------------------------------------
# single page app getter
@bblamp_app.route("/")
@bblamp_app.route("/<string:lapp_name>")
def main_page(lapp_name=None):
return render_template("index.html")
@bblamp_app.route("/ltest")
def logging_test():
return render_template("log_test.html")
#-------------------------------------------------------------------------------
def main():
print("<run>")
# file monitoring
monitor_log_worker = gevent.spawn(monitor_lapp_logfile)
monitor_output_worker = gevent.spawn(monitor_lapp_outfile)
monitor_status_worker = gevent.spawn(monitor_lapp_status)
# web server
server = WSGIServer(("0.0.0.0", 5000), bblamp_app)
server.serve_forever()
print("<run_done>")
return 0
if __name__ == "__main__":
sys.exit(main())
| agpl-3.0 |
kamladi/textback-web | twilio/rest/resources/sip/ip_access_control_lists.py | 4 | 3742 | from twilio.rest.resources import InstanceResource, ListResource
class IpAddress(InstanceResource):
""" An IP address entry in an Access Control List.
.. attribute:: sid
A 34 character string that uniquely identifies this resource.
.. attribute:: account_sid
The unique id of the Account responsible for this IpAddress.
.. attribute:: friendly_name
A human-readable name for this IP address.
.. attribute:: ip_address
The IP address in dotted-decimal IPv4 notation.
.. attribute:: date_created
The date that this resource was created.
.. attribute:: date_updated
The date that this resource was last updated.
"""
def update(self, **kwargs):
"""Update this address."""
return self.parent.update_instance(self.name, **kwargs)
def delete(self):
"""
Delete this address.
"""
return self.parent.delete_instance(self.name)
class IpAddresses(ListResource):
name = "IpAddresses"
key = "ip_addresses"
instance = IpAddress
def create(self, friendly_name, ip_address, **kwargs):
"""Add an IP address to a SipIpAccessControlList.
:param str friendly_name: A human-readable name for this address.
:param str ip_address: A dotted-decimal IPv4 address
"""
kwargs['friendly_name'] = friendly_name
kwargs['ip_address'] = ip_address
return self.create_instance(kwargs)
def update(self, sid, **kwargs):
"""Update an :class:`IpAddress`.
:param sid: String identifier for an address
"""
return self.update_instance(sid, kwargs)
def delete(self, sid):
"""Remove an :class:`IpAddress` from a :class:`SipIpAccessControlList`.
:param sid: String identifier for an address
"""
return self.delete_instance(sid)
class SipIpAccessControlList(InstanceResource):
""" A list of IP addresses for controlling access to a SIP Domain.
.. attribute:: sid
A 34 character string that uniquely identifies this resource.
.. attribute:: account_sid
The unique id of the Account responsible for this ACL.
.. attribute:: friendly_name
A human-readable name for this SipIpAccessControlList.
.. attribute:: date_created
The date that this resource was created.
.. attribute:: date_updated
The date that this resource was last updated.
"""
subresources = [IpAddresses]
def update(self, **kwargs):
"""Update this address."""
return self.parent.update_instance(self.name, **kwargs)
def delete(self):
"""
Delete this address.
"""
return self.parent.delete_instance(self.name)
class SipIpAccessControlLists(ListResource):
name = "IpAccessControlLists"
key = "ip_access_control_lists"
instance = SipIpAccessControlList
def create(self, friendly_name, **kwargs):
""" Create a :class:`SipIpAccessControlList`.
:param str friendly_name: A human-readable name for this ACL.
"""
kwargs['friendly_name'] = friendly_name
return self.create_instance(kwargs)
def update(self, sid, **kwargs):
""" Change the name of a :class:`SipIpAccessControlList`.
:param str sid: String identifier for a SipIpAccessControlList resource
:param str friendly_name: A human-readable name for the ACL.
"""
return self.update_instance(sid, kwargs)
def delete(self, sid):
"""
Delete a :class:`SipIpAccessControlList`.
:param sid: String identifier for a SipIpAccessControlList resource
"""
return self.delete_instance(sid)
| mit |
molly/brandeis | tests/testvalidator.py | 1 | 3946 | # -*- coding: utf-8 -*-
# Brandeis - A tool to convert plaintext court cases (from the lochner
# tool: http://gitorious.org/lochner/) to wikitext.
#
# Copyright (C) 2013 Molly White
#
# 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 validator import Validator
from bexceptions import *
import os, unittest
class TestFileValidation(unittest.TestCase):
'''Test functions that validate the input files.'''
def setUp(self):
pass
def tearDown(self):
self.buffer.close()
def testGoodTitlePlacement(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\n\n\t\t\t\t<h1>Person v. Person - 100 U.S. 25 (2000)</h1>')
v = Validator('buffer.txt')
try:
v.validateTitlePlacement()
except:
self.fail('Validator did not pass a good title.')
def testPoorlyPlacedTitle(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\n\n\t\t\t\t<div></div><h1>Person v. Person - 100 U.S. 25 (2000)</h1>')
v = Validator('buffer.txt')
with self.assertRaises(BadTitle, msg='Validator passed a title that was not at the '
'beginning of the file.'):
v.validateTitlePlacement()
def testNoTitle(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\n\n\t\t\t')
v = Validator('buffer.txt')
with self.assertRaises(BadTitle, msg='Validator passed a file with no title.'):
v.validateTitlePlacement()
def testGoodTitleParts(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\t\t\t\t<h1>Foo v. Bar - 100 U.S. 200 (2013)</h1><div>Extra stuff</div>')
v = Validator('buffer.txt')
try:
v.validateTitleParts()
except:
self.fail('Validator did not pass a title with good parts.')
def testIdentifyCaseGroup(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('\t\t\t<h1>Group of Cases - 100 U.S. 200 (2013)</h1>\t\t\t')
v = Validator('buffer.txt')
with self.assertRaises(GroupedCase, msg='Validator failed to identify a group of cases'
' as such.'):
v.validateTitleParts()
def testBadTitleDate(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('<h1>Foo v. Bar - 100 U.S. 200 (203)</h1>')
v = Validator('buffer.txt')
with self.assertRaises(BadTitle, msg='Validator passed a title containing an improperly'
'formatted date.'):
v.validateTitleParts()
def testBadTitleNumber(self):
with open('buffer.txt', 'w', encoding='utf-8') as self.buffer:
self.buffer.write('<h1>Foo v. Bar - U.S. 200 (2013)</h1>')
v = Validator('buffer.txt')
with self.assertRaises(BadTitle, msg='Validator passed a title containing an improperly'
'formatted case number.'):
v.validateTitleParts()
if __name__ == "__main__":
unittest.main()
try:
os.remove('buffer.txt')
except:
pass | gpl-3.0 |
Pakoach/Sick-Beard | tests/scene_helpers_tests.py | 67 | 7197 | import unittest
import test_lib as test
import sys, os.path
sys.path.append(os.path.abspath('..'))
from sickbeard import show_name_helpers, scene_exceptions, common, name_cache
import sickbeard
from sickbeard import db
from sickbeard.databases import cache_db
from sickbeard.tv import TVShow as Show
class SceneTests(test.SickbeardTestDBCase):
def _test_sceneToNormalShowNames(self, name, expected):
result = show_name_helpers.sceneToNormalShowNames(name)
self.assertTrue(len(set(expected).intersection(set(result))) == len(expected))
dot_result = show_name_helpers.sceneToNormalShowNames(name.replace(' ', '.'))
dot_expected = [x.replace(' ', '.') for x in expected]
self.assertTrue(len(set(dot_expected).intersection(set(dot_result))) == len(dot_expected))
def _test_allPossibleShowNames(self, name, tvdbid=0, tvrname=None, expected=[]):
s = Show(tvdbid)
s.name = name
s.tvrname = tvrname
result = show_name_helpers.allPossibleShowNames(s)
self.assertTrue(len(set(expected).intersection(set(result))) == len(expected))
def _test_filterBadReleases(self, name, expected):
result = show_name_helpers.filterBadReleases(name)
self.assertEqual(result, expected)
def _test_isGoodName(self, name, show):
self.assertTrue(show_name_helpers.isGoodResult(name, show))
def test_isGoodName(self):
listOfcases = [('Show.Name.S01E02.Test-Test', 'Show/Name'),
('Show.Name.S01E02.Test-Test', 'Show. Name'),
('Show.Name.S01E02.Test-Test', 'Show- Name'),
('Show.Name.Part.IV.Test-Test', 'Show Name'),
('Show.Name.S01.Test-Test', 'Show Name'),
('Show.Name.E02.Test-Test', 'Show: Name'),
('Show Name Season 2 Test', 'Show: Name'),
]
for testCase in listOfcases:
scene_name, show_name = testCase
s = Show(0)
s.name = show_name
self._test_isGoodName(scene_name, s)
def test_sceneToNormalShowNames(self):
self._test_sceneToNormalShowNames('Show Name 2010', ['Show Name 2010', 'Show Name (2010)'])
self._test_sceneToNormalShowNames('Show Name US', ['Show Name US', 'Show Name (US)'])
self._test_sceneToNormalShowNames('Show Name AU', ['Show Name AU', 'Show Name (AU)'])
self._test_sceneToNormalShowNames('Show Name CA', ['Show Name CA', 'Show Name (CA)'])
self._test_sceneToNormalShowNames('Show and Name', ['Show and Name', 'Show & Name'])
self._test_sceneToNormalShowNames('Show and Name 2010', ['Show and Name 2010', 'Show & Name 2010', 'Show and Name (2010)', 'Show & Name (2010)'])
self._test_sceneToNormalShowNames('show name us', ['show name us', 'show name (us)'])
self._test_sceneToNormalShowNames('Show And Name', ['Show And Name', 'Show & Name'])
# failure cases
self._test_sceneToNormalShowNames('Show Name 90210', ['Show Name 90210'])
self._test_sceneToNormalShowNames('Show Name YA', ['Show Name YA'])
def test_allPossibleShowNames(self):
#common.sceneExceptions[-1] = ['Exception Test']
myDB = db.DBConnection("cache.db")
myDB.action("INSERT INTO scene_exceptions (tvdb_id, show_name) VALUES (?,?)", [-1, 'Exception Test'])
common.countryList['Full Country Name'] = 'FCN'
self._test_allPossibleShowNames('Show Name', expected=['Show Name'])
self._test_allPossibleShowNames('Show Name', -1, expected=['Show Name', 'Exception Test'])
self._test_allPossibleShowNames('Show Name', tvrname='TVRage Name', expected=['Show Name', 'TVRage Name'])
self._test_allPossibleShowNames('Show Name FCN', expected=['Show Name FCN', 'Show Name (Full Country Name)'])
self._test_allPossibleShowNames('Show Name (FCN)', expected=['Show Name (FCN)', 'Show Name (Full Country Name)'])
self._test_allPossibleShowNames('Show Name Full Country Name', expected=['Show Name Full Country Name', 'Show Name (FCN)'])
self._test_allPossibleShowNames('Show Name (Full Country Name)', expected=['Show Name (Full Country Name)', 'Show Name (FCN)'])
self._test_allPossibleShowNames('Show Name (FCN)', -1, 'TVRage Name', expected=['Show Name (FCN)', 'Show Name (Full Country Name)', 'Exception Test', 'TVRage Name'])
def test_filterBadReleases(self):
self._test_filterBadReleases('Show.S02.German.Stuff-Grp', False)
self._test_filterBadReleases('Show.S02.Some.Stuff-Core2HD', False)
self._test_filterBadReleases('Show.S02.Some.German.Stuff-Grp', False)
self._test_filterBadReleases('German.Show.S02.Some.Stuff-Grp', True)
self._test_filterBadReleases('Show.S02.This.Is.German', False)
class SceneExceptionTestCase(test.SickbeardTestDBCase):
def setUp(self):
super(SceneExceptionTestCase, self).setUp()
scene_exceptions.retrieve_exceptions()
def test_sceneExceptionsEmpty(self):
self.assertEqual(scene_exceptions.get_scene_exceptions(0), [])
def test_sceneExceptionsBabylon5(self):
self.assertEqual(sorted(scene_exceptions.get_scene_exceptions(70726)), ['Babylon 5', 'Babylon5'])
def test_sceneExceptionByName(self):
self.assertEqual(scene_exceptions.get_scene_exception_by_name('Babylon5'), 70726)
self.assertEqual(scene_exceptions.get_scene_exception_by_name('babylon 5'), 70726)
self.assertEqual(scene_exceptions.get_scene_exception_by_name('Carlos 2010'), 164451)
def test_sceneExceptionByNameEmpty(self):
self.assertEqual(scene_exceptions.get_scene_exception_by_name('nothing useful'), None)
def test_sceneExceptionsResetNameCache(self):
# clear the exceptions
myDB = db.DBConnection("cache.db")
myDB.action("DELETE FROM scene_exceptions")
# put something in the cache
name_cache.addNameToCache('Cached Name', 0)
# updating should clear the cache so our previously "Cached Name" won't be in there
scene_exceptions.retrieve_exceptions()
self.assertEqual(name_cache.retrieveNameFromCache('Cached Name'), None)
# put something in the cache
name_cache.addNameToCache('Cached Name', 0)
# updating should not clear the cache this time since our exceptions didn't change
scene_exceptions.retrieve_exceptions()
self.assertEqual(name_cache.retrieveNameFromCache('Cached Name'), 0)
if __name__ == '__main__':
if len(sys.argv) > 1:
suite = unittest.TestLoader().loadTestsFromName('scene_helpers_tests.SceneExceptionTestCase.test_' + sys.argv[1])
unittest.TextTestRunner(verbosity=2).run(suite)
else:
suite = unittest.TestLoader().loadTestsFromTestCase(SceneTests)
unittest.TextTestRunner(verbosity=2).run(suite)
suite = unittest.TestLoader().loadTestsFromTestCase(SceneExceptionTestCase)
unittest.TextTestRunner(verbosity=2).run(suite)
| gpl-3.0 |
arbrandes/edx-platform | openedx/core/lib/tests/test_edx_api_utils.py | 4 | 12410 | """Tests covering edX API utilities."""
# pylint: disable=missing-docstring
import json
from unittest import mock
import httpretty
from django.core.cache import cache
from openedx.core.djangoapps.catalog.models import CatalogIntegration
from openedx.core.djangoapps.catalog.tests.mixins import CatalogIntegrationMixin
from openedx.core.djangoapps.catalog.utils import create_catalog_api_client
from openedx.core.djangoapps.credentials.tests.mixins import CredentialsApiConfigMixin
from openedx.core.djangolib.testing.utils import CacheIsolationTestCase, skip_unless_lms
from openedx.core.lib.edx_api_utils import get_edx_api_data
from common.djangoapps.student.tests.factories import UserFactory
UTILITY_MODULE = 'openedx.core.lib.edx_api_utils'
TEST_API_URL = 'http://www-internal.example.com/api'
@skip_unless_lms
@httpretty.activate
class TestGetEdxApiData(CatalogIntegrationMixin, CredentialsApiConfigMixin, CacheIsolationTestCase):
"""Tests for edX API data retrieval utility."""
ENABLED_CACHES = ['default']
def setUp(self):
super().setUp()
self.user = UserFactory()
httpretty.httpretty.reset()
cache.clear()
def _mock_catalog_api(self, responses, url=None):
assert httpretty.is_enabled(), 'httpretty must be enabled to mock Catalog API calls.'
url = url if url else CatalogIntegration.current().get_internal_api_url().strip('/') + '/programs/'
httpretty.register_uri(httpretty.GET, url, responses=responses)
def _assert_num_requests(self, count):
"""DRY helper for verifying request counts."""
assert len(httpretty.httpretty.latest_requests) == count
def test_get_unpaginated_data(self):
"""Verify that unpaginated data can be retrieved."""
catalog_integration = self.create_catalog_integration()
api = create_catalog_api_client(self.user)
expected_collection = ['some', 'test', 'data']
data = {
'next': None,
'results': expected_collection,
}
self._mock_catalog_api(
[httpretty.Response(body=json.dumps(data), content_type='application/json')]
)
with mock.patch('edx_rest_api_client.client.EdxRestApiClient.__init__') as mock_init:
actual_collection = get_edx_api_data(catalog_integration, 'programs', api=api)
# Verify that the helper function didn't initialize its own client.
assert not mock_init.called
assert actual_collection == expected_collection
# Verify the API was actually hit (not the cache)
self._assert_num_requests(1)
def test_get_paginated_data(self):
"""Verify that paginated data can be retrieved."""
catalog_integration = self.create_catalog_integration()
api = create_catalog_api_client(self.user)
expected_collection = ['some', 'test', 'data']
url = CatalogIntegration.current().get_internal_api_url().strip('/') + '/programs/?page={}'
responses = []
for page, record in enumerate(expected_collection, start=1):
data = {
'next': url.format(page + 1) if page < len(expected_collection) else None,
'results': [record],
}
body = json.dumps(data)
responses.append(
httpretty.Response(body=body, content_type='application/json')
)
self._mock_catalog_api(responses)
actual_collection = get_edx_api_data(catalog_integration, 'programs', api=api)
assert actual_collection == expected_collection
self._assert_num_requests(len(expected_collection))
def test_get_paginated_data_do_not_traverse_pagination(self):
"""
Verify that pagination is not traversed if traverse_pagination=False is passed as argument.
"""
catalog_integration = self.create_catalog_integration()
api = create_catalog_api_client(self.user)
url = CatalogIntegration.current().get_internal_api_url().strip('/') + '/programs/?page={}'
responses = [
{
'next': url.format(2),
'results': ['some'],
},
{
'next': url.format(None),
'results': ['test'],
},
]
expected_response = responses[0]
self._mock_catalog_api(
[httpretty.Response(body=json.dumps(body), content_type='application/json') for body in responses]
)
actual_collection = get_edx_api_data(catalog_integration, 'programs', api=api, traverse_pagination=False)
assert actual_collection == expected_response
self._assert_num_requests(1)
def test_get_specific_resource(self):
"""Verify that a specific resource can be retrieved."""
catalog_integration = self.create_catalog_integration()
api = create_catalog_api_client(self.user)
resource_id = 1
url = '{api_root}/programs/{resource_id}/'.format(
api_root=CatalogIntegration.current().get_internal_api_url().strip('/'),
resource_id=resource_id,
)
expected_resource = {'key': 'value'}
self._mock_catalog_api(
[httpretty.Response(body=json.dumps(expected_resource), content_type='application/json')],
url=url
)
actual_resource = get_edx_api_data(catalog_integration, 'programs', api=api, resource_id=resource_id)
assert actual_resource == expected_resource
self._assert_num_requests(1)
def test_get_specific_resource_with_falsey_id(self):
"""
Verify that a specific resource can be retrieved, and pagination parsing is
not attempted, if the ID passed is falsey (e.g., 0). The expected resource contains
a "results" key, as a paginatable item would have, so if the function looks for falsey
values in the resource_id field, rather than specifically None, the function will
return the value of that "results" key.
"""
catalog_integration = self.create_catalog_integration()
api = create_catalog_api_client(self.user)
resource_id = 0
url = '{api_root}/programs/{resource_id}/'.format(
api_root=CatalogIntegration.current().get_internal_api_url().strip('/'),
resource_id=resource_id,
)
expected_resource = {'key': 'value', 'results': []}
self._mock_catalog_api(
[httpretty.Response(body=json.dumps(expected_resource), content_type='application/json')],
url=url
)
actual_resource = get_edx_api_data(catalog_integration, 'programs', api=api, resource_id=resource_id)
assert actual_resource == expected_resource
self._assert_num_requests(1)
def test_get_specific_fields_from_cache_response(self):
"""Verify that resource response is cached and get required fields from cached response"""
catalog_integration = self.create_catalog_integration(cache_ttl=5)
api = create_catalog_api_client(self.user)
response = {'lang': 'en', 'weeks_to_complete': '5'}
resource_id = 'course-v1:testX+testABC+1T2019'
url = '{api_root}/course_runs/{resource_id}/'.format(
api_root=CatalogIntegration.current().get_internal_api_url().strip('/'),
resource_id=resource_id,
)
expected_resource_for_lang = {'lang': 'en'}
expected_resource_for_weeks_to_complete = {'weeks_to_complete': '5'}
self._mock_catalog_api(
[httpretty.Response(body=json.dumps(response), content_type='application/json')],
url=url
)
cache_key = CatalogIntegration.current().CACHE_KEY
# get response and set the cache.
actual_resource_for_lang = get_edx_api_data(
catalog_integration, 'course_runs', resource_id=resource_id, api=api, cache_key=cache_key, fields=['lang']
)
assert actual_resource_for_lang == expected_resource_for_lang
# Hit the cache
actual_resource = get_edx_api_data(
catalog_integration, 'course_runs', api=api, resource_id=resource_id, cache_key=cache_key,
fields=['weeks_to_complete']
)
assert actual_resource == expected_resource_for_weeks_to_complete
# Verify that only one requests were made, not three.
self._assert_num_requests(1)
def test_cache_utilization(self):
"""Verify that when enabled, the cache is used."""
catalog_integration = self.create_catalog_integration(cache_ttl=5)
api = create_catalog_api_client(self.user)
expected_collection = ['some', 'test', 'data']
data = {
'next': None,
'results': expected_collection,
}
self._mock_catalog_api(
[httpretty.Response(body=json.dumps(data), content_type='application/json')],
)
resource_id = 1
url = '{api_root}/programs/{resource_id}/'.format(
api_root=CatalogIntegration.current().get_internal_api_url().strip('/'),
resource_id=resource_id,
)
expected_resource = {'key': 'value'}
self._mock_catalog_api(
[httpretty.Response(body=json.dumps(expected_resource), content_type='application/json')],
url=url
)
cache_key = CatalogIntegration.current().CACHE_KEY
# Warm up the cache.
get_edx_api_data(catalog_integration, 'programs', api=api, cache_key=cache_key)
get_edx_api_data(catalog_integration, 'programs', api=api, resource_id=resource_id, cache_key=cache_key)
# Hit the cache.
actual_collection = get_edx_api_data(catalog_integration, 'programs', api=api, cache_key=cache_key)
assert actual_collection == expected_collection
actual_resource = get_edx_api_data(
catalog_integration, 'programs', api=api, resource_id=resource_id, cache_key=cache_key
)
assert actual_resource == expected_resource
# Verify that only two requests were made, not four.
self._assert_num_requests(2)
@mock.patch(UTILITY_MODULE + '.log.warning')
def test_api_config_disabled(self, mock_warning):
"""Verify that no data is retrieved if the provided config model is disabled."""
catalog_integration = self.create_catalog_integration(enabled=False)
actual = get_edx_api_data(catalog_integration, 'programs', api=None)
assert mock_warning.called
assert actual == []
@mock.patch(UTILITY_MODULE + '.log.exception')
def test_data_retrieval_failure(self, mock_exception):
"""Verify that an exception is logged when data can't be retrieved."""
catalog_integration = self.create_catalog_integration()
api = create_catalog_api_client(self.user)
self._mock_catalog_api(
[httpretty.Response(body='clunk', content_type='application/json', status_code=500)]
)
actual = get_edx_api_data(catalog_integration, 'programs', api=api)
assert mock_exception.called
assert actual == []
@mock.patch(UTILITY_MODULE + '.log.warning')
def test_api_config_disabled_with_id_and_not_collection(self, mock_warning):
"""Verify that no data is retrieved if the provided config model is disabled."""
catalog_integration = self.create_catalog_integration(enabled=False)
actual = get_edx_api_data(
catalog_integration,
'programs',
api=None,
resource_id=100,
many=False
)
assert mock_warning.called
assert actual == {}
@mock.patch(UTILITY_MODULE + '.log.exception')
def test_data_retrieval_failure_with_id(self, mock_exception):
"""Verify that an exception is logged when data can't be retrieved."""
catalog_integration = self.create_catalog_integration()
api = create_catalog_api_client(self.user)
self._mock_catalog_api(
[httpretty.Response(body='clunk', content_type='application/json', status_code=500)]
)
actual = get_edx_api_data(
catalog_integration,
'programs',
api=api,
resource_id=100,
many=False
)
assert mock_exception.called
assert actual == {}
| agpl-3.0 |
phenoxim/nova | nova/privsep/fs.py | 3 | 12041 | # Copyright 2016 Red Hat, Inc
# Copyright 2017 Rackspace Australia
#
# 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.
"""
Helpers for filesystem related routines.
"""
import hashlib
import six
from oslo_concurrency import processutils
from oslo_log import log as logging
import nova.privsep
LOG = logging.getLogger(__name__)
@nova.privsep.sys_admin_pctxt.entrypoint
def mount(fstype, device, mountpoint, options):
mount_cmd = ['mount']
if fstype:
mount_cmd.extend(['-t', fstype])
if options is not None:
mount_cmd.extend(options)
mount_cmd.extend([device, mountpoint])
return processutils.execute(*mount_cmd)
@nova.privsep.sys_admin_pctxt.entrypoint
def umount(mountpoint):
processutils.execute('umount', mountpoint, attempts=3, delay_on_retry=True)
@nova.privsep.sys_admin_pctxt.entrypoint
def lvcreate(size, lv, vg, preallocated=None):
cmd = ['lvcreate']
if not preallocated:
cmd.extend(['-L', '%db' % size])
else:
cmd.extend(['-L', '%db' % preallocated,
'--virtualsize', '%db' % size])
cmd.extend(['-n', lv, vg])
processutils.execute(*cmd, attempts=3)
@nova.privsep.sys_admin_pctxt.entrypoint
def vginfo(vg):
return processutils.execute('vgs', '--noheadings', '--nosuffix',
'--separator', '|', '--units', 'b',
'-o', 'vg_size,vg_free', vg)
@nova.privsep.sys_admin_pctxt.entrypoint
def lvlist(vg):
return processutils.execute('lvs', '--noheadings', '-o', 'lv_name', vg)
@nova.privsep.sys_admin_pctxt.entrypoint
def lvinfo(path):
return processutils.execute('lvs', '-o', 'vg_all,lv_all',
'--separator', '|', path)
@nova.privsep.sys_admin_pctxt.entrypoint
def lvremove(path):
processutils.execute('lvremove', '-f', path, attempts=3)
@nova.privsep.sys_admin_pctxt.entrypoint
def blockdev_size(path):
return processutils.execute('blockdev', '--getsize64', path)
@nova.privsep.sys_admin_pctxt.entrypoint
def blockdev_flush(path):
return processutils.execute('blockdev', '--flushbufs', path)
@nova.privsep.sys_admin_pctxt.entrypoint
def clear(path, volume_size, shred=False):
cmd = ['shred']
if shred:
cmd.extend(['-n3'])
else:
cmd.extend(['-n0', '-z'])
cmd.extend(['-s%d' % volume_size, path])
processutils.execute(*cmd)
@nova.privsep.sys_admin_pctxt.entrypoint
def loopsetup(path):
return processutils.execute('losetup', '--find', '--show', path)
@nova.privsep.sys_admin_pctxt.entrypoint
def loopremove(device):
return processutils.execute('losetup', '--detach', device, attempts=3)
@nova.privsep.sys_admin_pctxt.entrypoint
def nbd_connect(device, image):
return processutils.execute('qemu-nbd', '-c', device, image)
@nova.privsep.sys_admin_pctxt.entrypoint
def nbd_disconnect(device):
return processutils.execute('qemu-nbd', '-d', device)
@nova.privsep.sys_admin_pctxt.entrypoint
def create_device_maps(device):
return processutils.execute('kpartx', '-a', device)
@nova.privsep.sys_admin_pctxt.entrypoint
def remove_device_maps(device):
return processutils.execute('kpartx', '-d', device)
@nova.privsep.sys_admin_pctxt.entrypoint
def get_filesystem_type(device):
return processutils.execute('blkid', '-o', 'value', '-s', 'TYPE', device,
check_exit_code=[0, 2])
@nova.privsep.sys_admin_pctxt.entrypoint
def e2fsck(image, flags='-fp'):
unprivileged_e2fsck(image, flags=flags)
# NOTE(mikal): this method is deliberately not wrapped in a privsep entrypoint
def unprivileged_e2fsck(image, flags='-fp'):
processutils.execute('e2fsck', flags, image, check_exit_code=[0, 1, 2])
@nova.privsep.sys_admin_pctxt.entrypoint
def resize2fs(image, check_exit_code, size=None):
unprivileged_resize2fs(image, check_exit_code=check_exit_code, size=size)
# NOTE(mikal): this method is deliberately not wrapped in a privsep entrypoint
def unprivileged_resize2fs(image, check_exit_code, size=None):
if size:
cmd = ['resize2fs', image, size]
else:
cmd = ['resize2fs', image]
processutils.execute(*cmd, check_exit_code=check_exit_code)
@nova.privsep.sys_admin_pctxt.entrypoint
def create_partition_table(device, style, check_exit_code=True):
processutils.execute('parted', '--script', device, 'mklabel', style,
check_exit_code=check_exit_code)
@nova.privsep.sys_admin_pctxt.entrypoint
def create_partition(device, style, start, end, check_exit_code=True):
processutils.execute('parted', '--script', device, '--',
'mkpart', style, start, end,
check_exit_code=check_exit_code)
@nova.privsep.sys_admin_pctxt.entrypoint
def list_partitions(device):
return unprivileged_list_partitions(device)
# NOTE(mikal): this method is deliberately not wrapped in a privsep entrypoint
def unprivileged_list_partitions(device):
"""Return partition information (num, size, type) for a device."""
out, _err = processutils.execute('parted', '--script', '--machine',
device, 'unit s', 'print')
lines = [line for line in out.split('\n') if line]
partitions = []
LOG.debug('Partitions:')
for line in lines[2:]:
line = line.rstrip(';')
num, start, end, size, fstype, name, flags = line.split(':')
num = int(num)
start = int(start.rstrip('s'))
end = int(end.rstrip('s'))
size = int(size.rstrip('s'))
LOG.debug(' %(num)s: %(fstype)s %(size)d sectors',
{'num': num, 'fstype': fstype, 'size': size})
partitions.append((num, start, size, fstype, name, flags))
return partitions
@nova.privsep.sys_admin_pctxt.entrypoint
def resize_partition(device, start, end, bootable):
return unprivileged_resize_partition(device, start, end, bootable)
# NOTE(mikal): this method is deliberately not wrapped in a privsep entrypoint
def unprivileged_resize_partition(device, start, end, bootable):
processutils.execute('parted', '--script', device, 'rm', '1')
processutils.execute('parted', '--script', device, 'mkpart',
'primary', '%ds' % start, '%ds' % end)
if bootable:
processutils.execute('parted', '--script', device,
'set', '1', 'boot', 'on')
@nova.privsep.sys_admin_pctxt.entrypoint
def ext_journal_disable(device):
processutils.execute('tune2fs', '-O ^has_journal', device)
@nova.privsep.sys_admin_pctxt.entrypoint
def ext_journal_enable(device):
processutils.execute('tune2fs', '-j', device)
# NOTE(mikal): nova allows deployers to configure the command line which is
# used to create a filesystem of a given type. This is frankly a little bit
# weird, but its also historical and probably should be in some sort of
# museum. So, we do that thing here, but it requires a funny dance in order
# to load that configuration at startup.
# NOTE(mikal): I really feel like this whole thing should be deprecated, I
# just don't think its a great idea to let people specify a command in a
# configuration option to run a root.
_MKFS_COMMAND = {}
_DEFAULT_MKFS_COMMAND = None
FS_FORMAT_EXT2 = "ext2"
FS_FORMAT_EXT3 = "ext3"
FS_FORMAT_EXT4 = "ext4"
FS_FORMAT_XFS = "xfs"
FS_FORMAT_NTFS = "ntfs"
FS_FORMAT_VFAT = "vfat"
SUPPORTED_FS_TO_EXTEND = (
FS_FORMAT_EXT2,
FS_FORMAT_EXT3,
FS_FORMAT_EXT4)
_DEFAULT_FILE_SYSTEM = FS_FORMAT_VFAT
_DEFAULT_FS_BY_OSTYPE = {'linux': FS_FORMAT_EXT4,
'windows': FS_FORMAT_NTFS}
def load_mkfs_command(os_type, command):
global _MKFS_COMMAND
global _DEFAULT_MKFS_COMMAND
_MKFS_COMMAND[os_type] = command
if os_type == 'default':
_DEFAULT_MKFS_COMMAND = command
def get_fs_type_for_os_type(os_type):
global _MKFS_COMMAND
return os_type if _MKFS_COMMAND.get(os_type) else 'default'
# NOTE(mikal): this method needs to be duplicated from utils because privsep
# can't depend on code outside the privsep directory.
def _get_hash_str(base_str):
"""Returns string that represents MD5 hash of base_str (in hex format).
If base_str is a Unicode string, encode it to UTF-8.
"""
if isinstance(base_str, six.text_type):
base_str = base_str.encode('utf-8')
return hashlib.md5(base_str).hexdigest()
def get_file_extension_for_os_type(os_type, default_ephemeral_format,
specified_fs=None):
global _MKFS_COMMAND
global _DEFAULT_MKFS_COMMAND
mkfs_command = _MKFS_COMMAND.get(os_type, _DEFAULT_MKFS_COMMAND)
if mkfs_command:
extension = mkfs_command
else:
if not specified_fs:
specified_fs = default_ephemeral_format
if not specified_fs:
specified_fs = _DEFAULT_FS_BY_OSTYPE.get(os_type,
_DEFAULT_FILE_SYSTEM)
extension = specified_fs
return _get_hash_str(extension)[:7]
@nova.privsep.sys_admin_pctxt.entrypoint
def mkfs(fs, path, label=None):
unprivileged_mkfs(fs, path, label=None)
# NOTE(mikal): this method is deliberately not wrapped in a privsep entrypoint
def unprivileged_mkfs(fs, path, label=None):
"""Format a file or block device
:param fs: Filesystem type (examples include 'swap', 'ext3', 'ext4'
'btrfs', etc.)
:param path: Path to file or block device to format
:param label: Volume label to use
"""
if fs == 'swap':
args = ['mkswap']
else:
args = ['mkfs', '-t', fs]
# add -F to force no interactive execute on non-block device.
if fs in ('ext3', 'ext4', 'ntfs'):
args.extend(['-F'])
if label:
if fs in ('msdos', 'vfat'):
label_opt = '-n'
else:
label_opt = '-L'
args.extend([label_opt, label])
args.append(path)
processutils.execute(*args)
@nova.privsep.sys_admin_pctxt.entrypoint
def _inner_configurable_mkfs(os_type, fs_label, target):
mkfs_command = (_MKFS_COMMAND.get(os_type, _DEFAULT_MKFS_COMMAND) or
'') % {'fs_label': fs_label, 'target': target}
processutils.execute(*mkfs_command.split())
# NOTE(mikal): this method is deliberately not wrapped in a privsep entrypoint
def configurable_mkfs(os_type, fs_label, target, run_as_root,
default_ephemeral_format, specified_fs=None):
# Format a file or block device using a user provided command for each
# os type. If user has not provided any configuration, format type will
# be used according to a default_ephemeral_format configuration or a
# system default.
global _MKFS_COMMAND
global _DEFAULT_MKFS_COMMAND
mkfs_command = (_MKFS_COMMAND.get(os_type, _DEFAULT_MKFS_COMMAND) or
'') % {'fs_label': fs_label, 'target': target}
if mkfs_command:
if run_as_root:
_inner_configurable_mkfs(os_type, fs_label, target)
else:
processutils.execute(*mkfs_command.split())
else:
if not specified_fs:
specified_fs = default_ephemeral_format
if not specified_fs:
specified_fs = _DEFAULT_FS_BY_OSTYPE.get(os_type,
_DEFAULT_FILE_SYSTEM)
if run_as_root:
mkfs(specified_fs, target, fs_label)
else:
unprivileged_mkfs(specified_fs, target, fs_label)
| apache-2.0 |
enthought/distarray | docs/www/pelican-plugins/liquid_tags/include_code.py | 246 | 4490 | """
Include Code Tag
----------------
This implements a Liquid-style video tag for Pelican,
based on the octopress video tag [1]_
Syntax
------
{% include_code path/to/code [lang:python] [Title text] [codec:utf8] %}
The "path to code" is specified relative to the ``code`` subdirectory of
the content directory Optionally, this subdirectory can be specified in the
config file:
CODE_DIR = 'code'
If your input file is not ASCII/UTF-8 encoded, you need to specify the
appropriate input codec by using the ``codec`` option.
Example ``codec:iso-8859-1``
Using this option does not affect the output encoding.
For a list of valid codec identifiers, see
https://docs.python.org/2/library/codecs.html#standard-encodings
Example
-------
{% include_code myscript.py %}
This will import myscript.py from content/code/myscript.py
and output the contents in a syntax highlighted code block inside a figure,
with a figcaption listing the file name and download link.
The file link will be valid only if the 'code' directory is listed
in the STATIC_PATHS setting, e.g.:
STATIC_PATHS = ['images', 'code']
[1] https://github.com/imathis/octopress/blob/master/plugins/include_code.rb
"""
import re
import os
from .mdx_liquid_tags import LiquidTags
SYNTAX = "{% include_code /path/to/code.py [lang:python] [lines:X-Y] [:hidefilename:] [title] %}"
FORMAT = re.compile(r"""
^(?:\s+)? # Allow whitespace at beginning
(?P<src>\S+) # Find the path
(?:\s+)? # Whitespace
(?:(?:lang:)(?P<lang>\S+))? # Optional language
(?:\s+)? # Whitespace
(?:(?:lines:)(?P<lines>\d+-\d+))? # Optional lines
(?:\s+)? # Whitespace
(?P<hidefilename>:hidefilename:)? # Hidefilename flag
(?:\s+)? # Whitespace
(?:(?:codec:)(?P<codec>\S+))? # Optional language
(?:\s+)? # Whitespace
(?P<title>.+)?$ # Optional title
""", re.VERBOSE)
@LiquidTags.register('include_code')
def include_code(preprocessor, tag, markup):
title = None
lang = None
src = None
match = FORMAT.search(markup)
if match:
argdict = match.groupdict()
title = argdict['title'] or ""
lang = argdict['lang']
codec = argdict['codec'] or "utf8"
lines = argdict['lines']
hide_filename = bool(argdict['hidefilename'])
if lines:
first_line, last_line = map(int, lines.split("-"))
src = argdict['src']
if not src:
raise ValueError("Error processing input, "
"expected syntax: {0}".format(SYNTAX))
code_dir = preprocessor.configs.getConfig('CODE_DIR')
code_path = os.path.join('content', code_dir, src)
if not os.path.exists(code_path):
raise ValueError("File {0} could not be found".format(code_path))
with open(code_path) as fh:
if lines:
code = fh.readlines()[first_line - 1: last_line]
code[-1] = code[-1].rstrip()
code = "".join(code)
else:
code = fh.read()
if not title and hide_filename:
raise ValueError("Either title must be specified or filename must "
"be available")
if not hide_filename:
title += " %s" % os.path.basename(src)
if lines:
title += " [Lines %s]" % lines
title = title.strip()
url = '/{0}/{1}'.format(code_dir, src)
url = re.sub('/+', '/', url)
open_tag = ("<figure class='code'>\n<figcaption><span>{title}</span> "
"<a href='{url}'>download</a></figcaption>".format(title=title,
url=url))
close_tag = "</figure>"
# store HTML tags in the stash. This prevents them from being
# modified by markdown.
open_tag = preprocessor.configs.htmlStash.store(open_tag, safe=True)
close_tag = preprocessor.configs.htmlStash.store(close_tag, safe=True)
if lang:
lang_include = ':::' + lang + '\n '
else:
lang_include = ''
source = (open_tag
+ '\n\n '
+ lang_include
+ '\n '.join(code.decode(codec).split('\n')) + '\n\n'
+ close_tag + '\n')
return source
#----------------------------------------------------------------------
# This import allows image tag to be a Pelican plugin
from liquid_tags import register
| bsd-3-clause |
ualikhansars/Gwent | lib/python2.7/site-packages/django/contrib/gis/forms/fields.py | 504 | 4316 | from __future__ import unicode_literals
from django import forms
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.utils.translation import ugettext_lazy as _
from .widgets import OpenLayersWidget
class GeometryField(forms.Field):
"""
This is the basic form field for a Geometry. Any textual input that is
accepted by GEOSGeometry is accepted by this form. By default,
this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON.
"""
widget = OpenLayersWidget
geom_type = 'GEOMETRY'
default_error_messages = {
'required': _('No geometry value provided.'),
'invalid_geom': _('Invalid geometry value.'),
'invalid_geom_type': _('Invalid geometry type.'),
'transform_error': _('An error occurred when transforming the geometry '
'to the SRID of the geometry form field.'),
}
def __init__(self, **kwargs):
# Pop out attributes from the database field, or use sensible
# defaults (e.g., allow None).
self.srid = kwargs.pop('srid', None)
self.geom_type = kwargs.pop('geom_type', self.geom_type)
super(GeometryField, self).__init__(**kwargs)
self.widget.attrs['geom_type'] = self.geom_type
def to_python(self, value):
"""
Transforms the value to a Geometry object.
"""
if value in self.empty_values:
return None
if not isinstance(value, GEOSGeometry):
try:
value = GEOSGeometry(value)
except (GEOSException, ValueError, TypeError):
raise forms.ValidationError(self.error_messages['invalid_geom'], code='invalid_geom')
# Try to set the srid
if not value.srid:
try:
value.srid = self.widget.map_srid
except AttributeError:
if self.srid:
value.srid = self.srid
return value
def clean(self, value):
"""
Validates that the input value can be converted to a Geometry
object (which is returned). A ValidationError is raised if
the value cannot be instantiated as a Geometry.
"""
geom = super(GeometryField, self).clean(value)
if geom is None:
return geom
# Ensuring that the geometry is of the correct type (indicated
# using the OGC string label).
if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
raise forms.ValidationError(self.error_messages['invalid_geom_type'], code='invalid_geom_type')
# Transforming the geometry if the SRID was set.
if self.srid and self.srid != -1 and self.srid != geom.srid:
try:
geom.transform(self.srid)
except GEOSException:
raise forms.ValidationError(
self.error_messages['transform_error'], code='transform_error')
return geom
def has_changed(self, initial, data):
""" Compare geographic value of data with its initial value. """
try:
data = self.to_python(data)
initial = self.to_python(initial)
except forms.ValidationError:
return True
# Only do a geographic comparison if both values are available
if initial and data:
data.transform(initial.srid)
# If the initial value was not added by the browser, the geometry
# provided may be slightly different, the first time it is saved.
# The comparison is done with a very low tolerance.
return not initial.equals_exact(data, tolerance=0.000001)
else:
# Check for change of state of existence
return bool(initial) != bool(data)
class GeometryCollectionField(GeometryField):
geom_type = 'GEOMETRYCOLLECTION'
class PointField(GeometryField):
geom_type = 'POINT'
class MultiPointField(GeometryField):
geom_type = 'MULTIPOINT'
class LineStringField(GeometryField):
geom_type = 'LINESTRING'
class MultiLineStringField(GeometryField):
geom_type = 'MULTILINESTRING'
class PolygonField(GeometryField):
geom_type = 'POLYGON'
class MultiPolygonField(GeometryField):
geom_type = 'MULTIPOLYGON'
| mit |
18padx08/PPTex | PPTexEnv_x86_64/lib/python2.7/site-packages/sympy/mpmath/tests/test_convert.py | 20 | 7364 | import random
from sympy.mpmath import *
from sympy.mpmath.libmp import *
def test_basic_string():
"""
Test basic string conversion
"""
mp.dps = 15
assert mpf('3') == mpf('3.0') == mpf('0003.') == mpf('0.03e2') == mpf(3.0)
assert mpf('30') == mpf('30.0') == mpf('00030.') == mpf(30.0)
for i in range(10):
for j in range(10):
assert mpf('%ie%i' % (i,j)) == i * 10**j
assert str(mpf('25000.0')) == '25000.0'
assert str(mpf('2500.0')) == '2500.0'
assert str(mpf('250.0')) == '250.0'
assert str(mpf('25.0')) == '25.0'
assert str(mpf('2.5')) == '2.5'
assert str(mpf('0.25')) == '0.25'
assert str(mpf('0.025')) == '0.025'
assert str(mpf('0.0025')) == '0.0025'
assert str(mpf('0.00025')) == '0.00025'
assert str(mpf('0.000025')) == '2.5e-5'
assert str(mpf(0)) == '0.0'
assert str(mpf('2.5e1000000000000000000000')) == '2.5e+1000000000000000000000'
assert str(mpf('2.6e-1000000000000000000000')) == '2.6e-1000000000000000000000'
assert str(mpf(1.23402834e-15)) == '1.23402834e-15'
assert str(mpf(-1.23402834e-15)) == '-1.23402834e-15'
assert str(mpf(-1.2344e-15)) == '-1.2344e-15'
assert repr(mpf(-1.2344e-15)) == "mpf('-1.2343999999999999e-15')"
def test_pretty():
mp.pretty = True
assert repr(mpf(2.5)) == '2.5'
assert repr(mpc(2.5,3.5)) == '(2.5 + 3.5j)'
mp.pretty = False
iv.pretty = True
assert repr(mpi(2.5,3.5)) == '[2.5, 3.5]'
iv.pretty = False
def test_str_whitespace():
assert mpf('1.26 ') == 1.26
def test_unicode():
mp.dps = 15
try:
unicode = unicode
except NameError:
unicode = str
assert mpf(unicode('2.76')) == 2.76
assert mpf(unicode('inf')) == inf
def test_str_format():
assert to_str(from_float(0.1),15,strip_zeros=False) == '0.100000000000000'
assert to_str(from_float(0.0),15,show_zero_exponent=True) == '0.0e+0'
assert to_str(from_float(0.0),0,show_zero_exponent=True) == '.0e+0'
assert to_str(from_float(0.0),0,show_zero_exponent=False) == '.0'
assert to_str(from_float(0.0),1,show_zero_exponent=True) == '0.0e+0'
assert to_str(from_float(0.0),1,show_zero_exponent=False) == '0.0'
assert to_str(from_float(1.23),3,show_zero_exponent=True) == '1.23e+0'
assert to_str(from_float(1.23456789000000e-2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e-2'
assert to_str(from_float(1.23456789000000e+2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e+2'
assert to_str(from_float(2.1287e14), 15, max_fixed=1000) == '212870000000000.0'
assert to_str(from_float(2.1287e15), 15, max_fixed=1000) == '2128700000000000.0'
assert to_str(from_float(2.1287e16), 15, max_fixed=1000) == '21287000000000000.0'
assert to_str(from_float(2.1287e30), 15, max_fixed=1000) == '2128700000000000000000000000000.0'
def test_tight_string_conversion():
mp.dps = 15
# In an old version, '0.5' wasn't recognized as representing
# an exact binary number and was erroneously rounded up or down
assert from_str('0.5', 10, round_floor) == fhalf
assert from_str('0.5', 10, round_ceiling) == fhalf
def test_eval_repr_invariant():
"""Test that eval(repr(x)) == x"""
random.seed(123)
for dps in [10, 15, 20, 50, 100]:
mp.dps = dps
for i in range(1000):
a = mpf(random.random())**0.5 * 10**random.randint(-100, 100)
assert eval(repr(a)) == a
mp.dps = 15
def test_str_bugs():
mp.dps = 15
# Decimal rounding used to give the wrong exponent in some cases
assert str(mpf('1e600')) == '1.0e+600'
assert str(mpf('1e10000')) == '1.0e+10000'
def test_str_prec0():
assert to_str(from_float(1.234), 0) == '.0e+0'
assert to_str(from_float(1e-15), 0) == '.0e-15'
assert to_str(from_float(1e+15), 0) == '.0e+15'
assert to_str(from_float(-1e-15), 0) == '-.0e-15'
assert to_str(from_float(-1e+15), 0) == '-.0e+15'
def test_convert_rational():
mp.dps = 15
assert from_rational(30, 5, 53, round_nearest) == (0, 3, 1, 2)
assert from_rational(-7, 4, 53, round_nearest) == (1, 7, -2, 3)
assert to_rational((0, 1, -1, 1)) == (1, 2)
def test_custom_class():
class mympf:
@property
def _mpf_(self):
return mpf(3.5)._mpf_
class mympc:
@property
def _mpc_(self):
return mpf(3.5)._mpf_, mpf(2.5)._mpf_
assert mpf(2) + mympf() == 5.5
assert mympf() + mpf(2) == 5.5
assert mpf(mympf()) == 3.5
assert mympc() + mpc(2) == mpc(5.5, 2.5)
assert mpc(2) + mympc() == mpc(5.5, 2.5)
assert mpc(mympc()) == (3.5+2.5j)
def test_conversion_methods():
class SomethingRandom:
pass
class SomethingReal:
def _mpmath_(self, prec, rounding):
return mp.make_mpf(from_str('1.3', prec, rounding))
class SomethingComplex:
def _mpmath_(self, prec, rounding):
return mp.make_mpc((from_str('1.3', prec, rounding), \
from_str('1.7', prec, rounding)))
x = mpf(3)
z = mpc(3)
a = SomethingRandom()
y = SomethingReal()
w = SomethingComplex()
for d in [15, 45]:
mp.dps = d
assert (x+y).ae(mpf('4.3'))
assert (y+x).ae(mpf('4.3'))
assert (x+w).ae(mpc('4.3', '1.7'))
assert (w+x).ae(mpc('4.3', '1.7'))
assert (z+y).ae(mpc('4.3'))
assert (y+z).ae(mpc('4.3'))
assert (z+w).ae(mpc('4.3', '1.7'))
assert (w+z).ae(mpc('4.3', '1.7'))
x-y; y-x; x-w; w-x; z-y; y-z; z-w; w-z
x*y; y*x; x*w; w*x; z*y; y*z; z*w; w*z
x/y; y/x; x/w; w/x; z/y; y/z; z/w; w/z
x**y; y**x; x**w; w**x; z**y; y**z; z**w; w**z
x==y; y==x; x==w; w==x; z==y; y==z; z==w; w==z
mp.dps = 15
assert x.__add__(a) is NotImplemented
assert x.__radd__(a) is NotImplemented
assert x.__lt__(a) is NotImplemented
assert x.__gt__(a) is NotImplemented
assert x.__le__(a) is NotImplemented
assert x.__ge__(a) is NotImplemented
assert x.__eq__(a) is NotImplemented
assert x.__ne__(a) is NotImplemented
# implementation detail
if hasattr(x, "__cmp__"):
assert x.__cmp__(a) is NotImplemented
assert x.__sub__(a) is NotImplemented
assert x.__rsub__(a) is NotImplemented
assert x.__mul__(a) is NotImplemented
assert x.__rmul__(a) is NotImplemented
assert x.__div__(a) is NotImplemented
assert x.__rdiv__(a) is NotImplemented
assert x.__mod__(a) is NotImplemented
assert x.__rmod__(a) is NotImplemented
assert x.__pow__(a) is NotImplemented
assert x.__rpow__(a) is NotImplemented
assert z.__add__(a) is NotImplemented
assert z.__radd__(a) is NotImplemented
assert z.__eq__(a) is NotImplemented
assert z.__ne__(a) is NotImplemented
assert z.__sub__(a) is NotImplemented
assert z.__rsub__(a) is NotImplemented
assert z.__mul__(a) is NotImplemented
assert z.__rmul__(a) is NotImplemented
assert z.__div__(a) is NotImplemented
assert z.__rdiv__(a) is NotImplemented
assert z.__pow__(a) is NotImplemented
assert z.__rpow__(a) is NotImplemented
def test_mpmathify():
assert mpmathify('1/2') == 0.5
assert mpmathify('(1.0+1.0j)') == mpc(1, 1)
assert mpmathify('(1.2e-10 - 3.4e5j)') == mpc('1.2e-10', '-3.4e5')
assert mpmathify('1j') == mpc(1j)
| mit |
darkryder/django | tests/template_tests/syntax_tests/test_static.py | 335 | 2614 | from django.conf import settings
from django.test import SimpleTestCase, override_settings
from django.utils.six.moves.urllib.parse import urljoin
from ..utils import setup
@override_settings(MEDIA_URL="/media/", STATIC_URL="/static/")
class StaticTagTests(SimpleTestCase):
libraries = {'static': 'django.templatetags.static'}
@setup({'static-prefixtag01': '{% load static %}{% get_static_prefix %}'})
def test_static_prefixtag01(self):
output = self.engine.render_to_string('static-prefixtag01')
self.assertEqual(output, settings.STATIC_URL)
@setup({'static-prefixtag02': '{% load static %}'
'{% get_static_prefix as static_prefix %}{{ static_prefix }}'})
def test_static_prefixtag02(self):
output = self.engine.render_to_string('static-prefixtag02')
self.assertEqual(output, settings.STATIC_URL)
@setup({'static-prefixtag03': '{% load static %}{% get_media_prefix %}'})
def test_static_prefixtag03(self):
output = self.engine.render_to_string('static-prefixtag03')
self.assertEqual(output, settings.MEDIA_URL)
@setup({'static-prefixtag04': '{% load static %}'
'{% get_media_prefix as media_prefix %}{{ media_prefix }}'})
def test_static_prefixtag04(self):
output = self.engine.render_to_string('static-prefixtag04')
self.assertEqual(output, settings.MEDIA_URL)
@setup({'static-statictag01': '{% load static %}{% static "admin/base.css" %}'})
def test_static_statictag01(self):
output = self.engine.render_to_string('static-statictag01')
self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css'))
@setup({'static-statictag02': '{% load static %}{% static base_css %}'})
def test_static_statictag02(self):
output = self.engine.render_to_string('static-statictag02', {'base_css': 'admin/base.css'})
self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css'))
@setup({'static-statictag03': '{% load static %}{% static "admin/base.css" as foo %}{{ foo }}'})
def test_static_statictag03(self):
output = self.engine.render_to_string('static-statictag03')
self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css'))
@setup({'static-statictag04': '{% load static %}{% static base_css as foo %}{{ foo }}'})
def test_static_statictag04(self):
output = self.engine.render_to_string('static-statictag04', {'base_css': 'admin/base.css'})
self.assertEqual(output, urljoin(settings.STATIC_URL, 'admin/base.css'))
| bsd-3-clause |
postmanlabs/postman-chrome-interceptor | scripts/configure.py | 2 | 1336 | # Configure Postman for testing or production
import os
import os.path, time
import string
import json
import shutil
import PIL
from optparse import OptionParser
from datetime import datetime
from jinja2 import Environment, PackageLoader, Template
def generate_config_file(web_url):
directory = os.path.dirname(os.path.realpath(__file__))
config_template = open(directory + '/../extension/config_template.js')
s = config_template.read()
config_template.close()
template = Template(s)
if web_url == "production":
app_id = 'POSTMAN_APP_ID_PRODUCTION'
elif web_url == "staging":
app_id = 'POSTMAN_APP_ID_STAGING'
elif web_url == "dev":
app_id = 'POSTMAN_APP_ID_DEV'
elif web_url == "syncstage":
app_id = 'POSTMAN_APP_ID_SYNCSTAGE'
elif web_url == "beta":
app_id = 'POSTMAN_APP_ID_BETA'
else:
app_id = 'POSTMAN_APP_ID_LOCAL'
config_file = open(directory + "/../extension/config.js", "w")
config_file.write(template.render(app_id=app_id))
config_file.close()
def main():
parser = OptionParser(usage="Usage: %prog [options] filename")
parser.add_option("-u", "--web_url", dest="web_url", help="(production/staging/dev/syncstage/beta/local)")
(options, args) = parser.parse_args()
web_url = options.web_url
generate_config_file(web_url)
if __name__ == "__main__":
main() | apache-2.0 |
2ndQuadrant/ansible | lib/ansible/executor/action_write_locks.py | 140 | 1911 | # (c) 2016 - Red Hat, Inc. <info@ansible.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/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from multiprocessing import Lock
from ansible.module_utils.facts.system.pkg_mgr import PKG_MGRS
if 'action_write_locks' not in globals():
# Do not initialize this more than once because it seems to bash
# the existing one. multiprocessing must be reloading the module
# when it forks?
action_write_locks = dict()
# Below is a Lock for use when we weren't expecting a named module. It gets used when an action
# plugin invokes a module whose name does not match with the action's name. Slightly less
# efficient as all processes with unexpected module names will wait on this lock
action_write_locks[None] = Lock()
# These plugins are known to be called directly by action plugins with names differing from the
# action plugin name. We precreate them here as an optimization.
# If a list of service managers is created in the future we can do the same for them.
mods = set(p['name'] for p in PKG_MGRS)
mods.update(('copy', 'file', 'setup', 'slurp', 'stat'))
for mod_name in mods:
action_write_locks[mod_name] = Lock()
| gpl-3.0 |
basicthinker/ThyNVM | src/arch/x86/isa/insts/general_purpose/data_transfer/xchg.py | 89 | 3288 | # Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# 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 copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Gabe Black
microcode = '''
# All the memory versions need to use LOCK, regardless of if it was set
def macroop XCHG_R_R
{
# Use the xor trick instead of moves to reduce register pressure.
# This probably doesn't make much of a difference, but it's easy.
xor reg, reg, regm
xor regm, regm, reg
xor reg, reg, regm
};
def macroop XCHG_R_M
{
mfence
ldstl t1, seg, sib, disp
stul reg, seg, sib, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_R_P
{
rdip t7
mfence
ldstl t1, seg, riprel, disp
stul reg, seg, riprel, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_M_R
{
mfence
ldstl t1, seg, sib, disp
stul reg, seg, sib, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_P_R
{
rdip t7
mfence
ldstl t1, seg, riprel, disp
stul reg, seg, riprel, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_LOCKED_M_R
{
mfence
ldstl t1, seg, sib, disp
stul reg, seg, sib, disp
mfence
mov reg, reg, t1
};
def macroop XCHG_LOCKED_P_R
{
rdip t7
mfence
ldstl t1, seg, riprel, disp
stul reg, seg, riprel, disp
mfence
mov reg, reg, t1
};
'''
| bsd-3-clause |
toofishes/django-mailer | mailer/__init__.py | 9 | 3337 | VERSION = (0, 2, 0, "a", 1) # following PEP 386
DEV_N = 1
def get_version():
version = "%s.%s" % (VERSION[0], VERSION[1])
if VERSION[2]:
version = "%s.%s" % (version, VERSION[2])
if VERSION[3] != "f":
version = "%s%s%s" % (version, VERSION[3], VERSION[4])
if DEV_N:
version = "%s.dev%s" % (version, DEV_N)
return version
__version__ = get_version()
PRIORITY_MAPPING = {
"high": "1",
"medium": "2",
"low": "3",
"deferred": "4",
}
# replacement for django.core.mail.send_mail
def send_mail(subject, message, from_email, recipient_list, priority="medium",
fail_silently=False, auth_user=None, auth_password=None):
from django.utils.encoding import force_unicode
from mailer.models import make_message
priority = PRIORITY_MAPPING[priority]
# need to do this in case subject used lazy version of ugettext
subject = force_unicode(subject)
message = force_unicode(message)
make_message(subject=subject,
body=message,
from_email=from_email,
to=recipient_list,
priority=priority).save()
return 1
def send_html_mail(subject, message, message_html, from_email, recipient_list,
priority="medium", fail_silently=False, auth_user=None,
auth_password=None):
"""
Function to queue HTML e-mails
"""
from django.utils.encoding import force_unicode
from django.core.mail import EmailMultiAlternatives
from mailer.models import make_message
priority = PRIORITY_MAPPING[priority]
# need to do this in case subject used lazy version of ugettext
subject = force_unicode(subject)
message = force_unicode(message)
msg = make_message(subject=subject,
body=message,
from_email=from_email,
to=recipient_list,
priority=priority)
email = msg.email
email = EmailMultiAlternatives(email.subject, email.body, email.from_email, email.to)
email.attach_alternative(message_html, "text/html")
msg.email = email
msg.save()
return 1
def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
auth_password=None, connection=None):
from mailer.models import make_message
num_sent = 0
for subject, message, sender, recipient in datatuple:
num_sent += send_mail(subject, message, sender, recipient)
return num_sent
def mail_admins(subject, message, fail_silently=False, connection=None, priority="medium"):
from django.conf import settings
from django.utils.encoding import force_unicode
return send_mail(settings.EMAIL_SUBJECT_PREFIX + force_unicode(subject),
message,
settings.SERVER_EMAIL,
[a[1] for a in settings.ADMINS])
def mail_managers(subject, message, fail_silently=False, connection=None, priority="medium"):
from django.conf import settings
from django.utils.encoding import force_unicode
return send_mail(settings.EMAIL_SUBJECT_PREFIX + force_unicode(subject),
message,
settings.SERVER_EMAIL,
[a[1] for a in settings.MANAGERS])
| mit |
mchristopher/PokemonGo-DesktopMap | app/pylibs/win32/Cryptodome/SelfTest/Util/test_Padding.py | 2 | 5793 | #
# SelfTest/Util/test_Padding.py: Self-test for padding functions
#
# ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# 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.
#
# 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.
# ===================================================================
import unittest
from binascii import unhexlify as uh
from Cryptodome.Util.py3compat import *
from Cryptodome.SelfTest.st_common import list_test_cases
from Cryptodome.Util.Padding import pad, unpad
class PKCS7_Tests(unittest.TestCase):
def test1(self):
padded = pad(b(""), 4)
self.failUnless(padded == uh(b("04040404")))
padded = pad(b(""), 4, 'pkcs7')
self.failUnless(padded == uh(b("04040404")))
back = unpad(padded, 4)
self.failUnless(back == b(""))
def test2(self):
padded = pad(uh(b("12345678")), 4)
self.failUnless(padded == uh(b("1234567804040404")))
back = unpad(padded, 4)
self.failUnless(back == uh(b("12345678")))
def test3(self):
padded = pad(uh(b("123456")), 4)
self.failUnless(padded == uh(b("12345601")))
back = unpad(padded, 4)
self.failUnless(back == uh(b("123456")))
def test4(self):
padded = pad(uh(b("1234567890")), 4)
self.failUnless(padded == uh(b("1234567890030303")))
back = unpad(padded, 4)
self.failUnless(back == uh(b("1234567890")))
def testn1(self):
self.assertRaises(ValueError, pad, uh(b("12")), 4, 'pkcs8')
def testn2(self):
self.assertRaises(ValueError, unpad, b("\0\0\0"), 4)
def testn3(self):
self.assertRaises(ValueError, unpad, b("123456\x02"), 4)
self.assertRaises(ValueError, unpad, b("123456\x00"), 4)
self.assertRaises(ValueError, unpad, b("123456\x05\x05\x05\x05\x05"), 4)
class X923_Tests(unittest.TestCase):
def test1(self):
padded = pad(b(""), 4, 'x923')
self.failUnless(padded == uh(b("00000004")))
back = unpad(padded, 4, 'x923')
self.failUnless(back == b(""))
def test2(self):
padded = pad(uh(b("12345678")), 4, 'x923')
self.failUnless(padded == uh(b("1234567800000004")))
back = unpad(padded, 4, 'x923')
self.failUnless(back == uh(b("12345678")))
def test3(self):
padded = pad(uh(b("123456")), 4, 'x923')
self.failUnless(padded == uh(b("12345601")))
back = unpad(padded, 4, 'x923')
self.failUnless(back == uh(b("123456")))
def test4(self):
padded = pad(uh(b("1234567890")), 4, 'x923')
self.failUnless(padded == uh(b("1234567890000003")))
back = unpad(padded, 4, 'x923')
self.failUnless(back == uh(b("1234567890")))
def testn1(self):
self.assertRaises(ValueError, unpad, b("123456\x02"), 4, 'x923')
self.assertRaises(ValueError, unpad, b("123456\x00"), 4, 'x923')
self.assertRaises(ValueError, unpad, b("123456\x00\x00\x00\x00\x05"), 4, 'x923')
class ISO7816_Tests(unittest.TestCase):
def test1(self):
padded = pad(b(""), 4, 'iso7816')
self.failUnless(padded == uh(b("80000000")))
back = unpad(padded, 4, 'iso7816')
self.failUnless(back == b(""))
def test2(self):
padded = pad(uh(b("12345678")), 4, 'iso7816')
self.failUnless(padded == uh(b("1234567880000000")))
back = unpad(padded, 4, 'iso7816')
self.failUnless(back == uh(b("12345678")))
def test3(self):
padded = pad(uh(b("123456")), 4, 'iso7816')
self.failUnless(padded == uh(b("12345680")))
#import pdb; pdb.set_trace()
back = unpad(padded, 4, 'iso7816')
self.failUnless(back == uh(b("123456")))
def test4(self):
padded = pad(uh(b("1234567890")), 4, 'iso7816')
self.failUnless(padded == uh(b("1234567890800000")))
back = unpad(padded, 4, 'iso7816')
self.failUnless(back == uh(b("1234567890")))
def testn1(self):
self.assertRaises(ValueError, unpad, b("123456\x81"), 4, 'iso7816')
def get_tests(config={}):
tests = []
tests += list_test_cases(PKCS7_Tests)
tests += list_test_cases(X923_Tests)
tests += list_test_cases(ISO7816_Tests)
return tests
if __name__ == '__main__':
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
| mit |
jraede/dd-agent | dogstream/cassandra.py | 34 | 2560 | from datetime import datetime
import re
from dogstream import common
LOG4J_PRIORITY = [
"TRACE",
"DEBUG",
"INFO",
"WARN",
"ERROR",
"FATAL",
]
ALERT_TYPES = {
"FATAL": "error",
"ERROR": "error",
"WARN": "warning",
"INFO": "info",
"DEBUG": "info",
"TRACE": "info",
}
EVENT_TYPE = "cassandra.compaction"
THREADS = [
"CompactionExecutor",
]
DATE_FORMAT = '%Y-%m-%d %H:%M:%S,%f'
LEGACY_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
# Parse Cassandra default system.log log4j pattern: %5p [%t] %d{ISO8601} %F (line %L) %m%n
LOG_PATTERN = re.compile(r"".join([
r"\s*(?P<priority>%s)\s+" % "|".join("(%s)" % p for p in LOG4J_PRIORITY),
r"(\[CompactionExecutor:\d*\]\s+)?", # optional thread name and number
r"((?P<timestamp>\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2},\d*)|",
r"(?P<time>\d{2}:\d{2}:\d{2},\d*))\s+",
r"(\w+\.java \(line \d+\)\s+)?", # optional source file and line
r"(?P<msg>Compact(ed|ing) .*)\s*",
]))
def parse_date(timestamp):
try:
return common.parse_date(timestamp, DATE_FORMAT)
except ValueError:
# Only Python >= 2.6 supports %f in the date string
timestamp, _ = timestamp.split(',')
return common.parse_date(timestamp, LEGACY_DATE_FORMAT)
def parse_cassandra(log, line):
matched = LOG_PATTERN.match(line)
if matched:
event = matched.groupdict()
# Convert the timestamp string into an epoch timestamp
time_val = event.get('time', None)
if time_val:
event['timestamp'] = parse_date("%s %s" % (datetime.utcnow().strftime("%Y-%m-%d"), time_val))
else:
try:
event['timestamp'] = parse_date(event['timestamp'])
except ValueError:
# only python >= 2.6 supports %f in strptime
event
del event['time']
# Process the log priority
event['alert_type'] = ALERT_TYPES.get(event['priority'], "info")
if event['alert_type'] in ('error', 'warning'):
event['auto_priority'] = 1
else:
event['auto_priority'] = 0
del event['priority']
# Process the aggregation metadata
event['event_type'] = EVENT_TYPE
# Process the message
msg = event['msg']
if len(msg) > common.MAX_TITLE_LEN:
event['msg_title'] = msg[0:common.MAX_TITLE_LEN]
event['msg_text'] = msg
else:
event['msg_title'] = msg
del event['msg']
return [event]
else:
return None
| bsd-3-clause |
securestate/king-phisher | tests/server/server_rpc.py | 4 | 8736 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/server/server_rpc.py
#
# 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 project 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.
#
import types
import unittest
from king_phisher import errors
from king_phisher import startup
from king_phisher import version
from king_phisher.server import server_rpc
from king_phisher.testing import KingPhisherServerTestCase
from king_phisher.utilities import random_string
import advancedhttpserver
_certbot_bin_path = startup.which('certbot')
class ServerRPCTests(KingPhisherServerTestCase):
def test_rpc_config_get(self):
server_addresses = self.rpc('config/get', 'server.addresses')
self.assertIsInstance(server_addresses, list)
self.assertIsNotEmpty(server_addresses)
self.assertEqual(server_addresses, self.config.get('server.addresses'))
config_results = self.rpc('config/get', ['server.require_id', 'server.web_root'])
self.assertIsInstance(config_results, dict)
self.assertIn('server.require_id', config_results)
self.assertEqual(config_results['server.require_id'], self.config.get('server.require_id'))
self.assertIn('server.web_root', config_results)
self.assertEqual(config_results['server.web_root'], self.config.get('server.web_root'))
def test_rpc_config_get_permissions(self):
self.assertTrue(self.config.has_option('server.database'))
self.assertRPCPermissionDenied('config/get', 'server.database')
def test_rpc_campaign_delete(self):
campaign_name = random_string(10)
campaign_id = self.rpc('campaign/new', campaign_name)
self.rpc('db/table/delete', 'campaigns', campaign_id)
def test_rpc_campaign_new(self):
campaign_name = random_string(10)
campaign_id = self.rpc('campaign/new', campaign_name)
self.assertIsInstance(campaign_id, int)
campaigns = self.rpc.remote_table('campaigns')
self.assertIsInstance(campaigns, types.GeneratorType)
campaigns = list(campaigns)
self.assertEqual(len(campaigns), 1)
campaign = campaigns[0]
self.assertEqual(campaign.id, campaign_id)
self.assertEqual(campaign.name, campaign_name)
def test_rpc_config_set(self):
config_key = server_rpc.CONFIG_WRITEABLE[0]
config_value = random_string(10)
self.rpc('config/set', {config_key: config_value})
self.assertEqual(self.rpc('config/get', config_key), config_value)
def test_rpc_config_set_permissions(self):
config_key = random_string(10)
config_value = random_string(10)
self.assertRPCPermissionDenied('config/set', {config_key: config_value})
def test_rpc_graphql(self):
response = self.rpc('graphql', '{ version }')
self.assertIn('data', response)
self.assertIn('errors', response)
self.assertIsNotNone(response['data'])
self.assertIsNone(response['errors'])
response = response['data'].get('version')
self.assertEquals(response, version.version)
def test_rpc_graphql_rpc_errors(self):
bad_query = '{ foobar }'
with self.assertRaises(errors.KingPhisherGraphQLQueryError) as context:
self.rpc.graphql(bad_query)
error = context.exception
self.assertIsInstance(error.errors, list)
self.assertIsNotEmpty(error.errors)
self.assertIsInstance(error.query, str)
self.assertEqual(error.query, bad_query)
def test_rpc_graphql_raw_errors(self):
response = self.rpc('graphql', '{ foobar }')
self.assertIn('data', response)
self.assertIn('errors', response)
self.assertIsNone(response['data'])
self.assertIsNotNone(response['errors'])
self.assertIsNotEmpty(response['errors'])
for error in response['errors']:
self.assertIsInstance(error, str)
def test_rpc_hostnames_get(self):
hostnames = self.rpc('hostnames/get')
self.assertIsInstance(hostnames, list)
def test_rpc_hostnames_add(self):
new_hostname = random_string(16) + '.local'
self.rpc('hostnames/add', new_hostname)
hostnames = self.rpc('hostnames/get')
self.assertIsInstance(hostnames, list)
self.assertIn(new_hostname, hostnames)
def test_rpc_is_unauthorized(self):
http_response = self.http_request('/ping', method='RPC')
self.assertHTTPStatus(http_response, 401)
@unittest.skipUnless(_certbot_bin_path, 'due to certbot being unavailable')
def test_rpc_ssl_letsencrypt_certbot_version(self):
version = self.rpc('ssl/letsencrypt/certbot_version')
self.assertIsNotNone(version, 'the certbot version was not retrieved')
self.assertRegexpMatches(version, r'(\d.)*\d', 'the certbot version is invalid')
def test_rpc_ssl_sni_hostnames_get(self):
sni_hostnames = self.rpc('ssl/sni_hostnames/get')
self.assertIsInstance(sni_hostnames, dict)
def test_rpc_ssl_sni_hostnames_load(self):
fake_hostname = random_string(16)
self.assertFalse(self.rpc('ssl/sni_hostnames/load', fake_hostname))
def test_rpc_ssl_sni_hostnames_unload(self):
fake_hostname = random_string(16)
self.assertFalse(self.rpc('ssl/sni_hostnames/unload', fake_hostname))
def test_rpc_ssl_status(self):
ssl_status = self.rpc('ssl/status')
self.assertIsInstance(ssl_status, dict)
self.assertIn('enabled', ssl_status)
self.assertIn('has-sni', ssl_status)
self.assertEqual(ssl_status['has-sni'], advancedhttpserver.g_ssl_has_server_sni)
def test_rpc_ping(self):
self.assertTrue(self.rpc('ping'))
def test_rpc_remote_table(self):
self.test_rpc_campaign_new()
campaign = list(self.rpc.remote_table('campaigns'))[0]
campaign = campaign._asdict()
self.assertIsInstance(campaign, dict)
meta_table = self.server.tables_api['campaigns']
self.assertEqual(sorted(campaign.keys()), sorted(meta_table.column_names))
def test_rpc_shutdown(self):
self.assertIsNone(self.rpc('shutdown'))
self.shutdown_requested = True
def test_rpc_table_count(self):
self.assertEqual(self.rpc('db/table/count', 'campaigns'), 0)
self.assertEqual(self.rpc('db/table/count', 'messages'), 0)
self.assertEqual(self.rpc('db/table/count', 'visits'), 0)
self.test_rpc_campaign_new()
self.assertEqual(self.rpc('db/table/count', 'campaigns'), 1)
def test_rpc_table_view(self):
self.test_rpc_campaign_new()
campaign = self.rpc('db/table/view', 'campaigns')
self.assertTrue(bool(campaign))
self.assertEqual(len(campaign['rows']), 1)
meta_table = self.server.tables_api['campaigns']
self.assertEqual(len(campaign['rows'][0]), len(meta_table.column_names))
self.assertEqual(sorted(campaign['columns']), sorted(meta_table.column_names))
def test_rpc_set_value(self):
campaign_name = random_string(10)
new_campaign_name = random_string(10)
campaign_id = self.rpc('campaign/new', campaign_name)
campaign = self.rpc.remote_table_row('campaigns', campaign_id)
self.assertEqual(campaign.id, campaign_id)
self.assertEqual(campaign.name, campaign_name)
self.rpc('db/table/set', 'campaigns', campaign_id, 'name', new_campaign_name)
campaign = self.rpc.remote_table_row('campaigns', campaign_id)
self.assertEqual(campaign.name, new_campaign_name)
def test_rpc_version(self):
response = self.rpc('version')
self.assertIn('version', response)
self.assertIn('version_info', response)
self.assertEqual(response['version'], version.version)
self.assertEqual(response['version_info']['major'], version.version_info.major)
self.assertEqual(response['version_info']['minor'], version.version_info.minor)
self.assertEqual(response['version_info']['micro'], version.version_info.micro)
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
aristotle-tek/cuny-bdif | AWS/ec2/lib/boto-2.34.0/tests/unit/glacier/test_concurrent.py | 88 | 7261 | #!/usr/bin/env python
# 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.
#
import tempfile
from boto.compat import Queue
from tests.compat import mock, unittest
from tests.unit import AWSMockServiceTestCase
from boto.glacier.concurrent import ConcurrentUploader, ConcurrentDownloader
from boto.glacier.concurrent import UploadWorkerThread
from boto.glacier.concurrent import _END_SENTINEL
class FakeThreadedConcurrentUploader(ConcurrentUploader):
def _start_upload_threads(self, results_queue, upload_id,
worker_queue, filename):
self.results_queue = results_queue
self.worker_queue = worker_queue
self.upload_id = upload_id
def _wait_for_upload_threads(self, hash_chunks, result_queue, total_parts):
for i in range(total_parts):
hash_chunks[i] = b'foo'
class FakeThreadedConcurrentDownloader(ConcurrentDownloader):
def _start_download_threads(self, results_queue, worker_queue):
self.results_queue = results_queue
self.worker_queue = worker_queue
def _wait_for_download_threads(self, filename, result_queue, total_parts):
pass
class TestConcurrentUploader(unittest.TestCase):
def setUp(self):
super(TestConcurrentUploader, self).setUp()
self.stat_patch = mock.patch('os.stat')
self.addCleanup(self.stat_patch.stop)
self.stat_mock = self.stat_patch.start()
# Give a default value for tests that don't care
# what the file size is.
self.stat_mock.return_value.st_size = 1024 * 1024 * 8
def test_calculate_required_part_size(self):
self.stat_mock.return_value.st_size = 1024 * 1024 * 8
uploader = ConcurrentUploader(mock.Mock(), 'vault_name')
total_parts, part_size = uploader._calculate_required_part_size(
1024 * 1024 * 8)
self.assertEqual(total_parts, 2)
self.assertEqual(part_size, 4 * 1024 * 1024)
def test_calculate_required_part_size_too_small(self):
too_small = 1 * 1024 * 1024
self.stat_mock.return_value.st_size = 1024 * 1024 * 1024
uploader = ConcurrentUploader(mock.Mock(), 'vault_name',
part_size=too_small)
total_parts, part_size = uploader._calculate_required_part_size(
1024 * 1024 * 1024)
self.assertEqual(total_parts, 256)
# Part size if 4MB not the passed in 1MB.
self.assertEqual(part_size, 4 * 1024 * 1024)
def test_work_queue_is_correctly_populated(self):
uploader = FakeThreadedConcurrentUploader(mock.MagicMock(),
'vault_name')
uploader.upload('foofile')
q = uploader.worker_queue
items = [q.get() for i in range(q.qsize())]
self.assertEqual(items[0], (0, 4 * 1024 * 1024))
self.assertEqual(items[1], (1, 4 * 1024 * 1024))
# 2 for the parts, 10 for the end sentinels (10 threads).
self.assertEqual(len(items), 12)
def test_correct_low_level_api_calls(self):
api_mock = mock.MagicMock()
uploader = FakeThreadedConcurrentUploader(api_mock, 'vault_name')
uploader.upload('foofile')
# The threads call the upload_part, so we're just verifying the
# initiate/complete multipart API calls.
api_mock.initiate_multipart_upload.assert_called_with(
'vault_name', 4 * 1024 * 1024, None)
api_mock.complete_multipart_upload.assert_called_with(
'vault_name', mock.ANY, mock.ANY, 8 * 1024 * 1024)
def test_downloader_work_queue_is_correctly_populated(self):
job = mock.MagicMock()
job.archive_size = 8 * 1024 * 1024
downloader = FakeThreadedConcurrentDownloader(job)
downloader.download('foofile')
q = downloader.worker_queue
items = [q.get() for i in range(q.qsize())]
self.assertEqual(items[0], (0, 4 * 1024 * 1024))
self.assertEqual(items[1], (1, 4 * 1024 * 1024))
# 2 for the parts, 10 for the end sentinels (10 threads).
self.assertEqual(len(items), 12)
class TestUploaderThread(unittest.TestCase):
def setUp(self):
self.fileobj = tempfile.NamedTemporaryFile()
self.filename = self.fileobj.name
def test_fileobj_closed_when_thread_shuts_down(self):
thread = UploadWorkerThread(mock.Mock(), 'vault_name',
self.filename, 'upload_id',
Queue(), Queue())
fileobj = thread._fileobj
self.assertFalse(fileobj.closed)
# By settings should_continue to False, it should immediately
# exit, and we can still verify cleanup behavior.
thread.should_continue = False
thread.run()
self.assertTrue(fileobj.closed)
def test_upload_errors_have_exception_messages(self):
api = mock.Mock()
job_queue = Queue()
result_queue = Queue()
upload_thread = UploadWorkerThread(
api, 'vault_name', self.filename,
'upload_id', job_queue, result_queue, num_retries=1,
time_between_retries=0)
api.upload_part.side_effect = Exception("exception message")
job_queue.put((0, 1024))
job_queue.put(_END_SENTINEL)
upload_thread.run()
result = result_queue.get(timeout=1)
self.assertIn("exception message", str(result))
def test_num_retries_is_obeyed(self):
# total attempts is 1 + num_retries so if I have num_retries of 2,
# I'll attempt the upload once, and if that fails I'll retry up to
# 2 more times for a total of 3 attempts.
api = mock.Mock()
job_queue = Queue()
result_queue = Queue()
upload_thread = UploadWorkerThread(
api, 'vault_name', self.filename,
'upload_id', job_queue, result_queue, num_retries=2,
time_between_retries=0)
api.upload_part.side_effect = Exception()
job_queue.put((0, 1024))
job_queue.put(_END_SENTINEL)
upload_thread.run()
self.assertEqual(api.upload_part.call_count, 3)
if __name__ == '__main__':
unittest.main()
| mit |
jjz/v2ex | money.py | 16 | 1441 | #!/usr/bin/env python
# coding=utf-8
import os
import re
import time
import datetime
import hashlib
import string
import random
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.ext import db
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
from google.appengine.api.labs import taskqueue
from v2ex.babel import Member
from v2ex.babel import Counter
from v2ex.babel import Section
from v2ex.babel import Node
from v2ex.babel import Topic
from v2ex.babel import Reply
from v2ex.babel import Note
from v2ex.babel import Notification
from v2ex.babel import SYSTEM_VERSION
from v2ex.babel.security import *
from v2ex.babel.ua import *
from v2ex.babel.da import *
from v2ex.babel.l10n import *
from v2ex.babel.ext.cookies import Cookies
from v2ex.babel.handlers import BaseHandler
import config
template.register_template_library('v2ex.templatetags.filters')
class MoneyDashboardHandler(BaseHandler):
def get(self):
if self.member:
self.set_title(u'账户查询')
self.finalize(template_name='money_dashboard')
else:
self.redirect('/signin')
def main():
application = webapp.WSGIApplication([
('/money/dashboard/?', MoneyDashboardHandler)
],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main() | bsd-3-clause |
mind1master/aiohttp | tests/test_parser_buffer.py | 1 | 5653 | from unittest import mock
import pytest
from aiohttp import errors, parsers
@pytest.fixture
def stream():
return mock.Mock()
@pytest.fixture
def buf():
return parsers.ParserBuffer()
def test_feed_data(buf):
buf.feed_data(b'')
assert len(buf) == 0
buf.feed_data(b'data')
assert len(buf) == 4
assert bytes(buf), b'data'
def test_feed_data_after_exception(buf):
buf.feed_data(b'data')
exc = ValueError()
buf.set_exception(exc)
buf.feed_data(b'more')
assert len(buf) == 4
assert bytes(buf) == b'data'
def test_read_exc(buf):
p = buf.read(3)
next(p)
p.send(b'1')
exc = ValueError()
buf.set_exception(exc)
assert buf.exception() is exc
with pytest.raises(ValueError):
p.send(b'1')
def test_read_exc_multiple(buf):
p = buf.read(3)
next(p)
p.send(b'1')
exc = ValueError()
buf.set_exception(exc)
assert buf.exception() is exc
p = buf.read(3)
with pytest.raises(ValueError):
next(p)
def test_read(buf):
p = buf.read(3)
next(p)
p.send(b'1')
try:
p.send(b'234')
except StopIteration as exc:
res = exc.value
assert res == b'123'
assert b'4' == bytes(buf)
def test_readsome(buf):
p = buf.readsome(3)
next(p)
try:
p.send(b'1')
except StopIteration as exc:
res = exc.value
assert res == b'1'
p = buf.readsome(2)
next(p)
try:
p.send(b'234')
except StopIteration as exc:
res = exc.value
assert res == b'23'
assert b'4' == bytes(buf)
def test_readsome_exc(buf):
buf.set_exception(ValueError())
p = buf.readsome(3)
with pytest.raises(ValueError):
next(p)
def test_wait(buf):
p = buf.wait(3)
next(p)
p.send(b'1')
try:
p.send(b'234')
except StopIteration as exc:
res = exc.value
assert res == b'123'
assert b'1234' == bytes(buf)
def test_wait_exc(buf):
buf.set_exception(ValueError())
p = buf.wait(3)
with pytest.raises(ValueError):
next(p)
def test_skip(buf):
p = buf.skip(3)
next(p)
p.send(b'1')
try:
p.send(b'234')
except StopIteration as exc:
res = exc.value
assert res is None
assert b'4' == bytes(buf)
def test_skip_exc(buf):
buf.set_exception(ValueError())
p = buf.skip(3)
with pytest.raises(ValueError):
next(p)
def test_readuntil_limit(buf):
p = buf.readuntil(b'\n', 4)
next(p)
p.send(b'1')
p.send(b'234')
with pytest.raises(errors.LineLimitExceededParserError):
p.send(b'5')
def test_readuntil_limit2(buf):
p = buf.readuntil(b'\n', 4)
next(p)
with pytest.raises(errors.LineLimitExceededParserError):
p.send(b'12345\n6')
def test_readuntil_limit3(buf):
p = buf.readuntil(b'\n', 4)
next(p)
with pytest.raises(errors.LineLimitExceededParserError):
p.send(b'12345\n6')
def test_readuntil(buf):
p = buf.readuntil(b'\n', 4)
next(p)
p.send(b'123')
try:
p.send(b'\n456')
except StopIteration as exc:
res = exc.value
assert res == b'123\n'
assert b'456' == bytes(buf)
def test_readuntil_exc(buf):
buf.set_exception(ValueError())
p = buf.readuntil(b'\n', 4)
with pytest.raises(ValueError):
next(p)
def test_waituntil_limit(buf):
p = buf.waituntil(b'\n', 4)
next(p)
p.send(b'1')
p.send(b'234')
with pytest.raises(errors.LineLimitExceededParserError):
p.send(b'5')
def test_waituntil_limit2(buf):
p = buf.waituntil(b'\n', 4)
next(p)
with pytest.raises(errors.LineLimitExceededParserError):
p.send(b'12345\n6')
def test_waituntil_limit3(buf):
p = buf.waituntil(b'\n', 4)
next(p)
with pytest.raises(errors.LineLimitExceededParserError):
p.send(b'12345\n6')
def test_waituntil(buf):
p = buf.waituntil(b'\n', 4)
next(p)
p.send(b'123')
try:
p.send(b'\n456')
except StopIteration as exc:
res = exc.value
assert res == b'123\n'
assert b'123\n456' == bytes(buf)
def test_waituntil_exc(buf):
buf.set_exception(ValueError())
p = buf.waituntil(b'\n', 4)
with pytest.raises(ValueError):
next(p)
def test_skipuntil(buf):
p = buf.skipuntil(b'\n')
next(p)
p.send(b'123')
try:
p.send(b'\n456\n')
except StopIteration:
pass
assert b'456\n' == bytes(buf)
p = buf.skipuntil(b'\n')
try:
next(p)
except StopIteration:
pass
assert b'' == bytes(buf)
def test_skipuntil_exc(buf):
buf.set_exception(ValueError())
p = buf.skipuntil(b'\n')
with pytest.raises(ValueError):
next(p)
def test_lines_parser(buf, stream, loop):
out = parsers.FlowControlDataQueue(stream, loop=loop)
p = parsers.LinesParser()(out, buf)
next(p)
for d in (b'line1', b'\r\n', b'lin', b'e2\r', b'\ndata'):
p.send(d)
assert ([(bytearray(b'line1\r\n'), 7), (bytearray(b'line2\r\n'), 7)] ==
list(out._buffer))
try:
p.throw(parsers.EofStream())
except StopIteration:
pass
assert bytes(buf) == b'data'
def test_chunks_parser(stream, loop, buf):
out = parsers.FlowControlDataQueue(stream, loop=loop)
p = parsers.ChunksParser(5)(out, buf)
next(p)
for d in (b'line1', b'lin', b'e2d', b'ata'):
p.send(d)
assert ([(bytearray(b'line1'), 5), (bytearray(b'line2'), 5)] ==
list(out._buffer))
try:
p.throw(parsers.EofStream())
except StopIteration:
pass
assert bytes(buf) == b'data'
| apache-2.0 |
ron-rivest/split-value-voting | sv_tally.py | 2 | 2673 | # sv_tally.py
# python3
# Ronald L. Rivest
# 2014-06-23
""" Code for tally portion of simulated split-value election.
"""
# MIT open-source license.
# (See https://github.com/ron-rivest/split-value-voting.git)
import sys
import sv
def compute_tally(election):
""" Compute tallies for this election.
Data is from last column of mix servers.
"""
server = election.server
cols = server.cols
election.tally = dict()
for race in election.races:
race_id = race.race_id
for k in election.k_list:
choice_int_list = []
for p in election.p_list:
share_list = \
[(row+1, server.sdb[race_id][i][cols-1][k]['y'][p]) \
for row, i in enumerate(election.server.row_list)]
choice_int = sv.lagrange(share_list, server.rows,\
server.threshold, race.race_modulus)
choice_int_list.append(choice_int)
choice_str_list = [race.choice_int2str(choice_int)
for choice_int in choice_int_list]
choice_str_list = sorted(choice_str_list)
if k == election.k_list[0]:
last_choice_str_list = choice_str_list
else:
assert choice_str_list == last_choice_str_list
# now compute tally for this race
tally = dict()
for choice_str in race.choices:
if not all([c == '*' for c in choice_str]):
tally[choice_str] = 0
for choice_str in choice_str_list:
tally[choice_str] = tally.get(choice_str, 0) + 1
# save it
race.tally = tally
election.tally[race_id] = tally
def print_tally(election, f_out=sys.stdout):
""" Print tallies computed for this election to file f_out.
Uses results compiled by compute_tally, and saved in race.tally fields.
"""
print()
print("election results:", file=f_out)
for race in election.races:
print(" race: ", race.race_id, file=f_out)
tally_list = [(count, choice_str) \
for choice_str, count in list(race.tally.items())]
tally_list = sorted(tally_list)
tally_list.reverse() # put winners first!
for count, choice_str in tally_list:
print(" ", "%7d"%count, " ", choice_str, file=f_out)
print("end of election results.", file=f_out)
print()
def post_tally(election):
""" Save tallies to sbb. """
election.sbb.post("tally:results",
{"election_id": election.election_id,
"tally": election.tally})
| mit |
ryuunosukeyoshi/PartnerPoi-Bot | lib/youtube_dl/extractor/urplay.py | 50 | 2304 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class URPlayIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ur(?:play|skola)\.se/(?:program|Produkter)/(?P<id>[0-9]+)'
_TESTS = [{
'url': 'http://urplay.se/program/190031-tripp-trapp-trad-sovkudde',
'md5': 'ad5f0de86f16ca4c8062cd103959a9eb',
'info_dict': {
'id': '190031',
'ext': 'mp4',
'title': 'Tripp, Trapp, Träd : Sovkudde',
'description': 'md5:b86bffdae04a7e9379d1d7e5947df1d1',
},
}, {
'url': 'http://urskola.se/Produkter/155794-Smasagor-meankieli-Grodan-i-vida-varlden',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
urplayer_data = self._parse_json(self._search_regex(
r'urPlayer\.init\(({.+?})\);', webpage, 'urplayer data'), video_id)
host = self._download_json('http://streaming-loadbalancer.ur.se/loadbalancer.json', video_id)['redirect']
formats = []
for quality_attr, quality, preference in (('', 'sd', 0), ('_hd', 'hd', 1)):
file_http = urplayer_data.get('file_http' + quality_attr) or urplayer_data.get('file_http_sub' + quality_attr)
if file_http:
formats.extend(self._extract_wowza_formats(
'http://%s/%splaylist.m3u8' % (host, file_http), video_id, skip_protocols=['rtmp', 'rtsp']))
self._sort_formats(formats)
subtitles = {}
for subtitle in urplayer_data.get('subtitles', []):
subtitle_url = subtitle.get('file')
kind = subtitle.get('kind')
if not subtitle_url or (kind and kind != 'captions'):
continue
subtitles.setdefault(subtitle.get('label', 'Svenska'), []).append({
'url': subtitle_url,
})
return {
'id': video_id,
'title': urplayer_data['title'],
'description': self._og_search_description(webpage),
'thumbnail': urplayer_data.get('image'),
'series': urplayer_data.get('series_title'),
'subtitles': subtitles,
'formats': formats,
}
| gpl-3.0 |
bodi000/odoo | addons/l10n_hn/__openerp__.py | 87 | 2258 | # -*- encoding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2009-2010 Salvatore J. Trimarchi <salvatore@trimarchi.co.cc>
# (http://salvatoreweb.co.cc)
#
# 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/>.
#
##############################################################################
#
# This module provides a minimal Honduran chart of accounts that can be use
# to build upon a more complex one. It also includes a chart of taxes and
# the Lempira currency.
#
# This module is based on the Guatemalan chart of accounts:
# Copyright (c) 2009-2010 Soluciones Tecnologócias Prisma S.A. All Rights Reserved.
# José Rodrigo Fernández Menegazzo, Soluciones Tecnologócias Prisma S.A.
# (http://www.solucionesprisma.com)
#
# This module works with OpenERP 6.0
#
{
'name': 'Honduras - Accounting',
'version': '0.1',
'category': 'Localization/Account Charts',
'description': """
This is the base module to manage the accounting chart for Honduras.
====================================================================
Agrega una nomenclatura contable para Honduras. También incluye impuestos y la
moneda Lempira. -- Adds accounting chart for Honduras. It also includes taxes
and the Lempira currency.""",
'author': 'Salvatore Josue Trimarchi Pinto',
'website': 'http://trimarchi.co.cc',
'depends': ['base', 'account', 'account_chart'],
'data': [
'account_types.xml',
'account_chart.xml',
'account_tax.xml',
'l10n_hn_base.xml',
],
'demo': [],
'installable': True,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
dongguangming/python-for-android | src/buildlib/jinja2.egg/jinja2/meta.py | 659 | 4190 | # -*- coding: utf-8 -*-
"""
jinja2.meta
~~~~~~~~~~~
This module implements various functions that exposes information about
templates that might be interesting for various kinds of applications.
:copyright: (c) 2010 by the Jinja Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from jinja2 import nodes
from jinja2.compiler import CodeGenerator
from jinja2._compat import string_types
class TrackingCodeGenerator(CodeGenerator):
"""We abuse the code generator for introspection."""
def __init__(self, environment):
CodeGenerator.__init__(self, environment, '<introspection>',
'<introspection>')
self.undeclared_identifiers = set()
def write(self, x):
"""Don't write."""
def pull_locals(self, frame):
"""Remember all undeclared identifiers."""
self.undeclared_identifiers.update(frame.identifiers.undeclared)
def find_undeclared_variables(ast):
"""Returns a set of all variables in the AST that will be looked up from
the context at runtime. Because at compile time it's not known which
variables will be used depending on the path the execution takes at
runtime, all variables are returned.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
>>> meta.find_undeclared_variables(ast)
set(['bar'])
.. admonition:: Implementation
Internally the code generator is used for finding undeclared variables.
This is good to know because the code generator might raise a
:exc:`TemplateAssertionError` during compilation and as a matter of
fact this function can currently raise that exception as well.
"""
codegen = TrackingCodeGenerator(ast.environment)
codegen.visit(ast)
return codegen.undeclared_identifiers
def find_referenced_templates(ast):
"""Finds all the referenced templates from the AST. This will return an
iterator over all the hardcoded template extensions, inclusions and
imports. If dynamic inheritance or inclusion is used, `None` will be
yielded.
>>> from jinja2 import Environment, meta
>>> env = Environment()
>>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')
>>> list(meta.find_referenced_templates(ast))
['layout.html', None]
This function is useful for dependency tracking. For example if you want
to rebuild parts of the website after a layout template has changed.
"""
for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,
nodes.Include)):
if not isinstance(node.template, nodes.Const):
# a tuple with some non consts in there
if isinstance(node.template, (nodes.Tuple, nodes.List)):
for template_name in node.template.items:
# something const, only yield the strings and ignore
# non-string consts that really just make no sense
if isinstance(template_name, nodes.Const):
if isinstance(template_name.value, string_types):
yield template_name.value
# something dynamic in there
else:
yield None
# something dynamic we don't know about here
else:
yield None
continue
# constant is a basestring, direct template name
if isinstance(node.template.value, string_types):
yield node.template.value
# a tuple or list (latter *should* not happen) made of consts,
# yield the consts that are strings. We could warn here for
# non string values
elif isinstance(node, nodes.Include) and \
isinstance(node.template.value, (tuple, list)):
for template_name in node.template.value:
if isinstance(template_name, string_types):
yield template_name
# something else we don't care about, we could warn here
else:
yield None
| mit |
franky88/emperioanimesta | env/Lib/encodings/latin_1.py | 853 | 1264 | """ Python 'latin-1' Codec
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import codecs
### Codec APIs
class Codec(codecs.Codec):
# Note: Binding these as C functions will result in the class not
# converting them to methods. This is intended.
encode = codecs.latin_1_encode
decode = codecs.latin_1_decode
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.latin_1_encode(input,self.errors)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.latin_1_decode(input,self.errors)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
class StreamConverter(StreamWriter,StreamReader):
encode = codecs.latin_1_decode
decode = codecs.latin_1_encode
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='iso8859-1',
encode=Codec.encode,
decode=Codec.decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
| gpl-3.0 |
techdragon/django | tests/basic/tests.py | 16 | 29769 | from __future__ import unicode_literals
import threading
from datetime import datetime, timedelta
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
from django.db import DEFAULT_DB_ALIAS, DatabaseError, connections
from django.db.models.fields import Field
from django.db.models.manager import BaseManager
from django.db.models.query import EmptyQuerySet, QuerySet
from django.test import (
SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature,
skipUnlessDBFeature,
)
from django.utils.translation import ugettext_lazy
from .models import Article, ArticleSelectOnSave, SelfRef
class ModelInstanceCreationTests(TestCase):
def test_object_is_not_written_to_database_until_save_was_called(self):
a = Article(
id=None,
headline='Parrot programs in Python',
pub_date=datetime(2005, 7, 28),
)
self.assertIsNone(a.id)
self.assertEqual(Article.objects.all().count(), 0)
# Save it into the database. You have to call save() explicitly.
a.save()
self.assertIsNotNone(a.id)
self.assertEqual(Article.objects.all().count(), 1)
def test_can_initialize_model_instance_using_positional_arguments(self):
"""
You can initialize a model instance using positional arguments,
which should match the field order as defined in the model.
"""
a = Article(None, 'Second article', datetime(2005, 7, 29))
a.save()
self.assertEqual(a.headline, 'Second article')
self.assertEqual(a.pub_date, datetime(2005, 7, 29, 0, 0))
def test_can_create_instance_using_kwargs(self):
a = Article(
id=None,
headline='Third article',
pub_date=datetime(2005, 7, 30),
)
a.save()
self.assertEqual(a.headline, 'Third article')
self.assertEqual(a.pub_date, datetime(2005, 7, 30, 0, 0))
def test_autofields_generate_different_values_for_each_instance(self):
a1 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
a2 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
a3 = Article.objects.create(headline='First', pub_date=datetime(2005, 7, 30, 0, 0))
self.assertNotEqual(a3.id, a1.id)
self.assertNotEqual(a3.id, a2.id)
def test_can_mix_and_match_position_and_kwargs(self):
# You can also mix and match position and keyword arguments, but
# be sure not to duplicate field information.
a = Article(None, 'Fourth article', pub_date=datetime(2005, 7, 31))
a.save()
self.assertEqual(a.headline, 'Fourth article')
def test_cannot_create_instance_with_invalid_kwargs(self):
with self.assertRaisesMessage(TypeError, "'foo' is an invalid keyword argument for this function"):
Article(
id=None,
headline='Some headline',
pub_date=datetime(2005, 7, 31),
foo='bar',
)
def test_can_leave_off_value_for_autofield_and_it_gets_value_on_save(self):
"""
You can leave off the value for an AutoField when creating an
object, because it'll get filled in automatically when you save().
"""
a = Article(headline='Article 5', pub_date=datetime(2005, 7, 31))
a.save()
self.assertEqual(a.headline, 'Article 5')
self.assertIsNotNone(a.id)
def test_leaving_off_a_field_with_default_set_the_default_will_be_saved(self):
a = Article(pub_date=datetime(2005, 7, 31))
a.save()
self.assertEqual(a.headline, 'Default headline')
def test_for_datetimefields_saves_as_much_precision_as_was_given(self):
"""as much precision in *seconds*"""
a1 = Article(
headline='Article 7',
pub_date=datetime(2005, 7, 31, 12, 30),
)
a1.save()
self.assertEqual(Article.objects.get(id__exact=a1.id).pub_date, datetime(2005, 7, 31, 12, 30))
a2 = Article(
headline='Article 8',
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a2.save()
self.assertEqual(Article.objects.get(id__exact=a2.id).pub_date, datetime(2005, 7, 31, 12, 30, 45))
def test_saving_an_object_again_does_not_create_a_new_object(self):
a = Article(headline='original', pub_date=datetime(2014, 5, 16))
a.save()
current_id = a.id
a.save()
self.assertEqual(a.id, current_id)
a.headline = 'Updated headline'
a.save()
self.assertEqual(a.id, current_id)
def test_querysets_checking_for_membership(self):
headlines = [
'Parrot programs in Python', 'Second article', 'Third article']
some_pub_date = datetime(2014, 5, 16, 12, 1)
for headline in headlines:
Article(headline=headline, pub_date=some_pub_date).save()
a = Article(headline='Some headline', pub_date=some_pub_date)
a.save()
# You can use 'in' to test for membership...
self.assertIn(a, Article.objects.all())
# ... but there will often be more efficient ways if that is all you need:
self.assertTrue(Article.objects.filter(id=a.id).exists())
class ModelTest(TestCase):
def test_objects_attribute_is_only_available_on_the_class_itself(self):
with self.assertRaisesMessage(AttributeError, "Manager isn't accessible via Article instances"):
getattr(Article(), "objects",)
self.assertFalse(hasattr(Article(), 'objects'))
self.assertTrue(hasattr(Article, 'objects'))
def test_queryset_delete_removes_all_items_in_that_queryset(self):
headlines = [
'An article', 'Article One', 'Amazing article', 'Boring article']
some_pub_date = datetime(2014, 5, 16, 12, 1)
for headline in headlines:
Article(headline=headline, pub_date=some_pub_date).save()
self.assertQuerysetEqual(
Article.objects.all().order_by('headline'),
["<Article: Amazing article>",
"<Article: An article>",
"<Article: Article One>",
"<Article: Boring article>"]
)
Article.objects.filter(headline__startswith='A').delete()
self.assertQuerysetEqual(Article.objects.all().order_by('headline'), ["<Article: Boring article>"])
def test_not_equal_and_equal_operators_behave_as_expected_on_instances(self):
some_pub_date = datetime(2014, 5, 16, 12, 1)
a1 = Article.objects.create(headline='First', pub_date=some_pub_date)
a2 = Article.objects.create(headline='Second', pub_date=some_pub_date)
self.assertNotEqual(a1, a2)
self.assertEqual(a1, Article.objects.get(id__exact=a1.id))
self.assertNotEqual(Article.objects.get(id__exact=a1.id), Article.objects.get(id__exact=a2.id))
@skipUnlessDBFeature('supports_microsecond_precision')
def test_microsecond_precision(self):
# In PostgreSQL, microsecond-level precision is available.
a9 = Article(
headline='Article 9',
pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
)
a9.save()
self.assertEqual(Article.objects.get(pk=a9.pk).pub_date, datetime(2005, 7, 31, 12, 30, 45, 180))
@skipIfDBFeature('supports_microsecond_precision')
def test_microsecond_precision_not_supported(self):
# In MySQL, microsecond-level precision isn't always available. You'll
# lose microsecond-level precision once the data is saved.
a9 = Article(
headline='Article 9',
pub_date=datetime(2005, 7, 31, 12, 30, 45, 180),
)
a9.save()
self.assertEqual(
Article.objects.get(id__exact=a9.id).pub_date,
datetime(2005, 7, 31, 12, 30, 45),
)
@skipIfDBFeature('supports_microsecond_precision')
def test_microsecond_precision_not_supported_edge_case(self):
# In MySQL, microsecond-level precision isn't always available. You'll
# lose microsecond-level precision once the data is saved.
a = Article.objects.create(
headline='Article',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
self.assertEqual(
Article.objects.get(pk=a.pk).pub_date,
datetime(2008, 12, 31, 23, 59, 59),
)
def test_manually_specify_primary_key(self):
# You can manually specify the primary key when creating a new object.
a101 = Article(
id=101,
headline='Article 101',
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a101.save()
a101 = Article.objects.get(pk=101)
self.assertEqual(a101.headline, 'Article 101')
def test_create_method(self):
# You can create saved objects in a single step
a10 = Article.objects.create(
headline="Article 10",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
self.assertEqual(Article.objects.get(headline="Article 10"), a10)
def test_year_lookup_edge_case(self):
# Edge-case test: A year lookup should retrieve all objects in
# the given year, including Jan. 1 and Dec. 31.
Article.objects.create(
headline='Article 11',
pub_date=datetime(2008, 1, 1),
)
Article.objects.create(
headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__year=2008),
["<Article: Article 11>", "<Article: Article 12>"]
)
def test_unicode_data(self):
# Unicode data works, too.
a = Article(
headline='\u6797\u539f \u3081\u3050\u307f',
pub_date=datetime(2005, 7, 28),
)
a.save()
self.assertEqual(Article.objects.get(pk=a.id).headline, '\u6797\u539f \u3081\u3050\u307f')
def test_hash_function(self):
# Model instances have a hash function, so they can be used in sets
# or as dictionary keys. Two models compare as equal if their primary
# keys are equal.
a10 = Article.objects.create(
headline="Article 10",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
a11 = Article.objects.create(
headline='Article 11',
pub_date=datetime(2008, 1, 1),
)
a12 = Article.objects.create(
headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
s = {a10, a11, a12}
self.assertIn(Article.objects.get(headline='Article 11'), s)
def test_field_ordering(self):
"""
Field instances have a `__lt__` comparison function to define an
ordering based on their creation. Prior to #17851 this ordering
comparison relied on the now unsupported `__cmp__` and was assuming
compared objects were both Field instances raising `AttributeError`
when it should have returned `NotImplemented`.
"""
f1 = Field()
f2 = Field(auto_created=True)
f3 = Field()
self.assertLess(f2, f1)
self.assertGreater(f3, f1)
self.assertIsNotNone(f1)
self.assertNotIn(f2, (None, 1, ''))
def test_extra_method_select_argument_with_dashes_and_values(self):
# The 'select' argument to extra() supports names with dashes in
# them, as long as you use values().
Article.objects.create(
headline="Article 10",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
Article.objects.create(
headline='Article 11',
pub_date=datetime(2008, 1, 1),
)
Article.objects.create(
headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
dicts = Article.objects.filter(
pub_date__year=2008).extra(
select={'dashed-value': '1'}).values('headline', 'dashed-value')
self.assertEqual(
[sorted(d.items()) for d in dicts],
[[('dashed-value', 1), ('headline', 'Article 11')], [('dashed-value', 1), ('headline', 'Article 12')]]
)
def test_extra_method_select_argument_with_dashes(self):
# If you use 'select' with extra() and names containing dashes on a
# query that's *not* a values() query, those extra 'select' values
# will silently be ignored.
Article.objects.create(
headline="Article 10",
pub_date=datetime(2005, 7, 31, 12, 30, 45),
)
Article.objects.create(
headline='Article 11',
pub_date=datetime(2008, 1, 1),
)
Article.objects.create(
headline='Article 12',
pub_date=datetime(2008, 12, 31, 23, 59, 59, 999999),
)
articles = Article.objects.filter(
pub_date__year=2008).extra(select={'dashed-value': '1', 'undashedvalue': '2'})
self.assertEqual(articles[0].undashedvalue, 2)
def test_create_relation_with_ugettext_lazy(self):
"""
Test that ugettext_lazy objects work when saving model instances
through various methods. Refs #10498.
"""
notlazy = 'test'
lazy = ugettext_lazy(notlazy)
Article.objects.create(headline=lazy, pub_date=datetime.now())
article = Article.objects.get()
self.assertEqual(article.headline, notlazy)
# test that assign + save works with Promise objects
article.headline = lazy
article.save()
self.assertEqual(article.headline, notlazy)
# test .update()
Article.objects.update(headline=lazy)
article = Article.objects.get()
self.assertEqual(article.headline, notlazy)
# still test bulk_create()
Article.objects.all().delete()
Article.objects.bulk_create([Article(headline=lazy, pub_date=datetime.now())])
article = Article.objects.get()
self.assertEqual(article.headline, notlazy)
def test_emptyqs(self):
# Can't be instantiated
with self.assertRaises(TypeError):
EmptyQuerySet()
self.assertIsInstance(Article.objects.none(), EmptyQuerySet)
self.assertNotIsInstance('', EmptyQuerySet)
def test_emptyqs_values(self):
# test for #15959
Article.objects.create(headline='foo', pub_date=datetime.now())
with self.assertNumQueries(0):
qs = Article.objects.none().values_list('pk')
self.assertIsInstance(qs, EmptyQuerySet)
self.assertEqual(len(qs), 0)
def test_emptyqs_customqs(self):
# A hacky test for custom QuerySet subclass - refs #17271
Article.objects.create(headline='foo', pub_date=datetime.now())
class CustomQuerySet(QuerySet):
def do_something(self):
return 'did something'
qs = Article.objects.all()
qs.__class__ = CustomQuerySet
qs = qs.none()
with self.assertNumQueries(0):
self.assertEqual(len(qs), 0)
self.assertIsInstance(qs, EmptyQuerySet)
self.assertEqual(qs.do_something(), 'did something')
def test_emptyqs_values_order(self):
# Tests for ticket #17712
Article.objects.create(headline='foo', pub_date=datetime.now())
with self.assertNumQueries(0):
self.assertEqual(len(Article.objects.none().values_list('id').order_by('id')), 0)
with self.assertNumQueries(0):
self.assertEqual(len(Article.objects.none().filter(
id__in=Article.objects.values_list('id', flat=True))), 0)
@skipUnlessDBFeature('can_distinct_on_fields')
def test_emptyqs_distinct(self):
# Tests for #19426
Article.objects.create(headline='foo', pub_date=datetime.now())
with self.assertNumQueries(0):
self.assertEqual(len(Article.objects.none().distinct('headline', 'pub_date')), 0)
def test_ticket_20278(self):
sr = SelfRef.objects.create()
with self.assertRaises(ObjectDoesNotExist):
SelfRef.objects.get(selfref=sr)
def test_eq(self):
self.assertEqual(Article(id=1), Article(id=1))
self.assertNotEqual(Article(id=1), object())
self.assertNotEqual(object(), Article(id=1))
a = Article()
self.assertEqual(a, a)
self.assertNotEqual(Article(), a)
def test_hash(self):
# Value based on PK
self.assertEqual(hash(Article(id=1)), hash(1))
with self.assertRaises(TypeError):
# No PK value -> unhashable (because save() would then change
# hash)
hash(Article())
def test_delete_and_access_field(self):
# Accessing a field after it's deleted from a model reloads its value.
pub_date = datetime.now()
article = Article.objects.create(headline='foo', pub_date=pub_date)
new_pub_date = article.pub_date + timedelta(days=10)
article.headline = 'bar'
article.pub_date = new_pub_date
del article.headline
with self.assertNumQueries(1):
self.assertEqual(article.headline, 'foo')
# Fields that weren't deleted aren't reloaded.
self.assertEqual(article.pub_date, new_pub_date)
class ModelLookupTest(TestCase):
def setUp(self):
# Create an Article.
self.a = Article(
id=None,
headline='Swallow programs in Python',
pub_date=datetime(2005, 7, 28),
)
# Save it into the database. You have to call save() explicitly.
self.a.save()
def test_all_lookup(self):
# Change values by changing the attributes, then calling save().
self.a.headline = 'Parrot programs in Python'
self.a.save()
# Article.objects.all() returns all the articles in the database.
self.assertQuerysetEqual(Article.objects.all(), ['<Article: Parrot programs in Python>'])
def test_rich_lookup(self):
# Django provides a rich database lookup API.
self.assertEqual(Article.objects.get(id__exact=self.a.id), self.a)
self.assertEqual(Article.objects.get(headline__startswith='Swallow'), self.a)
self.assertEqual(Article.objects.get(pub_date__year=2005), self.a)
self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7), self.a)
self.assertEqual(Article.objects.get(pub_date__year=2005, pub_date__month=7, pub_date__day=28), self.a)
self.assertEqual(Article.objects.get(pub_date__week_day=5), self.a)
def test_equal_lookup(self):
# The "__exact" lookup type can be omitted, as a shortcut.
self.assertEqual(Article.objects.get(id=self.a.id), self.a)
self.assertEqual(Article.objects.get(headline='Swallow programs in Python'), self.a)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__year=2005),
['<Article: Swallow programs in Python>'],
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__year=2004),
[],
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__year=2005, pub_date__month=7),
['<Article: Swallow programs in Python>'],
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__week_day=5),
['<Article: Swallow programs in Python>'],
)
self.assertQuerysetEqual(
Article.objects.filter(pub_date__week_day=6),
[],
)
def test_does_not_exist(self):
# Django raises an Article.DoesNotExist exception for get() if the
# parameters don't match any object.
with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."):
Article.objects.get(id__exact=2000,)
# To avoid dict-ordering related errors check only one lookup
# in single assert.
with self.assertRaises(ObjectDoesNotExist):
Article.objects.get(pub_date__year=2005, pub_date__month=8)
with self.assertRaisesMessage(ObjectDoesNotExist, "Article matching query does not exist."):
Article.objects.get(pub_date__week_day=6,)
def test_lookup_by_primary_key(self):
# Lookup by a primary key is the most common case, so Django
# provides a shortcut for primary-key exact lookups.
# The following is identical to articles.get(id=a.id).
self.assertEqual(Article.objects.get(pk=self.a.id), self.a)
# pk can be used as a shortcut for the primary key name in any query.
self.assertQuerysetEqual(Article.objects.filter(pk__in=[self.a.id]), ["<Article: Swallow programs in Python>"])
# Model instances of the same type and same ID are considered equal.
a = Article.objects.get(pk=self.a.id)
b = Article.objects.get(pk=self.a.id)
self.assertEqual(a, b)
def test_too_many(self):
# Create a very similar object
a = Article(
id=None,
headline='Swallow bites Python',
pub_date=datetime(2005, 7, 28),
)
a.save()
self.assertEqual(Article.objects.count(), 2)
# Django raises an Article.MultipleObjectsReturned exception if the
# lookup matches more than one object
msg = "get() returned more than one Article -- it returned 2!"
with self.assertRaisesMessage(MultipleObjectsReturned, msg):
Article.objects.get(headline__startswith='Swallow',)
with self.assertRaisesMessage(MultipleObjectsReturned, msg):
Article.objects.get(pub_date__year=2005,)
with self.assertRaisesMessage(MultipleObjectsReturned, msg):
Article.objects.get(pub_date__year=2005, pub_date__month=7)
class ConcurrentSaveTests(TransactionTestCase):
available_apps = ['basic']
@skipUnlessDBFeature('test_db_allows_multiple_connections')
def test_concurrent_delete_with_save(self):
"""
Test fetching, deleting and finally saving an object - we should get
an insert in this case.
"""
a = Article.objects.create(headline='foo', pub_date=datetime.now())
exceptions = []
def deleter():
try:
# Do not delete a directly - doing so alters its state.
Article.objects.filter(pk=a.pk).delete()
except Exception as e:
exceptions.append(e)
finally:
connections[DEFAULT_DB_ALIAS].close()
self.assertEqual(len(exceptions), 0)
t = threading.Thread(target=deleter)
t.start()
t.join()
a.save()
self.assertEqual(Article.objects.get(pk=a.pk).headline, 'foo')
class ManagerTest(SimpleTestCase):
QUERYSET_PROXY_METHODS = [
'none',
'count',
'dates',
'datetimes',
'distinct',
'extra',
'get',
'get_or_create',
'update_or_create',
'create',
'bulk_create',
'filter',
'aggregate',
'annotate',
'complex_filter',
'exclude',
'in_bulk',
'iterator',
'earliest',
'latest',
'first',
'last',
'order_by',
'select_for_update',
'select_related',
'prefetch_related',
'values',
'values_list',
'update',
'reverse',
'defer',
'only',
'using',
'exists',
'_insert',
'_update',
'raw',
]
def test_manager_methods(self):
"""
This test ensures that the correct set of methods from `QuerySet`
are copied onto `Manager`.
It's particularly useful to prevent accidentally leaking new methods
into `Manager`. New `QuerySet` methods that should also be copied onto
`Manager` will need to be added to `ManagerTest.QUERYSET_PROXY_METHODS`.
"""
self.assertEqual(
sorted(BaseManager._get_queryset_methods(QuerySet).keys()),
sorted(self.QUERYSET_PROXY_METHODS),
)
class SelectOnSaveTests(TestCase):
def test_select_on_save(self):
a1 = Article.objects.create(pub_date=datetime.now())
with self.assertNumQueries(1):
a1.save()
asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
with self.assertNumQueries(2):
asos.save()
with self.assertNumQueries(1):
asos.save(force_update=True)
Article.objects.all().delete()
with self.assertRaises(DatabaseError):
with self.assertNumQueries(1):
asos.save(force_update=True)
def test_select_on_save_lying_update(self):
"""
Test that select_on_save works correctly if the database
doesn't return correct information about matched rows from
UPDATE.
"""
# Change the manager to not return "row matched" for update().
# We are going to change the Article's _base_manager class
# dynamically. This is a bit of a hack, but it seems hard to
# test this properly otherwise. Article's manager, because
# proxy models use their parent model's _base_manager.
orig_class = Article._base_manager._queryset_class
class FakeQuerySet(QuerySet):
# Make sure the _update method below is in fact called.
called = False
def _update(self, *args, **kwargs):
FakeQuerySet.called = True
super(FakeQuerySet, self)._update(*args, **kwargs)
return 0
try:
Article._base_manager._queryset_class = FakeQuerySet
asos = ArticleSelectOnSave.objects.create(pub_date=datetime.now())
with self.assertNumQueries(3):
asos.save()
self.assertTrue(FakeQuerySet.called)
# This is not wanted behavior, but this is how Django has always
# behaved for databases that do not return correct information
# about matched rows for UPDATE.
with self.assertRaises(DatabaseError):
asos.save(force_update=True)
with self.assertRaises(DatabaseError):
asos.save(update_fields=['pub_date'])
finally:
Article._base_manager._queryset_class = orig_class
class ModelRefreshTests(TestCase):
def _truncate_ms(self, val):
# MySQL < 5.6.4 removes microseconds from the datetimes which can cause
# problems when comparing the original value to that loaded from DB
return val - timedelta(microseconds=val.microsecond)
def test_refresh(self):
a = Article.objects.create(pub_date=self._truncate_ms(datetime.now()))
Article.objects.create(pub_date=self._truncate_ms(datetime.now()))
Article.objects.filter(pk=a.pk).update(headline='new headline')
with self.assertNumQueries(1):
a.refresh_from_db()
self.assertEqual(a.headline, 'new headline')
orig_pub_date = a.pub_date
new_pub_date = a.pub_date + timedelta(10)
Article.objects.update(headline='new headline 2', pub_date=new_pub_date)
with self.assertNumQueries(1):
a.refresh_from_db(fields=['headline'])
self.assertEqual(a.headline, 'new headline 2')
self.assertEqual(a.pub_date, orig_pub_date)
with self.assertNumQueries(1):
a.refresh_from_db()
self.assertEqual(a.pub_date, new_pub_date)
def test_unknown_kwarg(self):
s = SelfRef.objects.create()
with self.assertRaises(TypeError):
s.refresh_from_db(unknown_kwarg=10)
def test_refresh_fk(self):
s1 = SelfRef.objects.create()
s2 = SelfRef.objects.create()
s3 = SelfRef.objects.create(selfref=s1)
s3_copy = SelfRef.objects.get(pk=s3.pk)
s3_copy.selfref.touched = True
s3.selfref = s2
s3.save()
with self.assertNumQueries(1):
s3_copy.refresh_from_db()
with self.assertNumQueries(1):
# The old related instance was thrown away (the selfref_id has
# changed). It needs to be reloaded on access, so one query
# executed.
self.assertFalse(hasattr(s3_copy.selfref, 'touched'))
self.assertEqual(s3_copy.selfref, s2)
def test_refresh_null_fk(self):
s1 = SelfRef.objects.create()
s2 = SelfRef.objects.create(selfref=s1)
s2.selfref = None
s2.refresh_from_db()
self.assertEqual(s2.selfref, s1)
def test_refresh_unsaved(self):
pub_date = self._truncate_ms(datetime.now())
a = Article.objects.create(pub_date=pub_date)
a2 = Article(id=a.pk)
with self.assertNumQueries(1):
a2.refresh_from_db()
self.assertEqual(a2.pub_date, pub_date)
self.assertEqual(a2._state.db, "default")
def test_refresh_fk_on_delete_set_null(self):
a = Article.objects.create(
headline='Parrot programs in Python',
pub_date=datetime(2005, 7, 28),
)
s1 = SelfRef.objects.create(article=a)
a.delete()
s1.refresh_from_db()
self.assertIsNone(s1.article_id)
self.assertIsNone(s1.article)
def test_refresh_no_fields(self):
a = Article.objects.create(pub_date=self._truncate_ms(datetime.now()))
with self.assertNumQueries(0):
a.refresh_from_db(fields=[])
| bsd-3-clause |
redhatrises/freeipa | ipapython/errors.py | 9 | 1984 | # Authors: Petr Viktorin <pviktori@redhat.com>
#
# Copyright (C) 2014 Red Hat
# see file 'COPYING' for use and warranty information
#
# 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/>.
#
class SetseboolError(Exception):
"""Raised when setting a SELinux boolean fails
:param failed: Dictionary mapping boolean names to intended values
to their intended values, for booleans that cound not be set
:param command: Command the user can run to set the booleans
The initializer arguments are copied to attributes of the same name.
"""
def __init__(self, failed, command):
message = "Could not set SELinux booleans: %s" % ' '.join(
'%s=%s' % (name, value) for name, value in failed.items())
super(SetseboolError, self).__init__(message)
self.failed = failed
self.command = command
def format_service_warning(self, service_name):
"""Format warning for display when this is raised from service install
"""
return '\n'.join([
'WARNING: %(err)s',
'',
'The %(service)s may not function correctly until ',
'the booleans are successfully changed with the command:',
' %(cmd)s',
'Try updating the policycoreutils and selinux-policy packages.'
]) % {'err': self, 'service': service_name, 'cmd': self.command}
| gpl-3.0 |
apophys/freeipa | ipaclient/plugins/certprofile.py | 8 | 1499 | #
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
from ipaclient.frontend import MethodOverride
from ipalib import util
from ipalib.parameters import File
from ipalib.plugable import Registry
from ipalib.text import _
register = Registry()
@register(override=True, no_fail=True)
class certprofile_show(MethodOverride):
def forward(self, *keys, **options):
if 'out' in options:
util.check_writable_file(options['out'])
result = super(certprofile_show, self).forward(*keys, **options)
if 'out' in options and 'config' in result['result']:
with open(options['out'], 'wb') as f:
f.write(result['result'].pop('config'))
result['summary'] = (
_("Profile configuration stored in file '%(file)s'")
% dict(file=options['out'])
)
return result
@register(override=True, no_fail=True)
class certprofile_import(MethodOverride):
def get_options(self):
for option in super(certprofile_import, self).get_options():
if option.name == 'file':
option = option.clone_retype(option.name, File)
yield option
@register(override=True, no_fail=True)
class certprofile_mod(MethodOverride):
def get_options(self):
for option in super(certprofile_mod, self).get_options():
if option.name == 'file':
option = option.clone_retype(option.name, File)
yield option
| gpl-3.0 |
ttsirkia/a-plus | redirect_old_urls/tests.py | 2 | 4005 | from django.test import TestCase
from course.models import Course, CourseInstance, CourseModule,\
LearningObjectCategory
from exercise.exercise_models import StaticExercise
from django.contrib.auth.models import User
from django.utils import timezone
from datetime import timedelta
class RedirectTest(TestCase):
def setUp(self):
self.user = User(username="testUser")
self.user.set_password("testPassword")
self.user.save()
self.course = Course.objects.create(
name="test course",
code="123456",
url="Course-Url"
)
self.course_instance = CourseInstance.objects.create(
instance_name="Fall 2011",
starting_time=timezone.now(),
ending_time=timezone.now() + timedelta(days=5),
course=self.course,
url="T-00.1000_2011"
)
self.course_module = CourseModule.objects.create(
name="test module",
url="test-module",
points_to_pass=15,
course_instance=self.course_instance,
opening_time=timezone.now(),
closing_time=timezone.now() + timedelta(days=5)
)
self.learning_object_category = LearningObjectCategory.objects.create(
name="test category",
course_instance=self.course_instance,
points_to_pass=5
)
self.exercise = StaticExercise.objects.create(
name="test exercise",
course_module=self.course_module,
category=self.learning_object_category,
url='e1',
)
def test_course(self):
response = self.client.get('/course/course/')
self.assertEqual(response.status_code, 404)
response = self.client.get('/course/Course-Url/', follow=True)
self.assertTrue(response.redirect_chain)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'userprofile/login.html')
self.client.login(username="testUser", password="testPassword")
response = self.client.get('/course/Course-Url/', follow=True)
self.assertTrue(response.redirect_chain)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'course/course.html')
response = self.client.get('/another/course/Course-Url/')
self.assertEqual(response.status_code, 404)
def test_course_instance(self):
self.client.login(username="testUser", password="testPassword")
response = self.client.get('/course/Course-Url/foobar/', follow=True)
self.assertEqual(response.status_code, 404)
response = self.client.get('/course/Course-Url/T-00.1000_2011/', follow=True)
self.assertTrue(response.redirect_chain)
self.assertEqual(response.status_code, 200)
response = self.client.get('/another/course/Course-Url/T-00.1000_2011/')
self.assertEqual(response.status_code, 404)
def test_exercise(self):
self.client.login(username="testUser", password="testPassword")
response = self.client.get('/exercise/100/', follow=True)
self.assertEqual(response.status_code, 404)
response = self.client.get('/exercise/{:d}'.format(self.exercise.id), follow=True)
self.assertTrue(response.redirect_chain)
self.assertEqual(response.status_code, 200)
response = self.client.get('/foobar/exercise/{:d}'.format(self.exercise.id), follow=True)
self.assertEqual(response.status_code, 404)
def test_course_instance_exercise(self):
self.client.login(username="testUser", password="testPassword")
response = self.client.get('/Course-Url/T-00.1000_2011/exercises/{:d}'.format(self.exercise.id), follow=True)
self.assertTrue(response.redirect_chain)
self.assertEqual(response.status_code, 200)
response = self.client.get('/Course-Url/T-00.1000_2011/test-module/e1/')
self.assertEqual(response.status_code, 200)
| gpl-3.0 |
aniruddhkanojia/qtile | libqtile/state.py | 5 | 2582 | # Copyright (c) 2012, Tycho Andersen. 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, 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.
class QtileState(object):
"""
Represents the state of the qtile object. Primarily used for restoring
state across restarts; any additional state which doesn't fit nicely
into X atoms can go here.
"""
def __init__(self, qtile):
# Note: window state is saved and restored via _NET_WM_STATE, so
# the only thing we need to restore here is the layout and screen
# configurations.
self.groups = {}
self.screens = {}
self.current_screen = 0
for group in qtile.groups:
self.groups[group.name] = group.layout.name
for index, screen in enumerate(qtile.screens):
self.screens[index] = screen.group.name
if screen == qtile.currentScreen:
self.current_screen = index
def apply(self, qtile):
"""
Rearrange the windows in the specified Qtile object according to
this QtileState.
"""
for (group, layout) in self.groups.items():
try:
qtile.groupMap[group].layout = layout
except KeyError:
pass # group missing
for (screen, group) in self.screens.items():
try:
group = qtile.groupMap[group]
qtile.screens[screen].setGroup(group)
except (KeyError, IndexError):
pass # group or screen missing
qtile.toScreen(self.current_screen)
| mit |
dwitvliet/CATMAID | scripts/export/export_all_csv.py | 5 | 2541 | # Albert Cardona 2014-11-21
# This file is meant to be run from within ./manage.py shell in the environment, like:
# [1] load export_all_csv.py
# [2] project_id = 12
# [2] export(project_id, "all")
from __future__ import with_statement
from django.db import connection
from django.db import transaction
import gzip
def writeOneSkeleton(file, cursor, skid):
cursor.execute('''
select id, parent_id, location_x, location_y, location_z
from treenode
where skeleton_id=%s
''' % skid)
for row in cursor.fetchall():
file.write("%s,%s,%s,%s,%s,%s\n" % ((skid,) + row))
@transaction.atomic
def export(project_id, filename):
project_id = int(project_id)
cursor = connection.cursor()
# First CSV file: skeletons
with gzip.open(filename + "." + str(project_id) + ".skeletons.csv.gz", 'w') as file:
# Header
file.write('"skeleton ID", "treenode ID", "parent treenode ID", "x", "y", "z"\n')
# Filter skeletons as having more than one treenode
cursor.execute('''
select skeleton_id
from treenode
where project_id=%s
group by skeleton_id
having count(*) > 1
''' % project_id)
#
for row in cursor.fetchall():
print("Writing skeleton nodes for %s" % row[0])
writeOneSkeleton(file, cursor, row[0])
# Second CSV file: synapses
with gzip.open(filename + "." + str(project_id) + ".synapses.csv.gz", 'w') as file:
print("Writing synapses")
# Header
file.write('"synapse ID", "presynaptic treenode ID", "presynaptic skeleton ID", "postsynaptic treenode ID", "postsynaptic skeleton ID"\n')
cursor.execute('''
select relation_name, id from relation where project_id=%s
''' % project_id)
relations = dict(cursor.fetchall())
#
cursor.execute('''
select tc2.id, tc1.treenode_id, tc1.skeleton_id,
tc2.treenode_id, tc2.skeleton_id
from treenode_connector tc1,
treenode_connector tc2
where tc1.project_id=%s
and tc1.relation_id = %s
and tc2.relation_id = %s
and tc1.connector_id = tc2.connector_id
and tc1.skeleton_id IN (select skeleton_id from treenode where project_id=%s group by skeleton_id having count(*) > 1)
''' % (project_id, relations['presynaptic_to'], relations['postsynaptic_to'], project_id))
#
for row in cursor.fetchall():
file.write("%s,%s,%s,%s,%s\n" % row)
| gpl-3.0 |
Allow2CEO/browser-ios | brave/node_modules/ad-block/node_modules/bloom-filter-cpp/vendor/depot_tools/third_party/pylint/pyreverse/writer.py | 68 | 7866 | # -*- coding: utf-8 -*-
# Copyright (c) 2008-2013 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# 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.
"""Utilities for creating VCG and Dot diagrams"""
from logilab.common.vcgutils import VCGPrinter
from logilab.common.graph import DotBackend
from pylint.pyreverse.utils import is_exception
class DiagramWriter(object):
"""base class for writing project diagrams
"""
def __init__(self, config, styles):
self.config = config
self.pkg_edges, self.inh_edges, self.imp_edges, self.ass_edges = styles
self.printer = None # defined in set_printer
def write(self, diadefs):
"""write files for <project> according to <diadefs>
"""
for diagram in diadefs:
basename = diagram.title.strip().replace(' ', '_')
file_name = '%s.%s' % (basename, self.config.output_format)
self.set_printer(file_name, basename)
if diagram.TYPE == 'class':
self.write_classes(diagram)
else:
self.write_packages(diagram)
self.close_graph()
def write_packages(self, diagram):
"""write a package diagram"""
# sorted to get predictable (hence testable) results
for i, obj in enumerate(sorted(diagram.modules(), key=lambda x: x.title)):
self.printer.emit_node(i, label=self.get_title(obj), shape='box')
obj.fig_id = i
# package dependencies
for rel in diagram.get_relationships('depends'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id,
**self.pkg_edges)
def write_classes(self, diagram):
"""write a class diagram"""
# sorted to get predictable (hence testable) results
for i, obj in enumerate(sorted(diagram.objects, key=lambda x: x.title)):
self.printer.emit_node(i, **self.get_values(obj))
obj.fig_id = i
# inheritance links
for rel in diagram.get_relationships('specialization'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id,
**self.inh_edges)
# implementation links
for rel in diagram.get_relationships('implements'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id,
**self.imp_edges)
# generate associations
for rel in diagram.get_relationships('association'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id,
label=rel.name, **self.ass_edges)
def set_printer(self, file_name, basename):
"""set printer"""
raise NotImplementedError
def get_title(self, obj):
"""get project title"""
raise NotImplementedError
def get_values(self, obj):
"""get label and shape for classes."""
raise NotImplementedError
def close_graph(self):
"""finalize the graph"""
raise NotImplementedError
class DotWriter(DiagramWriter):
"""write dot graphs from a diagram definition and a project
"""
def __init__(self, config):
styles = [dict(arrowtail='none', arrowhead="open"),
dict(arrowtail='none', arrowhead='empty'),
dict(arrowtail='node', arrowhead='empty', style='dashed'),
dict(fontcolor='green', arrowtail='none',
arrowhead='diamond', style='solid'),
]
DiagramWriter.__init__(self, config, styles)
def set_printer(self, file_name, basename):
"""initialize DotWriter and add options for layout.
"""
layout = dict(rankdir="BT")
self.printer = DotBackend(basename, additionnal_param=layout)
self.file_name = file_name
def get_title(self, obj):
"""get project title"""
return obj.title
def get_values(self, obj):
"""get label and shape for classes.
The label contains all attributes and methods
"""
label = obj.title
if obj.shape == 'interface':
label = u'«interface»\\n%s' % label
if not self.config.only_classnames:
label = r'%s|%s\l|' % (label, r'\l'.join(obj.attrs))
for func in obj.methods:
label = r'%s%s()\l' % (label, func.name)
label = '{%s}' % label
if is_exception(obj.node):
return dict(fontcolor='red', label=label, shape='record')
return dict(label=label, shape='record')
def close_graph(self):
"""print the dot graph into <file_name>"""
self.printer.generate(self.file_name)
class VCGWriter(DiagramWriter):
"""write vcg graphs from a diagram definition and a project
"""
def __init__(self, config):
styles = [dict(arrowstyle='solid', backarrowstyle='none',
backarrowsize=0),
dict(arrowstyle='solid', backarrowstyle='none',
backarrowsize=10),
dict(arrowstyle='solid', backarrowstyle='none',
linestyle='dotted', backarrowsize=10),
dict(arrowstyle='solid', backarrowstyle='none',
textcolor='green'),
]
DiagramWriter.__init__(self, config, styles)
def set_printer(self, file_name, basename):
"""initialize VCGWriter for a UML graph"""
self.graph_file = open(file_name, 'w+')
self.printer = VCGPrinter(self.graph_file)
self.printer.open_graph(title=basename, layoutalgorithm='dfs',
late_edge_labels='yes', port_sharing='no',
manhattan_edges='yes')
self.printer.emit_node = self.printer.node
self.printer.emit_edge = self.printer.edge
def get_title(self, obj):
"""get project title in vcg format"""
return r'\fb%s\fn' % obj.title
def get_values(self, obj):
"""get label and shape for classes.
The label contains all attributes and methods
"""
if is_exception(obj.node):
label = r'\fb\f09%s\fn' % obj.title
else:
label = r'\fb%s\fn' % obj.title
if obj.shape == 'interface':
shape = 'ellipse'
else:
shape = 'box'
if not self.config.only_classnames:
attrs = obj.attrs
methods = [func.name for func in obj.methods]
# box width for UML like diagram
maxlen = max(len(name) for name in [obj.title] + methods + attrs)
line = '_' * (maxlen + 2)
label = r'%s\n\f%s' % (label, line)
for attr in attrs:
label = r'%s\n\f08%s' % (label, attr)
if attrs:
label = r'%s\n\f%s' % (label, line)
for func in methods:
label = r'%s\n\f10%s()' % (label, func)
return dict(label=label, shape=shape)
def close_graph(self):
"""close graph and file"""
self.printer.close_graph()
self.graph_file.close()
| mpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.