repo_name stringlengths 5 100 | path stringlengths 4 294 | copies stringclasses 990
values | size stringlengths 4 7 | content stringlengths 666 1M | license stringclasses 15
values |
|---|---|---|---|---|---|
VirtueSecurity/aws-extender | BappModules/boto/awslambda/__init__.py | 22 | 1753 | # Copyright (c) 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
from boto.regioninfo import RegionInfo, get_regions
from boto.regioninfo import connect
def regions():
"""
Get all available regions for the AWS Lambda service.
:rtype: list
:return: A list of :class:`boto.regioninfo.RegionInfo`
"""
from boto.awslambda.layer1 import AWSLambdaConnection
return get_regions('awslambda',
connection_cls=AWSLambdaConnection)
def connect_to_region(region_name, **kw_params):
from boto.awslambda.layer1 import AWSLambdaConnection
return connect('awslambda', region_name,
connection_cls=AWSLambdaConnection, **kw_params)
| mit |
hasadna/django | django/core/context_processors.py | 232 | 2269 | """
A set of request processors that return dictionaries to be merged into a
template context. Each function takes the request object as its only parameter
and returns a dictionary to add to the context.
These are referenced from the setting TEMPLATE_CONTEXT_PROCESSORS and used by
RequestContext.
"""
from __future__ import unicode_literals
from django.conf import settings
from django.middleware.csrf import get_token
from django.utils import six
from django.utils.encoding import smart_text
from django.utils.functional import lazy
def csrf(request):
"""
Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if
it has not been provided by either a view decorator or the middleware
"""
def _get_val():
token = get_token(request)
if token is None:
# In order to be able to provide debugging info in the
# case of misconfiguration, we use a sentinel value
# instead of returning an empty dict.
return 'NOTPROVIDED'
else:
return smart_text(token)
_get_val = lazy(_get_val, six.text_type)
return {'csrf_token': _get_val() }
def debug(request):
"Returns context variables helpful for debugging."
context_extras = {}
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
context_extras['debug'] = True
from django.db import connection
context_extras['sql_queries'] = connection.queries
return context_extras
def i18n(request):
from django.utils import translation
context_extras = {}
context_extras['LANGUAGES'] = settings.LANGUAGES
context_extras['LANGUAGE_CODE'] = translation.get_language()
context_extras['LANGUAGE_BIDI'] = translation.get_language_bidi()
return context_extras
def tz(request):
from django.utils import timezone
return {'TIME_ZONE': timezone.get_current_timezone_name()}
def static(request):
"""
Adds static-related context variables to the context.
"""
return {'STATIC_URL': settings.STATIC_URL}
def media(request):
"""
Adds media-related context variables to the context.
"""
return {'MEDIA_URL': settings.MEDIA_URL}
def request(request):
return {'request': request}
| bsd-3-clause |
mtconley/turntable | test/lib/python2.7/site-packages/scipy/sparse/linalg/isolve/utils.py | 21 | 3830 | from __future__ import division, print_function, absolute_import
__docformat__ = "restructuredtext en"
__all__ = []
from warnings import warn
from numpy import asanyarray, asarray, asmatrix, array, matrix, zeros
from scipy.sparse.linalg.interface import aslinearoperator, LinearOperator, \
IdentityOperator
_coerce_rules = {('f','f'):'f', ('f','d'):'d', ('f','F'):'F',
('f','D'):'D', ('d','f'):'d', ('d','d'):'d',
('d','F'):'D', ('d','D'):'D', ('F','f'):'F',
('F','d'):'D', ('F','F'):'F', ('F','D'):'D',
('D','f'):'D', ('D','d'):'D', ('D','F'):'D',
('D','D'):'D'}
def coerce(x,y):
if x not in 'fdFD':
x = 'd'
if y not in 'fdFD':
y = 'd'
return _coerce_rules[x,y]
def id(x):
return x
def make_system(A, M, x0, b, xtype=None):
"""Make a linear system Ax=b
Parameters
----------
A : LinearOperator
sparse or dense matrix (or any valid input to aslinearoperator)
M : {LinearOperator, Nones}
preconditioner
sparse or dense matrix (or any valid input to aslinearoperator)
x0 : {array_like, None}
initial guess to iterative method
b : array_like
right hand side
xtype : {'f', 'd', 'F', 'D', None}
dtype of the x vector
Returns
-------
(A, M, x, b, postprocess)
A : LinearOperator
matrix of the linear system
M : LinearOperator
preconditioner
x : rank 1 ndarray
initial guess
b : rank 1 ndarray
right hand side
postprocess : function
converts the solution vector to the appropriate
type and dimensions (e.g. (N,1) matrix)
"""
A_ = A
A = aslinearoperator(A)
if A.shape[0] != A.shape[1]:
raise ValueError('expected square matrix, but got shape=%s' % (A.shape,))
N = A.shape[0]
b = asanyarray(b)
if not (b.shape == (N,1) or b.shape == (N,)):
raise ValueError('A and b have incompatible dimensions')
if b.dtype.char not in 'fdFD':
b = b.astype('d') # upcast non-FP types to double
def postprocess(x):
if isinstance(b,matrix):
x = asmatrix(x)
return x.reshape(b.shape)
if xtype is None:
if hasattr(A,'dtype'):
xtype = A.dtype.char
else:
xtype = A.matvec(b).dtype.char
xtype = coerce(xtype, b.dtype.char)
else:
warn('Use of xtype argument is deprecated. '
'Use LinearOperator( ... , dtype=xtype) instead.',
DeprecationWarning)
if xtype == 0:
xtype = b.dtype.char
else:
if xtype not in 'fdFD':
raise ValueError("xtype must be 'f', 'd', 'F', or 'D'")
b = asarray(b,dtype=xtype) # make b the same type as x
b = b.ravel()
if x0 is None:
x = zeros(N, dtype=xtype)
else:
x = array(x0, dtype=xtype)
if not (x.shape == (N,1) or x.shape == (N,)):
raise ValueError('A and x have incompatible dimensions')
x = x.ravel()
# process preconditioner
if M is None:
if hasattr(A_,'psolve'):
psolve = A_.psolve
else:
psolve = id
if hasattr(A_,'rpsolve'):
rpsolve = A_.rpsolve
else:
rpsolve = id
if psolve is id and rpsolve is id:
M = IdentityOperator(shape=A.shape, dtype=A.dtype)
else:
M = LinearOperator(A.shape, matvec=psolve, rmatvec=rpsolve,
dtype=A.dtype)
else:
M = aslinearoperator(M)
if A.shape != M.shape:
raise ValueError('matrix and preconditioner have different shapes')
return A, M, x, b, postprocess
| mit |
indictranstech/trufil-erpnext | erpnext/hooks.py | 1 | 5037 | from __future__ import unicode_literals
from frappe import _
app_name = "erpnext"
app_title = "ERPNext"
app_publisher = "Frappe Technologies Pvt. Ltd."
app_description = """ERP made simple"""
app_icon = "icon-th"
app_color = "#e74c3c"
app_version = "6.10.2"
app_email = "info@erpnext.com"
app_license = "GNU General Public License (v3)"
source_link = "https://github.com/frappe/erpnext"
error_report_email = "support@erpnext.com"
app_include_js = "assets/js/erpnext.min.js"
app_include_css = "assets/css/erpnext.css"
web_include_js = "assets/js/erpnext-web.min.js"
web_include_css = "assets/erpnext/css/website.css"
# setup wizard
setup_wizard_requires = "assets/erpnext/js/setup_wizard.js"
setup_wizard_complete = "erpnext.setup.setup_wizard.setup_wizard.setup_complete"
after_install = "erpnext.setup.install.after_install"
boot_session = "erpnext.startup.boot.boot_session"
notification_config = "erpnext.startup.notifications.get_notification_config"
on_session_creation = "erpnext.shopping_cart.utils.set_cart_count"
on_logout = "erpnext.shopping_cart.utils.clear_cart_count"
# website
update_website_context = "erpnext.shopping_cart.utils.update_website_context"
my_account_context = "erpnext.shopping_cart.utils.update_my_account_context"
email_append_to = ["Job Applicant", "Opportunity", "Issue"]
calendars = ["Task", "Production Order", "Time Log", "Leave Application", "Sales Order", "Holiday List"]
website_generators = ["Item Group", "Item", "Sales Partner"]
website_context = {
"favicon": "/assets/erpnext/images/favicon.png",
"splash_image": "/assets/erpnext/images/splash.png"
}
website_route_rules = [
{"from_route": "/orders", "to_route": "Sales Order"},
{"from_route": "/orders/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Sales Order",
"parents": [{"title": _("Orders"), "name": "orders"}]
}
},
{"from_route": "/invoices", "to_route": "Sales Invoice"},
{"from_route": "/invoices/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Sales Invoice",
"parents": [{"title": _("Invoices"), "name": "invoices"}]
}
},
{"from_route": "/shipments", "to_route": "Delivery Note"},
{"from_route": "/shipments/<path:name>", "to_route": "order",
"defaults": {
"doctype": "Delivery Notes",
"parents": [{"title": _("Shipments"), "name": "shipments"}]
}
}
]
has_website_permission = {
"Sales Order": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Sales Invoice": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Delivery Note": "erpnext.controllers.website_list_for_contact.has_website_permission",
"Issue": "erpnext.support.doctype.issue.issue.has_website_permission",
"Address": "erpnext.utilities.doctype.address.address.has_website_permission"
}
permission_query_conditions = {
"Contact": "erpnext.utilities.address_and_contact.get_permission_query_conditions_for_contact",
"Address": "erpnext.utilities.address_and_contact.get_permission_query_conditions_for_address"
}
has_permission = {
"Contact": "erpnext.utilities.address_and_contact.has_permission",
"Address": "erpnext.utilities.address_and_contact.has_permission"
}
dump_report_map = "erpnext.startup.report_data_map.data_map"
before_tests = "erpnext.setup.utils.before_tests"
standard_queries = {
"Customer": "erpnext.selling.doctype.customer.customer.get_customer_list"
}
doc_events = {
"Stock Entry": {
"on_submit": "erpnext.stock.doctype.material_request.material_request.update_completed_and_requested_qty",
"on_cancel": "erpnext.stock.doctype.material_request.material_request.update_completed_and_requested_qty"
},
"User": {
"validate": "erpnext.hr.doctype.employee.employee.validate_employee_role",
"on_update": "erpnext.hr.doctype.employee.employee.update_user_permissions"
},
"Sales Taxes and Charges Template": {
"on_update": "erpnext.shopping_cart.doctype.shopping_cart_settings.shopping_cart_settings.validate_cart_settings"
},
"Price List": {
"on_update": "erpnext.shopping_cart.doctype.shopping_cart_settings.shopping_cart_settings.validate_cart_settings"
},
"Contact": {
"validate": "erpnext.crm.doctype.crm_module_customization.generate_contact_code"
},
"Address": {
"validate": "erpnext.crm.doctype.crm_module_customization.generate_address_code"
}
}
scheduler_events = {
"hourly": [
"erpnext.controllers.recurring_document.create_recurring_documents"
],
"daily": [
"erpnext.stock.reorder_item.reorder_item",
"erpnext.setup.doctype.email_digest.email_digest.send",
"erpnext.support.doctype.issue.issue.auto_close_tickets",
"erpnext.accounts.doctype.fiscal_year.fiscal_year.auto_create_fiscal_year",
"erpnext.hr.doctype.employee.employee.send_birthday_reminders"
]
}
default_mail_footer = """<div style="text-align: center;">
<a href="https://erpnext.com?source=via_email_footer" target="_blank" style="color: #8d99a6;">
Sent via ERPNext
</a>
</div>"""
get_translated_dict = {
("doctype", "Global Defaults"): "frappe.geo.country_info.get_translated_dict"
}
| agpl-3.0 |
cloew/KaoFlaskAuth | kao_flask_auth/kao_auth.py | 1 | 1714 | from .auth_route_decorator import AuthRouteDecorator
from .Controllers import GetAuthJsonController, GetCurrentUserController, GetLoginController, GetRegisterController, GetUpdateUserController
from kao_decorators import proxy_for, lazy_property
@proxy_for('authRouteDecorator', ['requires_auth'])
class KaoAuth:
""" Helper class to use to generate the Auth funcitonality based on a provided User class """
def __init__(self, userCls, usernameField="username"):
""" Initialize with the User Class to use """
self.userCls = userCls
self.usernameField = usernameField
self.authRouteDecorator = AuthRouteDecorator(self.userCls)
@lazy_property
def JSONController(self):
""" Return the Auth JSON Controller class for the User model """
return GetAuthJsonController(self.requires_auth)
@lazy_property
def CurrentUserController(self):
""" Return the Current User Controller class for the User model """
return GetCurrentUserController(self.JSONController)
@lazy_property
def LoginController(self):
""" Return the Login Controller class for the User model """
return GetLoginController(self.userCls, self.usernameField)
@lazy_property
def RegisterController(self):
""" Return the Register Controller class for the User model """
return GetRegisterController(self.userCls, self.LoginController)
@lazy_property
def UpdateUserController(self):
""" Return the Update User Controller class for the User model """
return GetUpdateUserController(self.userCls, self.requires_auth) | mit |
Suranjandas7/SketchPad | RedditComments/redditcomments.py | 1 | 6472 | import sqlite3
import praw
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import configparser
class work():
def __init__(self, limitP, limitC, database_name, r_name, c_type):
self.title = ''
self.list_of_comments = []
self.limitP = limitP
self.limitC = limitC
self.post_id = ''
self.tags = ''
self.database_name = str(database_name)
self.r_name = str(r_name)
self.c_type = str(c_type)
def data_count(self):
def control(mode):
def shortcut(data):
container = []
for lines in data:
container.append(lines)
return len(container)
conn = sqlite3.connect(self.database_name)
c = conn.cursor()
data = c.execute("SELECT DISTINCT * from {}".format(mode))
count = shortcut(data)
c.close()
conn.close()
return count
no_of_comments = control('Comments')
no_of_posts = control('Posts')
print 'No of Posts - {}\nNo of comments - {}'.format(
no_of_posts,
no_of_comments)
def make_wordcloud(self, w, h):
conn = sqlite3.connect(self.database_name)
c = conn.cursor()
lines = c.execute("SELECT DISTINCT * from Comments")
all_text = []
s = ''
for l in lines:
all_text.append(l[0].encode('utf-8'))
for at in all_text:
s = s+at
wordcloud = WordCloud(
width=w,
height=h,
).generate(s)
c.close()
conn.close()
plt.imshow(wordcloud)
plt.axis('off')
plt.show()
def read(self):
f = open('output.txt', 'w')
conn = sqlite3.connect(self.database_name)
c = conn.cursor()
post_dict = {}
list_of_unique_posts = c.execute(
"SELECT DISTINCT Title, PostID from Posts"
)
for post in list_of_unique_posts:
post_dict[post[1]] = post[0]
for key in post_dict:
current_parent_id = (key,)
f.write('\n\n[Title : {}]\n\n'.format(post_dict[key].encode('utf-8')))
list_of_unique_comments = c.execute(
"SELECT DISTINCT * from Comments WHERE ParentId=?",
current_parent_id
)
for comment in list_of_unique_comments:
f.write('\n{}'.format(comment[0].encode('utf-8')))
f.write('\n---END COMMENT---\n')
f.close()
c.close()
conn.close()
def create_database(self):
conn = sqlite3.connect(str(self.database_name)+'.db')
c = conn.cursor()
c.execute('''CREATE TABLE Posts
(Title text, PostId text)'''
)
c.execute('''CREATE TABLE Comments
(Content text, ParentId text, CommentId text)'''
)
conn.commit()
c.close()
conn.close()
def process(self):
def addtodb(post_title, post_id, list_of_comments):
conn = sqlite3.connect(self.database_name)
c = conn.cursor()
post_insert = (
post_title,
post_id,
)
c.execute("INSERT INTO Posts VALUES (?,?)", post_insert)
for comment in list_of_comments:
comment_insert = (
comment[0],
post_id,
comment[1],
)
c.execute("INSERT INTO comments VALUES (?,?,?)", comment_insert)
conn.commit()
c.close()
conn.close()
reddit = praw.Reddit('bot1')
subreddit = reddit.subreddit(self.r_name)
counter = 0
for s in subreddit.hot(limit=self.limitP):
submission = s
submission.comment_sort = self.c_type
self.title = submission.title
self.post_id = submission.id
comments = s.comments
i=0
for comment in comments:
w_o_a = comment.body
comment_id = comment.id
if w_o_a == '[deleted]' or w_o_a == '[removed]':
continue
else:
output = [w_o_a, comment_id]
self.list_of_comments.append(output)
i+=1
if i == self.limitC:
break
#display(self.title, self.list_of_comments, self.post_id)
counter +=1
print '[Writing to database]\t {} out of {}'.format(
str(counter),
str(self.limitP))
addtodb(self.title, self.post_id, self.list_of_comments)
self.title = ''
self.list_of_comments = []
self.tags = ''
def main():
reader = configparser.ConfigParser()
reader.read('config.ini')
flag = False
while flag==False:
choice = str(raw_input('''
1 - Read
2 - Catch
3 - WordCloud
4 - DataCount
5 - Create Database
'Exit' - Exit
Enter Your Choice :
'''))
if choice == '1':
name_of_db = str(raw_input('Enter name of db : '))
sd = work(0,0, name_of_db, 'NA', 'NA')
sd.read()
elif choice == '2':
name_of_db = str(raw_input('Enter name of db : '))
subreddit_name = reader.get(name_of_db, 'subreddit')
comment_type = reader.get(name_of_db, 'comments')
sd = work(15,45, name_of_db, subreddit_name, comment_type)
sd.process()
elif choice == '3':
name_of_db = str(raw_input('Enter name of db : '))
sd = work(0,0, name_of_db, 'NA', 'NA')
sd.make_wordcloud(1920,1080)
elif choice == '4':
name_of_db = str(raw_input('Enter name of db : '))
sd = work(0,0, name_of_db, 'NA', 'NA')
sd.data_count()
elif choice == '5':
name_of_db = str(raw_input('Enter name of database: '))
sd = work(0,0,name_of_db, 'NA', 'NA')
sd.create_database()
elif choice == 'Exit':
flag = True
else:
print 'INVALID OPTIOEN'
if __name__ == '__main__':
main()
| lgpl-3.0 |
lucafavatella/intellij-community | python/lib/Lib/telnetlib.py | 80 | 21665 | """TELNET client class.
Based on RFC 854: TELNET Protocol Specification, by J. Postel and
J. Reynolds
Example:
>>> from telnetlib import Telnet
>>> tn = Telnet('www.python.org', 79) # connect to finger port
>>> tn.write('guido\r\n')
>>> print tn.read_all()
Login Name TTY Idle When Where
guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
>>>
Note that read_all() won't read until eof -- it just reads some data
-- but it guarantees to read at least one byte unless EOF is hit.
It is possible to pass a Telnet object to select.select() in order to
wait until more data is available. Note that in this case,
read_eager() may return '' even if there was data on the socket,
because the protocol negotiation may have eaten the data. This is why
EOFError is needed in some cases to distinguish between "no data" and
"connection closed" (since the socket also appears ready for reading
when it is closed).
To do:
- option negotiation
- timeout should be intrinsic to the connection object instead of an
option on one of the read calls only
"""
# Imported modules
import sys
import socket
import os
if os.name == 'java':
from select import cpython_compatible_select as select
else:
from select import select
del os
__all__ = ["Telnet"]
# Tunable parameters
DEBUGLEVEL = 0
# Telnet protocol defaults
TELNET_PORT = 23
# Telnet protocol characters (don't change)
IAC = chr(255) # "Interpret As Command"
DONT = chr(254)
DO = chr(253)
WONT = chr(252)
WILL = chr(251)
theNULL = chr(0)
SE = chr(240) # Subnegotiation End
NOP = chr(241) # No Operation
DM = chr(242) # Data Mark
BRK = chr(243) # Break
IP = chr(244) # Interrupt process
AO = chr(245) # Abort output
AYT = chr(246) # Are You There
EC = chr(247) # Erase Character
EL = chr(248) # Erase Line
GA = chr(249) # Go Ahead
SB = chr(250) # Subnegotiation Begin
# Telnet protocol options code (don't change)
# These ones all come from arpa/telnet.h
BINARY = chr(0) # 8-bit data path
ECHO = chr(1) # echo
RCP = chr(2) # prepare to reconnect
SGA = chr(3) # suppress go ahead
NAMS = chr(4) # approximate message size
STATUS = chr(5) # give status
TM = chr(6) # timing mark
RCTE = chr(7) # remote controlled transmission and echo
NAOL = chr(8) # negotiate about output line width
NAOP = chr(9) # negotiate about output page size
NAOCRD = chr(10) # negotiate about CR disposition
NAOHTS = chr(11) # negotiate about horizontal tabstops
NAOHTD = chr(12) # negotiate about horizontal tab disposition
NAOFFD = chr(13) # negotiate about formfeed disposition
NAOVTS = chr(14) # negotiate about vertical tab stops
NAOVTD = chr(15) # negotiate about vertical tab disposition
NAOLFD = chr(16) # negotiate about output LF disposition
XASCII = chr(17) # extended ascii character set
LOGOUT = chr(18) # force logout
BM = chr(19) # byte macro
DET = chr(20) # data entry terminal
SUPDUP = chr(21) # supdup protocol
SUPDUPOUTPUT = chr(22) # supdup output
SNDLOC = chr(23) # send location
TTYPE = chr(24) # terminal type
EOR = chr(25) # end or record
TUID = chr(26) # TACACS user identification
OUTMRK = chr(27) # output marking
TTYLOC = chr(28) # terminal location number
VT3270REGIME = chr(29) # 3270 regime
X3PAD = chr(30) # X.3 PAD
NAWS = chr(31) # window size
TSPEED = chr(32) # terminal speed
LFLOW = chr(33) # remote flow control
LINEMODE = chr(34) # Linemode option
XDISPLOC = chr(35) # X Display Location
OLD_ENVIRON = chr(36) # Old - Environment variables
AUTHENTICATION = chr(37) # Authenticate
ENCRYPT = chr(38) # Encryption option
NEW_ENVIRON = chr(39) # New - Environment variables
# the following ones come from
# http://www.iana.org/assignments/telnet-options
# Unfortunately, that document does not assign identifiers
# to all of them, so we are making them up
TN3270E = chr(40) # TN3270E
XAUTH = chr(41) # XAUTH
CHARSET = chr(42) # CHARSET
RSP = chr(43) # Telnet Remote Serial Port
COM_PORT_OPTION = chr(44) # Com Port Control Option
SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
TLS = chr(46) # Telnet Start TLS
KERMIT = chr(47) # KERMIT
SEND_URL = chr(48) # SEND-URL
FORWARD_X = chr(49) # FORWARD_X
PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
EXOPL = chr(255) # Extended-Options-List
NOOPT = chr(0)
class Telnet:
"""Telnet interface class.
An instance of this class represents a connection to a telnet
server. The instance is initially not connected; the open()
method must be used to establish a connection. Alternatively, the
host name and optional port number can be passed to the
constructor, too.
Don't try to reopen an already connected instance.
This class has many read_*() methods. Note that some of them
raise EOFError when the end of the connection is read, because
they can return an empty string for other reasons. See the
individual doc strings.
read_until(expected, [timeout])
Read until the expected string has been seen, or a timeout is
hit (default is no timeout); may block.
read_all()
Read all data until EOF; may block.
read_some()
Read at least one byte or EOF; may block.
read_very_eager()
Read all data available already queued or on the socket,
without blocking.
read_eager()
Read either data already queued or some data available on the
socket, without blocking.
read_lazy()
Read all data in the raw queue (processing it first), without
doing any socket I/O.
read_very_lazy()
Reads all data in the cooked queue, without doing any socket
I/O.
read_sb_data()
Reads available data between SB ... SE sequence. Don't block.
set_option_negotiation_callback(callback)
Each time a telnet option is read on the input flow, this callback
(if set) is called with the following parameters :
callback(telnet socket, command, option)
option will be chr(0) when there is no option.
No other action is done afterwards by telnetlib.
"""
def __init__(self, host=None, port=0):
"""Constructor.
When called without arguments, create an unconnected instance.
With a hostname argument, it connects the instance; a port
number is optional.
"""
self.debuglevel = DEBUGLEVEL
self.host = host
self.port = port
self.sock = None
self.rawq = ''
self.irawq = 0
self.cookedq = ''
self.eof = 0
self.iacseq = '' # Buffer for IAC sequence.
self.sb = 0 # flag for SB and SE sequence.
self.sbdataq = ''
self.option_callback = None
if host is not None:
self.open(host, port)
def open(self, host, port=0):
"""Connect to a host.
The optional second argument is the port number, which
defaults to the standard telnet port (23).
Don't try to reopen an already connected instance.
"""
self.eof = 0
if not port:
port = TELNET_PORT
self.host = host
self.port = port
msg = "getaddrinfo returns an empty list"
for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res
try:
self.sock = socket.socket(af, socktype, proto)
self.sock.connect(sa)
except socket.error, msg:
if self.sock:
self.sock.close()
self.sock = None
continue
break
if not self.sock:
raise socket.error, msg
def __del__(self):
"""Destructor -- close the connection."""
self.close()
def msg(self, msg, *args):
"""Print a debug message, when the debug level is > 0.
If extra arguments are present, they are substituted in the
message using the standard string formatting operator.
"""
if self.debuglevel > 0:
print 'Telnet(%s,%d):' % (self.host, self.port),
if args:
print msg % args
else:
print msg
def set_debuglevel(self, debuglevel):
"""Set the debug level.
The higher it is, the more debug output you get (on sys.stdout).
"""
self.debuglevel = debuglevel
def close(self):
"""Close the connection."""
if self.sock:
self.sock.close()
self.sock = 0
self.eof = 1
self.iacseq = ''
self.sb = 0
def get_socket(self):
"""Return the socket object used internally."""
return self.sock
def fileno(self):
"""Return the fileno() of the socket object used internally."""
return self.sock.fileno()
def write(self, buffer):
"""Write a string to the socket, doubling any IAC characters.
Can block if the connection is blocked. May raise
socket.error if the connection is closed.
"""
if IAC in buffer:
buffer = buffer.replace(IAC, IAC+IAC)
self.msg("send %s", `buffer`)
self.sock.sendall(buffer)
def read_until(self, match, timeout=None):
"""Read until a given string is encountered or until timeout.
When no match is found, return whatever is available instead,
possibly the empty string. Raise EOFError if the connection
is closed and no cooked data is available.
"""
n = len(match)
self.process_rawq()
i = self.cookedq.find(match)
if i >= 0:
i = i+n
buf = self.cookedq[:i]
self.cookedq = self.cookedq[i:]
return buf
s_reply = ([self], [], [])
s_args = s_reply
if timeout is not None:
s_args = s_args + (timeout,)
while not self.eof and select(*s_args) == s_reply:
i = max(0, len(self.cookedq)-n)
self.fill_rawq()
self.process_rawq()
i = self.cookedq.find(match, i)
if i >= 0:
i = i+n
buf = self.cookedq[:i]
self.cookedq = self.cookedq[i:]
return buf
return self.read_very_lazy()
def read_all(self):
"""Read all data until EOF; block until connection closed."""
self.process_rawq()
while not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = ''
return buf
def read_some(self):
"""Read at least one byte of cooked data unless EOF is hit.
Return '' if EOF is hit. Block if no data is immediately
available.
"""
self.process_rawq()
while not self.cookedq and not self.eof:
self.fill_rawq()
self.process_rawq()
buf = self.cookedq
self.cookedq = ''
return buf
def read_very_eager(self):
"""Read everything that's possible without blocking in I/O (eager).
Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.
"""
self.process_rawq()
while not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy()
def read_eager(self):
"""Read readily available data.
Raise EOFError if connection closed and no cooked data
available. Return '' if no cooked data available otherwise.
Don't block unless in the midst of an IAC sequence.
"""
self.process_rawq()
while not self.cookedq and not self.eof and self.sock_avail():
self.fill_rawq()
self.process_rawq()
return self.read_very_lazy()
def read_lazy(self):
"""Process and return data that's already in the queues (lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block
unless in the midst of an IAC sequence.
"""
self.process_rawq()
return self.read_very_lazy()
def read_very_lazy(self):
"""Return any data available in the cooked queue (very lazy).
Raise EOFError if connection closed and no data available.
Return '' if no cooked data available otherwise. Don't block.
"""
buf = self.cookedq
self.cookedq = ''
if not buf and self.eof and not self.rawq:
raise EOFError, 'telnet connection closed'
return buf
def read_sb_data(self):
"""Return any data available in the SB ... SE queue.
Return '' if no SB ... SE available. Should only be called
after seeing a SB or SE command. When a new SB command is
found, old unread SB data will be discarded. Don't block.
"""
buf = self.sbdataq
self.sbdataq = ''
return buf
def set_option_negotiation_callback(self, callback):
"""Provide a callback function called after each receipt of a telnet option."""
self.option_callback = callback
def process_rawq(self):
"""Transfer from raw queue to cooked queue.
Set self.eof when connection is closed. Don't block unless in
the midst of an IAC sequence.
"""
buf = ['', '']
try:
while self.rawq:
c = self.rawq_getchar()
if not self.iacseq:
if c == theNULL:
continue
if c == "\021":
continue
if c != IAC:
buf[self.sb] = buf[self.sb] + c
continue
else:
self.iacseq += c
elif len(self.iacseq) == 1:
'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
if c in (DO, DONT, WILL, WONT):
self.iacseq += c
continue
self.iacseq = ''
if c == IAC:
buf[self.sb] = buf[self.sb] + c
else:
if c == SB: # SB ... SE start.
self.sb = 1
self.sbdataq = ''
elif c == SE:
self.sb = 0
self.sbdataq = self.sbdataq + buf[1]
buf[1] = ''
if self.option_callback:
# Callback is supposed to look into
# the sbdataq
self.option_callback(self.sock, c, NOOPT)
else:
# We can't offer automatic processing of
# suboptions. Alas, we should not get any
# unless we did a WILL/DO before.
self.msg('IAC %d not recognized' % ord(c))
elif len(self.iacseq) == 2:
cmd = self.iacseq[1]
self.iacseq = ''
opt = c
if cmd in (DO, DONT):
self.msg('IAC %s %d',
cmd == DO and 'DO' or 'DONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + WONT + opt)
elif cmd in (WILL, WONT):
self.msg('IAC %s %d',
cmd == WILL and 'WILL' or 'WONT', ord(opt))
if self.option_callback:
self.option_callback(self.sock, cmd, opt)
else:
self.sock.sendall(IAC + DONT + opt)
except EOFError: # raised by self.rawq_getchar()
self.iacseq = '' # Reset on EOF
self.sb = 0
pass
self.cookedq = self.cookedq + buf[0]
self.sbdataq = self.sbdataq + buf[1]
def rawq_getchar(self):
"""Get next char from raw queue.
Block if no data is immediately available. Raise EOFError
when connection is closed.
"""
if not self.rawq:
self.fill_rawq()
if self.eof:
raise EOFError
c = self.rawq[self.irawq]
self.irawq = self.irawq + 1
if self.irawq >= len(self.rawq):
self.rawq = ''
self.irawq = 0
return c
def fill_rawq(self):
"""Fill raw queue from exactly one recv() system call.
Block if no data is immediately available. Set self.eof when
connection is closed.
"""
if self.irawq >= len(self.rawq):
self.rawq = ''
self.irawq = 0
# The buffer size should be fairly small so as to avoid quadratic
# behavior in process_rawq() above
buf = self.sock.recv(50)
self.msg("recv %s", `buf`)
self.eof = (not buf)
self.rawq = self.rawq + buf
def sock_avail(self):
"""Test whether data is available on the socket."""
return select([self], [], [], 0) == ([self], [], [])
def interact(self):
"""Interaction function, emulates a very dumb telnet client."""
if sys.platform == "win32":
self.mt_interact()
return
while 1:
rfd, wfd, xfd = select([self, sys.stdin], [], [])
if self in rfd:
try:
text = self.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
break
if text:
sys.stdout.write(text)
sys.stdout.flush()
if sys.stdin in rfd:
line = sys.stdin.readline()
if not line:
break
self.write(line)
def mt_interact(self):
"""Multithreaded version of interact()."""
import thread
thread.start_new_thread(self.listener, ())
while 1:
line = sys.stdin.readline()
if not line:
break
self.write(line)
def listener(self):
"""Helper for mt_interact() -- this executes in the other thread."""
while 1:
try:
data = self.read_eager()
except EOFError:
print '*** Connection closed by remote host ***'
return
if data:
sys.stdout.write(data)
else:
sys.stdout.flush()
def expect(self, list, timeout=None):
"""Read until one from a list of a regular expressions matches.
The first argument is a list of regular expressions, either
compiled (re.RegexObject instances) or uncompiled (strings).
The optional second argument is a timeout, in seconds; default
is no timeout.
Return a tuple of three items: the index in the list of the
first regular expression that matches; the match object
returned; and the text read up till and including the match.
If EOF is read and no text was read, raise EOFError.
Otherwise, when nothing matches, return (-1, None, text) where
text is the text received so far (may be the empty string if a
timeout happened).
If a regular expression ends with a greedy match (e.g. '.*')
or if more than one expression can match the same input, the
results are undeterministic, and may depend on the I/O timing.
"""
re = None
list = list[:]
indices = range(len(list))
for i in indices:
if not hasattr(list[i], "search"):
if not re: import re
list[i] = re.compile(list[i])
while 1:
self.process_rawq()
for i in indices:
m = list[i].search(self.cookedq)
if m:
e = m.end()
text = self.cookedq[:e]
self.cookedq = self.cookedq[e:]
return (i, m, text)
if self.eof:
break
if timeout is not None:
r, w, x = select([self.fileno()], [], [], timeout)
if not r:
break
self.fill_rawq()
text = self.read_very_lazy()
if not text and self.eof:
raise EOFError
return (-1, None, text)
def test():
"""Test program for telnetlib.
Usage: python telnetlib.py [-d] ... [host [port]]
Default host is localhost; default port is 23.
"""
debuglevel = 0
while sys.argv[1:] and sys.argv[1] == '-d':
debuglevel = debuglevel+1
del sys.argv[1]
host = 'localhost'
if sys.argv[1:]:
host = sys.argv[1]
port = 0
if sys.argv[2:]:
portstr = sys.argv[2]
try:
port = int(portstr)
except ValueError:
port = socket.getservbyname(portstr, 'tcp')
tn = Telnet()
tn.set_debuglevel(debuglevel)
tn.open(host, port)
tn.interact()
tn.close()
if __name__ == '__main__':
test()
| apache-2.0 |
simonwydooghe/ansible | test/units/modules/cloud/xenserver/FakeXenAPI.py | 94 | 1996 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2019, Bojan Vitnik <bvitnik@mainstream.rs>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
FAKE_API_VERSION = "1.1"
class Failure(Exception):
def __init__(self, details):
self.details = details
def __str__(self):
return str(self.details)
class Session(object):
def __init__(self, uri, transport=None, encoding=None, verbose=0,
allow_none=1, ignore_ssl=False):
self.transport = transport
self._session = None
self.last_login_method = None
self.last_login_params = None
self.API_version = FAKE_API_VERSION
def _get_api_version(self):
return FAKE_API_VERSION
def _login(self, method, params):
self._session = "OpaqueRef:fake-xenapi-session-ref"
self.last_login_method = method
self.last_login_params = params
self.API_version = self._get_api_version()
def _logout(self):
self._session = None
self.last_login_method = None
self.last_login_params = None
self.API_version = FAKE_API_VERSION
def xenapi_request(self, methodname, params):
if methodname.startswith('login'):
self._login(methodname, params)
return None
elif methodname == 'logout' or methodname == 'session.logout':
self._logout()
return None
else:
# Should be patched with mocker.patch().
return None
def __getattr__(self, name):
if name == 'handle':
return self._session
elif name == 'xenapi':
# Should be patched with mocker.patch().
return None
elif name.startswith('login') or name.startswith('slave_local'):
return lambda *params: self._login(name, params)
elif name == 'logout':
return self._logout
def xapi_local():
return Session("http://_var_lib_xcp_xapi/")
| gpl-3.0 |
rhndg/openedx | common/djangoapps/util/tests/test_db.py | 109 | 4539 | """Tests for util.db module."""
import ddt
import threading
import time
import unittest
from django.contrib.auth.models import User
from django.db import connection, IntegrityError
from django.db.transaction import commit_on_success, TransactionManagementError
from django.test import TestCase, TransactionTestCase
from util.db import commit_on_success_with_read_committed, generate_int_id
@ddt.ddt
class TransactionIsolationLevelsTestCase(TransactionTestCase):
"""
Tests the effects of changing transaction isolation level to READ COMMITTED instead of REPEATABLE READ.
Note: This TestCase only works with MySQL.
To run it on devstack:
1. Add TEST_RUNNER = 'django_nose.NoseTestSuiteRunner' to envs/devstack.py
2. Run "./manage.py lms --settings=devstack test util.tests.test_db"
"""
@ddt.data(
(commit_on_success, IntegrityError, None, True),
(commit_on_success_with_read_committed, type(None), False, True),
)
@ddt.unpack
def test_concurrent_requests(self, transaction_decorator, exception_class, created_in_1, created_in_2):
"""
Test that when isolation level is set to READ COMMITTED get_or_create()
for the same row in concurrent requests does not raise an IntegrityError.
"""
if connection.vendor != 'mysql':
raise unittest.SkipTest('Only works on MySQL.')
class RequestThread(threading.Thread):
""" A thread which runs a dummy view."""
def __init__(self, delay, **kwargs):
super(RequestThread, self).__init__(**kwargs)
self.delay = delay
self.status = {}
@transaction_decorator
def run(self):
"""A dummy view."""
try:
try:
User.objects.get(username='student', email='student@edx.org')
except User.DoesNotExist:
pass
else:
raise AssertionError('Did not raise User.DoesNotExist.')
if self.delay > 0:
time.sleep(self.delay)
__, created = User.objects.get_or_create(username='student', email='student@edx.org')
except Exception as exception: # pylint: disable=broad-except
self.status['exception'] = exception
else:
self.status['created'] = created
thread1 = RequestThread(delay=1)
thread2 = RequestThread(delay=0)
thread1.start()
thread2.start()
thread2.join()
thread1.join()
self.assertIsInstance(thread1.status.get('exception'), exception_class)
self.assertEqual(thread1.status.get('created'), created_in_1)
self.assertIsNone(thread2.status.get('exception'))
self.assertEqual(thread2.status.get('created'), created_in_2)
def test_transaction_nesting(self):
"""Test that the decorator raises an error if there are already more than 1 levels of nested transactions."""
if connection.vendor != 'mysql':
raise unittest.SkipTest('Only works on MySQL.')
def do_nothing():
"""Just return."""
return
commit_on_success_with_read_committed(do_nothing)()
with commit_on_success():
commit_on_success_with_read_committed(do_nothing)()
with self.assertRaises(TransactionManagementError):
with commit_on_success():
with commit_on_success():
commit_on_success_with_read_committed(do_nothing)()
@ddt.ddt
class GenerateIntIdTestCase(TestCase):
"""Tests for `generate_int_id`"""
@ddt.data(10)
def test_no_used_ids(self, times):
"""
Verify that we get a random integer within the specified range
when there are no used ids.
"""
minimum = 1
maximum = times
for i in range(times):
self.assertIn(generate_int_id(minimum, maximum), range(minimum, maximum + 1))
@ddt.data(10)
def test_used_ids(self, times):
"""
Verify that we get a random integer within the specified range
but not in a list of used ids.
"""
minimum = 1
maximum = times
used_ids = {2, 4, 6, 8}
for i in range(times):
int_id = generate_int_id(minimum, maximum, used_ids)
self.assertIn(int_id, list(set(range(minimum, maximum + 1)) - used_ids))
| agpl-3.0 |
AdaEne/CATMAID | django/applications/catmaid/management/commands/catmaid_check_db_integrity.py | 2 | 3831 | import sys
from django.core.management.base import BaseCommand, CommandError
from django.db import connection
from catmaid.models import Project
class Command(BaseCommand):
args = '<project_id> <project_id> ...'
help = '''
Tests the integrity of the specified projects with several sanity checks
'''
def handle(self, *args, **options):
if not len(args):
project_ids = Project.objects.all().values_list('id', flat=True)
else:
project_ids = map(int, args)
passed = True
for project_id in project_ids:
passed = passed and self.check_project(project_id)
if not passed:
sys.exit(1)
def check_project(self, project_id):
if not Project.objects.filter(id=project_id).exists():
raise CommandError('Project with id %s does not exist.' % project_id)
project_passed = True
self.stdout.write('Checking integrity of project %s' % project_id)
self.stdout.write('Check that no connected treenodes are in different skeletons...', ending='')
cursor = connection.cursor()
cursor.execute('''
SELECT tn1.id, tn2.id
FROM treenode tn1,
treenode tn2
WHERE tn2.id = tn1.parent_id
AND tn1.skeleton_id <> tn2.skeleton_id
AND tn1.project_id = %s
''', (project_id,))
if cursor.rowcount == 0:
self.stdout.write('OK')
else:
project_passed = False
self.stdout.write('')
self.stdout.write('FAILED: found %s rows (should be 0)' % cursor.rowcount)
self.stdout.write('Check that each skeleton has exactly one root node...', ending='')
cursor.execute('''
SELECT t.skeleton_id, count(*)
FROM treenode t
WHERE t.parent_id IS NULL
AND t.project_id = %s
GROUP BY t.skeleton_id
HAVING count(*) <> 1
''', (project_id,))
if cursor.rowcount == 0:
self.stdout.write('OK')
else:
project_passed = False
self.stdout.write('')
self.stdout.write('FAILED: found %s rows (should be 0)' % cursor.rowcount)
self.stdout.write('Check that all treenodes in a skeleton are connected to the root node...', ending='')
cursor.execute('''
SELECT DISTINCT skeleton_id
FROM treenode
WHERE project_id = %s
''', (project_id,))
skeleton_ids = cursor.fetchall()
test_passed = True
for skeleton_id in skeleton_ids:
cursor.execute('''
WITH RECURSIVE nodes (id) AS (
SELECT t.id
FROM treenode t
WHERE t.parent_id IS NULL
AND t.skeleton_id = %s
UNION ALL
SELECT t.id
FROM treenode t
JOIN nodes p ON t.parent_id = p.id)
SELECT t.id, t.skeleton_id
FROM treenode t
WHERE t.skeleton_id = %s
AND NOT EXISTS (SELECT n.id FROM nodes n WHERE n.id = t.id);
''', (skeleton_id, skeleton_id))
if cursor.rowcount:
if test_passed:
self.stdout.write('')
test_passed = False
project_passed = False
row = cursor.fetchone()
self.stdout.write('FAILED: node %s is skeleton %s has no path to root' % row)
if test_passed:
self.stdout.write('OK')
self.stdout.write('')
return project_passed
| gpl-3.0 |
flyballlabs/threatdetectionservice | api/venv/lib/python2.7/site-packages/pip/_vendor/packaging/_structures.py | 1152 | 1416 | # This file is dual licensed under the terms of the Apache License, Version
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
# for complete details.
from __future__ import absolute_import, division, print_function
class Infinity(object):
def __repr__(self):
return "Infinity"
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return False
def __le__(self, other):
return False
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self, other):
return not isinstance(other, self.__class__)
def __gt__(self, other):
return True
def __ge__(self, other):
return True
def __neg__(self):
return NegativeInfinity
Infinity = Infinity()
class NegativeInfinity(object):
def __repr__(self):
return "-Infinity"
def __hash__(self):
return hash(repr(self))
def __lt__(self, other):
return True
def __le__(self, other):
return True
def __eq__(self, other):
return isinstance(other, self.__class__)
def __ne__(self, other):
return not isinstance(other, self.__class__)
def __gt__(self, other):
return False
def __ge__(self, other):
return False
def __neg__(self):
return Infinity
NegativeInfinity = NegativeInfinity()
| apache-2.0 |
kapil-malik/airflow | airflow/hooks/hive_hooks.py | 11 | 15954 | from __future__ import print_function
from builtins import zip
from past.builtins import basestring
import csv
import logging
import re
import subprocess
from tempfile import NamedTemporaryFile
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from hive_service import ThriftHive
import pyhs2
from airflow.utils import AirflowException
from airflow.hooks.base_hook import BaseHook
from airflow.utils import TemporaryDirectory
class HiveCliHook(BaseHook):
"""
Simple wrapper around the hive CLI.
It also supports the ``beeline``
a lighter CLI that runs JDBC and is replacing the heavier
traditional CLI. To enable ``beeline``, set the use_beeline param in the
extra field of your connection as in ``{ "use_beeline": true }``
Note that you can also set default hive CLI parameters using the
``hive_cli_params`` to be used in your connection as in
``{"hive_cli_params": "-hiveconf mapred.job.tracker=some.jobtracker:444"}``
"""
def __init__(
self,
hive_cli_conn_id="hive_cli_default"):
conn = self.get_connection(hive_cli_conn_id)
self.hive_cli_params = conn.extra_dejson.get('hive_cli_params', '')
self.use_beeline = conn.extra_dejson.get('use_beeline', False)
self.conn = conn
def run_cli(self, hql, schema=None, verbose=True):
"""
Run an hql statement using the hive cli
>>> hh = HiveCliHook()
>>> result = hh.run_cli("USE airflow;")
>>> ("OK" in result)
True
"""
conn = self.conn
schema = schema or conn.schema
if schema:
hql = "USE {schema};\n{hql}".format(**locals())
with TemporaryDirectory(prefix='airflow_hiveop_') as tmp_dir:
with NamedTemporaryFile(dir=tmp_dir) as f:
f.write(hql)
f.flush()
fname = f.name
hive_bin = 'hive'
cmd_extra = []
if self.use_beeline:
hive_bin = 'beeline'
jdbc_url = (
"jdbc:hive2://"
"{0}:{1}/{2}"
";auth=noSasl"
).format(conn.host, conn.port, conn.schema)
cmd_extra += ['-u', jdbc_url]
if conn.login:
cmd_extra += ['-n', conn.login]
if conn.password:
cmd_extra += ['-p', conn.password]
cmd_extra += ['-p', conn.login]
hive_cmd = [hive_bin, '-f', fname] + cmd_extra
if self.hive_cli_params:
hive_params_list = self.hive_cli_params.split()
hive_cmd.extend(hive_params_list)
if verbose:
logging.info(" ".join(hive_cmd))
sp = subprocess.Popen(
hive_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=tmp_dir)
self.sp = sp
stdout = ''
for line in iter(sp.stdout.readline, ''):
stdout += line
if verbose:
logging.info(line.strip())
sp.wait()
if sp.returncode:
raise AirflowException(stdout)
return stdout
def test_hql(self, hql):
"""
Test an hql statement using the hive cli and EXPLAIN
"""
create, insert, other = [], [], []
for query in hql.split(';'): # naive
query_original = query
query = query.lower().strip()
if query.startswith('create table'):
create.append(query_original)
elif query.startswith(('set ',
'add jar ',
'create temporary function')):
other.append(query_original)
elif query.startswith('insert'):
insert.append(query_original)
other = ';'.join(other)
for query_set in [create, insert]:
for query in query_set:
query_preview = ' '.join(query.split())[:50]
logging.info("Testing HQL [{0} (...)]".format(query_preview))
if query_set == insert:
query = other + '; explain ' + query
else:
query = 'explain ' + query
try:
self.run_cli(query, verbose=False)
except AirflowException as e:
message = e.args[0].split('\n')[-2]
logging.info(message)
error_loc = re.search('(\d+):(\d+)', message)
if error_loc and error_loc.group(1).isdigit():
l = int(error_loc.group(1))
begin = max(l-2, 0)
end = min(l+3, len(query.split('\n')))
context = '\n'.join(query.split('\n')[begin:end])
logging.info("Context :\n {0}".format(context))
else:
logging.info("SUCCESS")
def load_file(
self,
filepath,
table,
delimiter=",",
field_dict=None,
create=True,
overwrite=True,
partition=None,
recreate=False):
"""
Loads a local file into Hive
Note that the table generated in Hive uses ``STORED AS textfile``
which isn't the most efficient serialization format. If a
large amount of data is loaded and/or if the tables gets
queried considerably, you may want to use this operator only to
stage the data into a temporary table before loading it into its
final destination using a ``HiveOperator``.
:param table: target Hive table, use dot notation to target a
specific database
:type table: str
:param create: whether to create the table if it doesn't exist
:type create: bool
:param recreate: whether to drop and recreate the table at every
execution
:type recreate: bool
:param partition: target partition as a dict of partition columns
and values
:type partition: dict
:param delimiter: field delimiter in the file
:type delimiter: str
"""
hql = ''
if recreate:
hql += "DROP TABLE IF EXISTS {table};\n"
if create or recreate:
fields = ",\n ".join(
[k + ' ' + v for k, v in field_dict.items()])
hql += "CREATE TABLE IF NOT EXISTS {table} (\n{fields})\n"
if partition:
pfields = ",\n ".join(
[p + " STRING" for p in partition])
hql += "PARTITIONED BY ({pfields})\n"
hql += "ROW FORMAT DELIMITED\n"
hql += "FIELDS TERMINATED BY '{delimiter}'\n"
hql += "STORED AS textfile;"
hql = hql.format(**locals())
logging.info(hql)
self.run_cli(hql)
hql = "LOAD DATA LOCAL INPATH '{filepath}' "
if overwrite:
hql += "OVERWRITE "
hql += "INTO TABLE {table} "
if partition:
pvals = ", ".join(
["{0}='{1}'".format(k, v) for k, v in partition.items()])
hql += "PARTITION ({pvals});"
hql = hql.format(**locals())
logging.info(hql)
self.run_cli(hql)
def kill(self):
if hasattr(self, 'sp'):
if self.sp.poll() is None:
print("Killing the Hive job")
self.sp.kill()
class HiveMetastoreHook(BaseHook):
'''
Wrapper to interact with the Hive Metastore
'''
def __init__(self, metastore_conn_id='metastore_default'):
self.metastore_conn = self.get_connection(metastore_conn_id)
self.metastore = self.get_metastore_client()
def __getstate__(self):
# This is for pickling to work despite the thirft hive client not
# being pickable
d = dict(self.__dict__)
del d['metastore']
return d
def __setstate__(self, d):
self.__dict__.update(d)
self.__dict__['metastore'] = self.get_metastore_client()
def get_metastore_client(self):
'''
Returns a Hive thrift client.
'''
ms = self.metastore_conn
transport = TSocket.TSocket(ms.host, ms.port)
transport = TTransport.TBufferedTransport(transport)
protocol = TBinaryProtocol.TBinaryProtocol(transport)
return ThriftHive.Client(protocol)
def get_conn(self):
return self.metastore
def check_for_partition(self, schema, table, partition):
'''
Checks whether a partition exists
>>> hh = HiveMetastoreHook()
>>> t = 'static_babynames_partitioned'
>>> hh.check_for_partition('airflow', t, "ds='2015-01-01'")
True
'''
self.metastore._oprot.trans.open()
partitions = self.metastore.get_partitions_by_filter(
schema, table, partition, 1)
self.metastore._oprot.trans.close()
if partitions:
return True
else:
return False
def get_table(self, table_name, db='default'):
'''
Get a metastore table object
>>> hh = HiveMetastoreHook()
>>> t = hh.get_table(db='airflow', table_name='static_babynames')
>>> t.tableName
'static_babynames'
>>> [col.name for col in t.sd.cols]
['state', 'year', 'name', 'gender', 'num']
'''
self.metastore._oprot.trans.open()
if db == 'default' and '.' in table_name:
db, table_name = table_name.split('.')[:2]
table = self.metastore.get_table(dbname=db, tbl_name=table_name)
self.metastore._oprot.trans.close()
return table
def get_tables(self, db, pattern='*'):
'''
Get a metastore table object
'''
self.metastore._oprot.trans.open()
tables = self.metastore.get_tables(db_name=db, pattern=pattern)
objs = self.metastore.get_table_objects_by_name(db, tables)
self.metastore._oprot.trans.close()
return objs
def get_databases(self, pattern='*'):
'''
Get a metastore table object
'''
self.metastore._oprot.trans.open()
dbs = self.metastore.get_databases(pattern)
self.metastore._oprot.trans.close()
return dbs
def get_partitions(
self, schema, table_name, filter=None):
'''
Returns a list of all partitions in a table. Works only
for tables with less than 32767 (java short max val).
For subpartitioned table, the number might easily exceed this.
>>> hh = HiveMetastoreHook()
>>> t = 'static_babynames_partitioned'
>>> parts = hh.get_partitions(schema='airflow', table_name=t)
>>> len(parts)
1
>>> parts
[{'ds': '2015-01-01'}]
'''
self.metastore._oprot.trans.open()
table = self.metastore.get_table(dbname=schema, tbl_name=table_name)
if len(table.partitionKeys) == 0:
raise AirflowException("The table isn't partitioned")
else:
if filter:
parts = self.metastore.get_partitions_by_filter(
db_name=schema, tbl_name=table_name,
filter=filter, max_parts=32767)
else:
parts = self.metastore.get_partitions(
db_name=schema, tbl_name=table_name, max_parts=32767)
self.metastore._oprot.trans.close()
pnames = [p.name for p in table.partitionKeys]
return [dict(zip(pnames, p.values)) for p in parts]
def max_partition(self, schema, table_name, field=None, filter=None):
'''
Returns the maximum value for all partitions in a table. Works only
for tables that have a single partition key. For subpartitioned
table, we recommend using signal tables.
>>> hh = HiveMetastoreHook()
>>> t = 'static_babynames_partitioned'
>>> hh.max_partition(schema='airflow', table_name=t)
'2015-01-01'
'''
parts = self.get_partitions(schema, table_name, filter)
if not parts:
return None
elif len(parts[0]) == 1:
field = list(parts[0].keys())[0]
elif not field:
raise AirflowException(
"Please specify the field you want the max "
"value for")
return max([p[field] for p in parts])
class HiveServer2Hook(BaseHook):
'''
Wrapper around the pyhs2 library
Note that the default authMechanism is NOSASL, to override it you
can specify it in the ``extra`` of your connection in the UI as in
``{"authMechanism": "PLAIN"}``. Refer to the pyhs2 for more details.
'''
def __init__(self, hiveserver2_conn_id='hiveserver2_default'):
self.hiveserver2_conn_id = hiveserver2_conn_id
def get_conn(self):
db = self.get_connection(self.hiveserver2_conn_id)
return pyhs2.connect(
host=db.host,
port=db.port,
authMechanism=db.extra_dejson.get('authMechanism', 'NOSASL'),
user=db.login,
database=db.schema or 'default')
def get_results(self, hql, schema='default', arraysize=1000):
with self.get_conn() as conn:
if isinstance(hql, basestring):
hql = [hql]
results = {
'data': [],
'header': [],
}
for statement in hql:
with conn.cursor() as cur:
cur.execute(statement)
records = cur.fetchall()
if records:
results = {
'data': records,
'header': cur.getSchema(),
}
return results
def to_csv(self, hql, csv_filepath, schema='default'):
schema = schema or 'default'
with self.get_conn() as conn:
with conn.cursor() as cur:
logging.info("Running query: " + hql)
cur.execute(hql)
schema = cur.getSchema()
with open(csv_filepath, 'w') as f:
writer = csv.writer(f)
writer.writerow([c['columnName'] for c in cur.getSchema()])
i = 0
while cur.hasMoreRows:
rows = [row for row in cur.fetchmany() if row]
writer.writerows(rows)
i += len(rows)
logging.info("Written {0} rows so far.".format(i))
logging.info("Done. Loaded a total of {0} rows.".format(i))
def get_records(self, hql, schema='default'):
'''
Get a set of records from a Hive query.
>>> hh = HiveServer2Hook()
>>> sql = "SELECT * FROM airflow.static_babynames LIMIT 100"
>>> len(hh.get_records(sql))
100
'''
return self.get_results(hql, schema=schema)['data']
def get_pandas_df(self, hql, schema='default'):
'''
Get a pandas dataframe from a Hive query
>>> hh = HiveServer2Hook()
>>> sql = "SELECT * FROM airflow.static_babynames LIMIT 100"
>>> df = hh.get_pandas_df(sql)
>>> len(df.index)
100
'''
import pandas as pd
res = self.get_results(hql, schema=schema)
df = pd.DataFrame(res['data'])
df.columns = [c['columnName'] for c in res['header']]
return df
| apache-2.0 |
dfang/odoo | addons/mrp/tests/test_multicompany.py | 22 | 1397 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.tests import common
class TestMrpMulticompany(common.TransactionCase):
def setUp(self):
super(TestMrpMulticompany, self).setUp()
group_user = self.env.ref('base.group_user')
group_stock_manager = self.env.ref('stock.group_stock_manager')
company_2 = self.env.ref('stock.res_company_1')
self.multicompany_user_id = self.env['res.users'].create({
'name': 'multicomp',
'login': 'multicomp',
'groups_id': [(6, 0, [group_user.id, group_stock_manager.id])],
'company_id': company_2.id,
'company_ids': [(6, 0, [company_2.id])]
})
def test_00_multicompany_user(self):
"""check no error on getting default mrp.production values in multicompany setting"""
StockLocation = self.env['stock.location'].sudo(self.multicompany_user_id)
fields = ['location_src_id', 'location_dest_id']
defaults = StockLocation.default_get(['location_id', 'location_dest_id', 'type'])
for field in fields:
if defaults.get(field):
try:
StockLocation.check_access_rule([defaults[field]], 'read')
except Exception, exc:
assert False, "unreadable location %s: %s" % (field, exc)
| agpl-3.0 |
xpansa/stock-logistics-workflow | picking_dispatch/stock.py | 17 | 8202 | # -*- coding: utf-8 -*-
##############################################################################
#
# Author: Alexandre Fayolle
# Copyright 2012-2014 Camptocamp SA
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import logging
from openerp.osv import orm, fields
_logger = logging.getLogger(__name__)
class StockMove(orm.Model):
_inherit = 'stock.move'
_columns = {
'dispatch_id': fields.many2one(
'picking.dispatch', 'Dispatch',
select=True,
help='who this move is dispatched to'),
}
def copy_data(self, cr, uid, id, default=None, context=None):
if default is None:
default = {}
default = default.copy()
default['dispatch_id'] = False
return super(StockMove, self).\
copy_data(cr, uid, id, default=default, context=context)
def do_partial(self, cr, uid, ids, partial_datas, context=None):
"""
in addition to what the original method does, create backorder
picking.dispatches and set the state of picing.dispatch
according to the state of moves state
"""
move_obj = self.pool.get('stock.move')
dispatch_obj = self.pool.get('picking.dispatch')
_logger.debug('partial stock.moves %s %s', ids, partial_datas)
complete_move_ids = super(StockMove, self).do_partial(cr, uid, ids,
partial_datas,
context)
# in complete_move_ids, we have:
# * moves that were fully processed
# * newly created moves (the processed part of partially processed
# moves) belonging to the same dispatch as the original move
# so the difference between the original set of moves and the
# complete_moves is the set of unprocessed moves
unprocessed_move_ids = set(ids) - set(complete_move_ids)
_logger.debug(
'partial stock.moves: complete_move_ids %s, '
'unprocessed_move_ids %s',
complete_move_ids, unprocessed_move_ids)
# unprocessed moves are still linked to the dispatch : this dispatch
# must not be marked as Done
unfinished_dispatch_ids = {}
for move in move_obj.browse(cr, uid, list(unprocessed_move_ids),
context=context):
if not move.dispatch_id:
continue
# value will be set later to a new dispatch
unfinished_dispatch_ids[move.dispatch_id.id] = None
maybe_finished_dispatches = {}
for move in move_obj.browse(cr, uid, complete_move_ids,
context=context):
if not move.dispatch_id:
continue
dispatch_id = move.dispatch_id.id
if dispatch_id in unfinished_dispatch_ids:
# the dispatch was partially processed: we need to link the
# move to a new dispatch containing only fully processed moves
if unfinished_dispatch_ids[dispatch_id] is None:
# create a new dispatch, and record its id
_logger.debug(
'create backorder picking.dispatch of %s', dispatch_id)
new_dispatch_id = dispatch_obj.copy(cr, uid, dispatch_id, {
'backorder_id': dispatch_id,
})
unfinished_dispatch_ids[dispatch_id] = new_dispatch_id
dispatch_id = unfinished_dispatch_ids[dispatch_id]
maybe_finished_dispatches.setdefault(
dispatch_id, []).append(move.id)
for dispatch_id, move_ids in maybe_finished_dispatches.iteritems():
move_obj.write(cr, uid, move_ids, {'dispatch_id': dispatch_id})
dispatch_obj.check_finished(
cr, uid, list(maybe_finished_dispatches), context)
dispatch_obj.write(
cr, uid, list(unfinished_dispatch_ids), {'state': 'assigned'})
return complete_move_ids
def action_cancel(self, cr, uid, ids, context=None):
"""
in addition to what the method in the parent class does,
cancel the dispatches for which all moves where cancelled
"""
_logger.debug('cancel stock.moves %s', ids)
status = super(StockMove, self).action_cancel(cr, uid, ids, context)
if not ids:
return True
dispatch_obj = self.pool.get('picking.dispatch')
dispatches = set()
for move in self.browse(cr, uid, ids, context=context):
if move.dispatch_id:
dispatches.add(move.dispatch_id.id)
for dispatch in dispatch_obj.browse(cr, uid, list(dispatches),
context=context):
if any(move.state != 'cancel' for move in dispatch.move_ids):
dispatches.remove(dispatch.id)
if dispatches:
_logger.debug(
'set state to cancel for picking.dispatch %s',
list(dispatches))
dispatch_obj.write(
cr, uid, list(dispatches), {'state': 'cancel'}, context)
return status
def action_done(self, cr, uid, ids, context=None):
"""
in addition to the parent method does, set the dispatch done if all
moves are done or canceled
"""
_logger.debug('done stock.moves %s', ids)
status = super(StockMove, self).action_done(cr, uid, ids, context)
if not ids:
return True
dispatch_obj = self.pool.get('picking.dispatch')
dispatches = set()
for move in self.browse(cr, uid, ids, context=context):
if move.dispatch_id:
dispatches.add(move.dispatch_id.id)
dispatch_obj.check_finished(cr, uid, list(dispatches), context)
return status
class StockPicking(orm.Model):
_inherit = "stock.picking"
def _get_related_dispatch(self, cr, uid, ids, field_names, arg=None,
context=None):
result = {}
if not ids:
return result
for pick_id in ids:
result[pick_id] = []
sql = ("SELECT DISTINCT sm.picking_id, sm.dispatch_id "
"FROM stock_move sm "
"WHERE sm.picking_id in %s AND sm.dispatch_id is NOT NULL")
cr.execute(sql, (tuple(ids),))
res = cr.fetchall()
for picking_id, dispatch_id in res:
result[picking_id].append(dispatch_id)
return result
def _search_dispatch_pickings(self, cr, uid, obj, name, args,
context=None):
if not len(args):
return []
picking_ids = set()
for field, symbol, value in args:
move_obj = self.pool['stock.move']
move_ids = move_obj.search(cr, uid,
[('dispatch_id', symbol, value)],
context=context)
for move in move_obj.browse(cr, uid, move_ids, context=context):
picking_ids.add(move.picking_id.id)
return [('id', 'in', list(picking_ids))]
_columns = {
'related_dispatch_ids': fields.function(
_get_related_dispatch, fnct_search=_search_dispatch_pickings,
type='one2many', relation='picking.dispatch',
string='Related Dispatch Picking'),
}
| agpl-3.0 |
noironetworks/neutron | neutron/tests/unit/plugins/ml2/drivers/test_helpers.py | 3 | 5946 | # Copyright (c) 2014 Thales Services SAS
# 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 mock
from neutron_lib import context
from oslo_db import exception as exc
from sqlalchemy.orm import query
from neutron.plugins.ml2.drivers import type_vlan
from neutron.tests.unit import testlib_api
TENANT_NET = 'phys_net2'
VLAN_MIN = 200
VLAN_MAX = 209
VLAN_OUTSIDE = 100
NETWORK_VLAN_RANGES = {
TENANT_NET: [(VLAN_MIN, VLAN_MAX)],
}
class HelpersTest(testlib_api.SqlTestCase):
def setUp(self):
super(HelpersTest, self).setUp()
self.driver = type_vlan.VlanTypeDriver()
self.driver.network_vlan_ranges = NETWORK_VLAN_RANGES
self.driver._sync_vlan_allocations()
self.context = context.get_admin_context()
def check_raw_segment(self, expected, observed):
for key, value in expected.items():
self.assertEqual(value, observed[key])
def test_primary_keys(self):
self.assertEqual(set(['physical_network', 'vlan_id']),
self.driver.primary_keys)
def test_allocate_specific_unallocated_segment_in_pools(self):
expected = dict(physical_network=TENANT_NET, vlan_id=VLAN_MIN)
observed = self.driver.allocate_fully_specified_segment(self.context,
**expected)
self.check_raw_segment(expected, observed)
def test_allocate_specific_allocated_segment_in_pools(self):
raw_segment = dict(physical_network=TENANT_NET, vlan_id=VLAN_MIN)
self.driver.allocate_fully_specified_segment(self.context,
**raw_segment)
observed = self.driver.allocate_fully_specified_segment(self.context,
**raw_segment)
self.assertIsNone(observed)
def test_allocate_specific_finally_allocated_segment_in_pools(self):
# Test case: allocate a specific unallocated segment in pools but
# the segment is allocated concurrently between select and update
raw_segment = dict(physical_network=TENANT_NET, vlan_id=VLAN_MIN)
with mock.patch.object(query.Query, 'update', return_value=0):
observed = self.driver.allocate_fully_specified_segment(
self.context, **raw_segment)
self.assertIsNone(observed)
def test_allocate_specific_unallocated_segment_outside_pools(self):
expected = dict(physical_network=TENANT_NET, vlan_id=VLAN_OUTSIDE)
observed = self.driver.allocate_fully_specified_segment(self.context,
**expected)
self.check_raw_segment(expected, observed)
def test_allocate_specific_allocated_segment_outside_pools(self):
raw_segment = dict(physical_network=TENANT_NET, vlan_id=VLAN_OUTSIDE)
self.driver.allocate_fully_specified_segment(self.context,
**raw_segment)
observed = self.driver.allocate_fully_specified_segment(self.context,
**raw_segment)
self.assertIsNone(observed)
def test_allocate_specific_finally_unallocated_segment_outside_pools(self):
# Test case: allocate a specific allocated segment in pools but
# the segment is concurrently unallocated after select or update
expected = dict(physical_network=TENANT_NET, vlan_id=VLAN_MIN)
with mock.patch.object(self.driver.model, 'save'):
observed = self.driver.allocate_fully_specified_segment(
self.context, **expected)
self.check_raw_segment(expected, observed)
def test_allocate_partial_segment_without_filters(self):
expected = dict(physical_network=TENANT_NET)
observed = self.driver.allocate_partially_specified_segment(
self.context)
self.check_raw_segment(expected, observed)
def test_allocate_partial_segment_with_filter(self):
expected = dict(physical_network=TENANT_NET)
observed = self.driver.allocate_partially_specified_segment(
self.context, **expected)
self.check_raw_segment(expected, observed)
def test_allocate_partial_segment_no_resource_available(self):
for i in range(VLAN_MIN, VLAN_MAX + 1):
self.driver.allocate_partially_specified_segment(self.context)
observed = self.driver.allocate_partially_specified_segment(
self.context)
self.assertIsNone(observed)
def test_allocate_partial_segment_outside_pools(self):
raw_segment = dict(physical_network='other_phys_net')
observed = self.driver.allocate_partially_specified_segment(
self.context, **raw_segment)
self.assertIsNone(observed)
def test_allocate_partial_segment_first_attempt_fails(self):
expected = dict(physical_network=TENANT_NET)
with mock.patch.object(query.Query, 'update', side_effect=[0, 1]):
self.assertRaises(
exc.RetryRequest,
self.driver.allocate_partially_specified_segment,
self.context, **expected)
observed = self.driver.allocate_partially_specified_segment(
self.context, **expected)
self.check_raw_segment(expected, observed)
| apache-2.0 |
sgruszka/iwlegacy | tools/perf/scripts/python/syscall-counts-by-pid.py | 11180 | 1927 | # system call counts, by pid
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Displays system-wide system call totals, broken down by syscall.
# If a [comm] arg is specified, only syscalls called by [comm] are displayed.
import os, sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import syscall_name
usage = "perf script -s syscall-counts-by-pid.py [comm]\n";
for_comm = None
for_pid = None
if len(sys.argv) > 2:
sys.exit(usage)
if len(sys.argv) > 1:
try:
for_pid = int(sys.argv[1])
except:
for_comm = sys.argv[1]
syscalls = autodict()
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
print_syscall_totals()
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
if (for_comm and common_comm != for_comm) or \
(for_pid and common_pid != for_pid ):
return
try:
syscalls[common_comm][common_pid][id] += 1
except TypeError:
syscalls[common_comm][common_pid][id] = 1
def print_syscall_totals():
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events by comm/pid:\n\n",
print "%-40s %10s\n" % ("comm [pid]/syscalls", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"----------"),
comm_keys = syscalls.keys()
for comm in comm_keys:
pid_keys = syscalls[comm].keys()
for pid in pid_keys:
print "\n%s [%d]\n" % (comm, pid),
id_keys = syscalls[comm][pid].keys()
for id, val in sorted(syscalls[comm][pid].iteritems(), \
key = lambda(k, v): (v, k), reverse = True):
print " %-38s %10d\n" % (syscall_name(id), val),
| gpl-2.0 |
ant1b/Planets4X | pythonanywhere_app/static/Brython3.0.0-20141104-210332/Lib/unittest/test/test_loader.py | 738 | 49593 | import sys
import types
import unittest
class Test_TestLoader(unittest.TestCase):
### Tests for TestLoader.loadTestsFromTestCase
################################################################
# "Return a suite of all tests cases contained in the TestCase-derived
# class testCaseClass"
def test_loadTestsFromTestCase(self):
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
tests = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
loader = unittest.TestLoader()
self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
# "Return a suite of all tests cases contained in the TestCase-derived
# class testCaseClass"
#
# Make sure it does the right thing even if no tests were found
def test_loadTestsFromTestCase__no_matches(self):
class Foo(unittest.TestCase):
def foo_bar(self): pass
empty_suite = unittest.TestSuite()
loader = unittest.TestLoader()
self.assertEqual(loader.loadTestsFromTestCase(Foo), empty_suite)
# "Return a suite of all tests cases contained in the TestCase-derived
# class testCaseClass"
#
# What happens if loadTestsFromTestCase() is given an object
# that isn't a subclass of TestCase? Specifically, what happens
# if testCaseClass is a subclass of TestSuite?
#
# This is checked for specifically in the code, so we better add a
# test for it.
def test_loadTestsFromTestCase__TestSuite_subclass(self):
class NotATestCase(unittest.TestSuite):
pass
loader = unittest.TestLoader()
try:
loader.loadTestsFromTestCase(NotATestCase)
except TypeError:
pass
else:
self.fail('Should raise TypeError')
# "Return a suite of all tests cases contained in the TestCase-derived
# class testCaseClass"
#
# Make sure loadTestsFromTestCase() picks up the default test method
# name (as specified by TestCase), even though the method name does
# not match the default TestLoader.testMethodPrefix string
def test_loadTestsFromTestCase__default_method_name(self):
class Foo(unittest.TestCase):
def runTest(self):
pass
loader = unittest.TestLoader()
# This has to be false for the test to succeed
self.assertFalse('runTest'.startswith(loader.testMethodPrefix))
suite = loader.loadTestsFromTestCase(Foo)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [Foo('runTest')])
################################################################
### /Tests for TestLoader.loadTestsFromTestCase
### Tests for TestLoader.loadTestsFromModule
################################################################
# "This method searches `module` for classes derived from TestCase"
def test_loadTestsFromModule__TestCase_subclass(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromModule(m)
self.assertIsInstance(suite, loader.suiteClass)
expected = [loader.suiteClass([MyTestCase('test')])]
self.assertEqual(list(suite), expected)
# "This method searches `module` for classes derived from TestCase"
#
# What happens if no tests are found (no TestCase instances)?
def test_loadTestsFromModule__no_TestCase_instances(self):
m = types.ModuleType('m')
loader = unittest.TestLoader()
suite = loader.loadTestsFromModule(m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [])
# "This method searches `module` for classes derived from TestCase"
#
# What happens if no tests are found (TestCases instances, but no tests)?
def test_loadTestsFromModule__no_TestCase_tests(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromModule(m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [loader.suiteClass()])
# "This method searches `module` for classes derived from TestCase"s
#
# What happens if loadTestsFromModule() is given something other
# than a module?
#
# XXX Currently, it succeeds anyway. This flexibility
# should either be documented or loadTestsFromModule() should
# raise a TypeError
#
# XXX Certain people are using this behaviour. We'll add a test for it
def test_loadTestsFromModule__not_a_module(self):
class MyTestCase(unittest.TestCase):
def test(self):
pass
class NotAModule(object):
test_2 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromModule(NotAModule)
reference = [unittest.TestSuite([MyTestCase('test')])]
self.assertEqual(list(suite), reference)
# Check that loadTestsFromModule honors (or not) a module
# with a load_tests function.
def test_loadTestsFromModule__load_tests(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
load_tests_args = []
def load_tests(loader, tests, pattern):
self.assertIsInstance(tests, unittest.TestSuite)
load_tests_args.extend((loader, tests, pattern))
return tests
m.load_tests = load_tests
loader = unittest.TestLoader()
suite = loader.loadTestsFromModule(m)
self.assertIsInstance(suite, unittest.TestSuite)
self.assertEqual(load_tests_args, [loader, suite, None])
load_tests_args = []
suite = loader.loadTestsFromModule(m, use_load_tests=False)
self.assertEqual(load_tests_args, [])
def test_loadTestsFromModule__faulty_load_tests(self):
m = types.ModuleType('m')
def load_tests(loader, tests, pattern):
raise TypeError('some failure')
m.load_tests = load_tests
loader = unittest.TestLoader()
suite = loader.loadTestsFromModule(m)
self.assertIsInstance(suite, unittest.TestSuite)
self.assertEqual(suite.countTestCases(), 1)
test = list(suite)[0]
self.assertRaisesRegex(TypeError, "some failure", test.m)
################################################################
### /Tests for TestLoader.loadTestsFromModule()
### Tests for TestLoader.loadTestsFromName()
################################################################
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# Is ValueError raised in response to an empty name?
def test_loadTestsFromName__empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('')
except ValueError as e:
self.assertEqual(str(e), "Empty module name")
else:
self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when the name contains invalid characters?
def test_loadTestsFromName__malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise ValueError or ImportError?
try:
loader.loadTestsFromName('abc () //')
except ValueError:
pass
except ImportError:
pass
else:
self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve ... to a
# module"
#
# What happens when a module by that name can't be found?
def test_loadTestsFromName__unknown_module_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('sdasfasfasdf')
except ImportError as e:
self.assertEqual(str(e), "No module named 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise ImportError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when the module is found, but the attribute can't?
def test_loadTestsFromName__unknown_attr_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('unittest.sdasfasfasdf')
except AttributeError as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when we provide the module, but the attribute can't be
# found?
def test_loadTestsFromName__relative_unknown_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('sdasfasfasdf', unittest)
except AttributeError as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# Does loadTestsFromName raise ValueError when passed an empty
# name relative to a provided module?
#
# XXX Should probably raise a ValueError instead of an AttributeError
def test_loadTestsFromName__relative_empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('', unittest)
except AttributeError as e:
pass
else:
self.fail("Failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens when an impossible name is given, relative to the provided
# `module`?
def test_loadTestsFromName__relative_malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise AttributeError or ValueError?
try:
loader.loadTestsFromName('abc () //', unittest)
except ValueError:
pass
except AttributeError:
pass
else:
self.fail("TestLoader.loadTestsFromName failed to raise ValueError")
# "The method optionally resolves name relative to the given module"
#
# Does loadTestsFromName raise TypeError when the `module` argument
# isn't a module object?
#
# XXX Accepts the not-a-module object, ignorning the object's type
# This should raise an exception or the method name should be changed
#
# XXX Some people are relying on this, so keep it for now
def test_loadTestsFromName__relative_not_a_module(self):
class MyTestCase(unittest.TestCase):
def test(self):
pass
class NotAModule(object):
test_2 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromName('test_2', NotAModule)
reference = [MyTestCase('test')]
self.assertEqual(list(suite), reference)
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# Does it raise an exception if the name resolves to an invalid
# object?
def test_loadTestsFromName__relative_bad_object(self):
m = types.ModuleType('m')
m.testcase_1 = object()
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('testcase_1', m)
except TypeError:
pass
else:
self.fail("Should have raised TypeError")
# "The specifier name is a ``dotted name'' that may
# resolve either to ... a test case class"
def test_loadTestsFromName__relative_TestCase_subclass(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromName('testcase_1', m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [MyTestCase('test')])
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
def test_loadTestsFromName__relative_TestSuite(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testsuite = unittest.TestSuite([MyTestCase('test')])
loader = unittest.TestLoader()
suite = loader.loadTestsFromName('testsuite', m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [MyTestCase('test')])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a test method within a test case class"
def test_loadTestsFromName__relative_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromName('testcase_1.test', m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [MyTestCase('test')])
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# Does loadTestsFromName() raise the proper exception when trying to
# resolve "a test method within a test case class" that doesn't exist
# for the given name (relative to a provided module)?
def test_loadTestsFromName__relative_invalid_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
try:
loader.loadTestsFromName('testcase_1.testfoo', m)
except AttributeError as e:
self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
else:
self.fail("Failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a ... TestSuite instance"
def test_loadTestsFromName__callable__TestSuite(self):
m = types.ModuleType('m')
testcase_1 = unittest.FunctionTestCase(lambda: None)
testcase_2 = unittest.FunctionTestCase(lambda: None)
def return_TestSuite():
return unittest.TestSuite([testcase_1, testcase_2])
m.return_TestSuite = return_TestSuite
loader = unittest.TestLoader()
suite = loader.loadTestsFromName('return_TestSuite', m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [testcase_1, testcase_2])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a TestCase ... instance"
def test_loadTestsFromName__callable__TestCase_instance(self):
m = types.ModuleType('m')
testcase_1 = unittest.FunctionTestCase(lambda: None)
def return_TestCase():
return testcase_1
m.return_TestCase = return_TestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromName('return_TestCase', m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [testcase_1])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a TestCase ... instance"
#*****************************************************************
#Override the suiteClass attribute to ensure that the suiteClass
#attribute is used
def test_loadTestsFromName__callable__TestCase_instance_ProperSuiteClass(self):
class SubTestSuite(unittest.TestSuite):
pass
m = types.ModuleType('m')
testcase_1 = unittest.FunctionTestCase(lambda: None)
def return_TestCase():
return testcase_1
m.return_TestCase = return_TestCase
loader = unittest.TestLoader()
loader.suiteClass = SubTestSuite
suite = loader.loadTestsFromName('return_TestCase', m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [testcase_1])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a test method within a test case class"
#*****************************************************************
#Override the suiteClass attribute to ensure that the suiteClass
#attribute is used
def test_loadTestsFromName__relative_testmethod_ProperSuiteClass(self):
class SubTestSuite(unittest.TestSuite):
pass
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
loader.suiteClass=SubTestSuite
suite = loader.loadTestsFromName('testcase_1.test', m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [MyTestCase('test')])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a TestCase or TestSuite instance"
#
# What happens if the callable returns something else?
def test_loadTestsFromName__callable__wrong_type(self):
m = types.ModuleType('m')
def return_wrong():
return 6
m.return_wrong = return_wrong
loader = unittest.TestLoader()
try:
suite = loader.loadTestsFromName('return_wrong', m)
except TypeError:
pass
else:
self.fail("TestLoader.loadTestsFromName failed to raise TypeError")
# "The specifier can refer to modules and packages which have not been
# imported; they will be imported as a side-effect"
def test_loadTestsFromName__module_not_loaded(self):
# We're going to try to load this module as a side-effect, so it
# better not be loaded before we try.
#
module_name = 'unittest.test.dummy'
sys.modules.pop(module_name, None)
loader = unittest.TestLoader()
try:
suite = loader.loadTestsFromName(module_name)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [])
# module should now be loaded, thanks to loadTestsFromName()
self.assertIn(module_name, sys.modules)
finally:
if module_name in sys.modules:
del sys.modules[module_name]
################################################################
### Tests for TestLoader.loadTestsFromName()
### Tests for TestLoader.loadTestsFromNames()
################################################################
# "Similar to loadTestsFromName(), but takes a sequence of names rather
# than a single name."
#
# What happens if that sequence of names is empty?
def test_loadTestsFromNames__empty_name_list(self):
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames([])
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [])
# "Similar to loadTestsFromName(), but takes a sequence of names rather
# than a single name."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens if that sequence of names is empty?
#
# XXX Should this raise a ValueError or just return an empty TestSuite?
def test_loadTestsFromNames__relative_empty_name_list(self):
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames([], unittest)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [])
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# Is ValueError raised in response to an empty name?
def test_loadTestsFromNames__empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames([''])
except ValueError as e:
self.assertEqual(str(e), "Empty module name")
else:
self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when presented with an impossible module name?
def test_loadTestsFromNames__malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise ValueError or ImportError?
try:
loader.loadTestsFromNames(['abc () //'])
except ValueError:
pass
except ImportError:
pass
else:
self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when no module can be found for the given name?
def test_loadTestsFromNames__unknown_module_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['sdasfasfasdf'])
except ImportError as e:
self.assertEqual(str(e), "No module named 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromNames failed to raise ImportError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# What happens when the module can be found, but not the attribute?
def test_loadTestsFromNames__unknown_attr_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['unittest.sdasfasfasdf', 'unittest'])
except AttributeError as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromNames failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens when given an unknown attribute on a specified `module`
# argument?
def test_loadTestsFromNames__unknown_name_relative_1(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['sdasfasfasdf'], unittest)
except AttributeError as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# Do unknown attributes (relative to a provided module) still raise an
# exception even in the presence of valid attribute names?
def test_loadTestsFromNames__unknown_name_relative_2(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['TestCase', 'sdasfasfasdf'], unittest)
except AttributeError as e:
self.assertEqual(str(e), "'module' object has no attribute 'sdasfasfasdf'")
else:
self.fail("TestLoader.loadTestsFromName failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens when faced with the empty string?
#
# XXX This currently raises AttributeError, though ValueError is probably
# more appropriate
def test_loadTestsFromNames__relative_empty_name(self):
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames([''], unittest)
except AttributeError:
pass
else:
self.fail("Failed to raise ValueError")
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
# ...
# "The method optionally resolves name relative to the given module"
#
# What happens when presented with an impossible attribute name?
def test_loadTestsFromNames__relative_malformed_name(self):
loader = unittest.TestLoader()
# XXX Should this raise AttributeError or ValueError?
try:
loader.loadTestsFromNames(['abc () //'], unittest)
except AttributeError:
pass
except ValueError:
pass
else:
self.fail("TestLoader.loadTestsFromNames failed to raise ValueError")
# "The method optionally resolves name relative to the given module"
#
# Does loadTestsFromNames() make sure the provided `module` is in fact
# a module?
#
# XXX This validation is currently not done. This flexibility should
# either be documented or a TypeError should be raised.
def test_loadTestsFromNames__relative_not_a_module(self):
class MyTestCase(unittest.TestCase):
def test(self):
pass
class NotAModule(object):
test_2 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['test_2'], NotAModule)
reference = [unittest.TestSuite([MyTestCase('test')])]
self.assertEqual(list(suite), reference)
# "The specifier name is a ``dotted name'' that may resolve either to
# a module, a test case class, a TestSuite instance, a test method
# within a test case class, or a callable object which returns a
# TestCase or TestSuite instance."
#
# Does it raise an exception if the name resolves to an invalid
# object?
def test_loadTestsFromNames__relative_bad_object(self):
m = types.ModuleType('m')
m.testcase_1 = object()
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['testcase_1'], m)
except TypeError:
pass
else:
self.fail("Should have raised TypeError")
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a test case class"
def test_loadTestsFromNames__relative_TestCase_subclass(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['testcase_1'], m)
self.assertIsInstance(suite, loader.suiteClass)
expected = loader.suiteClass([MyTestCase('test')])
self.assertEqual(list(suite), [expected])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a TestSuite instance"
def test_loadTestsFromNames__relative_TestSuite(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testsuite = unittest.TestSuite([MyTestCase('test')])
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['testsuite'], m)
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [m.testsuite])
# "The specifier name is a ``dotted name'' that may resolve ... to ... a
# test method within a test case class"
def test_loadTestsFromNames__relative_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['testcase_1.test'], m)
self.assertIsInstance(suite, loader.suiteClass)
ref_suite = unittest.TestSuite([MyTestCase('test')])
self.assertEqual(list(suite), [ref_suite])
# "The specifier name is a ``dotted name'' that may resolve ... to ... a
# test method within a test case class"
#
# Does the method gracefully handle names that initially look like they
# resolve to "a test method within a test case class" but don't?
def test_loadTestsFromNames__relative_invalid_testmethod(self):
m = types.ModuleType('m')
class MyTestCase(unittest.TestCase):
def test(self):
pass
m.testcase_1 = MyTestCase
loader = unittest.TestLoader()
try:
loader.loadTestsFromNames(['testcase_1.testfoo'], m)
except AttributeError as e:
self.assertEqual(str(e), "type object 'MyTestCase' has no attribute 'testfoo'")
else:
self.fail("Failed to raise AttributeError")
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a ... TestSuite instance"
def test_loadTestsFromNames__callable__TestSuite(self):
m = types.ModuleType('m')
testcase_1 = unittest.FunctionTestCase(lambda: None)
testcase_2 = unittest.FunctionTestCase(lambda: None)
def return_TestSuite():
return unittest.TestSuite([testcase_1, testcase_2])
m.return_TestSuite = return_TestSuite
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['return_TestSuite'], m)
self.assertIsInstance(suite, loader.suiteClass)
expected = unittest.TestSuite([testcase_1, testcase_2])
self.assertEqual(list(suite), [expected])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a TestCase ... instance"
def test_loadTestsFromNames__callable__TestCase_instance(self):
m = types.ModuleType('m')
testcase_1 = unittest.FunctionTestCase(lambda: None)
def return_TestCase():
return testcase_1
m.return_TestCase = return_TestCase
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['return_TestCase'], m)
self.assertIsInstance(suite, loader.suiteClass)
ref_suite = unittest.TestSuite([testcase_1])
self.assertEqual(list(suite), [ref_suite])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a TestCase or TestSuite instance"
#
# Are staticmethods handled correctly?
def test_loadTestsFromNames__callable__call_staticmethod(self):
m = types.ModuleType('m')
class Test1(unittest.TestCase):
def test(self):
pass
testcase_1 = Test1('test')
class Foo(unittest.TestCase):
@staticmethod
def foo():
return testcase_1
m.Foo = Foo
loader = unittest.TestLoader()
suite = loader.loadTestsFromNames(['Foo.foo'], m)
self.assertIsInstance(suite, loader.suiteClass)
ref_suite = unittest.TestSuite([testcase_1])
self.assertEqual(list(suite), [ref_suite])
# "The specifier name is a ``dotted name'' that may resolve ... to
# ... a callable object which returns a TestCase or TestSuite instance"
#
# What happens when the callable returns something else?
def test_loadTestsFromNames__callable__wrong_type(self):
m = types.ModuleType('m')
def return_wrong():
return 6
m.return_wrong = return_wrong
loader = unittest.TestLoader()
try:
suite = loader.loadTestsFromNames(['return_wrong'], m)
except TypeError:
pass
else:
self.fail("TestLoader.loadTestsFromNames failed to raise TypeError")
# "The specifier can refer to modules and packages which have not been
# imported; they will be imported as a side-effect"
def test_loadTestsFromNames__module_not_loaded(self):
# We're going to try to load this module as a side-effect, so it
# better not be loaded before we try.
#
module_name = 'unittest.test.dummy'
sys.modules.pop(module_name, None)
loader = unittest.TestLoader()
try:
suite = loader.loadTestsFromNames([module_name])
self.assertIsInstance(suite, loader.suiteClass)
self.assertEqual(list(suite), [unittest.TestSuite()])
# module should now be loaded, thanks to loadTestsFromName()
self.assertIn(module_name, sys.modules)
finally:
if module_name in sys.modules:
del sys.modules[module_name]
################################################################
### /Tests for TestLoader.loadTestsFromNames()
### Tests for TestLoader.getTestCaseNames()
################################################################
# "Return a sorted sequence of method names found within testCaseClass"
#
# Test.foobar is defined to make sure getTestCaseNames() respects
# loader.testMethodPrefix
def test_getTestCaseNames(self):
class Test(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foobar(self): pass
loader = unittest.TestLoader()
self.assertEqual(loader.getTestCaseNames(Test), ['test_1', 'test_2'])
# "Return a sorted sequence of method names found within testCaseClass"
#
# Does getTestCaseNames() behave appropriately if no tests are found?
def test_getTestCaseNames__no_tests(self):
class Test(unittest.TestCase):
def foobar(self): pass
loader = unittest.TestLoader()
self.assertEqual(loader.getTestCaseNames(Test), [])
# "Return a sorted sequence of method names found within testCaseClass"
#
# Are not-TestCases handled gracefully?
#
# XXX This should raise a TypeError, not return a list
#
# XXX It's too late in the 2.5 release cycle to fix this, but it should
# probably be revisited for 2.6
def test_getTestCaseNames__not_a_TestCase(self):
class BadCase(int):
def test_foo(self):
pass
loader = unittest.TestLoader()
names = loader.getTestCaseNames(BadCase)
self.assertEqual(names, ['test_foo'])
# "Return a sorted sequence of method names found within testCaseClass"
#
# Make sure inherited names are handled.
#
# TestP.foobar is defined to make sure getTestCaseNames() respects
# loader.testMethodPrefix
def test_getTestCaseNames__inheritance(self):
class TestP(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foobar(self): pass
class TestC(TestP):
def test_1(self): pass
def test_3(self): pass
loader = unittest.TestLoader()
names = ['test_1', 'test_2', 'test_3']
self.assertEqual(loader.getTestCaseNames(TestC), names)
################################################################
### /Tests for TestLoader.getTestCaseNames()
### Tests for TestLoader.testMethodPrefix
################################################################
# "String giving the prefix of method names which will be interpreted as
# test methods"
#
# Implicit in the documentation is that testMethodPrefix is respected by
# all loadTestsFrom* methods.
def test_testMethodPrefix__loadTestsFromTestCase(self):
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
tests_1 = unittest.TestSuite([Foo('foo_bar')])
tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
loader = unittest.TestLoader()
loader.testMethodPrefix = 'foo'
self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_1)
loader.testMethodPrefix = 'test'
self.assertEqual(loader.loadTestsFromTestCase(Foo), tests_2)
# "String giving the prefix of method names which will be interpreted as
# test methods"
#
# Implicit in the documentation is that testMethodPrefix is respected by
# all loadTestsFrom* methods.
def test_testMethodPrefix__loadTestsFromModule(self):
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
m.Foo = Foo
tests_1 = [unittest.TestSuite([Foo('foo_bar')])]
tests_2 = [unittest.TestSuite([Foo('test_1'), Foo('test_2')])]
loader = unittest.TestLoader()
loader.testMethodPrefix = 'foo'
self.assertEqual(list(loader.loadTestsFromModule(m)), tests_1)
loader.testMethodPrefix = 'test'
self.assertEqual(list(loader.loadTestsFromModule(m)), tests_2)
# "String giving the prefix of method names which will be interpreted as
# test methods"
#
# Implicit in the documentation is that testMethodPrefix is respected by
# all loadTestsFrom* methods.
def test_testMethodPrefix__loadTestsFromName(self):
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
m.Foo = Foo
tests_1 = unittest.TestSuite([Foo('foo_bar')])
tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
loader = unittest.TestLoader()
loader.testMethodPrefix = 'foo'
self.assertEqual(loader.loadTestsFromName('Foo', m), tests_1)
loader.testMethodPrefix = 'test'
self.assertEqual(loader.loadTestsFromName('Foo', m), tests_2)
# "String giving the prefix of method names which will be interpreted as
# test methods"
#
# Implicit in the documentation is that testMethodPrefix is respected by
# all loadTestsFrom* methods.
def test_testMethodPrefix__loadTestsFromNames(self):
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
m.Foo = Foo
tests_1 = unittest.TestSuite([unittest.TestSuite([Foo('foo_bar')])])
tests_2 = unittest.TestSuite([Foo('test_1'), Foo('test_2')])
tests_2 = unittest.TestSuite([tests_2])
loader = unittest.TestLoader()
loader.testMethodPrefix = 'foo'
self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_1)
loader.testMethodPrefix = 'test'
self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests_2)
# "The default value is 'test'"
def test_testMethodPrefix__default_value(self):
loader = unittest.TestLoader()
self.assertEqual(loader.testMethodPrefix, 'test')
################################################################
### /Tests for TestLoader.testMethodPrefix
### Tests for TestLoader.sortTestMethodsUsing
################################################################
# "Function to be used to compare method names when sorting them in
# getTestCaseNames() and all the loadTestsFromX() methods"
def test_sortTestMethodsUsing__loadTestsFromTestCase(self):
def reversed_cmp(x, y):
return -((x > y) - (x < y))
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
loader = unittest.TestLoader()
loader.sortTestMethodsUsing = reversed_cmp
tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
# "Function to be used to compare method names when sorting them in
# getTestCaseNames() and all the loadTestsFromX() methods"
def test_sortTestMethodsUsing__loadTestsFromModule(self):
def reversed_cmp(x, y):
return -((x > y) - (x < y))
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
m.Foo = Foo
loader = unittest.TestLoader()
loader.sortTestMethodsUsing = reversed_cmp
tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
self.assertEqual(list(loader.loadTestsFromModule(m)), tests)
# "Function to be used to compare method names when sorting them in
# getTestCaseNames() and all the loadTestsFromX() methods"
def test_sortTestMethodsUsing__loadTestsFromName(self):
def reversed_cmp(x, y):
return -((x > y) - (x < y))
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
m.Foo = Foo
loader = unittest.TestLoader()
loader.sortTestMethodsUsing = reversed_cmp
tests = loader.suiteClass([Foo('test_2'), Foo('test_1')])
self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
# "Function to be used to compare method names when sorting them in
# getTestCaseNames() and all the loadTestsFromX() methods"
def test_sortTestMethodsUsing__loadTestsFromNames(self):
def reversed_cmp(x, y):
return -((x > y) - (x < y))
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
m.Foo = Foo
loader = unittest.TestLoader()
loader.sortTestMethodsUsing = reversed_cmp
tests = [loader.suiteClass([Foo('test_2'), Foo('test_1')])]
self.assertEqual(list(loader.loadTestsFromNames(['Foo'], m)), tests)
# "Function to be used to compare method names when sorting them in
# getTestCaseNames()"
#
# Does it actually affect getTestCaseNames()?
def test_sortTestMethodsUsing__getTestCaseNames(self):
def reversed_cmp(x, y):
return -((x > y) - (x < y))
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
loader = unittest.TestLoader()
loader.sortTestMethodsUsing = reversed_cmp
test_names = ['test_2', 'test_1']
self.assertEqual(loader.getTestCaseNames(Foo), test_names)
# "The default value is the built-in cmp() function"
# Since cmp is now defunct, we simply verify that the results
# occur in the same order as they would with the default sort.
def test_sortTestMethodsUsing__default_value(self):
loader = unittest.TestLoader()
class Foo(unittest.TestCase):
def test_2(self): pass
def test_3(self): pass
def test_1(self): pass
test_names = ['test_2', 'test_3', 'test_1']
self.assertEqual(loader.getTestCaseNames(Foo), sorted(test_names))
# "it can be set to None to disable the sort."
#
# XXX How is this different from reassigning cmp? Are the tests returned
# in a random order or something? This behaviour should die
def test_sortTestMethodsUsing__None(self):
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
loader = unittest.TestLoader()
loader.sortTestMethodsUsing = None
test_names = ['test_2', 'test_1']
self.assertEqual(set(loader.getTestCaseNames(Foo)), set(test_names))
################################################################
### /Tests for TestLoader.sortTestMethodsUsing
### Tests for TestLoader.suiteClass
################################################################
# "Callable object that constructs a test suite from a list of tests."
def test_suiteClass__loadTestsFromTestCase(self):
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
tests = [Foo('test_1'), Foo('test_2')]
loader = unittest.TestLoader()
loader.suiteClass = list
self.assertEqual(loader.loadTestsFromTestCase(Foo), tests)
# It is implicit in the documentation for TestLoader.suiteClass that
# all TestLoader.loadTestsFrom* methods respect it. Let's make sure
def test_suiteClass__loadTestsFromModule(self):
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
m.Foo = Foo
tests = [[Foo('test_1'), Foo('test_2')]]
loader = unittest.TestLoader()
loader.suiteClass = list
self.assertEqual(loader.loadTestsFromModule(m), tests)
# It is implicit in the documentation for TestLoader.suiteClass that
# all TestLoader.loadTestsFrom* methods respect it. Let's make sure
def test_suiteClass__loadTestsFromName(self):
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
m.Foo = Foo
tests = [Foo('test_1'), Foo('test_2')]
loader = unittest.TestLoader()
loader.suiteClass = list
self.assertEqual(loader.loadTestsFromName('Foo', m), tests)
# It is implicit in the documentation for TestLoader.suiteClass that
# all TestLoader.loadTestsFrom* methods respect it. Let's make sure
def test_suiteClass__loadTestsFromNames(self):
m = types.ModuleType('m')
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def foo_bar(self): pass
m.Foo = Foo
tests = [[Foo('test_1'), Foo('test_2')]]
loader = unittest.TestLoader()
loader.suiteClass = list
self.assertEqual(loader.loadTestsFromNames(['Foo'], m), tests)
# "The default value is the TestSuite class"
def test_suiteClass__default_value(self):
loader = unittest.TestLoader()
self.assertTrue(loader.suiteClass is unittest.TestSuite)
| mit |
blakeboswell/valence | setup.py | 1 | 1919 | #!/usr/bin/env python
import os
from setuptools import setup
from pyvalence import __version__
PKG_NAME = 'pyvalence'
PKG_AUTHOR = 'Audere Labs'
PKG_LICENSE = 'BSD'
AUTHOR_EMAIL = 'audere.labs@gmail.com'
MAINTAINER_EMAIL = '' # google group / forum
URL = 'https://audere.github.com/valence'
DOWNLOAD_URL = ''
DESCRIPTION = 'Package for processing analytical chemistry data.'
# Get the long description from the README file
LONG_DESCRIPTION = 'pyvalence is a python package for processing data generated from analytical chemistry. pyvalence reads analytical data from native formats into readily accessible pandas DataFrames and supports common analysis techniques (e.g. standard curves regression and utilization) to reduce manual, one-off data processing. Analysis conducted with pyvalence allows researchers to spend less time processing data and more time interpreting results.'
options = {
'version': __version__,
'name': PKG_NAME,
'author': PKG_AUTHOR,
'license': PKG_LICENSE,
'author_email': AUTHOR_EMAIL,
'maintainer_email': MAINTAINER_EMAIL,
'url': URL,
'download_url': DOWNLOAD_URL,
'description': DESCRIPTION,
'long_description': LONG_DESCRIPTION,
'platforms': ['Any'],
'classifiers': [
'Development Status :: 1 - Planning',
'Environment :: Console',
'Intended Audience :: Science/Research',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Scientific/Engineering :: Chemistry'
],
'packages': [
'pyvalence', 'pyvalence.build', 'pyvalence.analyze'
],
'package_data': {'pyvalence': []},
'include_package_data': True,
'install_requires': ['numpy', 'scipy', 'pandas']
}
setup(**options)
| bsd-3-clause |
pixbuffer/django-cms | cms/templatetags/cms_tags.py | 3 | 17870 | # -*- coding: utf-8 -*-
from itertools import chain
from classytags.arguments import Argument, MultiValueArgument
from classytags.core import Options, Tag
from classytags.helpers import InclusionTag, AsTag
from classytags.parser import Parser
from cms.models import Page, Placeholder as PlaceholderModel
from cms.plugin_rendering import render_placeholder
from cms.plugins.utils import get_plugins, assign_plugins
from cms.utils import get_language_from_request, get_cms_setting
from cms.utils.page_resolver import get_page_queryset, use_draft
from cms.utils.placeholder import validate_placeholder_name
from django import template
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.cache import cache
from django.core.mail import mail_managers
from django.utils.html import escape
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _, get_language
import re
from sekizai.helpers import Watcher, get_varname
register = template.Library()
def get_site_id(site):
if site:
if isinstance(site, Site):
site_id = site.id
elif isinstance(site, int) or (isinstance(site, basestring) and site.isdigit()):
site_id = int(site)
else:
site_id = settings.SITE_ID
else:
site_id = settings.SITE_ID
return site_id
def has_permission(page, request):
return page.has_change_permission(request)
register.filter(has_permission)
CLEAN_KEY_PATTERN = re.compile(r'[^a-zA-Z0-9_-]')
def _clean_key(key):
return CLEAN_KEY_PATTERN.sub('-', key)
def _get_cache_key(name, page_lookup, lang, site_id):
if isinstance(page_lookup, Page):
page_key = str(page_lookup.pk)
else:
page_key = str(page_lookup)
page_key = _clean_key(page_key)
return name + '__page_lookup:' + page_key + '_site:' + str(site_id) + '_lang:' + str(lang)
def _get_page_by_untyped_arg(page_lookup, request, site_id):
"""
The `page_lookup` argument can be of any of the following types:
- Integer: interpreted as `pk` of the desired page
- String: interpreted as `reverse_id` of the desired page
- `dict`: a dictionary containing keyword arguments to find the desired page
(for instance: `{'pk': 1}`)
- `Page`: you can also pass a Page object directly, in which case there will be no database lookup.
- `None`: the current page will be used
"""
if page_lookup is None:
return request.current_page
if isinstance(page_lookup, Page):
return page_lookup
if isinstance(page_lookup, basestring):
page_lookup = {'reverse_id': page_lookup}
elif isinstance(page_lookup, (int, long)):
page_lookup = {'pk': page_lookup}
elif not isinstance(page_lookup, dict):
raise TypeError('The page_lookup argument can be either a Dictionary, Integer, Page, or String.')
page_lookup.update({'site': site_id})
try:
if 'pk' in page_lookup:
page = Page.objects.all().get(**page_lookup)
if request and use_draft(request):
if page.publisher_is_draft:
return page
else:
return page.publisher_draft
else:
if page.publisher_is_draft:
return page.publisher_public
else:
return page
else:
return get_page_queryset(request).get(**page_lookup)
except Page.DoesNotExist:
site = Site.objects.get_current()
subject = _('Page not found on %(domain)s') % {'domain': site.domain}
body = _("A template tag couldn't find the page with lookup arguments `%(page_lookup)s\n`. "
"The URL of the request was: http://%(host)s%(path)s") \
% {'page_lookup': repr(page_lookup), 'host': site.domain, 'path': request.path}
if settings.DEBUG:
raise Page.DoesNotExist(body)
else:
if settings.SEND_BROKEN_LINK_EMAILS:
mail_managers(subject, body, fail_silently=True)
return None
class PageUrl(InclusionTag):
template = 'cms/content.html'
name = 'page_url'
options = Options(
Argument('page_lookup'),
Argument('lang', required=False, default=None),
Argument('site', required=False, default=None),
)
def get_context(self, context, page_lookup, lang, site):
site_id = get_site_id(site)
request = context.get('request', False)
if not request:
return {'content': ''}
if request.current_page == "dummy":
return {'content': ''}
if lang is None:
lang = get_language_from_request(request)
cache_key = _get_cache_key('page_url', page_lookup, lang, site_id) + '_type:absolute_url'
url = cache.get(cache_key)
if not url:
page = _get_page_by_untyped_arg(page_lookup, request, site_id)
if page:
url = page.get_absolute_url(language=lang)
cache.set(cache_key, url, get_cms_setting('CACHE_DURATIONS')['content'])
if url:
return {'content': url}
return {'content': ''}
register.tag(PageUrl)
register.tag('page_id_url', PageUrl)
def _get_placeholder(current_page, page, context, name):
from cms.utils.plugins import get_placeholders
placeholder_cache = getattr(current_page, '_tmp_placeholders_cache', {})
if page.pk in placeholder_cache:
return placeholder_cache[page.pk].get(name, None)
placeholder_cache[page.pk] = {}
slots = get_placeholders(page.get_template())
placeholders = page.placeholders.filter(slot__in=slots)
assign_plugins(context['request'], placeholders, get_language())
for placeholder in placeholders:
placeholder_cache[page.pk][placeholder.slot] = placeholder
placeholder.page = page
current_page._tmp_placeholders_cache = placeholder_cache
return placeholder_cache[page.pk].get(name, None)
def get_placeholder_content(context, request, current_page, name, inherit):
edit_mode = getattr(request, 'toolbar', None) and getattr(request.toolbar, 'edit_mode')
pages = [current_page]
# don't display inherited plugins in edit mode, so that the user doesn't
# mistakenly edit/delete them. This is a fix for issue #1303. See the discussion
# there for possible enhancements
if inherit and not edit_mode:
pages = chain([current_page], current_page.get_cached_ancestors(ascending=True))
for page in pages:
placeholder = _get_placeholder(current_page, page, context, name)
if placeholder is None:
continue
if not get_plugins(request, placeholder):
continue
content = render_placeholder(placeholder, context, name)
if content:
return content
# if we reach this point, we have an empty or non-existant placeholder
# call _get_placeholder again to get the placeholder properly rendered
# in frontend editing
placeholder = _get_placeholder(current_page, current_page, context, name)
return render_placeholder(placeholder, context, name)
class PlaceholderParser(Parser):
def parse_blocks(self):
for bit in getattr(self.kwargs['extra_bits'], 'value', self.kwargs['extra_bits']):
if getattr(bit, 'value', bit.var.value) == 'or':
return super(PlaceholderParser, self).parse_blocks()
return
class PlaceholderOptions(Options):
def get_parser_class(self):
return PlaceholderParser
class Placeholder(Tag):
"""
This template node is used to output page content and
is also used in the admin to dynamically generate input fields.
eg: {% placeholder "placeholder_name" %}
{% placeholder "sidebar" inherit %}
{% placeholder "footer" inherit or %}
<a href="/about/">About us</a>
{% endplaceholder %}
Keyword arguments:
name -- the name of the placeholder
width -- additional width attribute (integer) which gets added to the plugin context
(deprecated, use `{% with 320 as width %}{% placeholder "foo"}{% endwith %}`)
inherit -- optional argument which if given will result in inheriting
the content of the placeholder with the same name on parent pages
or -- optional argument which if given will make the template tag a block
tag whose content is shown if the placeholder is empty
"""
name = 'placeholder'
options = PlaceholderOptions(
Argument('name', resolve=False),
MultiValueArgument('extra_bits', required=False, resolve=False),
blocks=[
('endplaceholder', 'nodelist'),
]
)
def render_tag(self, context, name, extra_bits, nodelist=None):
validate_placeholder_name(name)
width = None
inherit = False
for bit in extra_bits:
if bit == 'inherit':
inherit = True
elif bit.isdigit():
width = int(bit)
import warnings
warnings.warn(
"The width parameter for the placeholder tag is deprecated.",
DeprecationWarning
)
if not 'request' in context:
return ''
request = context['request']
if width:
context.update({'width': width})
page = request.current_page
if not page or page == 'dummy':
if nodelist:
return nodelist.render(context)
return ''
content = get_placeholder_content(context, request, page, name, inherit)
if not content and nodelist:
return nodelist.render(context)
return content
def get_name(self):
return self.kwargs['name'].var.value.strip('"').strip("'")
register.tag(Placeholder)
class RenderPlugin(InclusionTag):
template = 'cms/content.html'
name = 'render_plugin'
options = Options(
Argument('plugin')
)
def get_context(self, context, plugin):
# Prepend frontedit toolbar output if applicable
edit = False
request = context['request']
toolbar = getattr(request, 'toolbar', None)
page = request.current_page
if toolbar.edit_mode and (not page or page.has_change_permission(request)):
edit = True
if edit:
from cms.middleware.toolbar import toolbar_plugin_processor
processors = (toolbar_plugin_processor,)
else:
processors = None
return {'content': plugin.render_plugin(context, processors=processors)}
register.tag(RenderPlugin)
class PageAttribute(AsTag):
"""
This template node is used to output attribute from a page such
as its title or slug.
Synopsis
{% page_attribute "field-name" %}
{% page_attribute "field-name" as varname %}
{% page_attribute "field-name" page_lookup %}
{% page_attribute "field-name" page_lookup as varname %}
Example
{# Output current page's page_title attribute: #}
{% page_attribute "page_title" %}
{# Output page_title attribute of the page with reverse_id "the_page": #}
{% page_attribute "page_title" "the_page" %}
{# Output slug attribute of the page with pk 10: #}
{% page_attribute "slug" 10 %}
{# Assign page_title attribute to a variable: #}
{% page_attribute "page_title" as title %}
Keyword arguments:
field-name -- the name of the field to output. Use one of:
- title
- menu_title
- page_title
- slug
- meta_description
- meta_keywords
page_lookup -- lookup argument for Page, if omitted field-name of current page is returned.
See _get_page_by_untyped_arg() for detailed information on the allowed types and their interpretation
for the page_lookup argument.
varname -- context variable name. Output will be added to template context as this variable.
This argument is required to follow the 'as' keyword.
"""
name = 'page_attribute'
options = Options(
Argument('name', resolve=False),
Argument('page_lookup', required=False, default=None),
'as',
Argument('varname', required=False, resolve=False)
)
valid_attributes = [
"title",
"slug",
"meta_description",
"meta_keywords",
"page_title",
"menu_title"
]
def get_value(self, context, name, page_lookup):
if not 'request' in context:
return ''
name = name.lower()
request = context['request']
lang = get_language_from_request(request)
page = _get_page_by_untyped_arg(page_lookup, request, get_site_id(None))
if page == "dummy":
return ''
if page and name in self.valid_attributes:
func = getattr(page, "get_%s" % name)
return escape(func(language=lang, fallback=True))
return ''
register.tag(PageAttribute)
class CleanAdminListFilter(InclusionTag):
template = 'admin/filter.html'
name = 'clean_admin_list_filter'
options = Options(
Argument('cl'),
Argument('spec'),
)
def get_context(self, context, cl, spec):
choices = sorted(list(spec.choices(cl)), key=lambda k: k['query_string'])
query_string = None
unique_choices = []
for choice in choices:
if choice['query_string'] != query_string:
unique_choices.append(choice)
query_string = choice['query_string']
return {'title': spec.title(), 'choices': unique_choices}
def _restore_sekizai(context, changes):
varname = get_varname()
sekizai_container = context[varname]
for key, values in changes.items():
sekizai_namespace = sekizai_container[key]
for value in values:
sekizai_namespace.append(value)
def _show_placeholder_for_page(context, placeholder_name, page_lookup, lang=None,
site=None, cache_result=True):
"""
Shows the content of a page with a placeholder name and given lookup
arguments in the given language.
This is useful if you want to have some more or less static content that is
shared among many pages, such as a footer.
See _get_page_by_untyped_arg() for detailed information on the allowed types
and their interpretation for the page_lookup argument.
"""
validate_placeholder_name(placeholder_name)
request = context.get('request', False)
site_id = get_site_id(site)
if not request:
return {'content': ''}
if lang is None:
lang = get_language_from_request(request)
if cache_result:
base_key = _get_cache_key('_show_placeholder_for_page', page_lookup, lang, site_id)
cache_key = _clean_key('%s_placeholder:%s' % (base_key, placeholder_name))
cached_value = cache.get(cache_key)
if isinstance(cached_value, dict): # new style
_restore_sekizai(context, cached_value['sekizai'])
return {'content': mark_safe(cached_value['content'])}
elif isinstance(cached_value, basestring): # old style
return {'content': mark_safe(cached_value)}
page = _get_page_by_untyped_arg(page_lookup, request, site_id)
if not page:
return {'content': ''}
try:
placeholder = page.placeholders.get(slot=placeholder_name)
except PlaceholderModel.DoesNotExist:
if settings.DEBUG:
raise
return {'content': ''}
watcher = Watcher(context)
content = render_placeholder(placeholder, context, placeholder_name)
changes = watcher.get_changes()
if cache_result:
cache.set(cache_key, {'content': content, 'sekizai': changes}, get_cms_setting('CACHE_DURATIONS')['content'])
if content:
return {'content': mark_safe(content)}
return {'content': ''}
class ShowPlaceholderById(InclusionTag):
template = 'cms/content.html'
name = 'show_placeholder_by_id'
options = Options(
Argument('placeholder_name'),
Argument('reverse_id'),
Argument('lang', required=False, default=None),
Argument('site', required=False, default=None),
)
def get_context(self, *args, **kwargs):
return _show_placeholder_for_page(**self.get_kwargs(*args, **kwargs))
def get_kwargs(self, context, placeholder_name, reverse_id, lang, site):
return {
'context': context,
'placeholder_name': placeholder_name,
'page_lookup': reverse_id,
'lang': lang,
'site': site
}
register.tag(ShowPlaceholderById)
register.tag('show_placeholder', ShowPlaceholderById)
class ShowUncachedPlaceholderById(ShowPlaceholderById):
name = 'show_uncached_placeholder_by_id'
def get_kwargs(self, *args, **kwargs):
kwargs = super(ShowUncachedPlaceholderById, self).get_kwargs(*args, **kwargs)
kwargs['cache_result'] = False
return kwargs
register.tag(ShowUncachedPlaceholderById)
register.tag('show_uncached_placeholder', ShowUncachedPlaceholderById)
class CMSToolbar(InclusionTag):
template = 'cms/toolbar/toolbar.html'
name = 'cms_toolbar'
def render(self, context):
request = context.get('request', None)
if not request:
return ''
toolbar = getattr(request, 'toolbar', None)
if not toolbar:
return ''
if not toolbar.show_toolbar:
return ''
return super(CMSToolbar, self).render(context)
def get_context(self, context):
context['CMS_TOOLBAR_CONFIG'] = context['request'].toolbar.as_json(context)
return context
register.tag(CMSToolbar)
| bsd-3-clause |
fxfitz/ansible | test/units/modules/network/enos/test_enos_config.py | 45 | 5146 | #
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from ansible.compat.tests.mock import patch
from ansible.modules.network.enos import enos_config
from .enos_module import TestEnosModule, load_fixture, set_module_args
class TestEnosConfigModule(TestEnosModule):
module = enos_config
def setUp(self):
self.patcher_get_config = patch('ansible.modules.network.enos.enos_config.get_config')
self.mock_get_config = self.patcher_get_config.start()
self.patcher_exec_command = patch('ansible.modules.network.enos.enos_config.load_config')
self.mock_exec_command = self.patcher_exec_command.start()
def tearDown(self):
self.patcher_get_config.stop()
self.patcher_exec_command.stop()
def load_fixtures(self, commands=None):
config_file = 'enos_config_config.cfg'
self.mock_get_config.return_value = load_fixture(config_file)
self.mock_exec_command.return_value = 'dummy diff'
def test_enos_config_unchanged(self):
src = load_fixture('enos_config_config.cfg')
set_module_args(dict(src=src))
self.execute_module()
def test_enos_config_src(self):
src = load_fixture('enos_config_src.cfg')
set_module_args(dict(src=src))
commands = ['hostname foo', 'interface ip 13',
'no ip ospf enable']
self.execute_module(changed=True, commands=commands)
def test_enos_config_backup(self):
set_module_args(dict(backup=True))
result = self.execute_module()
self.assertIn('__backup__', result)
def test_enos_config_lines_wo_parents(self):
set_module_args(dict(lines=['hostname foo']))
commands = ['hostname foo']
self.execute_module(changed=True, commands=commands)
def test_enos_config_lines_w_parents(self):
set_module_args(dict(lines=['shutdown'], parents=['interface ip 13']))
commands = ['interface ip 13', 'shutdown']
self.execute_module(changed=True, commands=commands)
def test_enos_config_before(self):
set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2']))
commands = ['test1', 'test2', 'hostname foo']
self.execute_module(changed=True, commands=commands, sort=False)
def test_enos_config_after(self):
set_module_args(dict(lines=['hostname foo'], after=['test1', 'test2']))
commands = ['hostname foo', 'test1', 'test2']
self.execute_module(changed=True, commands=commands, sort=False)
def test_enos_config_before_after_no_change(self):
set_module_args(dict(lines=['hostname router'],
before=['test1', 'test2'],
after=['test3', 'test4']))
self.execute_module()
def test_enos_config_config(self):
config = 'hostname localhost'
set_module_args(dict(lines=['hostname router'], config=config))
commands = ['hostname router']
self.execute_module(changed=True, commands=commands)
def test_enos_config_replace_block(self):
lines = ['description test string', 'test string']
parents = ['interface ip 13']
set_module_args(dict(lines=lines, replace='block', parents=parents))
commands = parents + lines
self.execute_module(changed=True, commands=commands)
def test_enos_config_match_none(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'description test string']
parents = ['interface ip 13']
set_module_args(dict(lines=lines, parents=parents, match='none'))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
def test_enos_config_match_strict(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'exit']
parents = ['interface ip 13']
set_module_args(dict(lines=lines, parents=parents, match='strict'))
commands = parents + ['exit']
self.execute_module(changed=True, commands=commands, sort=False)
def test_enos_config_match_exact(self):
lines = ['ip address 1.2.3.4 255.255.255.0', 'description test string',
'shutdown']
parents = ['interface ip 13']
set_module_args(dict(lines=lines, parents=parents, match='exact'))
commands = parents + lines
self.execute_module(changed=True, commands=commands, sort=False)
| gpl-3.0 |
ctb/cvxpy | examples/advanced/test.py | 12 | 2380 | from cvxpy import *
import cvxopt
import numpy as np
# # Problem data.
# m = 100
# n = 30
# A = cvxopt.normal(m,n)
# b = cvxopt.normal(m)
# import cProfile
# # Construct the problem.
# x = Variable(n)
# u = m*[[1]]
# t = Variable(m,m)
# # objective = Minimize( sum(t) )
# # constraints = [0 <= t, t <= 1]
# # p = Problem(objective, constraints)
# # The optimal objective is returned by p.solve().
# cProfile.run("""
# sum(t)
# """)
# # The optimal value for x is stored in x.value.
# #print x.value
# # The optimal Lagrange multiplier for a constraint
# # is stored in constraint.dual_value.
# #print constraints[0].dual_value
class MyMeta(type):
def __getitem__(self, key):
print key
return 2
def __len__(self):
return 1
def __contains__(self, obj):
print "hello"
return 0
class Exp(object):
def __add__(self, other):
return 0
def __radd__(self, other):
return 1
def __rmul__(self, other):
print 1
__array_priority__ = 100
import numpy as np
a = np.random.random((2,2))
class Bar1(object):
__metaclass__ = MyMeta
def __add__(self, rhs): return 0
def __radd__(self, rhs): return 1
def __lt__(self, rhs): return 0
def __le__(self, rhs): return 1
def __eq__(self, rhs): return 2
def __ne__(self, rhs): return 3
def __gt__(self, rhs): return 4
def __ge__(self, rhs): return 5
def __array_prepare__(self):
print "hello"
return self
def __array_wrap__(self):
return self
def __array__(self):
print "Afafaf"
arr = np.array([self], dtype="object")
return arr
__array_priority__ = 100
def override(name):
if name == "equal":
def ufunc(x, y):
print y
if isinstance(y, Bar1) or \
isinstance(y, np.ndarray) and isinstance(y[0], Bar1):
return NotImplemented
return getattr(np, name)(x, y)
return ufunc
else:
def ufunc(x, y):
print y
if isinstance(y, Bar1):
return NotImplemented
return getattr(np, name)(x, y)
return ufunc
np.set_numeric_ops(
** {
ufunc : override(ufunc) for ufunc in (
"less_equal", "equal", "greater_equal"
)
}
)
b = Bar1()
print a == b
print a <= b
print a + b | gpl-3.0 |
duramato/SickRage | sickbeard/providers/binsearch.py | 2 | 3923 | # Author: moparisthebest <admin@moparisthebest.com>
#
# This file is part of Sick Beard.
#
# Sick Beard 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.
#
# Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>.
import urllib
import re
import generic
from sickbeard import logger
from sickbeard import tvcache
class BinSearchProvider(generic.NZBProvider):
def __init__(self):
generic.NZBProvider.__init__(self, "BinSearch")
self.enabled = False
self.public = True
self.cache = BinSearchCache(self)
self.urls = {'base_url': 'https://www.binsearch.info/'}
self.url = self.urls['base_url']
def isEnabled(self):
return self.enabled
class BinSearchCache(tvcache.TVCache):
def __init__(self, provider):
tvcache.TVCache.__init__(self, provider)
# only poll Binsearch every 30 minutes max
self.minTime = 30
# compile and save our regular expressions
# this pulls the title from the URL in the description
self.descTitleStart = re.compile('^.*https?://www\.binsearch\.info/.b=')
self.descTitleEnd = re.compile('&.*$')
# these clean up the horrible mess of a title if the above fail
self.titleCleaners = [
re.compile('.?yEnc.?\(\d+/\d+\)$'),
re.compile(' \[\d+/\d+\] '),
]
def _get_title_and_url(self, item):
"""
Retrieves the title and URL data from the item XML node
item: An elementtree.ElementTree element representing the <item> tag of the RSS feed
Returns: A tuple containing two strings representing title and URL respectively
"""
title = item.get('description')
if title:
title = u'' + title
if self.descTitleStart.match(title):
title = self.descTitleStart.sub('', title)
title = self.descTitleEnd.sub('', title)
title = title.replace('+', '.')
else:
# just use the entire title, looks hard/impossible to parse
title = item.get('title')
if title:
for titleCleaner in self.titleCleaners:
title = titleCleaner.sub('', title)
url = item.get('link')
if url:
url = url.replace('&', '&')
return (title, url)
def updateCache(self):
# check if we should update
if not self.shouldUpdate():
return
# clear cache
self._clearCache()
# set updated
self.setLastUpdate()
cl = []
for group in ['alt.binaries.boneless','alt.binaries.misc','alt.binaries.hdtv','alt.binaries.hdtv.x264','alt.binaries.tv','alt.binaries.tvseries','alt.binaries.teevee']:
url = self.provider.url + 'rss.php?'
urlArgs = {'max': 1000,'g': group}
url += urllib.urlencode(urlArgs)
logger.log(u"Cache update URL: %s " % url, logger.DEBUG)
for item in self.getRSSFeed(url)['entries'] or []:
ci = self._parseItem(item)
if ci is not None:
cl.append(ci)
if len(cl) > 0:
myDB = self._getDB()
myDB.mass_action(cl)
def _checkAuth(self, data):
return data if data['feed'] and data['feed']['title'] != 'Invalid Link' else None
provider = BinSearchProvider()
| gpl-3.0 |
rspavel/spack | var/spack/repos/builtin/packages/turbomole/package.py | 5 | 6080 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import os
import subprocess
class Turbomole(Package):
"""TURBOMOLE: Program Package for ab initio Electronic Structure
Calculations.
Note: Turbomole requires purchase of a license to download. Go to the
Turbomole home page, http://www.turbomole-gmbh.com, for details.
Spack will search the current directory for this file. It is
probably best to add this file to a Spack mirror so that it can be
found from anywhere. For information on setting up a Spack mirror
see http://spack.readthedocs.io/en/latest/mirrors.html"""
homepage = "http://www.turbomole-gmbh.com/"
manual_download = True
version('7.0.2', '92b97e1e52e8dcf02a4d9ac0147c09d6',
url="file://%s/turbolinux702.tar.gz" % os.getcwd())
variant('mpi', default=True, description='Set up MPI environment')
variant('smp', default=False, description='Set up SMP environment')
# Turbomole's install is odd. There are three variants
# - serial
# - parallel, MPI
# - parallel, SMP
#
# Only one of these can be active at a time. MPI and SMP are set as
# variants so there could be up to 3 installs per version. Switching
# between them would be accomplished with `module swap` commands.
def do_fetch(self, mirror_only=True):
if '+mpi' in self.spec and '+smp' in self.spec:
raise InstallError('Can not have both SMP and MPI enabled in the '
'same build.')
super(Turbomole, self).do_fetch(mirror_only)
def get_tm_arch(self):
if 'TURBOMOLE' in os.getcwd():
tm_sysname = Executable('./scripts/sysname')
tm_arch = tm_sysname(output=str)
return tm_arch.rstrip('\n')
else:
return
def install(self, spec, prefix):
calculate_version = 'calculate_2.4_linux64'
molecontrol_version = 'MoleControl_2.5'
tm_arch = self.get_tm_arch()
tar = which('tar')
dst = join_path(prefix, 'TURBOMOLE')
tar('-x', '-z', '-f', 'thermocalc.tar.gz')
with working_dir('thermocalc'):
subprocess.call('./install<<<y', shell=True)
install_tree('basen', join_path(dst, 'basen'))
install_tree('cabasen', join_path(dst, 'cabasen'))
install_tree(calculate_version, join_path(dst, calculate_version))
install_tree('cbasen', join_path(dst, 'cbasen'))
install_tree('DOC', join_path(dst, 'DOC'))
install_tree('jbasen', join_path(dst, 'jbasen'))
install_tree('jkbasen', join_path(dst, 'jkbasen'))
install_tree(molecontrol_version, join_path(dst, molecontrol_version))
install_tree('parameter', join_path(dst, 'parameter'))
install_tree('perlmodules', join_path(dst, 'perlmodules'))
install_tree('scripts', join_path(dst, 'scripts'))
install_tree('smprun_scripts', join_path(dst, 'smprun_scripts'))
install_tree('structures', join_path(dst, 'structures'))
install_tree('thermocalc', join_path(dst, 'thermocalc'))
install_tree('TURBOTEST', join_path(dst, 'TURBOTEST'))
install_tree('xbasen', join_path(dst, 'xbasen'))
install('Config_turbo_env', dst)
install('Config_turbo_env.tcsh', dst)
install('README', dst)
install('README_LICENSES', dst)
install('TURBOMOLE_702_LinuxPC', dst)
if '+mpi' in spec:
install_tree('bin/%s_mpi' % tm_arch,
join_path(dst, 'bin', '%s_mpi' % tm_arch))
install_tree('libso/%s_mpi' % tm_arch,
join_path(dst, 'libso', '%s_mpi' % tm_arch))
install_tree('mpirun_scripts/%s_mpi' % tm_arch,
join_path(dst, 'mpirun_scripts', '%s_mpi' % tm_arch))
elif '+smp' in spec:
install_tree('bin/%s_smp' % tm_arch,
join_path(dst, 'bin', '%s_smp' % tm_arch))
install_tree('libso/%s_smp' % tm_arch,
join_path(dst, 'libso', '%s_smp' % tm_arch))
install_tree('mpirun_scripts/%s_smp' % tm_arch,
join_path(dst, 'mpirun_scripts', '%s_smp' % tm_arch))
else:
install_tree('bin/%s' % tm_arch, join_path(dst, 'bin', tm_arch))
if '+mpi' in spec or '+smp' in spec:
install('mpirun_scripts/ccsdf12', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/dscf', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/grad', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/mpgrad', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/pnoccsd', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/rdgrad', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/ricc2', join_path(dst, 'mpirun_scripts'))
install('mpirun_scripts/ridft', join_path(dst, 'mpirun_scripts'))
def setup_run_environment(self, env):
molecontrol_version = 'MoleControl_2.5'
tm_arch = self.get_tm_arch()
env.set('TURBODIR', self.prefix.TURBOMOLE)
env.set('MOLE_CONTROL',
join_path(self.prefix, 'TURBOMOLE', molecontrol_version))
env.prepend_path('PATH', self.prefix.TURBOMOLE.thermocalc)
env.prepend_path('PATH', self.prefix.TURBOMOLE.scripts)
if '+mpi' in self.spec:
env.set('PARA_ARCH', 'MPI')
env.prepend_path('PATH', join_path(
self.prefix, 'TURBOMOLE', 'bin', '%s_mpi' % tm_arch))
elif '+smp' in self.spec:
env.set('PARA_ARCH', 'SMP')
env.prepend_path('PATH', join_path(
self.prefix, 'TURBOMOLE', 'bin', '%s_smp' % tm_arch))
else:
env.prepend_path('PATH', join_path(
self.prefix, 'TURBOMOLE', 'bin', tm_arch))
| lgpl-2.1 |
GEMScienceTools/catalogue_toolkit | eqcat/parsers/converters.py | 2 | 8002 | # -*- coding: utf-8 -*-
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# LICENSE
#
# Copyright (c) 2015 GEM Foundation
#
# The Catalogue Toolkit 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.
#
# You should have received a copy of the GNU Affero General Public License
# with this download. If not, see <http://www.gnu.org/licenses/>
#!/usr/bin/env/python
'''
Parser for generic catalogue into either ISFCatalogue format or
GCMT catalogue format
'''
import csv
import datetime
import numpy as np
import eqcat.gcmt_utils as utils
from math import floor
from eqcat.parsers.base import _to_int, _to_str, _to_float
from eqcat.parsers.generic_catalogue import GeneralCsvCatalogue
from eqcat.isf_catalogue import (ISFCatalogue, Magnitude,
Origin, Location, Event)
from eqcat.parsers.gcmt_ndk_parser import ParseNDKtoGCMT
def _header_check(input_keys, catalogue_keys):
valid_key_list = []
for element in input_keys:
if element in catalogue_keys:
valid_key_list.append(element)
else:
print('Catalogue Attribute %s is not a recognised '\
'catalogue key' % element)
return valid_key_list
def _float_check(attribute_array, value):
"""
Checks if value is valid float, appends to array if valid, appends
nan if not
"""
value = value.strip(' ')
if value:
attribute_array = np.hstack([attribute_array, float(value)])
else:
attribute_array = np.hstack([attribute_array, np.nan])
return attribute_array
def _int_check(attribute_array, value):
"""
Checks if value is valid integer, appends to array if valid, appends
nan if not
"""
value = value.strip(' ')
if value:
attribute_array = np.hstack([attribute_array, int(value)])
else:
attribute_array = np.hstack([attribute_array, np.nan])
return attribute_array
class GenericCataloguetoISFParser(object):
'''
Reads the generic csv catalogue file to return an instance of the
ISFCatalogue class
'''
def __init__(self, filename):
'''
'''
self.filename = filename
self.catalogue = GeneralCsvCatalogue()
def parse(self, cat_id, cat_name):
'''
Opens the raw file parses the catalogue then exports
'''
filedata = open(self.filename, 'rU')
#self.catalogue = GeneralCsvCatalogue()
# Reading the data file
data = csv.DictReader(filedata)
# Parsing the data content
for irow, row in enumerate(data):
if irow == 0:
valid_key_list = _header_check(list(row.keys()),
self.catalogue.TOTAL_ATTRIBUTE_LIST)
for key in valid_key_list:
if key in self.catalogue.FLOAT_ATTRIBUTE_LIST:
self.catalogue.data[key] = _float_check(
self.catalogue.data[key],
row[key])
elif key in self.catalogue.INT_ATTRIBUTE_LIST:
self.catalogue.data[key] = _int_check(
self.catalogue.data[key],
row[key])
else:
self.catalogue.data[key].append(row[key])
output_cat = self.export(cat_id, cat_name)
return output_cat
def export(self, cat_id=None, cat_name=None):
"""
Exports the catalogue to ISF Format
"""
return self.catalogue.write_to_isf_catalogue(cat_id, cat_name)
class GenericCataloguetoGCMT(GenericCataloguetoISFParser):
'''
Reads the generic csv catalogue file to return an instance of the
GCMT class class
'''
def export(self, cat_id=None, cat_name=None):
"""
Exports the catalogue to GCMT format
"""
return catalogue.write_to_gcmt_class()
class GCMTtoISFParser(object):
'''
Read in a file in GCMT NDK format and parse to ISF Catalogue
'''
def __init__(self, gcmt_file=None):
'''
'''
if gcmt_file:
self.filename = gcmt_file
parser = ParseNDKtoGCMT(self.filename)
self.catalogue = parser.read_file()
else:
self.filename = None
self.catalogue = None
@classmethod
def from_catalogue(cls, catalogue, cat_id, cat_name):
"""
If a different parser has been used just instantiate the class
"""
self = cls()
self.catalogue = catalogue
if not len(self.catalogue):
print("No events in catalogue - returning None")
return None
return self.parse(cat_id, cat_name)
def parse(self, cat_id="GCMT", cat_name="GCMT"):
'''
Returns the catalogue as an instance of an ISFCatalogue
An ISF catalogue will have two origins: The hypocentre solution and
the centroid
'''
isf_cat = ISFCatalogue(cat_id, cat_name)
n_cmts = self.catalogue.number_events()
base_id = cat_id + '_'
counter = 1
for gcmt in self.catalogue.gcmts:
# Get IDs
event_id = base_id + ("%06d" % counter)
counter += 1
origin_id = gcmt.identifier.strip(' ')
# Two origins - 1 hypocentre (mb, Ms, Mw), 2 - centroid (Mw)
origin_mags = []
if gcmt.hypocentre.m_b:
origin_mags.append(Magnitude(event_id,
origin_id,
gcmt.hypocentre.m_b,
gcmt.hypocentre.source,
scale='mb'))
if gcmt.hypocentre.m_s:
origin_mags.append(Magnitude(event_id,
origin_id,
gcmt.hypocentre.m_s,
gcmt.hypocentre.source,
scale='Ms'))
m_w = Magnitude(event_id,
origin_id + "-C", gcmt.magnitude, cat_id,
scale='Mw')
#origin_mags.append(m_w)
# Get locations
hypo_loc = Location(origin_id,
gcmt.hypocentre.longitude,
gcmt.hypocentre.latitude,
gcmt.hypocentre.depth)
centroid_loc = Location(origin_id + "-C",
gcmt.centroid.longitude,
gcmt.centroid.latitude,
gcmt.centroid.depth,
depth_error=gcmt.centroid.depth_error)
# Get origins
hypo = Origin(origin_id,
gcmt.hypocentre.date,
gcmt.hypocentre.time,
hypo_loc,
gcmt.hypocentre.source,
is_prime=True)
hypo.magnitudes = origin_mags
# Get centroids
centroid = Origin(origin_id + "-C",
gcmt.centroid.date,
gcmt.centroid.time,
centroid_loc,
cat_id,
is_centroid=True,
time_error=gcmt.centroid.time_error)
centroid.magnitudes = [m_w]
event = Event(event_id, [hypo, centroid],
hypo.magnitudes + centroid.magnitudes,
gcmt.hypocentre.location)
setattr(event, 'tensor', gcmt.moment_tensor)
isf_cat.events.append(event)
return isf_cat
| agpl-3.0 |
nzavagli/UnrealPy | UnrealPyEmbed/Source/Python/Lib/python27/encodings/cp861.py | 593 | 34889 | """ Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP861.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp861',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00d0, # LATIN CAPITAL LETTER ETH
0x008c: 0x00f0, # LATIN SMALL LETTER ETH
0x008d: 0x00de, # LATIN CAPITAL LETTER THORN
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00fe, # LATIN SMALL LETTER THORN
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE
0x0098: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE
0x00a5: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE
0x00a6: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE
0x00a7: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Decoding Table
decoding_table = (
u'\x00' # 0x0000 -> NULL
u'\x01' # 0x0001 -> START OF HEADING
u'\x02' # 0x0002 -> START OF TEXT
u'\x03' # 0x0003 -> END OF TEXT
u'\x04' # 0x0004 -> END OF TRANSMISSION
u'\x05' # 0x0005 -> ENQUIRY
u'\x06' # 0x0006 -> ACKNOWLEDGE
u'\x07' # 0x0007 -> BELL
u'\x08' # 0x0008 -> BACKSPACE
u'\t' # 0x0009 -> HORIZONTAL TABULATION
u'\n' # 0x000a -> LINE FEED
u'\x0b' # 0x000b -> VERTICAL TABULATION
u'\x0c' # 0x000c -> FORM FEED
u'\r' # 0x000d -> CARRIAGE RETURN
u'\x0e' # 0x000e -> SHIFT OUT
u'\x0f' # 0x000f -> SHIFT IN
u'\x10' # 0x0010 -> DATA LINK ESCAPE
u'\x11' # 0x0011 -> DEVICE CONTROL ONE
u'\x12' # 0x0012 -> DEVICE CONTROL TWO
u'\x13' # 0x0013 -> DEVICE CONTROL THREE
u'\x14' # 0x0014 -> DEVICE CONTROL FOUR
u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x0016 -> SYNCHRONOUS IDLE
u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x0018 -> CANCEL
u'\x19' # 0x0019 -> END OF MEDIUM
u'\x1a' # 0x001a -> SUBSTITUTE
u'\x1b' # 0x001b -> ESCAPE
u'\x1c' # 0x001c -> FILE SEPARATOR
u'\x1d' # 0x001d -> GROUP SEPARATOR
u'\x1e' # 0x001e -> RECORD SEPARATOR
u'\x1f' # 0x001f -> UNIT SEPARATOR
u' ' # 0x0020 -> SPACE
u'!' # 0x0021 -> EXCLAMATION MARK
u'"' # 0x0022 -> QUOTATION MARK
u'#' # 0x0023 -> NUMBER SIGN
u'$' # 0x0024 -> DOLLAR SIGN
u'%' # 0x0025 -> PERCENT SIGN
u'&' # 0x0026 -> AMPERSAND
u"'" # 0x0027 -> APOSTROPHE
u'(' # 0x0028 -> LEFT PARENTHESIS
u')' # 0x0029 -> RIGHT PARENTHESIS
u'*' # 0x002a -> ASTERISK
u'+' # 0x002b -> PLUS SIGN
u',' # 0x002c -> COMMA
u'-' # 0x002d -> HYPHEN-MINUS
u'.' # 0x002e -> FULL STOP
u'/' # 0x002f -> SOLIDUS
u'0' # 0x0030 -> DIGIT ZERO
u'1' # 0x0031 -> DIGIT ONE
u'2' # 0x0032 -> DIGIT TWO
u'3' # 0x0033 -> DIGIT THREE
u'4' # 0x0034 -> DIGIT FOUR
u'5' # 0x0035 -> DIGIT FIVE
u'6' # 0x0036 -> DIGIT SIX
u'7' # 0x0037 -> DIGIT SEVEN
u'8' # 0x0038 -> DIGIT EIGHT
u'9' # 0x0039 -> DIGIT NINE
u':' # 0x003a -> COLON
u';' # 0x003b -> SEMICOLON
u'<' # 0x003c -> LESS-THAN SIGN
u'=' # 0x003d -> EQUALS SIGN
u'>' # 0x003e -> GREATER-THAN SIGN
u'?' # 0x003f -> QUESTION MARK
u'@' # 0x0040 -> COMMERCIAL AT
u'A' # 0x0041 -> LATIN CAPITAL LETTER A
u'B' # 0x0042 -> LATIN CAPITAL LETTER B
u'C' # 0x0043 -> LATIN CAPITAL LETTER C
u'D' # 0x0044 -> LATIN CAPITAL LETTER D
u'E' # 0x0045 -> LATIN CAPITAL LETTER E
u'F' # 0x0046 -> LATIN CAPITAL LETTER F
u'G' # 0x0047 -> LATIN CAPITAL LETTER G
u'H' # 0x0048 -> LATIN CAPITAL LETTER H
u'I' # 0x0049 -> LATIN CAPITAL LETTER I
u'J' # 0x004a -> LATIN CAPITAL LETTER J
u'K' # 0x004b -> LATIN CAPITAL LETTER K
u'L' # 0x004c -> LATIN CAPITAL LETTER L
u'M' # 0x004d -> LATIN CAPITAL LETTER M
u'N' # 0x004e -> LATIN CAPITAL LETTER N
u'O' # 0x004f -> LATIN CAPITAL LETTER O
u'P' # 0x0050 -> LATIN CAPITAL LETTER P
u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
u'R' # 0x0052 -> LATIN CAPITAL LETTER R
u'S' # 0x0053 -> LATIN CAPITAL LETTER S
u'T' # 0x0054 -> LATIN CAPITAL LETTER T
u'U' # 0x0055 -> LATIN CAPITAL LETTER U
u'V' # 0x0056 -> LATIN CAPITAL LETTER V
u'W' # 0x0057 -> LATIN CAPITAL LETTER W
u'X' # 0x0058 -> LATIN CAPITAL LETTER X
u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
u'Z' # 0x005a -> LATIN CAPITAL LETTER Z
u'[' # 0x005b -> LEFT SQUARE BRACKET
u'\\' # 0x005c -> REVERSE SOLIDUS
u']' # 0x005d -> RIGHT SQUARE BRACKET
u'^' # 0x005e -> CIRCUMFLEX ACCENT
u'_' # 0x005f -> LOW LINE
u'`' # 0x0060 -> GRAVE ACCENT
u'a' # 0x0061 -> LATIN SMALL LETTER A
u'b' # 0x0062 -> LATIN SMALL LETTER B
u'c' # 0x0063 -> LATIN SMALL LETTER C
u'd' # 0x0064 -> LATIN SMALL LETTER D
u'e' # 0x0065 -> LATIN SMALL LETTER E
u'f' # 0x0066 -> LATIN SMALL LETTER F
u'g' # 0x0067 -> LATIN SMALL LETTER G
u'h' # 0x0068 -> LATIN SMALL LETTER H
u'i' # 0x0069 -> LATIN SMALL LETTER I
u'j' # 0x006a -> LATIN SMALL LETTER J
u'k' # 0x006b -> LATIN SMALL LETTER K
u'l' # 0x006c -> LATIN SMALL LETTER L
u'm' # 0x006d -> LATIN SMALL LETTER M
u'n' # 0x006e -> LATIN SMALL LETTER N
u'o' # 0x006f -> LATIN SMALL LETTER O
u'p' # 0x0070 -> LATIN SMALL LETTER P
u'q' # 0x0071 -> LATIN SMALL LETTER Q
u'r' # 0x0072 -> LATIN SMALL LETTER R
u's' # 0x0073 -> LATIN SMALL LETTER S
u't' # 0x0074 -> LATIN SMALL LETTER T
u'u' # 0x0075 -> LATIN SMALL LETTER U
u'v' # 0x0076 -> LATIN SMALL LETTER V
u'w' # 0x0077 -> LATIN SMALL LETTER W
u'x' # 0x0078 -> LATIN SMALL LETTER X
u'y' # 0x0079 -> LATIN SMALL LETTER Y
u'z' # 0x007a -> LATIN SMALL LETTER Z
u'{' # 0x007b -> LEFT CURLY BRACKET
u'|' # 0x007c -> VERTICAL LINE
u'}' # 0x007d -> RIGHT CURLY BRACKET
u'~' # 0x007e -> TILDE
u'\x7f' # 0x007f -> DELETE
u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE
u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA
u'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE
u'\xd0' # 0x008b -> LATIN CAPITAL LETTER ETH
u'\xf0' # 0x008c -> LATIN SMALL LETTER ETH
u'\xde' # 0x008d -> LATIN CAPITAL LETTER THORN
u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE
u'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE
u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xfe' # 0x0095 -> LATIN SMALL LETTER THORN
u'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xdd' # 0x0097 -> LATIN CAPITAL LETTER Y WITH ACUTE
u'\xfd' # 0x0098 -> LATIN SMALL LETTER Y WITH ACUTE
u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xf8' # 0x009b -> LATIN SMALL LETTER O WITH STROKE
u'\xa3' # 0x009c -> POUND SIGN
u'\xd8' # 0x009d -> LATIN CAPITAL LETTER O WITH STROKE
u'\u20a7' # 0x009e -> PESETA SIGN
u'\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK
u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE
u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE
u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE
u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE
u'\xc1' # 0x00a4 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xcd' # 0x00a5 -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xd3' # 0x00a6 -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xda' # 0x00a7 -> LATIN CAPITAL LETTER U WITH ACUTE
u'\xbf' # 0x00a8 -> INVERTED QUESTION MARK
u'\u2310' # 0x00a9 -> REVERSED NOT SIGN
u'\xac' # 0x00aa -> NOT SIGN
u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF
u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER
u'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK
u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2591' # 0x00b0 -> LIGHT SHADE
u'\u2592' # 0x00b1 -> MEDIUM SHADE
u'\u2593' # 0x00b2 -> DARK SHADE
u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL
u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
u'\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
u'\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
u'\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
u'\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL
u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT
u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT
u'\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
u'\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT
u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT
u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL
u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
u'\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
u'\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL
u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
u'\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
u'\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
u'\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
u'\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
u'\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
u'\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
u'\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
u'\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
u'\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
u'\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT
u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT
u'\u2588' # 0x00db -> FULL BLOCK
u'\u2584' # 0x00dc -> LOWER HALF BLOCK
u'\u258c' # 0x00dd -> LEFT HALF BLOCK
u'\u2590' # 0x00de -> RIGHT HALF BLOCK
u'\u2580' # 0x00df -> UPPER HALF BLOCK
u'\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA
u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S
u'\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA
u'\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI
u'\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA
u'\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA
u'\xb5' # 0x00e6 -> MICRO SIGN
u'\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU
u'\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI
u'\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA
u'\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA
u'\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA
u'\u221e' # 0x00ec -> INFINITY
u'\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI
u'\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON
u'\u2229' # 0x00ef -> INTERSECTION
u'\u2261' # 0x00f0 -> IDENTICAL TO
u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN
u'\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO
u'\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO
u'\u2320' # 0x00f4 -> TOP HALF INTEGRAL
u'\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL
u'\xf7' # 0x00f6 -> DIVISION SIGN
u'\u2248' # 0x00f7 -> ALMOST EQUAL TO
u'\xb0' # 0x00f8 -> DEGREE SIGN
u'\u2219' # 0x00f9 -> BULLET OPERATOR
u'\xb7' # 0x00fa -> MIDDLE DOT
u'\u221a' # 0x00fb -> SQUARE ROOT
u'\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N
u'\xb2' # 0x00fd -> SUPERSCRIPT TWO
u'\u25a0' # 0x00fe -> BLACK SQUARE
u'\xa0' # 0x00ff -> NO-BREAK SPACE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0025: 0x0025, # PERCENT SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK
0x00a3: 0x009c, # POUND SIGN
0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00ac: 0x00aa, # NOT SIGN
0x00b0: 0x00f8, # DEGREE SIGN
0x00b1: 0x00f1, # PLUS-MINUS SIGN
0x00b2: 0x00fd, # SUPERSCRIPT TWO
0x00b5: 0x00e6, # MICRO SIGN
0x00b7: 0x00fa, # MIDDLE DOT
0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER
0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF
0x00bf: 0x00a8, # INVERTED QUESTION MARK
0x00c1: 0x00a4, # LATIN CAPITAL LETTER A WITH ACUTE
0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE
0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA
0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE
0x00cd: 0x00a5, # LATIN CAPITAL LETTER I WITH ACUTE
0x00d0: 0x008b, # LATIN CAPITAL LETTER ETH
0x00d3: 0x00a6, # LATIN CAPITAL LETTER O WITH ACUTE
0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x00d8: 0x009d, # LATIN CAPITAL LETTER O WITH STROKE
0x00da: 0x00a7, # LATIN CAPITAL LETTER U WITH ACUTE
0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00dd: 0x0097, # LATIN CAPITAL LETTER Y WITH ACUTE
0x00de: 0x008d, # LATIN CAPITAL LETTER THORN
0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S
0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE
0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE
0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS
0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE
0x00e6: 0x0091, # LATIN SMALL LIGATURE AE
0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA
0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE
0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE
0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS
0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE
0x00f0: 0x008c, # LATIN SMALL LETTER ETH
0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE
0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS
0x00f7: 0x00f6, # DIVISION SIGN
0x00f8: 0x009b, # LATIN SMALL LETTER O WITH STROKE
0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE
0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS
0x00fd: 0x0098, # LATIN SMALL LETTER Y WITH ACUTE
0x00fe: 0x0095, # LATIN SMALL LETTER THORN
0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK
0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA
0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA
0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA
0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI
0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA
0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA
0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA
0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON
0x03c0: 0x00e3, # GREEK SMALL LETTER PI
0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA
0x03c4: 0x00e7, # GREEK SMALL LETTER TAU
0x03c6: 0x00ed, # GREEK SMALL LETTER PHI
0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N
0x20a7: 0x009e, # PESETA SIGN
0x2219: 0x00f9, # BULLET OPERATOR
0x221a: 0x00fb, # SQUARE ROOT
0x221e: 0x00ec, # INFINITY
0x2229: 0x00ef, # INTERSECTION
0x2248: 0x00f7, # ALMOST EQUAL TO
0x2261: 0x00f0, # IDENTICAL TO
0x2264: 0x00f3, # LESS-THAN OR EQUAL TO
0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO
0x2310: 0x00a9, # REVERSED NOT SIGN
0x2320: 0x00f4, # TOP HALF INTEGRAL
0x2321: 0x00f5, # BOTTOM HALF INTEGRAL
0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL
0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL
0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT
0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL
0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT
0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2580: 0x00df, # UPPER HALF BLOCK
0x2584: 0x00dc, # LOWER HALF BLOCK
0x2588: 0x00db, # FULL BLOCK
0x258c: 0x00dd, # LEFT HALF BLOCK
0x2590: 0x00de, # RIGHT HALF BLOCK
0x2591: 0x00b0, # LIGHT SHADE
0x2592: 0x00b1, # MEDIUM SHADE
0x2593: 0x00b2, # DARK SHADE
0x25a0: 0x00fe, # BLACK SQUARE
}
| mit |
digris/openbroadcast.org | website/apps/exporter/views.py | 2 | 3128 | import logging
from django.views.generic import ListView, UpdateView, CreateView, DeleteView, View
from django.views.generic.detail import TemplateResponseMixin
from django.views.generic.edit import FormMixin, ProcessFormView
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponse
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.utils.functional import lazy
from django import http
import json
from braces.views import PermissionRequiredMixin, LoginRequiredMixin
from sendfile import sendfile
from exporter.models import Export
log = logging.getLogger(__name__)
class JSONResponseMixin(object):
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
def get_json_response(self, content, **httpresponse_kwargs):
"Construct an `HttpResponse` object."
return http.HttpResponse(
content, content_type="application/json", **httpresponse_kwargs
)
def convert_context_to_json(self, context):
return json.dumps(context["result"])
class ExportListView(PermissionRequiredMixin, LoginRequiredMixin, ListView):
model = Export
permission_required = "exporter.add_export"
raise_exception = True
def get_queryset(self):
kwargs = {}
return Export.objects.filter(user=self.request.user)
class ExportDeleteView(PermissionRequiredMixin, LoginRequiredMixin, DeleteView):
model = Export
success_url = lazy(reverse, str)("exporter-export-list-legacy")
permission_required = "exporter.delete_export"
raise_exception = True
def get_queryset(self):
kwargs = {}
return Export.objects.filter(user=self.request.user)
class ExportDeleteAllView(PermissionRequiredMixin, LoginRequiredMixin, View):
model = Export
success_url = lazy(reverse, str)("exporter-export-list-legacy")
permission_required = "exporter.delete_export"
raise_exception = True
def get_queryset(self):
kwargs = {}
return Export.objects.filter(user=self.request.user)
def get(self, *args, **kwargs):
Export.objects.filter(user=self.request.user).delete()
return HttpResponseRedirect(reverse("exporter-export-list-legacy"))
@login_required
def export_download(request, uuid, token):
log = logging.getLogger("exporter.views.export_download")
log.info("Download Request by: %s" % (request.user.username))
export = get_object_or_404(Export, uuid=uuid)
download_permission = False
if request.user == export.user and token == export.token:
download_permission = True
if not download_permission:
return HttpResponseForbidden("forbidden")
filename = "%s.%s" % (export.filename, "zip")
export.set_downloaded()
return sendfile(
request, export.file.path, attachment=True, attachment_filename=filename
)
| gpl-3.0 |
julianwang/cinder | cinder/tests/unit/api/contrib/test_snapshot_actions.py | 2 | 2791 | # Copyright 2013, Red Hat, 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 oslo_serialization import jsonutils
import webob
from cinder import db
from cinder import test
from cinder.tests.unit.api import fakes
from cinder.tests.unit.api.v2 import stubs
class SnapshotActionsTest(test.TestCase):
def setUp(self):
super(SnapshotActionsTest, self).setUp()
def test_update_snapshot_status(self):
self.stubs.Set(db, 'snapshot_get', stub_snapshot_get)
self.stubs.Set(db, 'snapshot_update', stub_snapshot_update)
body = {'os-update_snapshot_status': {'status': 'available'}}
req = webob.Request.blank('/v2/fake/snapshots/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 202)
def test_update_snapshot_status_invalid_status(self):
self.stubs.Set(db, 'snapshot_get', stub_snapshot_get)
body = {'os-update_snapshot_status': {'status': 'in-use'}}
req = webob.Request.blank('/v2/fake/snapshots/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 400)
def test_update_snapshot_status_without_status(self):
self.stubs.Set(db, 'snapshot_get', stub_snapshot_get)
body = {'os-update_snapshot_status': {}}
req = webob.Request.blank('/v2/fake/snapshots/1/action')
req.method = "POST"
req.body = jsonutils.dumps(body)
req.headers["content-type"] = "application/json"
res = req.get_response(fakes.wsgi_app())
self.assertEqual(res.status_int, 400)
def stub_snapshot_get(context, snapshot_id):
snapshot = stubs.stub_snapshot(snapshot_id)
if snapshot_id == 3:
snapshot['status'] = 'error'
elif snapshot_id == 1:
snapshot['status'] = 'creating'
elif snapshot_id == 7:
snapshot['status'] = 'available'
else:
snapshot['status'] = 'creating'
return snapshot
def stub_snapshot_update(self, context, id, **kwargs):
pass
| apache-2.0 |
ooici/pyon | pyon/ion/conversation_log.py | 1 | 2865 | #!/usr/bin/env python
"""Conversation Log"""
__author__ = 'Prashant Kediyal'
from pyon.core import bootstrap
from pyon.core.exception import BadRequest
from pyon.datastore.datastore import DataStore
from pyon.net.endpoint import Subscriber
from pyon.util.async import spawn
from pyon.util.log import log
from interface.objects import ConversationMessage
# @TODO: configurable
CONV_DS_NAME = 'conversations'
class ConvSubscriber(Subscriber):
def __init__(self, callback=None, pattern='#', *args, **kwargs):
"""
Note: a ConversationSubscriber needs to be closed to free broker resources
"""
self._cbthread = None
self.binding = pattern
log.debug("ConversationSubscriber pattern %s", self.binding)
Subscriber.__init__(self, binding=self.binding, callback=callback, **kwargs)
def start(self):
"""
Pass in a subscriber here, this will make it listen in a background greenlet.
"""
assert not self._cbthread, "start called twice on ConversationSubscriber"
gl = spawn(self.listen)
self._cbthread = gl
self._ready_event.wait(timeout=5)
log.info("ConversationSubscriber started; pattern=%s" % self.binding)
return gl
def stop(self):
self.close()
self._cbthread.join(timeout=5)
self._cbthread.kill()
self._cbthread = None
log.info("ConversationSubscriber stopped. Conversation pattern=%s" % self.binding)
def __str__(self):
return "ConversationSubscriber callback: %s" % str(self._callback)
class ConvRepository(object):
"""
Class that uses a data store to provide a persistent repository for ION events.
"""
def __init__(self, datastore_manager=None):
# Get an instance of datastore configured as directory.
# May be persistent or mock, forced clean, with indexes
datastore_manager = datastore_manager or bootstrap.container_instance.datastore_manager
self.conv_store = datastore_manager.get_datastore(DataStore.DS_CONVERSATIONS, DataStore.DS_PROFILE.CONV)
def close(self):
"""
Pass-through method to close the underlying datastore.
"""
self.conv_store.close()
def put_conv(self, conv):
log.debug("Store %s conversation persistently")
if not isinstance(conv, ConversationMessage):
raise BadRequest("conv must be type ConversationMessage, not %s" % type(conv))
return self.conv_store.create(conv)
def put_convs(self, convs):
log.debug("Store %s conversation persistently", len(convs))
if convs:
if type(convs) is not list:
raise BadRequest("Conversation must be type list, not %s" % type(convs))
return self.conv_store.create_mult(convs)
else:
return None
| bsd-2-clause |
ivanhorvath/openshift-tools | ansible/roles/lib_openshift_3.2/build/ansible/oc_edit.py | 13 | 3158 | # pylint: skip-file
def main():
'''
ansible oc module for editing objects
'''
module = AnsibleModule(
argument_spec=dict(
kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'),
state=dict(default='present', type='str',
choices=['present']),
debug=dict(default=False, type='bool'),
namespace=dict(default='default', type='str'),
name=dict(default=None, required=True, type='str'),
kind=dict(required=True,
type='str',
choices=['dc', 'deploymentconfig',
'rc', 'replicationcontroller',
'svc', 'service',
'scc', 'securitycontextconstraints',
'ns', 'namespace', 'project', 'projects',
'is', 'imagestream',
'istag', 'imagestreamtag',
'bc', 'buildconfig',
'routes',
'node',
'secret',
'pv', 'persistentvolume',
]),
file_name=dict(default=None, type='str'),
file_format=dict(default='yaml', type='str'),
content=dict(default=None, required=True, type='dict'),
force=dict(default=False, type='bool'),
separator=dict(default='.', type='str'),
),
supports_check_mode=True,
)
ocedit = Edit(module.params['kind'],
module.params['namespace'],
module.params['name'],
kubeconfig=module.params['kubeconfig'],
separator=module.params['separator'],
verbose=module.params['debug'])
state = module.params['state']
api_rval = ocedit.get()
########
# Create
########
if not Utils.exists(api_rval['results'], module.params['name']):
module.fail_json(msg=api_rval)
########
# Update
########
api_rval = ocedit.update(module.params['file_name'],
module.params['content'],
module.params['force'],
module.params['file_format'])
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
if api_rval.has_key('updated') and not api_rval['updated']:
module.exit_json(changed=False, results=api_rval, state="present")
# return the created object
api_rval = ocedit.get()
if api_rval['returncode'] != 0:
module.fail_json(msg=api_rval)
module.exit_json(changed=True, results=api_rval, state="present")
module.exit_json(failed=True,
changed=False,
results='Unknown state passed. %s' % state,
state="unknown")
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
# import module snippets. This are required
from ansible.module_utils.basic import *
main()
| apache-2.0 |
battlemidget/conjure-up | test/test_controllers_summary_gui.py | 1 | 2092 | #!/usr/bin/env python
#
# tests controllers/summary/gui.py
#
# Copyright 2016 Canonical, Ltd.
import unittest
from unittest.mock import MagicMock, call, patch, sentinel
from conjureup.controllers.summary.gui import SummaryController
class SummaryGUIRenderTestCase(unittest.TestCase):
def setUp(self):
self.finish_patcher = patch(
'conjureup.controllers.summary.gui.SummaryController.finish')
self.mock_finish = self.finish_patcher.start()
self.view_patcher = patch(
'conjureup.controllers.summary.gui.SummaryView')
self.view_patcher.start()
self.app_patcher = patch(
'conjureup.controllers.summary.gui.app')
mock_app = self.app_patcher.start()
mock_app.ui = MagicMock(name="app.ui")
self.controller = SummaryController()
self.controller.save_path = sentinel.savepath
def tearDown(self):
self.finish_patcher.stop()
self.view_patcher.stop()
self.app_patcher.stop()
def test_render_empty(self):
"call render with no results"
with patch("conjureup.controllers.summary.gui.common") as m_c:
self.controller.render({})
m_c.write_results.assert_called_once_with({}, sentinel.savepath)
class SummaryGUIFinishTestCase(unittest.TestCase):
def setUp(self):
self.render_patcher = patch(
'conjureup.controllers.summary.gui.SummaryController.render')
self.mock_render = self.render_patcher.start()
self.app_patcher = patch(
'conjureup.controllers.summary.gui.app')
self.mock_app = self.app_patcher.start()
self.mock_app.ui = MagicMock(name="app.ui")
self.controller = SummaryController()
def tearDown(self):
self.render_patcher.stop()
self.app_patcher.stop()
def test_finish(self):
"finish should stop event loop"
with patch("conjureup.controllers.summary.gui.EventLoop") as m_ev:
self.controller.finish()
m_ev.assert_has_calls([call.remove_alarms(), call.exit(0)])
| mit |
deadblue/baidupan_shell | pyasn1/codec/ber/encoder.py | 185 | 13626 | # BER encoder
from pyasn1.type import base, tag, univ, char, useful
from pyasn1.codec.ber import eoo
from pyasn1.compat.octets import int2oct, oct2int, ints2octs, null, str2octs
from pyasn1 import debug, error
class Error(Exception): pass
class AbstractItemEncoder:
supportIndefLenMode = 1
def encodeTag(self, t, isConstructed):
tagClass, tagFormat, tagId = t.asTuple() # this is a hotspot
v = tagClass | tagFormat
if isConstructed:
v = v|tag.tagFormatConstructed
if tagId < 31:
return int2oct(v|tagId)
else:
s = int2oct(tagId&0x7f)
tagId = tagId >> 7
while tagId:
s = int2oct(0x80|(tagId&0x7f)) + s
tagId = tagId >> 7
return int2oct(v|0x1F) + s
def encodeLength(self, length, defMode):
if not defMode and self.supportIndefLenMode:
return int2oct(0x80)
if length < 0x80:
return int2oct(length)
else:
substrate = null
while length:
substrate = int2oct(length&0xff) + substrate
length = length >> 8
substrateLen = len(substrate)
if substrateLen > 126:
raise Error('Length octets overflow (%d)' % substrateLen)
return int2oct(0x80 | substrateLen) + substrate
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
raise Error('Not implemented')
def _encodeEndOfOctets(self, encodeFun, defMode):
if defMode or not self.supportIndefLenMode:
return null
else:
return encodeFun(eoo.endOfOctets, defMode)
def encode(self, encodeFun, value, defMode, maxChunkSize):
substrate, isConstructed = self.encodeValue(
encodeFun, value, defMode, maxChunkSize
)
tagSet = value.getTagSet()
if tagSet:
if not isConstructed: # primitive form implies definite mode
defMode = 1
return self.encodeTag(
tagSet[-1], isConstructed
) + self.encodeLength(
len(substrate), defMode
) + substrate + self._encodeEndOfOctets(encodeFun, defMode)
else:
return substrate # untagged value
class EndOfOctetsEncoder(AbstractItemEncoder):
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
return null, 0
class ExplicitlyTaggedItemEncoder(AbstractItemEncoder):
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
if isinstance(value, base.AbstractConstructedAsn1Item):
value = value.clone(tagSet=value.getTagSet()[:-1],
cloneValueFlag=1)
else:
value = value.clone(tagSet=value.getTagSet()[:-1])
return encodeFun(value, defMode, maxChunkSize), 1
explicitlyTaggedItemEncoder = ExplicitlyTaggedItemEncoder()
class BooleanEncoder(AbstractItemEncoder):
supportIndefLenMode = 0
_true = ints2octs((1,))
_false = ints2octs((0,))
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
return value and self._true or self._false, 0
class IntegerEncoder(AbstractItemEncoder):
supportIndefLenMode = 0
supportCompactZero = False
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
if value == 0: # shortcut for zero value
if self.supportCompactZero:
# this seems to be a correct way for encoding zeros
return null, 0
else:
# this seems to be a widespread way for encoding zeros
return ints2octs((0,)), 0
octets = []
value = int(value) # to save on ops on asn1 type
while 1:
octets.insert(0, value & 0xff)
if value == 0 or value == -1:
break
value = value >> 8
if value == 0 and octets[0] & 0x80:
octets.insert(0, 0)
while len(octets) > 1 and \
(octets[0] == 0 and octets[1] & 0x80 == 0 or \
octets[0] == 0xff and octets[1] & 0x80 != 0):
del octets[0]
return ints2octs(octets), 0
class BitStringEncoder(AbstractItemEncoder):
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
if not maxChunkSize or len(value) <= maxChunkSize*8:
r = {}; l = len(value); p = 0; j = 7
while p < l:
i, j = divmod(p, 8)
r[i] = r.get(i,0) | value[p]<<(7-j)
p = p + 1
keys = list(r); keys.sort()
return int2oct(7-j) + ints2octs([r[k] for k in keys]), 0
else:
pos = 0; substrate = null
while 1:
# count in octets
v = value.clone(value[pos*8:pos*8+maxChunkSize*8])
if not v:
break
substrate = substrate + encodeFun(v, defMode, maxChunkSize)
pos = pos + maxChunkSize
return substrate, 1
class OctetStringEncoder(AbstractItemEncoder):
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
if not maxChunkSize or len(value) <= maxChunkSize:
return value.asOctets(), 0
else:
pos = 0; substrate = null
while 1:
v = value.clone(value[pos:pos+maxChunkSize])
if not v:
break
substrate = substrate + encodeFun(v, defMode, maxChunkSize)
pos = pos + maxChunkSize
return substrate, 1
class NullEncoder(AbstractItemEncoder):
supportIndefLenMode = 0
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
return null, 0
class ObjectIdentifierEncoder(AbstractItemEncoder):
supportIndefLenMode = 0
precomputedValues = {
(1, 3, 6, 1, 2): (43, 6, 1, 2),
(1, 3, 6, 1, 4): (43, 6, 1, 4)
}
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
oid = value.asTuple()
if oid[:5] in self.precomputedValues:
octets = self.precomputedValues[oid[:5]]
index = 5
else:
if len(oid) < 2:
raise error.PyAsn1Error('Short OID %s' % (value,))
# Build the first twos
if oid[0] > 6 or oid[1] > 39 or oid[0] == 6 and oid[1] > 15:
raise error.PyAsn1Error(
'Initial sub-ID overflow %s in OID %s' % (oid[:2], value)
)
octets = (oid[0] * 40 + oid[1],)
index = 2
# Cycle through subids
for subid in oid[index:]:
if subid > -1 and subid < 128:
# Optimize for the common case
octets = octets + (subid & 0x7f,)
elif subid < 0 or subid > 0xFFFFFFFF:
raise error.PyAsn1Error(
'SubId overflow %s in %s' % (subid, value)
)
else:
# Pack large Sub-Object IDs
res = (subid & 0x7f,)
subid = subid >> 7
while subid > 0:
res = (0x80 | (subid & 0x7f),) + res
subid = subid >> 7
# Add packed Sub-Object ID to resulted Object ID
octets += res
return ints2octs(octets), 0
class RealEncoder(AbstractItemEncoder):
supportIndefLenMode = 0
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
if value.isPlusInfinity():
return int2oct(0x40), 0
if value.isMinusInfinity():
return int2oct(0x41), 0
m, b, e = value
if not m:
return null, 0
if b == 10:
return str2octs('\x03%dE%s%d' % (m, e == 0 and '+' or '', e)), 0
elif b == 2:
fo = 0x80 # binary enoding
if m < 0:
fo = fo | 0x40 # sign bit
m = -m
while int(m) != m: # drop floating point
m *= 2
e -= 1
while m & 0x1 == 0: # mantissa normalization
m >>= 1
e += 1
eo = null
while e not in (0, -1):
eo = int2oct(e&0xff) + eo
e >>= 8
if e == 0 and eo and oct2int(eo[0]) & 0x80:
eo = int2oct(0) + eo
n = len(eo)
if n > 0xff:
raise error.PyAsn1Error('Real exponent overflow')
if n == 1:
pass
elif n == 2:
fo |= 1
elif n == 3:
fo |= 2
else:
fo |= 3
eo = int2oct(n//0xff+1) + eo
po = null
while m:
po = int2oct(m&0xff) + po
m >>= 8
substrate = int2oct(fo) + eo + po
return substrate, 0
else:
raise error.PyAsn1Error('Prohibited Real base %s' % b)
class SequenceEncoder(AbstractItemEncoder):
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
value.setDefaultComponents()
value.verifySizeSpec()
substrate = null; idx = len(value)
while idx > 0:
idx = idx - 1
if value[idx] is None: # Optional component
continue
component = value.getDefaultComponentByPosition(idx)
if component is not None and component == value[idx]:
continue
substrate = encodeFun(
value[idx], defMode, maxChunkSize
) + substrate
return substrate, 1
class SequenceOfEncoder(AbstractItemEncoder):
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
value.verifySizeSpec()
substrate = null; idx = len(value)
while idx > 0:
idx = idx - 1
substrate = encodeFun(
value[idx], defMode, maxChunkSize
) + substrate
return substrate, 1
class ChoiceEncoder(AbstractItemEncoder):
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
return encodeFun(value.getComponent(), defMode, maxChunkSize), 1
class AnyEncoder(OctetStringEncoder):
def encodeValue(self, encodeFun, value, defMode, maxChunkSize):
return value.asOctets(), defMode == 0
tagMap = {
eoo.endOfOctets.tagSet: EndOfOctetsEncoder(),
univ.Boolean.tagSet: BooleanEncoder(),
univ.Integer.tagSet: IntegerEncoder(),
univ.BitString.tagSet: BitStringEncoder(),
univ.OctetString.tagSet: OctetStringEncoder(),
univ.Null.tagSet: NullEncoder(),
univ.ObjectIdentifier.tagSet: ObjectIdentifierEncoder(),
univ.Enumerated.tagSet: IntegerEncoder(),
univ.Real.tagSet: RealEncoder(),
# Sequence & Set have same tags as SequenceOf & SetOf
univ.SequenceOf.tagSet: SequenceOfEncoder(),
univ.SetOf.tagSet: SequenceOfEncoder(),
univ.Choice.tagSet: ChoiceEncoder(),
# character string types
char.UTF8String.tagSet: OctetStringEncoder(),
char.NumericString.tagSet: OctetStringEncoder(),
char.PrintableString.tagSet: OctetStringEncoder(),
char.TeletexString.tagSet: OctetStringEncoder(),
char.VideotexString.tagSet: OctetStringEncoder(),
char.IA5String.tagSet: OctetStringEncoder(),
char.GraphicString.tagSet: OctetStringEncoder(),
char.VisibleString.tagSet: OctetStringEncoder(),
char.GeneralString.tagSet: OctetStringEncoder(),
char.UniversalString.tagSet: OctetStringEncoder(),
char.BMPString.tagSet: OctetStringEncoder(),
# useful types
useful.GeneralizedTime.tagSet: OctetStringEncoder(),
useful.UTCTime.tagSet: OctetStringEncoder()
}
# Type-to-codec map for ambiguous ASN.1 types
typeMap = {
univ.Set.typeId: SequenceEncoder(),
univ.SetOf.typeId: SequenceOfEncoder(),
univ.Sequence.typeId: SequenceEncoder(),
univ.SequenceOf.typeId: SequenceOfEncoder(),
univ.Choice.typeId: ChoiceEncoder(),
univ.Any.typeId: AnyEncoder()
}
class Encoder:
def __init__(self, tagMap, typeMap={}):
self.__tagMap = tagMap
self.__typeMap = typeMap
def __call__(self, value, defMode=1, maxChunkSize=0):
debug.logger & debug.flagEncoder and debug.logger('encoder called in %sdef mode, chunk size %s for type %s, value:\n%s' % (not defMode and 'in' or '', maxChunkSize, value.__class__.__name__, value.prettyPrint()))
tagSet = value.getTagSet()
if len(tagSet) > 1:
concreteEncoder = explicitlyTaggedItemEncoder
else:
if value.typeId is not None and value.typeId in self.__typeMap:
concreteEncoder = self.__typeMap[value.typeId]
elif tagSet in self.__tagMap:
concreteEncoder = self.__tagMap[tagSet]
else:
tagSet = value.baseTagSet
if tagSet in self.__tagMap:
concreteEncoder = self.__tagMap[tagSet]
else:
raise Error('No encoder for %s' % (value,))
debug.logger & debug.flagEncoder and debug.logger('using value codec %s chosen by %r' % (concreteEncoder.__class__.__name__, tagSet))
substrate = concreteEncoder.encode(
self, value, defMode, maxChunkSize
)
debug.logger & debug.flagEncoder and debug.logger('built %s octets of substrate: %s\nencoder completed' % (len(substrate), debug.hexdump(substrate)))
return substrate
encode = Encoder(tagMap, typeMap)
| gpl-2.0 |
keerts/home-assistant | homeassistant/util/async.py | 22 | 5833 | """Asyncio backports for Python 3.4.3 compatibility."""
import concurrent.futures
import threading
import logging
from asyncio import coroutines
from asyncio.futures import Future
try:
# pylint: disable=ungrouped-imports
from asyncio import ensure_future
except ImportError:
# Python 3.4.3 and earlier has this as async
# pylint: disable=unused-import
from asyncio import async
ensure_future = async
_LOGGER = logging.getLogger(__name__)
def _set_result_unless_cancelled(fut, result):
"""Helper setting the result only if the future was not cancelled."""
if fut.cancelled():
return
fut.set_result(result)
def _set_concurrent_future_state(concurr, source):
"""Copy state from a future to a concurrent.futures.Future."""
assert source.done()
if source.cancelled():
concurr.cancel()
if not concurr.set_running_or_notify_cancel():
return
exception = source.exception()
if exception is not None:
concurr.set_exception(exception)
else:
result = source.result()
concurr.set_result(result)
def _copy_future_state(source, dest):
"""Internal helper to copy state from another Future.
The other Future may be a concurrent.futures.Future.
"""
assert source.done()
if dest.cancelled():
return
assert not dest.done()
if source.cancelled():
dest.cancel()
else:
exception = source.exception()
if exception is not None:
dest.set_exception(exception)
else:
result = source.result()
dest.set_result(result)
def _chain_future(source, destination):
"""Chain two futures so that when one completes, so does the other.
The result (or exception) of source will be copied to destination.
If destination is cancelled, source gets cancelled too.
Compatible with both asyncio.Future and concurrent.futures.Future.
"""
if not isinstance(source, (Future, concurrent.futures.Future)):
raise TypeError('A future is required for source argument')
if not isinstance(destination, (Future, concurrent.futures.Future)):
raise TypeError('A future is required for destination argument')
# pylint: disable=protected-access
source_loop = source._loop if isinstance(source, Future) else None
dest_loop = destination._loop if isinstance(destination, Future) else None
def _set_state(future, other):
if isinstance(future, Future):
_copy_future_state(other, future)
else:
_set_concurrent_future_state(future, other)
def _call_check_cancel(destination):
if destination.cancelled():
if source_loop is None or source_loop is dest_loop:
source.cancel()
else:
source_loop.call_soon_threadsafe(source.cancel)
def _call_set_state(source):
if dest_loop is None or dest_loop is source_loop:
_set_state(destination, source)
else:
dest_loop.call_soon_threadsafe(_set_state, destination, source)
destination.add_done_callback(_call_check_cancel)
source.add_done_callback(_call_set_state)
def run_coroutine_threadsafe(coro, loop):
"""Submit a coroutine object to a given event loop.
Return a concurrent.futures.Future to access the result.
"""
ident = loop.__dict__.get("_thread_ident")
if ident is not None and ident == threading.get_ident():
raise RuntimeError('Cannot be called from within the event loop')
if not coroutines.iscoroutine(coro):
raise TypeError('A coroutine object is required')
future = concurrent.futures.Future()
def callback():
"""Callback to call the coroutine."""
try:
# pylint: disable=deprecated-method
_chain_future(ensure_future(coro, loop=loop), future)
# pylint: disable=broad-except
except Exception as exc:
if future.set_running_or_notify_cancel():
future.set_exception(exc)
else:
_LOGGER.warning("Exception on lost future: ", exc_info=True)
loop.call_soon_threadsafe(callback)
return future
def fire_coroutine_threadsafe(coro, loop):
"""Submit a coroutine object to a given event loop.
This method does not provide a way to retrieve the result and
is intended for fire-and-forget use. This reduces the
work involved to fire the function on the loop.
"""
ident = loop.__dict__.get("_thread_ident")
if ident is not None and ident == threading.get_ident():
raise RuntimeError('Cannot be called from within the event loop')
if not coroutines.iscoroutine(coro):
raise TypeError('A coroutine object is required: %s' % coro)
def callback():
"""Callback to fire coroutine."""
# pylint: disable=deprecated-method
ensure_future(coro, loop=loop)
loop.call_soon_threadsafe(callback)
return
def run_callback_threadsafe(loop, callback, *args):
"""Submit a callback object to a given event loop.
Return a concurrent.futures.Future to access the result.
"""
ident = loop.__dict__.get("_thread_ident")
if ident is not None and ident == threading.get_ident():
raise RuntimeError('Cannot be called from within the event loop')
future = concurrent.futures.Future()
def run_callback():
"""Run callback and store result."""
try:
future.set_result(callback(*args))
# pylint: disable=broad-except
except Exception as exc:
if future.set_running_or_notify_cancel():
future.set_exception(exc)
else:
_LOGGER.warning("Exception on lost future: ", exc_info=True)
loop.call_soon_threadsafe(run_callback)
return future
| apache-2.0 |
NewCaliforniaWaterAtlas/ca-freshwater-species-backend | wkg/data_loader.py | 1 | 11204 | #!/usr/bin/env python
#
# Run this from the top level as
#
# honcho run python wkg/data_loader.py 'subdirectory'
#
import os
import psycopg2
from petl import *
import argparse
# get the subdirectory containing the .csv files from the command line and check that it exists.
#
parser = argparse.ArgumentParser(description='Import .csv files for the Freshwater Species Database.')
parser.add_argument('subdir', help="name of the database subdirectory (expected to be in 'wkg/')")
args = parser.parse_args()
if not os.path.exists(os.path.join('wkg', args.subdir)):
print('Error: ' + args.subdir + " does not exist as a subdirectory of 'wkg/'.")
exit()
# Set up the database connection
#
connection = psycopg2.connect(
database=os.environ['DB'],
user=os.environ['DB_USER'],
password=os.environ['DB_PASSWORD'],
host=os.environ['DB_HOST'],
)
cursor = connection.cursor()
# Origin: create, map, and load
#
cursor.execute("""
DROP TABLE IF EXISTS origins CASCADE;
CREATE TABLE origins (
id BIGSERIAL NOT NULL UNIQUE PRIMARY KEY,
org_id INTEGER NOT NULL UNIQUE,
org_name VARCHAR(32) NOT NULL
);
""")
f = fromcsv(os.path.join('wkg', args.subdir, 'Origin.csv'))
f = cutout(f, 'OBJECTID')
f = rename(f, {
'Org_ID': 'org_id',
'Org_Name': 'org_name',
})
f = convertnumbers(f)
todb(f, connection, 'origins')
# ObservationType: create, map, and load
#
cursor.execute("""
DROP TABLE IF EXISTS observation_types CASCADE;
CREATE TABLE observation_types (
id BIGSERIAL NOT NULL UNIQUE PRIMARY KEY,
obs_typ_id INTEGER UNIQUE,
obs_typ_name VARCHAR(64) NOT NULL UNIQUE,
range_obs VARCHAR(32),
current_other VARCHAR(32),
group_ VARCHAR(32)
);
""")
f = fromcsv(os.path.join('wkg', args.subdir, 'ObservationType.csv'))
f = cutout(f, 'OBJECTID')
f = rename(f, {
'ObsTyp_ID': 'obs_typ_id',
'ObsTyp_Name': 'obs_typ_name',
'Range_Obs': 'range_obs',
'Current_Other': 'current_other',
'Group_': 'group_',
})
f = convertnumbers(f)
todb(f, connection, 'observation_types')
# Source: create, map, and load
#
# @todo source_name should be UNIQUE.
cursor.execute("""
DROP TABLE IF EXISTS sources CASCADE;
CREATE TABLE sources (
id BIGSERIAL NOT NULL UNIQUE PRIMARY KEY,
source_id INTEGER NOT NULL UNIQUE,
source_name VARCHAR(256),
sourcegrp_name VARCHAR(64),
use_agree TEXT,
permission_request_needed VARCHAR(64),
permission_contact_name VARCHAR(32),
permission_contact_email VARCHAR(64),
permission_status TEXT,
permission VARCHAR(32),
comment_id INTEGER,
citation TEXT,
weblink VARCHAR(128),
pre_release_review VARCHAR(8),
aggregator VARCHAR(32),
count_huc12s INTEGER,
count_elm_ids INTEGER
);
CREATE INDEX ON sources (source_id);
""")
f = fromcsv(os.path.join('wkg', args.subdir, 'Source.csv'))
f = cutout(f, 'OBJECTID')
f = rename(f, {
'Source_ID': 'source_id',
'Source_Name': 'source_name',
'SourceGrp_Name': 'sourcegrp_name',
'Use_agree': 'use_agree',
'Permission_request_needed': 'permission_request_needed',
'Permission_contact_name': 'permission_contact_name',
'Permission_contact_email': 'permission_contact_email',
'Permission_status': 'permission_status',
'Permission': 'permission',
'Comment_ID': 'comment_id',
'Citation': 'citation',
'Weblink': 'weblink',
'Pre_release_review': 'pre_release_review',
'Aggregator': 'aggregator',
'Count_HUC12s': 'count_huc12s',
'Count_Elm_IDs': 'count_elm_ids'
})
f = convertnumbers(f)
f = convert(f, (
'source_id',
'comment_id',
'count_huc12s',
'count_elm_ids',
), lambda v: int(v))
todb(f, connection, 'sources')
# HabitatUsage: create, map, and load
#
cursor.execute("""
DROP TABLE IF EXISTS habitat_usages CASCADE;
CREATE TABLE habitat_usages (
id BIGSERIAL NOT NULL UNIQUE PRIMARY KEY,
hab_usage_id INTEGER UNIQUE,
hab_usage_name VARCHAR(32) UNIQUE
);
""")
f = fromcsv(os.path.join('wkg', args.subdir, 'HabitatUsage.csv'))
f = cutout(f, 'OBJECTID')
f = rename(f, {
'HabU_ID': 'hab_usage_id',
'HabU_Name': 'hab_usage_name',
})
f = convertnumbers(f)
todb(f, connection, 'habitat_usages')
# Element: create, map, and load
#
cursor.execute("""
DROP TABLE IF EXISTS elements CASCADE;
CREATE TABLE elements (
id BIGSERIAL NOT NULL UNIQUE PRIMARY KEY,
elm_scinam VARCHAR(64),
elm_comnam VARCHAR(64),
group_ VARCHAR(32) NOT NULL,
fwa_v1 INTEGER,
tax_list VARCHAR(32),
g_rank VARCHAR(16),
s_rank VARCHAR(32),
elm_scin_1 VARCHAR(64),
elm_scin_2 VARCHAR(64),
elm_scin_3 VARCHAR(64),
elm_scin_4 VARCHAR(64),
kingdom VARCHAR(32),
phylum VARCHAR(32),
tax_class VARCHAR(32),
tax_order VARCHAR(32),
family VARCHAR(32),
genus VARCHAR(32),
species VARCHAR(32),
subsp_var VARCHAR(32),
kingdom_id VARCHAR(5),
phylum_id VARCHAR(5),
tax_class_i VARCHAR(5),
tax_order_i VARCHAR(5),
family_id VARCHAR(5),
genus_id VARCHAR(5),
species_id VARCHAR(5),
elm_id INTEGER NOT NULL UNIQUE,
other_id VARCHAR(5),
sensitive_fam VARCHAR(32),
ns_endemic INTEGER,
safit_endemic INTEGER,
other_endemic INTEGER,
endemism_comment TEXT,
fed_list VARCHAR(64),
state_list VARCHAR(64),
other_list VARCHAR(64),
mgtag_list VARCHAR(32),
listed BOOLEAN,
vulnerable BOOLEAN,
endemic BOOLEAN,
common BOOLEAN,
not_evaluated BOOLEAN,
extinct BOOLEAN,
status VARCHAR(32)
);
CREATE INDEX ON elements (elm_id);
CREATE INDEX ON elements (group_);
""")
f = fromcsv(os.path.join('wkg', args.subdir, 'Elements.csv'))
f = cutout(f, 'OBJECTID')
f = rename(f, {
'ELM_SCINAM': 'elm_scinam',
'ELM_COMNAM': 'elm_comnam',
'GROUP_': 'group_',
'FWA_v1': 'fwa_v1',
'TAX_LIST': 'tax_list',
'G_Rank': 'g_rank',
'S_Rank': 's_rank',
'ELM_SCIN_1': 'elm_scin_1',
'ELM_SCIN_2': 'elm_scin_2',
'ELM_SCIN_3': 'elm_scin_3',
'ELM_SCIN_4': 'elm_scin_4',
'Kingdom': 'kingdom',
'Phylum': 'phylum',
'TaxClass': 'tax_class',
'TaxOrder': 'tax_order',
'Family': 'family',
'Genus': 'genus',
'Species': 'species',
'Subsp_Var': 'subsp_var',
'Kingdom_ID': 'kingdom_id',
'Phylum_ID': 'phylum_id',
'TaxClass_I': 'tax_class_i',
'TaxOrder_I': 'tax_order_i',
'Family_ID': 'family_id',
'Genus_ID': 'genus_id',
'Species_ID': 'species_id',
'ELM_ID': 'elm_id',
'Other_ID': 'other_id',
'Sensitive_Fam': 'sensitive_fam',
'NS_endemic': 'ns_endemic',
'SAFIT_endemic': 'safit_endemic',
'Other_endemic': 'other_endemic',
'Endemism_comment': 'endemism_comment',
'Fed_list': 'fed_list',
'State_list': 'state_list',
'Other_list': 'other_list',
'MgtAg_list': 'mgtag_list',
'Listed': 'listed',
'Vulnerable': 'vulnerable',
'Endemic': 'endemic',
'Common': 'common',
'Not_evaluated': 'not_evaluated',
'Extinct': 'extinct',
'Status': 'status',
})
# @todo resolve this hack: Deal with the mussels (multiple rows having elm_id = 81077)
f = selectnotin(f, 'elm_scinam', [
'Anodonta californiensis',
'Anodonta dejecta',
'Anodonta oregonensis',
])
# Attempt to pull the comma-as-thousands separator out.
f = sub(f, (
'fwa_v1',
'kingdom_id',
'phylum_id',
'tax_class_i',
'tax_order_i',
'family_id',
'genus_id',
'species_id',
'elm_id',
'other_id',
), ',', '')
# Convert the new values to integers; this can handle nulls.
f = convert(f, (
'fwa_v1',
'elm_id',
), lambda v: int(v))
# Don't really have to do this, but seems cleaner.
f = convert(f, (
'listed',
'vulnerable',
'endemic',
'common',
'not_evaluated',
'extinct',
), { 0: False, 1 : True })
todb(f, connection, 'elements')
# AU_v_elm: create, map, and load
#
cursor.execute("""
DROP TABLE IF EXISTS au_v_elms CASCADE;
CREATE TABLE au_v_elms (
id BIGSERIAL NOT NULL UNIQUE PRIMARY KEY,
elm_id INTEGER REFERENCES elements (elm_id),
huc_12 VARCHAR(12),
obs_typ_id INTEGER REFERENCES observation_types (obs_typ_id),
source_id INTEGER REFERENCES sources (source_id),
frequency DOUBLE PRECISION,
sum_amount DOUBLE PRECISION
);
""")
f = fromcsv(os.path.join('wkg', args.subdir, 'AU_v_Elm_sum.csv'))
f = cutout(f, 'OID_')
f = rename(f, {
'Elm_ID': 'elm_id',
'HUC_12': 'huc_12',
'ObsTyp_ID': 'obs_typ_id',
'Source_ID': 'source_id',
'FREQUENCY': 'frequency',
'SUM_Amount': 'sum_amount',
})
f = sub(f, (
'elm_id',
'source_id',
'sum_amount',
), ',', '')
f = convert(f, ('elm_id', 'source_id'), lambda v: int(float(v)))
f = convert(f, ('sum_amount'), lambda v: float(v))
todb(f, connection, 'au_v_elms')
# Persist and be tidy
connection.commit()
cursor.close()
connection.close()
| mit |
JioCloud/nova | nova/tests/unit/scheduler/test_filter_scheduler.py | 20 | 14276 | # Copyright 2011 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
# under the License.
"""
Tests For Filter Scheduler.
"""
import mock
from nova import exception
from nova.scheduler import filter_scheduler
from nova.scheduler import host_manager
from nova.scheduler import utils as scheduler_utils
from nova.scheduler import weights
from nova.tests.unit.scheduler import fakes
from nova.tests.unit.scheduler import test_scheduler
def fake_get_filtered_hosts(hosts, filter_properties, index):
return list(hosts)
class FilterSchedulerTestCase(test_scheduler.SchedulerTestCase):
"""Test case for Filter Scheduler."""
driver_cls = filter_scheduler.FilterScheduler
@mock.patch('nova.objects.ServiceList.get_by_binary',
return_value=fakes.SERVICES)
@mock.patch('nova.objects.InstanceList.get_by_host')
@mock.patch('nova.objects.ComputeNodeList.get_all',
return_value=fakes.COMPUTE_NODES)
@mock.patch('nova.db.instance_extra_get_by_instance_uuid',
return_value={'numa_topology': None,
'pci_requests': None})
def test_schedule_happy_day(self, mock_get_extra, mock_get_all,
mock_by_host, mock_get_by_binary):
"""Make sure there's nothing glaringly wrong with _schedule()
by doing a happy day pass through.
"""
self.next_weight = 1.0
def _fake_weigh_objects(_self, functions, hosts, options):
self.next_weight += 2.0
host_state = hosts[0]
return [weights.WeighedHost(host_state, self.next_weight)]
self.stubs.Set(self.driver.host_manager, 'get_filtered_hosts',
fake_get_filtered_hosts)
self.stubs.Set(weights.HostWeightHandler,
'get_weighed_objects', _fake_weigh_objects)
request_spec = {'num_instances': 10,
'instance_type': {'memory_mb': 512, 'root_gb': 512,
'ephemeral_gb': 0,
'vcpus': 1},
'instance_properties': {'project_id': 1,
'root_gb': 512,
'memory_mb': 512,
'ephemeral_gb': 0,
'vcpus': 1,
'os_type': 'Linux',
'uuid': 'fake-uuid'}}
self.mox.ReplayAll()
weighed_hosts = self.driver._schedule(self.context, request_spec, {})
self.assertEqual(len(weighed_hosts), 10)
for weighed_host in weighed_hosts:
self.assertIsNotNone(weighed_host.obj)
def test_max_attempts(self):
self.flags(scheduler_max_attempts=4)
self.assertEqual(4, scheduler_utils._max_attempts())
def test_invalid_max_attempts(self):
self.flags(scheduler_max_attempts=0)
self.assertRaises(exception.NovaException,
scheduler_utils._max_attempts)
def test_add_retry_host(self):
retry = dict(num_attempts=1, hosts=[])
filter_properties = dict(retry=retry)
host = "fakehost"
node = "fakenode"
scheduler_utils._add_retry_host(filter_properties, host, node)
hosts = filter_properties['retry']['hosts']
self.assertEqual(1, len(hosts))
self.assertEqual([host, node], hosts[0])
def test_post_select_populate(self):
# Test addition of certain filter props after a node is selected.
retry = {'hosts': [], 'num_attempts': 1}
filter_properties = {'retry': retry}
host_state = host_manager.HostState('host', 'node')
host_state.limits['vcpus'] = 5
scheduler_utils.populate_filter_properties(filter_properties,
host_state)
self.assertEqual(['host', 'node'],
filter_properties['retry']['hosts'][0])
self.assertEqual({'vcpus': 5}, host_state.limits)
@mock.patch('nova.objects.ServiceList.get_by_binary',
return_value=fakes.SERVICES)
@mock.patch('nova.objects.InstanceList.get_by_host')
@mock.patch('nova.objects.ComputeNodeList.get_all',
return_value=fakes.COMPUTE_NODES)
@mock.patch('nova.db.instance_extra_get_by_instance_uuid',
return_value={'numa_topology': None,
'pci_requests': None})
def test_schedule_host_pool(self, mock_get_extra, mock_get_all,
mock_by_host, mock_get_by_binary):
"""Make sure the scheduler_host_subset_size property works properly."""
self.flags(scheduler_host_subset_size=2)
self.stubs.Set(self.driver.host_manager, 'get_filtered_hosts',
fake_get_filtered_hosts)
instance_properties = {'project_id': 1,
'root_gb': 512,
'memory_mb': 512,
'ephemeral_gb': 0,
'vcpus': 1,
'os_type': 'Linux',
'uuid': 'fake-uuid'}
request_spec = dict(instance_properties=instance_properties,
instance_type={})
filter_properties = {}
self.mox.ReplayAll()
hosts = self.driver._schedule(self.context, request_spec,
filter_properties=filter_properties)
# one host should be chosen
self.assertEqual(len(hosts), 1)
@mock.patch('nova.objects.ServiceList.get_by_binary',
return_value=fakes.SERVICES)
@mock.patch('nova.objects.InstanceList.get_by_host')
@mock.patch('nova.objects.ComputeNodeList.get_all',
return_value=fakes.COMPUTE_NODES)
@mock.patch('nova.db.instance_extra_get_by_instance_uuid',
return_value={'numa_topology': None,
'pci_requests': None})
def test_schedule_large_host_pool(self, mock_get_extra, mock_get_all,
mock_by_host, mock_get_by_binary):
"""Hosts should still be chosen if pool size
is larger than number of filtered hosts.
"""
self.flags(scheduler_host_subset_size=20)
self.stubs.Set(self.driver.host_manager, 'get_filtered_hosts',
fake_get_filtered_hosts)
instance_properties = {'project_id': 1,
'root_gb': 512,
'memory_mb': 512,
'ephemeral_gb': 0,
'vcpus': 1,
'os_type': 'Linux',
'uuid': 'fake-uuid'}
request_spec = dict(instance_properties=instance_properties,
instance_type={})
filter_properties = {}
self.mox.ReplayAll()
hosts = self.driver._schedule(self.context, request_spec,
filter_properties=filter_properties)
# one host should be chose
self.assertEqual(len(hosts), 1)
@mock.patch('nova.scheduler.host_manager.HostManager._add_instance_info')
@mock.patch('nova.objects.ServiceList.get_by_binary',
return_value=fakes.SERVICES)
@mock.patch('nova.objects.ComputeNodeList.get_all',
return_value=fakes.COMPUTE_NODES)
@mock.patch('nova.db.instance_extra_get_by_instance_uuid',
return_value={'numa_topology': None,
'pci_requests': None})
def test_schedule_chooses_best_host(self, mock_get_extra, mock_cn_get_all,
mock_get_by_binary,
mock_add_inst_info):
"""If scheduler_host_subset_size is 1, the largest host with greatest
weight should be returned.
"""
self.flags(scheduler_host_subset_size=1)
self.stubs.Set(self.driver.host_manager, 'get_filtered_hosts',
fake_get_filtered_hosts)
self.next_weight = 50
def _fake_weigh_objects(_self, functions, hosts, options):
this_weight = self.next_weight
self.next_weight = 0
host_state = hosts[0]
return [weights.WeighedHost(host_state, this_weight)]
instance_properties = {'project_id': 1,
'root_gb': 512,
'memory_mb': 512,
'ephemeral_gb': 0,
'vcpus': 1,
'os_type': 'Linux',
'uuid': 'fake-uuid'}
request_spec = dict(instance_properties=instance_properties,
instance_type={})
self.stubs.Set(weights.HostWeightHandler,
'get_weighed_objects', _fake_weigh_objects)
filter_properties = {}
self.mox.ReplayAll()
hosts = self.driver._schedule(self.context, request_spec,
filter_properties=filter_properties)
# one host should be chosen
self.assertEqual(1, len(hosts))
self.assertEqual(50, hosts[0].weight)
@mock.patch('nova.objects.ServiceList.get_by_binary',
return_value=fakes.SERVICES)
@mock.patch('nova.objects.InstanceList.get_by_host')
@mock.patch('nova.objects.ComputeNodeList.get_all',
return_value=fakes.COMPUTE_NODES)
@mock.patch('nova.db.instance_extra_get_by_instance_uuid',
return_value={'numa_topology': None,
'pci_requests': None})
def test_select_destinations(self, mock_get_extra, mock_get_all,
mock_by_host, mock_get_by_binary):
"""select_destinations is basically a wrapper around _schedule().
Similar to the _schedule tests, this just does a happy path test to
ensure there is nothing glaringly wrong.
"""
self.next_weight = 1.0
selected_hosts = []
selected_nodes = []
def _fake_weigh_objects(_self, functions, hosts, options):
self.next_weight += 2.0
host_state = hosts[0]
selected_hosts.append(host_state.host)
selected_nodes.append(host_state.nodename)
return [weights.WeighedHost(host_state, self.next_weight)]
self.stubs.Set(self.driver.host_manager, 'get_filtered_hosts',
fake_get_filtered_hosts)
self.stubs.Set(weights.HostWeightHandler,
'get_weighed_objects', _fake_weigh_objects)
request_spec = {'instance_type': {'memory_mb': 512, 'root_gb': 512,
'ephemeral_gb': 0,
'vcpus': 1},
'instance_properties': {'project_id': 1,
'root_gb': 512,
'memory_mb': 512,
'ephemeral_gb': 0,
'vcpus': 1,
'os_type': 'Linux',
'uuid': 'fake-uuid'},
'num_instances': 1}
self.mox.ReplayAll()
dests = self.driver.select_destinations(self.context, request_spec, {})
(host, node) = (dests[0]['host'], dests[0]['nodename'])
self.assertEqual(host, selected_hosts[0])
self.assertEqual(node, selected_nodes[0])
@mock.patch.object(filter_scheduler.FilterScheduler, '_schedule')
def test_select_destinations_notifications(self, mock_schedule):
mock_schedule.return_value = [mock.Mock()]
with mock.patch.object(self.driver.notifier, 'info') as mock_info:
request_spec = {'num_instances': 1}
self.driver.select_destinations(self.context, request_spec, {})
expected = [
mock.call(self.context, 'scheduler.select_destinations.start',
dict(request_spec=request_spec)),
mock.call(self.context, 'scheduler.select_destinations.end',
dict(request_spec=request_spec))]
self.assertEqual(expected, mock_info.call_args_list)
def test_select_destinations_no_valid_host(self):
def _return_no_host(*args, **kwargs):
return []
self.stubs.Set(self.driver, '_schedule', _return_no_host)
self.assertRaises(exception.NoValidHost,
self.driver.select_destinations, self.context,
{'num_instances': 1}, {})
def test_select_destinations_no_valid_host_not_enough(self):
# Tests that we have fewer hosts available than number of instances
# requested to build.
consumed_hosts = [mock.MagicMock(), mock.MagicMock()]
with mock.patch.object(self.driver, '_schedule',
return_value=consumed_hosts):
try:
self.driver.select_destinations(
self.context, {'num_instances': 3}, {})
self.fail('Expected NoValidHost to be raised.')
except exception.NoValidHost as e:
# Make sure that we provided a reason why NoValidHost.
self.assertIn('reason', e.kwargs)
self.assertTrue(len(e.kwargs['reason']) > 0)
# Make sure that the consumed hosts have chance to be reverted.
for host in consumed_hosts:
self.assertIsNone(host.obj.updated)
| apache-2.0 |
BT-ojossen/odoo | openerp/service/report.py | 324 | 5148 | # -*- coding: utf-8 -*-
import base64
import logging
import sys
import threading
import openerp
import openerp.report
from openerp import tools
import security
_logger = logging.getLogger(__name__)
# TODO: set a maximum report number per user to avoid DOS attacks
#
# Report state:
# False -> True
self_reports = {}
self_id = 0
self_id_protect = threading.Semaphore()
def dispatch(method, params):
(db, uid, passwd ) = params[0:3]
threading.current_thread().uid = uid
params = params[3:]
if method not in ['report', 'report_get', 'render_report']:
raise KeyError("Method not supported %s" % method)
security.check(db,uid,passwd)
openerp.modules.registry.RegistryManager.check_registry_signaling(db)
fn = globals()['exp_' + method]
res = fn(db, uid, *params)
openerp.modules.registry.RegistryManager.signal_caches_change(db)
return res
def exp_render_report(db, uid, object, ids, datas=None, context=None):
if not datas:
datas={}
if not context:
context={}
self_id_protect.acquire()
global self_id
self_id += 1
id = self_id
self_id_protect.release()
self_reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None}
cr = openerp.registry(db).cursor()
try:
result, format = openerp.report.render_report(cr, uid, ids, object, datas, context)
if not result:
tb = sys.exc_info()
self_reports[id]['exception'] = openerp.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb)
self_reports[id]['result'] = result
self_reports[id]['format'] = format
self_reports[id]['state'] = True
except Exception, exception:
_logger.exception('Exception: %s\n', exception)
if hasattr(exception, 'name') and hasattr(exception, 'value'):
self_reports[id]['exception'] = openerp.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value))
else:
tb = sys.exc_info()
self_reports[id]['exception'] = openerp.exceptions.DeferredException(tools.exception_to_unicode(exception), tb)
self_reports[id]['state'] = True
cr.commit()
cr.close()
return _check_report(id)
def exp_report(db, uid, object, ids, datas=None, context=None):
if not datas:
datas={}
if not context:
context={}
self_id_protect.acquire()
global self_id
self_id += 1
id = self_id
self_id_protect.release()
self_reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None}
def go(id, uid, ids, datas, context):
with openerp.api.Environment.manage():
cr = openerp.registry(db).cursor()
try:
result, format = openerp.report.render_report(cr, uid, ids, object, datas, context)
if not result:
tb = sys.exc_info()
self_reports[id]['exception'] = openerp.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb)
self_reports[id]['result'] = result
self_reports[id]['format'] = format
self_reports[id]['state'] = True
except Exception, exception:
_logger.exception('Exception: %s\n', exception)
if hasattr(exception, 'name') and hasattr(exception, 'value'):
self_reports[id]['exception'] = openerp.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value))
else:
tb = sys.exc_info()
self_reports[id]['exception'] = openerp.exceptions.DeferredException(tools.exception_to_unicode(exception), tb)
self_reports[id]['state'] = True
cr.commit()
cr.close()
return True
threading.Thread(target=go, args=(id, uid, ids, datas, context)).start()
return id
def _check_report(report_id):
result = self_reports[report_id]
exc = result['exception']
if exc:
raise openerp.osv.orm.except_orm(exc.message, exc.traceback)
res = {'state': result['state']}
if res['state']:
if tools.config['reportgz']:
import zlib
res2 = zlib.compress(result['result'])
res['code'] = 'zlib'
else:
#CHECKME: why is this needed???
if isinstance(result['result'], unicode):
res2 = result['result'].encode('latin1', 'replace')
else:
res2 = result['result']
if res2:
res['result'] = base64.encodestring(res2)
res['format'] = result['format']
del self_reports[report_id]
return res
def exp_report_get(db, uid, report_id):
if report_id in self_reports:
if self_reports[report_id]['uid'] == uid:
return _check_report(report_id)
else:
raise Exception, 'AccessDenied'
else:
raise Exception, 'ReportNotFound'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
trishnaguha/ansible | lib/ansible/plugins/callback/cgroup_memory_recap.py | 95 | 4266 | # -*- coding: utf-8 -*-
# (c) 2018 Matt Martz <matt@sivel.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
callback: cgroup_memory_recap
callback_type: aggregate
requirements:
- whitelist in configuration
- cgroups
short_description: Profiles maximum memory usage of tasks and full execution using cgroups
version_added: "2.6"
description:
- This is an ansible callback plugin that profiles maximum memory usage of ansible and individual tasks, and displays a recap at the end using cgroups
notes:
- Requires ansible to be run from within a cgroup, such as with C(cgexec -g memory:ansible_profile ansible-playbook ...)
- This cgroup should only be used by ansible to get accurate results
- To create the cgroup, first use a command such as C(sudo cgcreate -a ec2-user:ec2-user -t ec2-user:ec2-user -g memory:ansible_profile)
options:
max_mem_file:
required: True
description: Path to cgroups C(memory.max_usage_in_bytes) file. Example C(/sys/fs/cgroup/memory/ansible_profile/memory.max_usage_in_bytes)
env:
- name: CGROUP_MAX_MEM_FILE
ini:
- section: callback_cgroupmemrecap
key: max_mem_file
cur_mem_file:
required: True
description: Path to C(memory.usage_in_bytes) file. Example C(/sys/fs/cgroup/memory/ansible_profile/memory.usage_in_bytes)
env:
- name: CGROUP_CUR_MEM_FILE
ini:
- section: callback_cgroupmemrecap
key: cur_mem_file
'''
import time
import threading
from ansible.plugins.callback import CallbackBase
class MemProf(threading.Thread):
"""Python thread for recording memory usage"""
def __init__(self, path, obj=None):
threading.Thread.__init__(self)
self.obj = obj
self.path = path
self.results = []
self.running = True
def run(self):
while self.running:
with open(self.path) as f:
val = f.read()
self.results.append(int(val.strip()) / 1024 / 1024)
time.sleep(0.001)
class CallbackModule(CallbackBase):
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'cgroup_memory_recap'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self, display=None):
super(CallbackModule, self).__init__(display)
self._task_memprof = None
self.task_results = []
def set_options(self, task_keys=None, var_options=None, direct=None):
super(CallbackModule, self).set_options(task_keys=task_keys, var_options=var_options, direct=direct)
self.cgroup_max_file = self.get_option('max_mem_file')
self.cgroup_current_file = self.get_option('cur_mem_file')
with open(self.cgroup_max_file, 'w+') as f:
f.write('0')
def _profile_memory(self, obj=None):
prev_task = None
results = None
try:
self._task_memprof.running = False
results = self._task_memprof.results
prev_task = self._task_memprof.obj
except AttributeError:
pass
if obj is not None:
self._task_memprof = MemProf(self.cgroup_current_file, obj=obj)
self._task_memprof.start()
if results is not None:
self.task_results.append((prev_task, max(results)))
def v2_playbook_on_task_start(self, task, is_conditional):
self._profile_memory(task)
def v2_playbook_on_stats(self, stats):
self._profile_memory()
with open(self.cgroup_max_file) as f:
max_results = int(f.read().strip()) / 1024 / 1024
self._display.banner('CGROUP MEMORY RECAP')
self._display.display('Execution Maximum: %0.2fMB\n\n' % max_results)
for task, memory in self.task_results:
self._display.display('%s (%s): %0.2fMB' % (task.get_name(), task._uuid, memory))
| gpl-3.0 |
kaarl/pyload | module/plugins/hoster/MegaCoNz.py | 1 | 14728 | # -*- coding: utf-8 -*-
import base64
import os
import random
import re
import struct
import Crypto.Cipher.AES
import Crypto.Util.Counter
from module.network.HTTPRequest import BadHeader
from module.plugins.internal.Hoster import Hoster
from module.plugins.internal.misc import decode, encode, exists, fsjoin, json
############################ General errors ###################################
# EINTERNAL (-1): An internal error has occurred. Please submit a bug report, detailing the exact circumstances in which this error occurred
# EARGS (-2): You have passed invalid arguments to this command
# EAGAIN (-3): (always at the request level) A temporary congestion or server malfunction prevented your request from being processed. No data was altered. Retry. Retries must be spaced with exponential backoff
# ERATELIMIT (-4): You have exceeded your command weight per time quota. Please wait a few seconds, then try again (this should never happen in sane real-life applications)
#
############################ Upload errors ####################################
# EFAILED (-5): The upload failed. Please restart it from scratch
# ETOOMANY (-6): Too many concurrent IP addresses are accessing this upload target URL
# ERANGE (-7): The upload file packet is out of range or not starting and ending on a chunk boundary
# EEXPIRED (-8): The upload target URL you are trying to access has expired. Please request a fresh one
#
############################ Stream/System errors #############################
# ENOENT (-9): Object (typically, node or user) not found
# ECIRCULAR (-10): Circular linkage attempted
# EACCESS (-11): Access violation (e.g., trying to write to a read-only share)
# EEXIST (-12): Trying to create an object that already exists
# EINCOMPLETE (-13): Trying to access an incomplete resource
# EKEY (-14): A decryption operation failed (never returned by the API)
# ESID (-15): Invalid or expired user session, please relogin
# EBLOCKED (-16): User blocked
# EOVERQUOTA (-17): Request over quota
# ETEMPUNAVAIL (-18): Resource temporarily not available, please try again later
# ETOOMANYCONNECTIONS (-19): Too many connections on this resource
# EWRITE (-20): Write failed
# EREAD (-21): Read failed
# EAPPKEY (-22): Invalid application key; request not processed
class MegaCrypto(object):
@staticmethod
def base64_decode(data):
data += '=' * (-len(data) % 4) #: Add padding, we need a string with a length multiple of 4
return base64.b64decode(str(data), "-_")
@staticmethod
def base64_encode(data):
return base64.b64encode(data, "-_")
@staticmethod
def a32_to_str(a):
return struct.pack(">%dI" % len(a), *a) #: big-endian, unsigned int
@staticmethod
def str_to_a32(s):
s += '\0' * (-len(s) % 4) # Add padding, we need a string with a length multiple of 4
return struct.unpack(">%dI" % (len(s) / 4), s) #: big-endian, unsigned int
@staticmethod
def base64_to_a32(s):
return MegaCrypto.str_to_a32(MegaCrypto.base64_decode(s))
@staticmethod
def cbc_decrypt(data, key):
cbc = Crypto.Cipher.AES.new(MegaCrypto.a32_to_str(key), Crypto.Cipher.AES.MODE_CBC, "\0" * 16)
return cbc.decrypt(data)
@staticmethod
def cbc_encrypt(data, key):
cbc = Crypto.Cipher.AES.new(MegaCrypto.a32_to_str(key), Crypto.Cipher.AES.MODE_CBC, "\0" * 16)
return cbc.encrypt(data)
@staticmethod
def get_cipher_key(key):
"""
Construct the cipher key from the given data
"""
k = (key[0] ^ key[4], key[1] ^ key[5], key[2] ^ key[6], key[3] ^ key[7])
iv = key[4:6] + (0, 0)
meta_mac = key[6:8]
return k, iv, meta_mac
@staticmethod
def decrypt_attr(data, key):
"""
Decrypt an encrypted attribute (usually 'a' or 'at' member of a node)
"""
data = MegaCrypto.base64_decode(data)
k, iv, meta_mac = MegaCrypto.get_cipher_key(key)
attr = MegaCrypto.cbc_decrypt(data, k)
#: Data is padded, 0-bytes must be stripped
return json.loads(re.search(r'{.+?}', attr).group(0)) if attr[:6] == 'MEGA{"' else False
@staticmethod
def decrypt_key(data, key):
"""
Decrypt an encrypted key ('k' member of a node)
"""
data = MegaCrypto.base64_decode(data)
return sum((MegaCrypto.str_to_a32(MegaCrypto.cbc_decrypt(data[_i:_i + 16], key))
for _i in xrange(0, len(data), 16)), ())
@staticmethod
def get_chunks(size):
"""
Calculate chunks for a given encrypted file size
"""
chunk_start = 0
chunk_size = 0x20000
while chunk_start + chunk_size < size:
yield (chunk_start, chunk_size)
chunk_start += chunk_size
if chunk_size < 0x100000:
chunk_size += 0x20000
if chunk_start < size:
yield (chunk_start, size - chunk_start)
class Checksum(object):
"""
interface for checking CBC-MAC checksum
"""
def __init__(self, key):
k, iv, meta_mac = MegaCrypto.get_cipher_key(key)
self.hash = '\0' * 16
self.key = MegaCrypto.a32_to_str(k)
self.iv = MegaCrypto.a32_to_str(iv[0:2] * 2)
self.AES = Crypto.Cipher.AES.new(self.key, mode=Crypto.Cipher.AES.MODE_CBC, IV=self.hash)
def update(self, chunk):
cbc = Crypto.Cipher.AES.new(self.key, mode=Crypto.Cipher.AES.MODE_CBC, IV=self.iv)
for j in xrange(0, len(chunk), 16):
block = chunk[j:j + 16].ljust(16, '\0')
hash = cbc.encrypt(block)
self.hash = self.AES.encrypt(hash)
def digest(self):
"""
Return the **binary** (non-printable) CBC-MAC of the message that has been authenticated so far.
"""
d = MegaCrypto.str_to_a32(self.hash)
return (d[0] ^ d[1], d[2] ^ d[3])
def hexdigest(self):
"""
Return the **printable** CBC-MAC of the message that has been authenticated so far.
"""
return "".join(["%02x" % ord(x)
for x in MegaCrypto.a32_to_str(self.digest())])
@staticmethod
def new(key):
return MegaCrypto.Checksum(key)
class MegaClient(object):
API_URL = "https://eu.api.mega.co.nz/cs"
def __init__(self, plugin, node_id):
self.plugin = plugin
self.node_id = node_id
def api_response(self, **kwargs):
"""
Dispatch a call to the api, see https://mega.co.nz/#developers
"""
uid = random.randint(10 << 9, 10 ** 10) #: Generate a session id, no idea where to obtain elsewhere
try:
res = self.plugin.load(self.API_URL,
get={'id': uid, 'n': self.node_id},
post=json.dumps([kwargs]))
except BadHeader, e:
if e.code == 500:
self.plugin.retry(wait_time=60, reason=_("Server busy"))
else:
raise
self.plugin.log_debug(_("Api Response: ") + res)
return json.loads(res)
def check_error(self, code):
ecode = abs(code)
if ecode in (9, 16, 21):
self.plugin.offline()
elif ecode in (3, 13, 17, 18, 19):
self.plugin.temp_offline()
elif ecode in (1, 4, 6, 10, 15, 21):
self.plugin.retry(max_tries=5, wait_time=30, reason=_("Error code: [%s]") % -ecode)
else:
self.plugin.fail(_("Error code: [%s]") % -ecode)
class MegaCoNz(Hoster):
__name__ = "MegaCoNz"
__type__ = "hoster"
__version__ = "0.46"
__status__ = "testing"
__pattern__ = r'(https?://(?:www\.)?mega(\.co)?\.nz/|mega:|chrome:.+?)#(?P<TYPE>N|)!(?P<ID>[\w^_]+)!(?P<KEY>[\w\-,=]+)(?:###n=(?P<OWNER>[\w^_]+))?'
__config__ = [("activated", "bool", "Activated", True)]
__description__ = """Mega.co.nz hoster plugin"""
__license__ = "GPLv3"
__authors__ = [("RaNaN", "ranan@pyload.org" ),
("Walter Purcaro", "vuolter@gmail.com" ),
("GammaC0de", "nitzo2001[AT}yahoo[DOT]com")]
FILE_SUFFIX = ".crypted"
def decrypt_file(self, key):
"""
Decrypts and verifies checksum to the file at 'last_download'
"""
k, iv, meta_mac = MegaCrypto.get_cipher_key(key)
ctr = Crypto.Util.Counter.new(128, initial_value = ((iv[0] << 32) + iv[1]) << 64)
cipher = Crypto.Cipher.AES.new(MegaCrypto.a32_to_str(k), Crypto.Cipher.AES.MODE_CTR, counter=ctr)
self.pyfile.setStatus("decrypting")
self.pyfile.setProgress(0)
file_crypted = encode(self.last_download)
file_decrypted = file_crypted.rsplit(self.FILE_SUFFIX)[0]
try:
f = open(file_crypted, "rb")
df = open(file_decrypted, "wb")
except IOError, e:
self.fail(e.message)
encrypted_size = os.path.getsize(file_crypted)
checksum_activated = self.config.get("activated", default=False, plugin="Checksum")
check_checksum = self.config.get("check_checksum", default=True, plugin="Checksum")
cbc_mac = MegaCrypto.Checksum(key) if checksum_activated and check_checksum else None
progress = 0
for chunk_start, chunk_size in MegaCrypto.get_chunks(encrypted_size):
buf = f.read(chunk_size)
if not buf:
break
chunk = cipher.decrypt(buf)
df.write(chunk)
progress += chunk_size
self.pyfile.setProgress(int((100.0 / encrypted_size) * progress))
if checksum_activated and check_checksum:
cbc_mac.update(chunk)
self.pyfile.setProgress(100)
f.close()
df.close()
self.log_info(_("File decrypted"))
os.remove(file_crypted)
if checksum_activated and check_checksum:
file_mac = cbc_mac.digest()
if file_mac == meta_mac:
self.log_info(_('File integrity of "%s" verified by CBC-MAC checksum (%s)') %
(self.pyfile.name.rsplit(self.FILE_SUFFIX)[0], meta_mac))
else:
self.log_warning(_('CBC-MAC checksum for file "%s" does not match (%s != %s)') %
(self.pyfile.name.rsplit(self.FILE_SUFFIX)[0], file_mac, meta_mac))
self.checksum_failed(file_decrypted, _("Checksums do not match"))
self.last_download = decode(file_decrypted)
def checksum_failed(self, local_file, msg):
check_action = self.config.get("check_action", default="retry", plugin="Checksum")
if check_action == "retry":
max_tries = self.config.get("max_tries", default=2, plugin="Checksum")
retry_action = self.config.get("retry_action", default="fail", plugin="Checksum")
if all(_r < max_tries for _id, _r in self.retries.items()):
os.remove(local_file)
wait_time = self.config.get("wait_time", default=1, plugin="Checksum")
self.retry(max_tries, wait_time, msg)
elif retry_action == "nothing":
return
elif check_action == "nothing":
return
os.remove(local_file)
self.fail(msg)
def check_exists(self, name):
"""
Because of Mega downloads a temporary encrypted file with the extension of '.crypted',
pyLoad cannot correctly detect if the file exists before downloading.
This function corrects this.
Raises Skip() if file exists and 'skip_existing' configuration option is set to True.
"""
if self.pyload.config.get("download", "skip_existing"):
download_folder = self.pyload.config.get('general', 'download_folder')
dest_file = fsjoin(download_folder,
self.pyfile.package().folder if self.pyload.config.get("general", "folder_per_package") else "",
name)
if exists(dest_file):
self.pyfile.name = name
self.skip(_("File exists."))
def process(self, pyfile):
id = self.info['pattern']['ID']
key = self.info['pattern']['KEY']
public = self.info['pattern']['TYPE'] == ""
owner = self.info['pattern']['OWNER']
if not public and not owner:
self.log_error(_("Missing owner in URL"))
self.fail(_("Missing owner in URL"))
self.log_debug(_("ID: %s") % id,
_("Key: %s") % key,
_("Type: %s") % ("public" if public else "node"),
_("Owner: %s") % owner)
key = MegaCrypto.base64_to_a32(key)
if len(key) != 8:
self.log_error(_("Invalid key length"))
self.fail(_("Invalid key length"))
mega = MegaClient(self, self.info['pattern']['OWNER'] or self.info['pattern']['ID'])
#: G is for requesting a download url
#: This is similar to the calls in the mega js app, documentation is very bad
if public:
res = mega.api_response(a="g", g=1, p=id, ssl=1)
else:
res = mega.api_response(a="g", g=1, n=id, ssl=1)
if isinstance(res, int):
mega.check_error(res)
elif isinstance(res, list):
res = res[0]
if "e" in res:
mega.check_error(res['e'])
attr = MegaCrypto.decrypt_attr(res['at'], key)
if not attr:
self.fail(_("Decryption failed"))
self.log_debug(_("Decrypted Attr: %s") % decode(attr))
name = attr['n']
self.check_exists(name)
pyfile.name = name + self.FILE_SUFFIX
pyfile.size = res['s']
time_left = res.get('tl', 0)
if time_left:
self.log_warning(_("Free download limit reached"))
self.retry(wait=time_left, msg=_("Free download limit reached"))
# self.req.http.c.setopt(pycurl.SSL_CIPHER_LIST, "RC4-MD5:DEFAULT")
self.download(res['g'])
self.decrypt_file(key)
#: Everything is finished and final name can be set
pyfile.name = name
| gpl-3.0 |
xiachufang/ImageServer | imageserver/app.py | 1 | 3888 | from flask import request, jsonify, Response
from .lib.dbclient import WriteFailedError
from .lib.image import ImageWrapper, OpenImageException
from .init import app, beans
from .tasks import async_upload_to_cloud
@app.after_request
def after_request(resp):
resp.headers['Access-Control-Allow-Origin'] = '*'
resp.headers['Access-Control-Allow-Methods'] = 'GET,OPTIONS,PUT,POST'
return resp
@app.route('/upload', methods=['POST'])
def upload():
'''size=100x50,200x200,300x0,150x<100'''
size_str = request.form.get('sizes', '').strip()
image = request.files.get('image')
sizes = [xy.split('x') for xy in size_str.split(',') if xy]
ident = request.form.get('ident', '').strip()
callback = request.form.get('callback', '').strip()
sync = request.form.get('sync', 'true').strip()
app.logger.debug('callback %s', callback)
try:
im = ImageWrapper(image)
except OpenImageException as e:
return error(str(e))
if ident:
# Data contained in the key might be huge, so get the corresponing meta data.
if beans.get('?%s' % ident):
# if uploading to a specified ident, check wheather the ident has data in it first.
return error('Can not replace existing data')
else:
# generate an unique ident
ident = beans.gen_ident()
try:
beans.set_image(ident, im, sizes)
except WriteFailedError as e:
return error('Save to beansdb error: %s' % e)
app.logger.debug('sync: %s', sync)
if sync == 'true':
async_upload_to_cloud.delay(ident, sizes, callback=callback)
return ok({'ident': ident, 'sizes': sizes})
@app.route('/image/<ident>.jpg', methods=['POST'])
@app.route('/resize/<ident>.jpg', methods=['POST'])
def resize_image(ident):
size_str = request.form.get('sizes', '').strip()
sizes = [xy.split('x') for xy in size_str.split(',') if xy]
callback = request.form.get('callback', '').strip()
sync = request.form.get('sync', 'true').strip()
app.logger.debug('callback %s', callback)
try:
beans.resize_image(ident, sizes)
except (WriteFailedError, OpenImageException) as e:
return error('Resize image error: %r' % e)
if sync == 'true':
async_upload_to_cloud.delay(ident, sizes, callback=callback)
return ok({'ident': ident, 'sizes': sizes})
@app.route('/sync/<ident>.jpg', methods=['POST'])
def sync_image(ident):
size_str = request.form.get('sizes', '').strip()
sizes = [xy.split('x') for xy in size_str.split(',') if xy]
callback = request.form.get('callback', '').strip()
app.logger.debug('callback %s', callback)
async_upload_to_cloud.delay(ident, sizes, callback=callback)
return ok({'ident': ident, 'sizes': sizes})
@app.route('/image/<width>/<height>/<ident>.jpg')
def pic_show(width, height, ident):
ident_ = beans.compute_ident(ident, width, height)
if not ident_:
return error('Image corresponding to %s@%sx%s doesn\'t exist!' % (ident, width, height), status_code=404)
app.logger.debug('Beans get: %s', ident_)
image_binary = beans.get(ident_)
if not image_binary:
return error('Image corresponding to %s@%sx%s doesn\'t exist!' % (ident, width, height), status_code=404)
return Response(image_binary, mimetype='image/jpeg')
@app.route('/image/<width>/<ident>.jpg')
def pic_show3(width, ident):
return pic_show(width, None, ident)
@app.route('/image/<ident>.jpg')
def pic_shows(ident):
'''width and height are in query parameters'''
width = request.args.get('width')
height = request.args.get('height')
return pic_show(width, height, ident)
def ok(res):
return jsonify({
'status': 'ok',
'content': res,
})
def error(res, status_code=400):
return jsonify({
'status': 'error',
'content': res,
}), status_code
| mit |
JeffAbrahamson/UNA_compta | ffa_qif.py | 1 | 4576 | #!/usr/bin/python3
"""Convert FFA downloads (CSV) to QIF for import to gnucash.
"""
import argparse
import dateutil.parser as dp
import pandas as pd
import sys
import base64
def piece_comptable(row):
"""Create the accounting ID in the format I want.
"""
xact_date_raw = row['DATE ECR']
# Remove time part of date, everything after the first space; also
# remove '/'.
xact_date = xact_date_raw[:xact_date_raw.find(' ')].replace('/','')
xact_id = base64.urlsafe_b64encode(xact_date.encode('ascii')).decode()
return 'FFA-{date}-{id}'.format(date=xact_date, id=xact_id)
def entry_remark(row):
"""Create the value for the entry's remark field.
"""
this_fullname = row['LIBELLE']
return '{d})'.format(d=this_fullname)
def get_data(infile):
"""Read dataframe from CSV file and return view.
"""
data = pd.read_csv(
infile,
sep=';',
)
data['amount'] = pd.Series(
[float(s.replace(',', '.'))
for s
in data['DEBIT']])
data['transaction_date_yyyy_mm_dd'] = pd.Series(
[dp.parse(val, dayfirst=True)
for val
in data['DATE ECR']])
data['transaction_date_qif'] = pd.Series([
'{d:0>2d}/{m:0>2d}/{y:0>4d}'.format(y=val.year, m=val.month, d=val.day)
for val
in data.transaction_date_yyyy_mm_dd])
data['transaction_yyyymmdd'] = pd.Series([
'{y:0>4d}{m:0>2d}{d:0>2d}'.format(y=val.year, m=val.month, d=val.day)
for val
in data.transaction_date_yyyy_mm_dd])
data['description'] = pd.Series(
[val.strip()
for val
in data.LIBELLE])
data['type'] = pd.Series(
[val.strip()
for val
in data['TYPE ECR']])
data['piece-comptable'] = data.apply(piece_comptable, axis=1)
data_view = data[['transaction_date_yyyy_mm_dd', 'transaction_date_qif',
'description', 'type',
'piece-comptable', 'amount']]
return data_view.sort_values(by=['transaction_date_yyyy_mm_dd'])
def make_qif(data_view):
"""Build qif file from dataframe.
The dataframe should have columns as provided by get_data(), above.
We want a qif so that we can construct splits.
Cf. https://en.wikipedia.org/wiki/Quicken_Interchange_Format
"""
qif_data_view = data_view[['transaction_date_qif', 'piece-comptable',
'description', 'type', 'amount']]
qif = '!Account\n'
qif += 'N401_FFA licences\n'
qif += '^\n'
qif += '!Type:Bank\n'
def qif_entry(row):
"""Create a single QIF file entry.
"""
this_transaction_date = row['transaction_date_qif']
this_piece_comptable = row['piece-comptable']
this_description = row['description']
this_type = row['type']
this_amount = -row['amount']
# D is the date. It may be required to be in English "dd mmmm
# yyyy" format.
# T is the amount of the transaction.
# N is the id number (pièce comptable).
# P is the payee (which quicken thinks of as the comment, not the account)
# M is a memo
entry = 'D{date}\nT{total}\nN{pc}\nP{payee}\nM{memo}\n'.format(
date=this_transaction_date,
total=this_amount,
pc=this_piece_comptable, payee=this_description,
memo=this_type)
# S is the split category (account number on split line).
# $ is the amount of the split entry.
# E is the split memo.
split_line = 'S{cpty}\n${amt}\nE{memo}\n'
entry += split_line.format(
cpty='6075_FFA licences',
amt=-this_amount,
memo='')
return entry
rows = qif_data_view.to_dict('records')
transactions = []
for row in rows:
if row['amount'] != 0:
transactions.append(qif_entry(row))
qif += '\n^\n'.join(transactions) + '\n^\n'
return qif
def main():
"""Do what we do.
"""
parser = argparse.ArgumentParser()
parser.add_argument('--infile', type=str, required=True,
help='Name of file to read')
parser.add_argument('--outfile', type=str, required=False,
help='Name of file to write')
args = parser.parse_args()
data_view = get_data(args.infile)
qif = make_qif(data_view)
if args.outfile:
with open(args.outfile, 'w') as f_ptr:
f_ptr.write(qif)
else:
print(qif)
return 0
if __name__ == '__main__':
retval = main()
sys.exit(retval)
| gpl-3.0 |
mattvonrocketstein/smash | smashlib/ipy3x/utils/importstring.py | 1 | 1485 | # encoding: utf-8
"""
A simple utility to import something by its string name.
Authors:
* Brian Granger
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Functions and classes
#-----------------------------------------------------------------------------
def import_item(name):
"""Import and return ``bar`` given the string ``foo.bar``.
Calling ``bar = import_item("foo.bar")`` is the functional equivalent of
executing the code ``from foo import bar``.
Parameters
----------
name : string
The fully qualified name of the module/package being imported.
Returns
-------
mod : module object
The module that was imported.
"""
parts = name.rsplit('.', 1)
if len(parts) == 2:
# called with 'foo.bar....'
package, obj = parts
module = __import__(package, fromlist=[obj])
try:
pak = module.__dict__[obj]
except KeyError:
raise ImportError('No module named %s' % obj)
return pak
else:
# called with un-dotted string
return __import__(parts[0])
| mit |
samj1912/picard | picard/const/countries.py | 8 | 6400 | # -*- coding: utf-8 -*-
# Automatically generated - don't edit.
# Use `python setup.py update_constants` to update it.
RELEASE_COUNTRIES = {
'AD': 'Andorra',
'AE': 'United Arab Emirates',
'AF': 'Afghanistan',
'AG': 'Antigua and Barbuda',
'AI': 'Anguilla',
'AL': 'Albania',
'AM': 'Armenia',
'AN': 'Netherlands Antilles',
'AO': 'Angola',
'AQ': 'Antarctica',
'AR': 'Argentina',
'AS': 'American Samoa',
'AT': 'Austria',
'AU': 'Australia',
'AW': 'Aruba',
'AX': 'Åland Islands',
'AZ': 'Azerbaijan',
'BA': 'Bosnia and Herzegovina',
'BB': 'Barbados',
'BD': 'Bangladesh',
'BE': 'Belgium',
'BF': 'Burkina Faso',
'BG': 'Bulgaria',
'BH': 'Bahrain',
'BI': 'Burundi',
'BJ': 'Benin',
'BL': 'Saint Barthélemy',
'BM': 'Bermuda',
'BN': 'Brunei',
'BO': 'Bolivia',
'BQ': 'Bonaire, Sint Eustatius and Saba',
'BR': 'Brazil',
'BS': 'Bahamas',
'BT': 'Bhutan',
'BV': 'Bouvet Island',
'BW': 'Botswana',
'BY': 'Belarus',
'BZ': 'Belize',
'CA': 'Canada',
'CC': 'Cocos (Keeling) Islands',
'CD': 'Democratic Republic of the Congo',
'CF': 'Central African Republic',
'CG': 'Congo',
'CH': 'Switzerland',
'CI': 'Côte d\'Ivoire',
'CK': 'Cook Islands',
'CL': 'Chile',
'CM': 'Cameroon',
'CN': 'China',
'CO': 'Colombia',
'CR': 'Costa Rica',
'CS': 'Serbia and Montenegro',
'CU': 'Cuba',
'CV': 'Cape Verde',
'CW': 'Curaçao',
'CX': 'Christmas Island',
'CY': 'Cyprus',
'CZ': 'Czech Republic',
'DE': 'Germany',
'DJ': 'Djibouti',
'DK': 'Denmark',
'DM': 'Dominica',
'DO': 'Dominican Republic',
'DZ': 'Algeria',
'EC': 'Ecuador',
'EE': 'Estonia',
'EG': 'Egypt',
'EH': 'Western Sahara',
'ER': 'Eritrea',
'ES': 'Spain',
'ET': 'Ethiopia',
'FI': 'Finland',
'FJ': 'Fiji',
'FK': 'Falkland Islands',
'FM': 'Federated States of Micronesia',
'FO': 'Faroe Islands',
'FR': 'France',
'GA': 'Gabon',
'GB': 'United Kingdom',
'GD': 'Grenada',
'GE': 'Georgia',
'GF': 'French Guiana',
'GG': 'Guernsey',
'GH': 'Ghana',
'GI': 'Gibraltar',
'GL': 'Greenland',
'GM': 'Gambia',
'GN': 'Guinea',
'GP': 'Guadeloupe',
'GQ': 'Equatorial Guinea',
'GR': 'Greece',
'GS': 'South Georgia and the South Sandwich Islands',
'GT': 'Guatemala',
'GU': 'Guam',
'GW': 'Guinea-Bissau',
'GY': 'Guyana',
'HK': 'Hong Kong',
'HM': 'Heard Island and McDonald Islands',
'HN': 'Honduras',
'HR': 'Croatia',
'HT': 'Haiti',
'HU': 'Hungary',
'ID': 'Indonesia',
'IE': 'Ireland',
'IL': 'Israel',
'IM': 'Isle of Man',
'IN': 'India',
'IO': 'British Indian Ocean Territory',
'IQ': 'Iraq',
'IR': 'Iran',
'IS': 'Iceland',
'IT': 'Italy',
'JE': 'Jersey',
'JM': 'Jamaica',
'JO': 'Jordan',
'JP': 'Japan',
'KE': 'Kenya',
'KG': 'Kyrgyzstan',
'KH': 'Cambodia',
'KI': 'Kiribati',
'KM': 'Comoros',
'KN': 'Saint Kitts and Nevis',
'KP': 'North Korea',
'KR': 'South Korea',
'KW': 'Kuwait',
'KY': 'Cayman Islands',
'KZ': 'Kazakhstan',
'LA': 'Laos',
'LB': 'Lebanon',
'LC': 'Saint Lucia',
'LI': 'Liechtenstein',
'LK': 'Sri Lanka',
'LR': 'Liberia',
'LS': 'Lesotho',
'LT': 'Lithuania',
'LU': 'Luxembourg',
'LV': 'Latvia',
'LY': 'Libya',
'MA': 'Morocco',
'MC': 'Monaco',
'MD': 'Moldova',
'ME': 'Montenegro',
'MF': 'Saint Martin (French part)',
'MG': 'Madagascar',
'MH': 'Marshall Islands',
'MK': 'Macedonia',
'ML': 'Mali',
'MM': 'Myanmar',
'MN': 'Mongolia',
'MO': 'Macao',
'MP': 'Northern Mariana Islands',
'MQ': 'Martinique',
'MR': 'Mauritania',
'MS': 'Montserrat',
'MT': 'Malta',
'MU': 'Mauritius',
'MV': 'Maldives',
'MW': 'Malawi',
'MX': 'Mexico',
'MY': 'Malaysia',
'MZ': 'Mozambique',
'NA': 'Namibia',
'NC': 'New Caledonia',
'NE': 'Niger',
'NF': 'Norfolk Island',
'NG': 'Nigeria',
'NI': 'Nicaragua',
'NL': 'Netherlands',
'NO': 'Norway',
'NP': 'Nepal',
'NR': 'Nauru',
'NU': 'Niue',
'NZ': 'New Zealand',
'OM': 'Oman',
'PA': 'Panama',
'PE': 'Peru',
'PF': 'French Polynesia',
'PG': 'Papua New Guinea',
'PH': 'Philippines',
'PK': 'Pakistan',
'PL': 'Poland',
'PM': 'Saint Pierre and Miquelon',
'PN': 'Pitcairn',
'PR': 'Puerto Rico',
'PS': 'Palestine',
'PT': 'Portugal',
'PW': 'Palau',
'PY': 'Paraguay',
'QA': 'Qatar',
'RE': 'Réunion',
'RO': 'Romania',
'RS': 'Serbia',
'RU': 'Russia',
'RW': 'Rwanda',
'SA': 'Saudi Arabia',
'SB': 'Solomon Islands',
'SC': 'Seychelles',
'SD': 'Sudan',
'SE': 'Sweden',
'SG': 'Singapore',
'SH': 'Saint Helena, Ascension and Tristan da Cunha',
'SI': 'Slovenia',
'SJ': 'Svalbard and Jan Mayen',
'SK': 'Slovakia',
'SL': 'Sierra Leone',
'SM': 'San Marino',
'SN': 'Senegal',
'SO': 'Somalia',
'SR': 'Suriname',
'SS': 'South Sudan',
'ST': 'Sao Tome and Principe',
'SU': 'Soviet Union',
'SV': 'El Salvador',
'SX': 'Sint Maarten (Dutch part)',
'SY': 'Syria',
'SZ': 'Swaziland',
'TC': 'Turks and Caicos Islands',
'TD': 'Chad',
'TF': 'French Southern Territories',
'TG': 'Togo',
'TH': 'Thailand',
'TJ': 'Tajikistan',
'TK': 'Tokelau',
'TL': 'Timor-Leste',
'TM': 'Turkmenistan',
'TN': 'Tunisia',
'TO': 'Tonga',
'TR': 'Turkey',
'TT': 'Trinidad and Tobago',
'TV': 'Tuvalu',
'TW': 'Taiwan',
'TZ': 'Tanzania',
'UA': 'Ukraine',
'UG': 'Uganda',
'UM': 'United States Minor Outlying Islands',
'US': 'United States',
'UY': 'Uruguay',
'UZ': 'Uzbekistan',
'VA': 'Vatican City',
'VC': 'Saint Vincent and The Grenadines',
'VE': 'Venezuela',
'VG': 'British Virgin Islands',
'VI': 'U.S. Virgin Islands',
'VN': 'Vietnam',
'VU': 'Vanuatu',
'WF': 'Wallis and Futuna',
'WS': 'Samoa',
'XC': 'Czechoslovakia',
'XE': 'Europe',
'XG': 'East Germany',
'XK': 'Kosovo',
'XW': '[Worldwide]',
'YE': 'Yemen',
'YT': 'Mayotte',
'YU': 'Yugoslavia',
'ZA': 'South Africa',
'ZM': 'Zambia',
'ZW': 'Zimbabwe',
}
| gpl-2.0 |
edry/edx-platform | common/test/acceptance/tests/video/test_video_handout.py | 136 | 6655 | # -*- coding: utf-8 -*-
"""
Acceptance tests for CMS Video Handout.
"""
from nose.plugins.attrib import attr
from .test_studio_video_module import CMSVideoBaseTest
@attr('shard_5')
class VideoHandoutTest(CMSVideoBaseTest):
"""
CMS Video Handout Test Class
"""
def setUp(self):
super(VideoHandoutTest, self).setUp()
def _create_course_unit_with_handout(self, handout_filename, save_settings=True):
"""
Create a course with unit and also upload handout
Arguments:
handout_filename (str): handout file name to be uploaded
save_settings (bool): save settings or not
"""
self.navigate_to_course_unit()
self.edit_component()
self.open_advanced_tab()
self.video.upload_handout(handout_filename)
if save_settings:
self.save_unit_settings()
def test_handout_uploads_correctly(self):
"""
Scenario: Handout uploading works correctly
Given I have created a Video component with handout file "textbook.pdf"
Then I can see video button "handout"
And I can download handout file with mime type "application/pdf"
"""
self._create_course_unit_with_handout('textbook.pdf')
self.assertTrue(self.video.is_handout_button_visible)
self.assertEqual(self.video.download_handout('application/pdf'), (True, True))
def test_handout_download_works_with_save(self):
"""
Scenario: Handout downloading works correctly w/ preliminary saving
Given I have created a Video component with handout file "textbook.pdf"
And I save changes
And I edit the component
And I open tab "Advanced"
And I can download handout file in editor with mime type "application/pdf"
"""
self._create_course_unit_with_handout('textbook.pdf')
self.edit_component()
self.open_advanced_tab()
self.assertEqual(self.video.download_handout('application/pdf', is_editor=True), (True, True))
def test_handout_download_works_wo_save(self):
"""
Scenario: Handout downloading works correctly w/o preliminary saving
Given I have created a Video component with handout file "textbook.pdf"
And I can download handout file in editor with mime type "application/pdf"
"""
self._create_course_unit_with_handout('textbook.pdf', save_settings=False)
self.assertEqual(self.video.download_handout('application/pdf', is_editor=True), (True, True))
def test_handout_clearing_works_w_save(self):
"""
Scenario: Handout clearing works correctly w/ preliminary saving
Given I have created a Video component with handout file "textbook.pdf"
And I save changes
And I can download handout file with mime type "application/pdf"
And I edit the component
And I open tab "Advanced"
And I clear handout
And I save changes
Then I do not see video button "handout"
"""
self._create_course_unit_with_handout('textbook.pdf')
self.assertEqual(self.video.download_handout('application/pdf'), (True, True))
self.edit_component()
self.open_advanced_tab()
self.video.clear_handout()
self.save_unit_settings()
self.assertFalse(self.video.is_handout_button_visible)
def test_handout_clearing_works_wo_save(self):
"""
Scenario: Handout clearing works correctly w/o preliminary saving
Given I have created a Video component with handout file "asset.html"
And I clear handout
And I save changes
Then I do not see video button "handout"
"""
self._create_course_unit_with_handout('asset.html', save_settings=False)
self.video.clear_handout()
self.save_unit_settings()
self.assertFalse(self.video.is_handout_button_visible)
def test_handout_replace_w_save(self):
"""
Scenario: User can easy replace the handout by another one w/ preliminary saving
Given I have created a Video component with handout file "asset.html"
And I save changes
Then I can see video button "handout"
And I can download handout file with mime type "text/html"
And I edit the component
And I open tab "Advanced"
And I replace handout file by "textbook.pdf"
And I save changes
Then I can see video button "handout"
And I can download handout file with mime type "application/pdf"
"""
self._create_course_unit_with_handout('asset.html')
self.assertTrue(self.video.is_handout_button_visible)
self.assertEqual(self.video.download_handout('text/html'), (True, True))
self.edit_component()
self.open_advanced_tab()
self.video.upload_handout('textbook.pdf')
self.save_unit_settings()
self.assertTrue(self.video.is_handout_button_visible)
self.assertEqual(self.video.download_handout('application/pdf'), (True, True))
def test_handout_replace_wo_save(self):
"""
Scenario: User can easy replace the handout by another one w/o preliminary saving
Given I have created a Video component with handout file "asset.html"
And I replace handout file by "textbook.pdf"
And I save changes
Then I can see video button "handout"
And I can download handout file with mime type "application/pdf"
"""
self._create_course_unit_with_handout('asset.html', save_settings=False)
self.video.upload_handout('textbook.pdf')
self.save_unit_settings()
self.assertTrue(self.video.is_handout_button_visible)
self.assertEqual(self.video.download_handout('application/pdf'), (True, True))
def test_handout_upload_and_clear_works(self):
"""
Scenario: Upload file "A" -> Remove it -> Upload file "B"
Given I have created a Video component with handout file "asset.html"
And I clear handout
And I upload handout file "textbook.pdf"
And I save changes
Then I can see video button "handout"
And I can download handout file with mime type "application/pdf"
"""
self._create_course_unit_with_handout('asset.html', save_settings=False)
self.video.clear_handout()
self.video.upload_handout('textbook.pdf')
self.save_unit_settings()
self.assertTrue(self.video.is_handout_button_visible)
self.assertEqual(self.video.download_handout('application/pdf'), (True, True))
| agpl-3.0 |
garyjyao1/ansible | lib/ansible/modules/core/packaging/os/yum.py | 5 | 35069 | #!/usr/bin/python -tt
# -*- coding: utf-8 -*-
# (c) 2012, Red Hat, Inc
# Written by Seth Vidal <skvidal at fedoraproject.org>
# (c) 2014, Epic Games, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
import traceback
import os
import yum
import rpm
import platform
import tempfile
import shutil
from distutils.version import LooseVersion
try:
from yum.misc import find_unfinished_transactions, find_ts_remaining
from rpmUtils.miscutils import splitFilename
transaction_helpers = True
except:
transaction_helpers = False
DOCUMENTATION = '''
---
module: yum
version_added: historical
short_description: Manages packages with the I(yum) package manager
description:
- Installs, upgrade, removes, and lists packages and groups with the I(yum) package manager.
options:
name:
description:
- "Package name, or package specifier with version, like C(name-1.0). When using state=latest, this can be '*' which means run: yum -y update. You can also pass a url or a local path to a rpm file. To operate on several packages this can accept a comma separated list of packages or (as of 2.0) a list of packages."
required: true
default: null
aliases: []
exclude:
description:
- "Package name(s) to exclude when state=present, or latest"
required: false
version_added: "2.0"
default: null
list:
description:
- Various (non-idempotent) commands for usage with C(/usr/bin/ansible) and I(not) playbooks. See examples.
required: false
default: null
state:
description:
- Whether to install (C(present), C(latest)), or remove (C(absent)) a package.
required: false
choices: [ "present", "latest", "absent" ]
default: "present"
enablerepo:
description:
- I(Repoid) of repositories to enable for the install/update operation.
These repos will not persist beyond the transaction.
When specifying multiple repos, separate them with a ",".
required: false
version_added: "0.9"
default: null
aliases: []
disablerepo:
description:
- I(Repoid) of repositories to disable for the install/update operation.
These repos will not persist beyond the transaction.
When specifying multiple repos, separate them with a ",".
required: false
version_added: "0.9"
default: null
aliases: []
conf_file:
description:
- The remote yum configuration file to use for the transaction.
required: false
version_added: "0.6"
default: null
aliases: []
disable_gpg_check:
description:
- Whether to disable the GPG checking of signatures of packages being
installed. Has an effect only if state is I(present) or I(latest).
required: false
version_added: "1.2"
default: "no"
choices: ["yes", "no"]
aliases: []
update_cache:
description:
- Force updating the cache. Has an effect only if state is I(present)
or I(latest).
required: false
version_added: "1.9"
default: "no"
choices: ["yes", "no"]
aliases: []
notes:
- When used with a loop of package names in a playbook, ansible optimizes
the call to the yum module. Instead of calling the module with a single
package each time through the loop, ansible calls the module once with all
of the package names from the loop.
- In versions prior to 1.9.2 this module installed and removed each package
given to the yum module separately. This caused problems when packages
specified by filename or url had to be installed or removed together. In
1.9.2 this was fixed so that packages are installed in one yum
transaction. However, if one of the packages adds a new yum repository
that the other packages come from (such as epel-release) then that package
needs to be installed in a separate task. This mimics yum's command line
behaviour.
# informational: requirements for nodes
requirements: [ yum ]
author:
- "Ansible Core Team"
- "Seth Vidal"
'''
EXAMPLES = '''
- name: install the latest version of Apache
yum: name=httpd state=latest
- name: remove the Apache package
yum: name=httpd state=absent
- name: install the latest version of Apache from the testing repo
yum: name=httpd enablerepo=testing state=present
- name: install one specific version of Apache
yum: name=httpd-2.2.29-1.4.amzn1 state=present
- name: upgrade all packages
yum: name=* state=latest
- name: install the nginx rpm from a remote repo
yum: name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
- name: install nginx rpm from a local file
yum: name=/usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present
- name: install the 'Development tools' package group
yum: name="@Development tools" state=present
'''
# 64k. Number of bytes to read at a time when manually downloading pkgs via a url
BUFSIZE = 65536
def_qf = "%{name}-%{version}-%{release}.%{arch}"
def yum_base(conf_file=None):
my = yum.YumBase()
my.preconf.debuglevel=0
my.preconf.errorlevel=0
if conf_file and os.path.exists(conf_file):
my.preconf.fn = conf_file
if os.geteuid() != 0:
if hasattr(my, 'setCacheDir'):
my.setCacheDir()
else:
cachedir = yum.misc.getCacheDir()
my.repos.setCacheDir(cachedir)
my.conf.cache = 0
return my
def ensure_yum_utils(module):
repoquerybin = module.get_bin_path('repoquery', required=False)
if module.params['install_repoquery'] and not repoquerybin and not module.check_mode:
yum_path = module.get_bin_path('yum')
if yum_path:
rc, so, se = module.run_command('%s -y install yum-utils' % yum_path)
repoquerybin = module.get_bin_path('repoquery', required=False)
return repoquerybin
def po_to_nevra(po):
if hasattr(po, 'ui_nevra'):
return po.ui_nevra
else:
return '%s-%s-%s.%s' % (po.name, po.version, po.release, po.arch)
def is_installed(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=None, dis_repos=None, is_pkg=False):
if en_repos is None:
en_repos = []
if dis_repos is None:
dis_repos = []
if not repoq:
pkgs = []
try:
my = yum_base(conf_file)
for rid in dis_repos:
my.repos.disableRepo(rid)
for rid in en_repos:
my.repos.enableRepo(rid)
e, m, u = my.rpmdb.matchPackageNames([pkgspec])
pkgs = e + m
if not pkgs:
pkgs.extend(my.returnInstalledPackagesByDep(pkgspec))
except Exception, e:
module.fail_json(msg="Failure talking to yum: %s" % e)
return [ po_to_nevra(p) for p in pkgs ]
else:
cmd = repoq + ["--disablerepo=*", "--pkgnarrow=installed", "--qf", qf, pkgspec]
rc, out, err = module.run_command(cmd)
if not is_pkg:
cmd = repoq + ["--disablerepo=*", "--pkgnarrow=installed", "--qf", qf, "--whatprovides", pkgspec]
rc2, out2, err2 = module.run_command(cmd)
else:
rc2, out2, err2 = (0, '', '')
if rc == 0 and rc2 == 0:
out += out2
return [p for p in out.split('\n') if p.strip()]
else:
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err + err2))
return []
def is_available(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=None, dis_repos=None):
if en_repos is None:
en_repos = []
if dis_repos is None:
dis_repos = []
if not repoq:
pkgs = []
try:
my = yum_base(conf_file)
for rid in dis_repos:
my.repos.disableRepo(rid)
for rid in en_repos:
my.repos.enableRepo(rid)
e,m,u = my.pkgSack.matchPackageNames([pkgspec])
pkgs = e + m
if not pkgs:
pkgs.extend(my.returnPackagesByDep(pkgspec))
except Exception, e:
module.fail_json(msg="Failure talking to yum: %s" % e)
return [ po_to_nevra(p) for p in pkgs ]
else:
myrepoq = list(repoq)
r_cmd = ['--disablerepo', ','.join(dis_repos)]
myrepoq.extend(r_cmd)
r_cmd = ['--enablerepo', ','.join(en_repos)]
myrepoq.extend(r_cmd)
cmd = myrepoq + ["--qf", qf, pkgspec]
rc,out,err = module.run_command(cmd)
if rc == 0:
return [ p for p in out.split('\n') if p.strip() ]
else:
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err))
return []
def is_update(module, repoq, pkgspec, conf_file, qf=def_qf, en_repos=None, dis_repos=None):
if en_repos is None:
en_repos = []
if dis_repos is None:
dis_repos = []
if not repoq:
retpkgs = []
pkgs = []
updates = []
try:
my = yum_base(conf_file)
for rid in dis_repos:
my.repos.disableRepo(rid)
for rid in en_repos:
my.repos.enableRepo(rid)
pkgs = my.returnPackagesByDep(pkgspec) + my.returnInstalledPackagesByDep(pkgspec)
if not pkgs:
e,m,u = my.pkgSack.matchPackageNames([pkgspec])
pkgs = e + m
updates = my.doPackageLists(pkgnarrow='updates').updates
except Exception, e:
module.fail_json(msg="Failure talking to yum: %s" % e)
for pkg in pkgs:
if pkg in updates:
retpkgs.append(pkg)
return set([ po_to_nevra(p) for p in retpkgs ])
else:
myrepoq = list(repoq)
r_cmd = ['--disablerepo', ','.join(dis_repos)]
myrepoq.extend(r_cmd)
r_cmd = ['--enablerepo', ','.join(en_repos)]
myrepoq.extend(r_cmd)
cmd = myrepoq + ["--pkgnarrow=updates", "--qf", qf, pkgspec]
rc,out,err = module.run_command(cmd)
if rc == 0:
return set([ p for p in out.split('\n') if p.strip() ])
else:
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err))
return set()
def what_provides(module, repoq, req_spec, conf_file, qf=def_qf, en_repos=None, dis_repos=None):
if en_repos is None:
en_repos = []
if dis_repos is None:
dis_repos = []
if not repoq:
pkgs = []
try:
my = yum_base(conf_file)
for rid in dis_repos:
my.repos.disableRepo(rid)
for rid in en_repos:
my.repos.enableRepo(rid)
pkgs = my.returnPackagesByDep(req_spec) + my.returnInstalledPackagesByDep(req_spec)
if not pkgs:
e,m,u = my.pkgSack.matchPackageNames([req_spec])
pkgs.extend(e)
pkgs.extend(m)
e,m,u = my.rpmdb.matchPackageNames([req_spec])
pkgs.extend(e)
pkgs.extend(m)
except Exception, e:
module.fail_json(msg="Failure talking to yum: %s" % e)
return set([ po_to_nevra(p) for p in pkgs ])
else:
myrepoq = list(repoq)
r_cmd = ['--disablerepo', ','.join(dis_repos)]
myrepoq.extend(r_cmd)
r_cmd = ['--enablerepo', ','.join(en_repos)]
myrepoq.extend(r_cmd)
cmd = myrepoq + ["--qf", qf, "--whatprovides", req_spec]
rc,out,err = module.run_command(cmd)
cmd = myrepoq + ["--qf", qf, req_spec]
rc2,out2,err2 = module.run_command(cmd)
if rc == 0 and rc2 == 0:
out += out2
pkgs = set([ p for p in out.split('\n') if p.strip() ])
if not pkgs:
pkgs = is_installed(module, repoq, req_spec, conf_file, qf=qf)
return pkgs
else:
module.fail_json(msg='Error from repoquery: %s: %s' % (cmd, err + err2))
return set()
def transaction_exists(pkglist):
"""
checks the package list to see if any packages are
involved in an incomplete transaction
"""
conflicts = []
if not transaction_helpers:
return conflicts
# first, we create a list of the package 'nvreas'
# so we can compare the pieces later more easily
pkglist_nvreas = []
for pkg in pkglist:
pkglist_nvreas.append(splitFilename(pkg))
# next, we build the list of packages that are
# contained within an unfinished transaction
unfinished_transactions = find_unfinished_transactions()
for trans in unfinished_transactions:
steps = find_ts_remaining(trans)
for step in steps:
# the action is install/erase/etc., but we only
# care about the package spec contained in the step
(action, step_spec) = step
(n,v,r,e,a) = splitFilename(step_spec)
# and see if that spec is in the list of packages
# requested for installation/updating
for pkg in pkglist_nvreas:
# if the name and arch match, we're going to assume
# this package is part of a pending transaction
# the label is just for display purposes
label = "%s-%s" % (n,a)
if n == pkg[0] and a == pkg[4]:
if label not in conflicts:
conflicts.append("%s-%s" % (n,a))
break
return conflicts
def local_nvra(module, path):
"""return nvra of a local rpm passed in"""
ts = rpm.TransactionSet()
ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES)
fd = os.open(path, os.O_RDONLY)
try:
header = ts.hdrFromFdno(fd)
finally:
os.close(fd)
return '%s-%s-%s.%s' % (header[rpm.RPMTAG_NAME],
header[rpm.RPMTAG_VERSION],
header[rpm.RPMTAG_RELEASE],
header[rpm.RPMTAG_ARCH])
def pkg_to_dict(pkgstr):
if pkgstr.strip():
n,e,v,r,a,repo = pkgstr.split('|')
else:
return {'error_parsing': pkgstr}
d = {
'name':n,
'arch':a,
'epoch':e,
'release':r,
'version':v,
'repo':repo,
'nevra': '%s:%s-%s-%s.%s' % (e,n,v,r,a)
}
if repo == 'installed':
d['yumstate'] = 'installed'
else:
d['yumstate'] = 'available'
return d
def repolist(module, repoq, qf="%{repoid}"):
cmd = repoq + ["--qf", qf, "-a"]
rc,out,err = module.run_command(cmd)
ret = []
if rc == 0:
ret = set([ p for p in out.split('\n') if p.strip() ])
return ret
def list_stuff(module, repoquerybin, conf_file, stuff):
qf = "%{name}|%{epoch}|%{version}|%{release}|%{arch}|%{repoid}"
repoq = [repoquerybin, '--show-duplicates', '--plugins', '--quiet']
if conf_file and os.path.exists(conf_file):
repoq += ['-c', conf_file]
if stuff == 'installed':
return [ pkg_to_dict(p) for p in is_installed(module, repoq, '-a', conf_file, qf=qf) if p.strip() ]
elif stuff == 'updates':
return [ pkg_to_dict(p) for p in is_update(module, repoq, '-a', conf_file, qf=qf) if p.strip() ]
elif stuff == 'available':
return [ pkg_to_dict(p) for p in is_available(module, repoq, '-a', conf_file, qf=qf) if p.strip() ]
elif stuff == 'repos':
return [ dict(repoid=name, state='enabled') for name in repolist(module, repoq) if name.strip() ]
else:
return [ pkg_to_dict(p) for p in is_installed(module, repoq, stuff, conf_file, qf=qf) + is_available(module, repoq, stuff, conf_file, qf=qf) if p.strip() ]
def install(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
pkgs = []
res = {}
res['results'] = []
res['msg'] = ''
res['rc'] = 0
res['changed'] = False
tempdir = tempfile.mkdtemp()
for spec in items:
pkg = None
# check if pkgspec is installed (if possible for idempotence)
# localpkg
if spec.endswith('.rpm') and '://' not in spec:
# get the pkg name-v-r.arch
if not os.path.exists(spec):
res['msg'] += "No Package file matching '%s' found on system" % spec
module.fail_json(**res)
nvra = local_nvra(module, spec)
# look for them in the rpmdb
if is_installed(module, repoq, nvra, conf_file, en_repos=en_repos, dis_repos=dis_repos):
# if they are there, skip it
continue
pkg = spec
# URL
elif '://' in spec:
pkg = spec
# Check if Enterprise Linux 5 or less, as yum on those versions do not support installing via url
distribution_version = get_distribution_version()
distribution = platform.dist()
if distribution[0] == "redhat" and LooseVersion(distribution_version) < LooseVersion("6"):
package = os.path.join(tempdir, str(pkg.rsplit('/', 1)[1]))
try:
rsp, info = fetch_url(module, pkg)
f = open(package, 'w')
data = rsp.read(BUFSIZE)
while data:
f.write(data)
data = rsp.read(BUFSIZE)
f.close()
pkg = package
except Exception, e:
shutil.rmtree(tempdir)
module.fail_json(msg="Failure downloading %s, %s" % (spec, e))
#groups :(
elif spec.startswith('@'):
# complete wild ass guess b/c it's a group
pkg = spec
# range requires or file-requires or pkgname :(
else:
# most common case is the pkg is already installed and done
# short circuit all the bs - and search for it as a pkg in is_installed
# if you find it then we're done
if not set(['*','?']).intersection(set(spec)):
installed_pkgs = is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos, is_pkg=True)
if installed_pkgs:
res['results'].append('%s providing %s is already installed' % (installed_pkgs[0], spec))
continue
# look up what pkgs provide this
pkglist = what_provides(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos)
if not pkglist:
res['msg'] += "No Package matching '%s' found available, installed or updated" % spec
module.fail_json(**res)
# if any of the packages are involved in a transaction, fail now
# so that we don't hang on the yum operation later
conflicts = transaction_exists(pkglist)
if len(conflicts) > 0:
res['msg'] += "The following packages have pending transactions: %s" % ", ".join(conflicts)
module.fail_json(**res)
# if any of them are installed
# then nothing to do
found = False
for this in pkglist:
if is_installed(module, repoq, this, conf_file, en_repos=en_repos, dis_repos=dis_repos, is_pkg=True):
found = True
res['results'].append('%s providing %s is already installed' % (this, spec))
break
# if the version of the pkg you have installed is not in ANY repo, but there are
# other versions in the repos (both higher and lower) then the previous checks won't work.
# so we check one more time. This really only works for pkgname - not for file provides or virt provides
# but virt provides should be all caught in what_provides on its own.
# highly irritating
if not found:
if is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos):
found = True
res['results'].append('package providing %s is already installed' % (spec))
if found:
continue
# if not - then pass in the spec as what to install
# we could get here if nothing provides it but that's not
# the error we're catching here
pkg = spec
pkgs.append(pkg)
if pkgs:
cmd = yum_basecmd + ['install'] + pkgs
if module.check_mode:
# Remove rpms downloaded for EL5 via url
try:
shutil.rmtree(tempdir)
except Exception, e:
module.fail_json(msg="Failure deleting temp directory %s, %s" % (tempdir, e))
module.exit_json(changed=True, results=res['results'], changes=dict(installed=pkgs))
changed = True
rc, out, err = module.run_command(cmd)
if (rc == 1):
for spec in items:
# Fail on invalid urls:
if ('://' in spec and ('No package %s available.' % spec in out or 'Cannot open: %s. Skipping.' % spec in err)):
err = 'Package at %s could not be installed' % spec
module.fail_json(changed=False,msg=err,rc=1)
if (rc != 0 and 'Nothing to do' in err) or 'Nothing to do' in out:
# avoid failing in the 'Nothing To Do' case
# this may happen with an URL spec.
# for an already installed group,
# we get rc = 0 and 'Nothing to do' in out, not in err.
rc = 0
err = ''
out = '%s: Nothing to do' % spec
changed = False
res['rc'] = rc
res['results'].append(out)
res['msg'] += err
# FIXME - if we did an install - go and check the rpmdb to see if it actually installed
# look for each pkg in rpmdb
# look for each pkg via obsoletes
# Record change
res['changed'] = changed
# Remove rpms downloaded for EL5 via url
try:
shutil.rmtree(tempdir)
except Exception, e:
module.fail_json(msg="Failure deleting temp directory %s, %s" % (tempdir, e))
return res
def remove(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
pkgs = []
res = {}
res['results'] = []
res['msg'] = ''
res['changed'] = False
res['rc'] = 0
for pkg in items:
is_group = False
# group remove - this is doom on a stick
if pkg.startswith('@'):
is_group = True
else:
if not is_installed(module, repoq, pkg, conf_file, en_repos=en_repos, dis_repos=dis_repos):
res['results'].append('%s is not installed' % pkg)
continue
pkgs.append(pkg)
if pkgs:
# run an actual yum transaction
cmd = yum_basecmd + ["remove"] + pkgs
if module.check_mode:
module.exit_json(changed=True, results=res['results'], changes=dict(removed=pkgs))
rc, out, err = module.run_command(cmd)
res['rc'] = rc
res['results'].append(out)
res['msg'] = err
# compile the results into one batch. If anything is changed
# then mark changed
# at the end - if we've end up failed then fail out of the rest
# of the process
# at this point we should check to see if the pkg is no longer present
for pkg in pkgs:
if not pkg.startswith('@'): # we can't sensibly check for a group being uninstalled reliably
# look to see if the pkg shows up from is_installed. If it doesn't
if not is_installed(module, repoq, pkg, conf_file, en_repos=en_repos, dis_repos=dis_repos):
res['changed'] = True
else:
module.fail_json(**res)
if rc != 0:
module.fail_json(**res)
return res
def latest(module, items, repoq, yum_basecmd, conf_file, en_repos, dis_repos):
res = {}
res['results'] = []
res['msg'] = ''
res['changed'] = False
res['rc'] = 0
pkgs = {}
pkgs['update'] = []
pkgs['install'] = []
updates = {}
update_all = False
cmd = None
# determine if we're doing an update all
if '*' in items:
update_all = True
# run check-update to see if we have packages pending
rc, out, err = module.run_command(yum_basecmd + ['check-update'])
if rc == 0 and update_all:
res['results'].append('Nothing to do here, all packages are up to date')
return res
elif rc == 100:
available_updates = out.split('\n')
# build update dictionary
for line in available_updates:
line = line.split()
# ignore irrelevant lines
# FIXME... revisit for something less kludgy
if '*' in line or len(line) != 3 or '.' not in line[0]:
continue
else:
pkg, version, repo = line
name, dist = pkg.rsplit('.', 1)
updates.update({name: {'version': version, 'dist': dist, 'repo': repo}})
elif rc == 1:
res['msg'] = err
res['rc'] = rc
module.fail_json(**res)
if update_all:
cmd = yum_basecmd + ['update']
else:
for spec in items:
# some guess work involved with groups. update @<group> will install the group if missing
if spec.startswith('@'):
pkgs['update'].append(spec)
continue
# dep/pkgname - find it
else:
if is_installed(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos):
pkgs['update'].append(spec)
else:
pkgs['install'].append(spec)
pkglist = what_provides(module, repoq, spec, conf_file, en_repos=en_repos, dis_repos=dis_repos)
# FIXME..? may not be desirable to throw an exception here if a single package is missing
if not pkglist:
res['msg'] += "No Package matching '%s' found available, installed or updated" % spec
module.fail_json(**res)
nothing_to_do = True
for this in pkglist:
if spec in pkgs['install'] and is_available(module, repoq, this, conf_file, en_repos=en_repos, dis_repos=dis_repos):
nothing_to_do = False
break
if spec in pkgs['update'] and spec in updates.keys():
nothing_to_do = False
if nothing_to_do:
res['results'].append("All packages providing %s are up to date" % spec)
continue
# if any of the packages are involved in a transaction, fail now
# so that we don't hang on the yum operation later
conflicts = transaction_exists(pkglist)
if len(conflicts) > 0:
res['msg'] += "The following packages have pending transactions: %s" % ", ".join(conflicts)
module.fail_json(**res)
# list of package updates
if update_all:
will_update = updates.keys()
else:
will_update = [u for u in pkgs['update'] if u in updates.keys() or u.startswith('@')]
# check_mode output
if module.check_mode:
to_update = []
for w in will_update:
if w.startswith('@'):
to_update.append((w, None))
msg = '%s will be updated' % w
else:
to_update.append((w, '%s.%s from %s' % (updates[w]['version'], updates[w]['dist'], updates[w]['repo'])))
res['changes'] = dict(installed=pkgs['install'], updated=to_update)
if len(will_update) > 0 or len(pkgs['install']) > 0:
res['changed'] = True
return res
# run commands
if cmd: # update all
rc, out, err = module.run_command(cmd)
res['changed'] = True
else:
if len(pkgs['install']) > 0: # install missing
cmd = yum_basecmd + ['install'] + pkgs['install']
rc, out, err = module.run_command(cmd)
res['changed'] = True
else:
rc, out, err = [0, '', '']
if len(will_update) > 0: # update present
cmd = yum_basecmd + ['update'] + pkgs['update']
rc2, out2, err2 = module.run_command(cmd)
res['changed'] = True
else:
rc2, out2, err2 = [0, '', '']
if not update_all:
rc += rc2
out += out2
err += err2
res['rc'] += rc
res['msg'] += err
res['results'].append(out)
if rc:
res['failed'] = True
return res
def ensure(module, state, pkgs, conf_file, enablerepo, disablerepo,
disable_gpg_check, exclude, repoq):
yumbin = module.get_bin_path('yum')
# need debug level 2 to get 'Nothing to do' for groupinstall.
yum_basecmd = [yumbin, '-d', '2', '-y']
if conf_file and os.path.exists(conf_file):
yum_basecmd += ['-c', conf_file]
if repoq:
repoq += ['-c', conf_file]
dis_repos =[]
en_repos = []
if disablerepo:
dis_repos = disablerepo.split(',')
r_cmd = ['--disablerepo=%s' % disablerepo]
yum_basecmd.extend(r_cmd)
if enablerepo:
en_repos = enablerepo.split(',')
r_cmd = ['--enablerepo=%s' % enablerepo]
yum_basecmd.extend(r_cmd)
if exclude:
e_cmd = ['--exclude=%s' % exclude]
yum_basecmd.extend(e_cmd)
if state in ['installed', 'present', 'latest']:
if module.params.get('update_cache'):
module.run_command(yum_basecmd + ['makecache'])
my = yum_base(conf_file)
try:
if disablerepo:
my.repos.disableRepo(disablerepo)
current_repos = my.repos.repos.keys()
if enablerepo:
try:
my.repos.enableRepo(enablerepo)
new_repos = my.repos.repos.keys()
for i in new_repos:
if not i in current_repos:
rid = my.repos.getRepo(i)
a = rid.repoXML.repoid
current_repos = new_repos
except yum.Errors.YumBaseError, e:
module.fail_json(msg="Error setting/accessing repos: %s" % (e))
except yum.Errors.YumBaseError, e:
module.fail_json(msg="Error accessing repos: %s" % e)
if state in ['installed', 'present']:
if disable_gpg_check:
yum_basecmd.append('--nogpgcheck')
res = install(module, pkgs, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
elif state in ['removed', 'absent']:
res = remove(module, pkgs, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
elif state == 'latest':
if disable_gpg_check:
yum_basecmd.append('--nogpgcheck')
res = latest(module, pkgs, repoq, yum_basecmd, conf_file, en_repos, dis_repos)
else:
# should be caught by AnsibleModule argument_spec
module.fail_json(msg="we should never get here unless this all"
" failed", changed=False, results='', errors='unepected state')
return res
def main():
# state=installed name=pkgspec
# state=removed name=pkgspec
# state=latest name=pkgspec
#
# informational commands:
# list=installed
# list=updates
# list=available
# list=repos
# list=pkgspec
module = AnsibleModule(
argument_spec = dict(
name=dict(aliases=['pkg'], type="list"),
exclude=dict(required=False, default=None),
# removed==absent, installed==present, these are accepted as aliases
state=dict(default='installed', choices=['absent','present','installed','removed','latest']),
enablerepo=dict(),
disablerepo=dict(),
list=dict(),
conf_file=dict(default=None),
disable_gpg_check=dict(required=False, default="no", type='bool'),
update_cache=dict(required=False, default="no", type='bool'),
# this should not be needed, but exists as a failsafe
install_repoquery=dict(required=False, default="yes", type='bool'),
),
required_one_of = [['name','list']],
mutually_exclusive = [['name','list']],
supports_check_mode = True
)
params = module.params
if params['list']:
repoquerybin = ensure_yum_utils(module)
if not repoquerybin:
module.fail_json(msg="repoquery is required to use list= with this module. Please install the yum-utils package.")
results = dict(results=list_stuff(module, repoquerybin, params['conf_file'], params['list']))
else:
# If rhn-plugin is installed and no rhn-certificate is available on
# the system then users will see an error message using the yum API.
# Use repoquery in those cases.
my = yum_base(params['conf_file'])
# A sideeffect of accessing conf is that the configuration is
# loaded and plugins are discovered
my.conf
repoquery = None
try:
yum_plugins = my.plugins._plugins
except AttributeError:
pass
else:
if 'rhnplugin' in yum_plugins:
repoquerybin = ensure_yum_utils(module)
if repoquerybin:
repoquery = [repoquerybin, '--show-duplicates', '--plugins', '--quiet']
pkg = [ p.strip() for p in params['name']]
exclude = params['exclude']
state = params['state']
enablerepo = params.get('enablerepo', '')
disablerepo = params.get('disablerepo', '')
disable_gpg_check = params['disable_gpg_check']
results = ensure(module, state, pkg, params['conf_file'], enablerepo,
disablerepo, disable_gpg_check, exclude, repoquery)
if repoquery:
results['msg'] = '%s %s' % (results.get('msg',''), 'Warning: Due to potential bad behaviour with rhnplugin and certificates, used slower repoquery calls instead of Yum API.')
module.exit_json(**results)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.urls import *
if __name__ == '__main__':
main()
| gpl-3.0 |
ptphp/PyLib | src/devs/trevp-tlslite-cac0c81/tlslite/integration/httptlsconnection.py | 1 | 4457 | # Authors:
# Trevor Perrin
# Kees Bos - Added ignoreAbruptClose parameter
# Dimitris Moraitis - Anon ciphersuites
#
# See the LICENSE file for legal information regarding use of this file.
"""TLS Lite + httplib."""
import socket
import httplib
from tlslite.tlsconnection import TLSConnection
from tlslite.integration.clienthelper import ClientHelper
class HTTPTLSConnection(httplib.HTTPConnection, ClientHelper):
"""This class extends L{httplib.HTTPConnection} to support TLS."""
def __init__(self, host, port=None, strict=None,
timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
source_address=None,
username=None, password=None,
certChain=None, privateKey=None,
x509Fingerprint=None,
tackID=None,
hardTack=None,
settings=None,
ignoreAbruptClose=False,
anon=False):
"""Create a new HTTPTLSConnection.
For client authentication, use one of these argument
combinations:
- username, password (SRP)
- certChain, privateKey (certificate)
For server authentication, you can either rely on the
implicit mutual authentication performed by SRP
or you can do certificate-based server
authentication with one of these argument combinations:
- x509Fingerprint
Certificate-based server authentication is compatible with
SRP or certificate-based client authentication.
The constructor does not perform the TLS handshake itself, but
simply stores these arguments for later. The handshake is
performed only when this class needs to connect with the
server. Thus you should be prepared to handle TLS-specific
exceptions when calling methods inherited from
L{httplib.HTTPConnection} such as request(), connect(), and
send(). See the client handshake functions in
L{tlslite.TLSConnection.TLSConnection} for details on which
exceptions might be raised.
@type host: str
@param host: Server to connect to.
@type port: int
@param port: Port to connect to.
@type username: str
@param username: SRP username. Requires the
'password' argument.
@type password: str
@param password: SRP password for mutual authentication.
Requires the 'username' argument.
@type certChain: L{tlslite.x509certchain.X509CertChain} or
@param certChain: Certificate chain for client authentication.
Requires the 'privateKey' argument. Excludes the SRP arguments.
@type privateKey: L{tlslite.utils.rsakey.RSAKey}
@param privateKey: Private key for client authentication.
Requires the 'certChain' argument. Excludes the SRP arguments.
@type x509Fingerprint: str
@param x509Fingerprint: Hex-encoded X.509 fingerprint for
server authentication.
@type tackID: str
@param tackID: TACK ID for server authentication.
@type hardTack: bool
@param hardTack: Whether to raise TackBreakSigError on TACK Break.
@type settings: L{tlslite.handshakesettings.HandshakeSettings}
@param settings: Various settings which can be used to control
the ciphersuites, certificate types, and SSL/TLS versions
offered by the client.
@type ignoreAbruptClose: bool
@param ignoreAbruptClose: ignore the TLSAbruptCloseError on
unexpected hangup.
"""
if source_address:
httplib.HTTPConnection.__init__(self, host, port, strict,
timeout, source_address)
if not source_address:
httplib.HTTPConnection.__init__(self, host, port, strict,
timeout)
self.ignoreAbruptClose = ignoreAbruptClose
ClientHelper.__init__(self,
username, password,
certChain, privateKey,
x509Fingerprint,
tackID,
hardTack,
settings,
anon)
def connect(self):
httplib.HTTPConnection.connect(self)
self.sock = TLSConnection(self.sock)
self.sock.ignoreAbruptClose = self.ignoreAbruptClose
ClientHelper._handshake(self, self.sock)
| apache-2.0 |
Zac-HD/home-assistant | homeassistant/components/switch/insteon_local.py | 6 | 5416 | """
Support for Insteon switch devices via local hub support.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/switch.insteon_local/
"""
import json
import logging
import os
from datetime import timedelta
from homeassistant.components.switch import SwitchDevice
from homeassistant.loader import get_component
import homeassistant.util as util
_CONFIGURING = {}
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['insteon_local']
DOMAIN = 'switch'
INSTEON_LOCAL_SWITCH_CONF = 'insteon_local_switch.conf'
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(milliseconds=100)
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=10)
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Set up the Insteon local switch platform."""
insteonhub = hass.data['insteon_local']
conf_switches = config_from_file(hass.config.path(
INSTEON_LOCAL_SWITCH_CONF))
if len(conf_switches):
for device_id in conf_switches:
setup_switch(
device_id, conf_switches[device_id], insteonhub, hass,
add_devices)
else:
linked = insteonhub.get_linked()
for device_id in linked:
if linked[device_id]['cat_type'] == 'switch'\
and device_id not in conf_switches:
request_configuration(device_id, insteonhub,
linked[device_id]['model_name'] + ' ' +
linked[device_id]['sku'],
hass, add_devices)
def request_configuration(device_id, insteonhub, model, hass,
add_devices_callback):
"""Request configuration steps from the user."""
configurator = get_component('configurator')
# We got an error if this method is called while we are configuring
if device_id in _CONFIGURING:
configurator.notify_errors(
_CONFIGURING[device_id], 'Failed to register, please try again.')
return
def insteon_switch_config_callback(data):
"""The actions to do when our configuration callback is called."""
setup_switch(device_id, data.get('name'), insteonhub, hass,
add_devices_callback)
_CONFIGURING[device_id] = configurator.request_config(
hass, 'Insteon Switch ' + model + ' addr: ' + device_id,
insteon_switch_config_callback,
description=('Enter a name for ' + model + ' addr: ' + device_id),
entity_picture='/static/images/config_insteon.png',
submit_caption='Confirm',
fields=[{'id': 'name', 'name': 'Name', 'type': ''}]
)
def setup_switch(device_id, name, insteonhub, hass, add_devices_callback):
"""Set up the switch."""
if device_id in _CONFIGURING:
request_id = _CONFIGURING.pop(device_id)
configurator = get_component('configurator')
configurator.request_done(request_id)
_LOGGER.info("Device configuration done!")
conf_switch = config_from_file(hass.config.path(INSTEON_LOCAL_SWITCH_CONF))
if device_id not in conf_switch:
conf_switch[device_id] = name
if not config_from_file(
hass.config.path(INSTEON_LOCAL_SWITCH_CONF), conf_switch):
_LOGGER.error("Failed to save configuration file")
device = insteonhub.switch(device_id)
add_devices_callback([InsteonLocalSwitchDevice(device, name)])
def config_from_file(filename, config=None):
"""Small configuration file management function."""
if config:
# We're writing configuration
try:
with open(filename, 'w') as fdesc:
fdesc.write(json.dumps(config))
except IOError as error:
_LOGGER.error("Saving configuration file failed: %s", error)
return False
return True
else:
# We're reading config
if os.path.isfile(filename):
try:
with open(filename, 'r') as fdesc:
return json.loads(fdesc.read())
except IOError as error:
_LOGGER.error("Reading config file failed: %s", error)
# This won't work yet
return False
else:
return {}
class InsteonLocalSwitchDevice(SwitchDevice):
"""An abstract Class for an Insteon node."""
def __init__(self, node, name):
"""Initialize the device."""
self.node = node
self.node.deviceName = name
self._state = False
@property
def name(self):
"""Return the the name of the node."""
return self.node.deviceName
@property
def unique_id(self):
"""Return the ID of this Insteon node."""
return 'insteon_local_{}'.format(self.node.device_id)
@util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update(self):
"""Get the updated status of the switch."""
resp = self.node.status(0)
if 'cmd2' in resp:
self._state = int(resp['cmd2'], 16) > 0
@property
def is_on(self):
"""Return the boolean response if the node is on."""
return self._state
def turn_on(self, **kwargs):
"""Turn device on."""
self.node.on()
self._state = True
def turn_off(self, **kwargs):
"""Turn device off."""
self.node.off()
self._state = False
| apache-2.0 |
samnazarko/osmc | package/mediacenter-eventclients-common-osmc/files/usr/share/pyshared/xbmc/ps3/sixpair.py | 208 | 2903 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import usb
vendor = 0x054c
product = 0x0268
timeout = 5000
passed_value = 0x03f5
def find_sixaxes():
res = []
for bus in usb.busses():
for dev in bus.devices:
if dev.idVendor == vendor and dev.idProduct == product:
res.append(dev)
return res
def find_interface(dev):
for cfg in dev.configurations:
for itf in cfg.interfaces:
for alt in itf:
if alt.interfaceClass == 3:
return alt
raise Exception("Unable to find interface")
def mac_to_string(mac):
return "%02x:%02x:%02x:%02x:%02x:%02x" % (mac[0], mac[1], mac[2], mac[3], mac[4], mac[5])
def set_pair_filename(dirname, filename, mac):
for bus in usb.busses():
if int(bus.dirname) == int(dirname):
for dev in bus.devices:
if int(dev.filename) == int(filename):
if dev.idVendor == vendor and dev.idProduct == product:
update_pair(dev, mac)
return
else:
raise Exception("Device is not a sixaxis")
raise Exception("Device not found")
def set_pair(dev, mac):
itf = find_interface(dev)
handle = dev.open()
msg = (0x01, 0x00) + mac;
try:
handle.detachKernelDriver(itf.interfaceNumber)
except usb.USBError:
pass
handle.claimInterface(itf.interfaceNumber)
try:
handle.controlMsg(usb.ENDPOINT_OUT | usb.TYPE_CLASS | usb.RECIP_INTERFACE
, usb.REQ_SET_CONFIGURATION, msg, passed_value, itf.interfaceNumber, timeout)
finally:
handle.releaseInterface()
def get_pair(dev):
itf = find_interface(dev)
handle = dev.open()
try:
handle.detachKernelDriver(itf.interfaceNumber)
except usb.USBError:
pass
handle.claimInterface(itf.interfaceNumber)
try:
msg = handle.controlMsg(usb.ENDPOINT_IN | usb.TYPE_CLASS | usb.RECIP_INTERFACE
, usb.REQ_CLEAR_FEATURE, 8, passed_value, itf.interfaceNumber, timeout)
finally:
handle.releaseInterface()
return msg[2:8]
def set_pair_all(mac):
devs = find_sixaxes()
for dev in devs:
update_pair(dev, mac)
def update_pair(dev, mac):
old = get_pair(dev)
if old != mac:
print "Reparing sixaxis from:" + mac_to_string(old) + " to:" + mac_to_string(mac)
set_pair(dev, mac)
if __name__=="__main__":
devs = find_sixaxes()
mac = None
if len(sys.argv) > 1:
try:
mac = sys.argv[1].split(':')
mac = tuple([int(x, 16) for x in mac])
if len(mac) != 6:
print "Invalid length of HCI address, should be 6 parts"
mac = None
except:
print "Failed to parse HCI address"
mac = None
for dev in devs:
if mac:
update_pair(dev, mac)
else:
print "Found sixaxis paired to: " + mac_to_string(get_pair(dev))
| gpl-2.0 |
zduputel/wphase | bin/make_cwp.py | 1 | 7164 | #!/usr/bin/env python
# *-* coding: iso-8859-1 *-*
############################################################################
#
# W phase source inversion package
# -------------
#
# Main authors: Zacharie Duputel, Luis Rivera and Hiroo Kanamori
#
# (c) California Institute of Technology and Universite de Strasbourg / CNRS
# April 2013
#
# Neither the name of the California Institute of Technology (Caltech)
# nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written
# permission
#
# 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/>.
#
############################################################################
# CONCATENATED W PHASE TRACES
from Arguments import *
#Customizing matplotlib
import matplotlib
matplotlib.use('PDF')
# Import external modules
import os,sys,re
import getopt as go
import numpy as np
import matplotlib.pyplot as plt
# Import internal modules
import sacpy
# Internal functions
def usage(cmd):
print('usage: %s [chan1 chan2 (default: LHZ LHN LHE LH1 LH2)] [option] (for help see %s -h)'%(cmd,cmd))
# All done
return;
def disphelp(cmd):
print('Make CWP traces\n')
usage(cmd)
print('\nAll parameters are optional:')
print('\n -i, --ifort15 input fort.15 file (e.g. fort.15, ts_fort.15, xy_fort.15)')
print('\n -n, --noref no reference solution')
print('\n -h, --help display this help and exit')
print('\nReport bugs to: <zacharie.duputel@eost.u-strasbg.fr>')
# All done
return;
def main(argv):
# Input parameters
try:
opts, args = go.gnu_getopt(argv[1:],'i:nh',["ifort15=","noref","help"])
except getopt.GetoptError as err:
raise
o_wpfile = O_WPINVERSION
predfile = ''
isref = 1
CHAN = ['LHZ', 'LHN', 'LHE', 'LH1', 'LH2']
for o, a in opts:
if o == '-h' or o == '--help':
disphelp(sys.argv[0])
sys.exit(0)
if o == '-i' or o == '--ifort15':
predfile = a
if o == '-n' or o == '--noref':
isref = 0
if len(args):
CHAN = args
if not os.path.exists(o_wpfile):
sys.stderr.write('Error: file %s not available\n'%(o_wpfile))
if len(predfile) and not os.path.exists(predfile):
raise IOError('No fort.15 file named %s\n'%(predfile))
if not len(predfile):
predfile = 'xy_fort.15'
if not os.path.exists(predfile):
predfile = 'ts_fort.15'
if not os.path.exists(predfile):
predfile = 'fort.15'
if not os.path.exists(predfile):
raise IOError('No fort.15 file found\n')
sys.stdout.write('Input fort.15 file: %s\n'%predfile)
count = 0
sys.stdout.write('Input channels are: ')
for chan in CHAN:
if not os.path.exists('%s_%s'%(predfile,chan)):
continue
else:
count += 1
sys.stdout.write('%5s'%chan)
if not count:
ErrMsg = 'Error: No fort.15_ file for'
for chan in CHAN:
ErrMsg += '%5s'%(chan)
raise IOError(ErrMsg)
sys.stdout.write('\nRead %s ...\n%s pages:\n'%(o_wpfile,count))
# Main loop
sac = sacpy.sac()
L = open(o_wpfile).readlines()
ppW = matplotlib.backends.backend_pdf.PdfPages('CWP_W.pdf')
sys.stdout.write('CWP_W.pdf\n')
if isref:
ppR = matplotlib.backends.backend_pdf.PdfPages('CWP_R.pdf')
sys.stdout.write('CWP_R.pdf')
for chan in CHAN:
cb = 0.0
stat_label = []
stat_posit = []
# Read o_wpinversion
for l in L:
items = l.strip().split()
sac.rsac(items[0])
if sac.kcmpnm[2] != chan[2]:
continue
stat_label.append(sac.kstnm)
i1 = int(items[3])
i2 = int(items[4])
npts = float(i2-i1)
stat_posit.append(cb+npts/2.0)
cb += npts
if not len(stat_label):
sys.stderr.write('WARNING: No channel %s in %s\n'%(chan,o_wpfile))
continue
# Read predfile
ifile = predfile+'_'+chan
L2 = open(ifile).readlines()
ncol = len(L2[0].strip().split())
if ncol < 3 and isref:
print('Warning No ref solution in %s'%ifile)
isref = 0
else:
Wref = []
Wdat = []
Wsyn = []
for l in L2:
items = l.strip().split()
Wdat.append(float(items[0])*1000.0)
Wsyn.append(float(items[1])*1000.0)
if isref:
if len(items)<3:
raise IOError('ERROR: error reading %s\n'%(ifile))
Wref.append(float(items[2])*1000.0)
t = np.arange(0,len(Wdat),dtype='float')
# Display
fig=plt.figure(figsize=CWP_FIGSIZE)
fig.subplots_adjust(left=0.08,bottom=0.12,right=0.96,top=0.88,wspace=0.2,hspace=0.2)
plt.plot(t,Wdat,'k')
plt.plot(t,Wsyn,'r')
ymin = 1.1*min(Wdat)
ymax = 1.1*max(Wdat)
for stnm,x in zip(stat_label,stat_posit):
plt.text(x,ymax*0.6,stnm,rotation=90,fontsize=16,fontstyle='italic')
plt.ylim([ymin,ymax])
plt.xlim([0,t[-1]])
plt.xlabel('time, sec')
plt.ylabel('displacement, mm')
plt.title('Data fit, W Phase solution, %s'%chan[2])
ppW.savefig(papertype='a4',orientation='landscape')
plt.close()
if isref:
fig = plt.figure(figsize=CWP_FIGSIZE)
fig.subplots_adjust(left=0.08,bottom=0.12,right=0.96,top=0.88,wspace=0.2,hspace=0.2)
plt.plot(t,Wdat,'k')
plt.plot(t,Wref,'r')
ymin = 1.1*min(Wdat)
ymax = 1.1*max(Wdat)
for stnm,x in zip(stat_label,stat_posit):
plt.text(x,ymax*0.6,stnm,rotation=90,fontsize=16,fontstyle='italic')
plt.ylim([ymin,ymax])
plt.xlim([0,t[-1]])
plt.xlabel('time, sec')
plt.ylabel('displacement, mm')
plt.title('Data fit, Reference solution, %s'%chan[2])
ppR.savefig(papertype='a4',orientation='landscape')
plt.close()
sys.stdout.write('\n')
ppW.close()
if isref:
ppR.close()
if __name__=='__main__':
main(sys.argv)
| gpl-3.0 |
llhe/tensorflow | tensorflow/contrib/tensor_forest/python/kernel_tests/best_splits_op_test.py | 80 | 4532 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tf.contrib.tensor_forest.ops.best_splits_op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow # pylint: disable=unused-import
from tensorflow.contrib.tensor_forest.python.ops import tensor_forest_ops
from tensorflow.python.framework import test_util
from tensorflow.python.platform import googletest
class BestSplitsClassificationTests(test_util.TensorFlowTestCase):
def setUp(self):
self.finished = [3, 5]
self.node_map = [-1, -1, -1, 0, -1, 3, -1, -1, -1]
self.candidate_counts = [[[153., 50., 60., 40., 3.],
[200., 70., 30., 70., 30.]],
[[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]],
[[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.]],
[[40., 10., 10., 10., 10.],
[30., 10., 5., 5., 10.]]]
self.total_counts = [[400., 100., 100., 100., 100.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[400., 100., 100., 100., 100.]]
self.squares = []
def testSimple(self):
with self.test_session():
split_indices = tensor_forest_ops.best_splits(
self.finished,
self.node_map,
self.candidate_counts,
self.squares,
self.total_counts,
self.squares,
regression=False)
self.assertAllEqual([0, 1], split_indices.eval())
def testNoFinished(self):
with self.test_session():
split_indices = tensor_forest_ops.best_splits(
[],
self.node_map,
self.candidate_counts,
self.squares,
self.total_counts,
self.squares,
regression=False)
self.assertAllEqual([], split_indices.eval())
def testBadInput(self):
del self.total_counts[1]
with self.test_session():
with self.assertRaisesOpError(
'Number of accumulators should be the same in split_sums '
'and accumulator_sums.'):
tensor_forest_ops.best_splits(
self.finished,
self.node_map,
self.candidate_counts,
self.squares,
self.total_counts,
self.squares,
regression=False).eval()
class BestSplitsRegressionTests(test_util.TensorFlowTestCase):
def setUp(self):
self.finished = [3, 5]
self.node_map = [-1, -1, -1, 0, -1, 3, -1, -1, -1]
self.candidate_sums = [[[5., 8., 8., 8.], [5., 10., 10., 10.]],
[[0., 0., 0., 0.], [0., 0., 0., 0.]],
[[0., 0., 0., 0.], [0., 0., 0., 0.]],
[[10., 10., 20., 10.], [10., 5., 5., 5.]]]
self.candidate_squares = [[[5., 50., 50., 50.], [5., 50., 50., 50.]],
[[0., 0., 0., 0.], [0., 0., 0., 0.]],
[[0., 0., 0., 0.], [0., 0., 0., 0.]],
[[10., 40., 50., 60.], [10., 40., 40., 40.]]]
self.total_sums = [[15., 10., 10., 10.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[20., 20., 20., 20.]]
self.total_squares = [[15., 50., 50., 50.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[20., 60., 60., 60.]]
def testSimple(self):
with self.test_session():
split_indices = tensor_forest_ops.best_splits(
self.finished,
self.node_map,
self.candidate_sums,
self.candidate_squares,
self.total_sums,
self.total_squares,
regression=True)
self.assertAllEqual([1, 0], split_indices.eval())
if __name__ == '__main__':
googletest.main()
| apache-2.0 |
xuleiboy1234/autoTitle | tensorflow/tensorflow/contrib/opt/python/training/lazy_adam_optimizer.py | 86 | 3881 | # Copyright 2017 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.
# ==============================================================================
"""Variant of the Adam optimizer that handles sparse updates more efficiently.
Compared with the original Adam optimizer, the one in this file can provide a
large improvement in model training throughput for some applications. However,
it provides slightly different semantics than the original Adam algorithm, and
may lead to different empirical results.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.training import adam
class LazyAdamOptimizer(adam.AdamOptimizer):
"""Variant of the Adam optimizer that handles sparse updates more efficiently.
The original Adam algorithm maintains two moving-average accumulators for
each trainable variable; the accumulators are updated at every step.
This class provides lazier handling of gradient updates for sparse variables.
It only updates moving-average accumulators for sparse variable indices that
appear in the current batch, rather than updating the accumulators for all
indices. Compared with the original Adam optimizer, it can provide large
improvements in model training throughput for some applications. However, it
provides slightly different semantics than the original Adam algorithm, and
may lead to different empirical results.
"""
def _apply_sparse(self, grad, var):
beta1_power = math_ops.cast(self._beta1_power, var.dtype.base_dtype)
beta2_power = math_ops.cast(self._beta2_power, var.dtype.base_dtype)
lr_t = math_ops.cast(self._lr_t, var.dtype.base_dtype)
beta1_t = math_ops.cast(self._beta1_t, var.dtype.base_dtype)
beta2_t = math_ops.cast(self._beta2_t, var.dtype.base_dtype)
epsilon_t = math_ops.cast(self._epsilon_t, var.dtype.base_dtype)
lr = (lr_t * math_ops.sqrt(1 - beta2_power) / (1 - beta1_power))
# m := beta1 * m + (1 - beta1) * g_t
m = self.get_slot(var, "m")
m_t = state_ops.scatter_update(m, grad.indices,
beta1_t * array_ops.gather(m, grad.indices) +
(1 - beta1_t) * grad.values,
use_locking=self._use_locking)
# v := beta2 * v + (1 - beta2) * (g_t * g_t)
v = self.get_slot(var, "v")
v_t = state_ops.scatter_update(v, grad.indices,
beta2_t * array_ops.gather(v, grad.indices) +
(1 - beta2_t) * math_ops.square(grad.values),
use_locking=self._use_locking)
# variable -= learning_rate * m_t / (epsilon_t + sqrt(v_t))
m_t_slice = array_ops.gather(m_t, grad.indices)
v_t_slice = array_ops.gather(v_t, grad.indices)
denominator_slice = math_ops.sqrt(v_t_slice) + epsilon_t
var_update = state_ops.scatter_sub(var, grad.indices,
lr * m_t_slice / denominator_slice,
use_locking=self._use_locking)
return control_flow_ops.group(var_update, m_t, v_t)
| mit |
ryfeus/lambda-packs | Tensorflow_OpenCV_Nightly/source/tensorflow/tensorboard/backend/event_processing/event_file_loader.py | 68 | 2971 | # Copyright 2015 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.
# ==============================================================================
"""Functionality for loading events from a record file."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.util import event_pb2
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.framework import errors
from tensorflow.python.platform import app
from tensorflow.python.platform import resource_loader
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import compat
class EventFileLoader(object):
"""An EventLoader is an iterator that yields Event protos."""
def __init__(self, file_path):
if file_path is None:
raise ValueError('A file path is required')
file_path = resource_loader.readahead_file_path(file_path)
logging.debug('Opening a record reader pointing at %s', file_path)
with errors.raise_exception_on_not_ok_status() as status:
self._reader = pywrap_tensorflow.PyRecordReader_New(
compat.as_bytes(file_path), 0, compat.as_bytes(''), status)
# Store it for logging purposes.
self._file_path = file_path
if not self._reader:
raise IOError('Failed to open a record reader pointing to %s' % file_path)
def Load(self):
"""Loads all new values from disk.
Calling Load multiple times in a row will not 'drop' events as long as the
return value is not iterated over.
Yields:
All values that were written to disk that have not been yielded yet.
"""
while True:
try:
with errors.raise_exception_on_not_ok_status() as status:
self._reader.GetNext(status)
except (errors.DataLossError, errors.OutOfRangeError):
# We ignore partial read exceptions, because a record may be truncated.
# PyRecordReader holds the offset prior to the failed read, so retrying
# will succeed.
break
event = event_pb2.Event()
event.ParseFromString(self._reader.record())
yield event
logging.debug('No more events in %s', self._file_path)
def main(argv):
if len(argv) != 2:
print('Usage: event_file_loader <path-to-the-recordio-file>')
return 1
loader = EventFileLoader(argv[1])
for event in loader.Load():
print(event)
if __name__ == '__main__':
app.run()
| mit |
Karaage-Cluster/karaage-debian | karaage/legacy/projects/south_migrations/0014_move_projects.py | 3 | 13986 | # -*- coding: utf-8 -*-
from south.v2 import DataMigration
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
for src in orm.Project.objects.iterator():
try:
dst = orm.ProjectTmp.objects.get(pid=src.pid)
except orm.ProjectTmp.DoesNotExist:
dst = orm.ProjectTmp(pid=src.pid)
dst.name = src.name
dst.group = src.group
dst.institute = src.institute
dst.description = src.description
dst.is_approved = src.is_approved
dst.start_date = src.start_date
dst.end_date = src.end_date
dst.additional_req = src.additional_req
dst.is_active = src.is_active
dst.approved_by = src.approved_by
dst.date_approved = src.date_approved
dst.deleted_by = src.deleted_by
dst.date_deleted = src.date_deleted
dst.last_usage = src.last_usage
dst.save()
dst.leaders = src.leaders.iterator()
for pq in orm.ProjectQuota.objects.iterator():
try:
src = pq.project
dst = orm.ProjectTmp.objects.get(pid=src.pid)
pq.project_tmp = dst
pq.save()
except orm.Project.DoesNotExist:
pq.delete()
def backwards(self, orm):
"Write your backwards methods here."
for src in orm.ProjectTmp.objects.iterator():
try:
dst = orm.Project.objects.get(pid=src.pid)
except orm.Project.DoesNotExist:
dst = orm.Project(pid=src.pid)
dst.name = src.name
dst.group = src.group
dst.institute = src.institute
dst.description = src.description
dst.is_approved = src.is_approved
dst.start_date = src.start_date
dst.end_date = src.end_date
dst.additional_req = src.additional_req
dst.is_active = src.is_active
dst.approved_by = src.approved_by
dst.date_approved = src.date_approved
dst.deleted_by = src.deleted_by
dst.date_deleted = src.date_deleted
dst.last_usage = src.last_usage
dst.save()
dst.leaders = src.leaders.iterator()
for pq in orm.ProjectQuota.objects.iterator():
src = pq.project_tmp
dst = orm.Project.objects.get(pid=src.pid)
pq.project = dst
pq.save()
models = {
'institutes.institute': {
'Meta': {'ordering': "['name']", 'object_name': 'Institute', 'db_table': "'institute'"},
'delegates': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'delegate'", 'to': "orm['people.Person']", 'through': "orm['institutes.InstituteDelegate']", 'blank': 'True', 'symmetrical': 'False', 'null': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Group']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'}),
'saml_entityid': ('django.db.models.fields.CharField', [], {'max_length': '200', 'unique': 'True', 'null': 'True', 'blank': 'True'})
},
'institutes.institutedelegate': {
'Meta': {'object_name': 'InstituteDelegate', 'db_table': "'institutedelegate'"},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['institutes.Institute']"}),
'person': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Person']"}),
'send_email': ('django.db.models.fields.BooleanField', [], {'default': 'False'})
},
'machines.machinecategory': {
'Meta': {'object_name': 'MachineCategory', 'db_table': "'machine_category'"},
'datastore': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'people.group': {
'Meta': {'ordering': "['name']", 'object_name': 'Group'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'members': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'groups'", 'symmetrical': 'False', 'to': "orm['people.Person']"}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '100'})
},
'people.person': {
'Meta': {'ordering': "['full_name', 'short_name']", 'object_name': 'Person', 'db_table': "'person'"},
'address': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_approver'", 'null': 'True', 'to': "orm['people.Person']"}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'comment': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}),
'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'user_deletor'", 'null': 'True', 'to': "orm['people.Person']"}),
'department': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'db_index': 'True'}),
'expires': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '50', 'null': 'True', 'blank': 'True'}),
'full_name': ('django.db.models.fields.CharField', [], {'max_length': '60'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['institutes.Institute']"}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_admin': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_systemuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'legacy_ldap_password': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}),
'login_enabled': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'mobile': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'position': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'postcode': ('django.db.models.fields.CharField', [], {'max_length': '8', 'null': 'True', 'blank': 'True'}),
'saml_id': ('django.db.models.fields.CharField', [], {'max_length': '200', 'unique': 'True', 'null': 'True', 'blank': 'True'}),
'short_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}),
'state': ('django.db.models.fields.CharField', [], {'max_length': '4', 'null': 'True', 'blank': 'True'}),
'supervisor': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}),
'telephone': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '10', 'null': 'True', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}),
'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
'projects.project': {
'Meta': {'ordering': "['pid']", 'object_name': 'Project', 'db_table': "'project'"},
'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_approver'", 'null': 'True', 'to': "orm['people.Person']"}),
'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_deletor'", 'null': 'True', 'to': "orm['people.Person']"}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Group']"}),
'institute': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['institutes.Institute']"}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'leaders': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'leaders'", 'symmetrical': 'False', 'to': "orm['people.Person']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'pid': ('django.db.models.fields.CharField', [], {'max_length': '50', 'primary_key': 'True'}),
'start_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2013, 9, 17, 0, 0)'})
},
'projects.projectquota': {
'Meta': {'unique_together': "(('project', 'machine_category'),)", 'object_name': 'ProjectQuota', 'db_table': "'project_quota'"},
'cap': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'machine_category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['machines.MachineCategory']"}),
'project': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.Project']"}),
'project_tmp': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['projects.ProjectTmp']", 'null': 'True'})
},
'projects.projecttmp': {
'Meta': {'object_name': 'ProjectTmp'},
'additional_req': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'approved_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_approver_tmp'", 'null': 'True', 'to': "orm['people.Person']"}),
'date_approved': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'date_deleted': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'deleted_by': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'project_deletor_tmp'", 'null': 'True', 'to': "orm['people.Person']"}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Group']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'institute': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'project_tmp'", 'to': "orm['institutes.Institute']"}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_approved': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_usage': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'leaders': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'leaders_tmp'", 'symmetrical': 'False', 'to': "orm['people.Person']"}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'pid': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'start_date': ('django.db.models.fields.DateField', [], {'default': 'datetime.datetime(2013, 9, 17, 0, 0)'})
}
}
complete_apps = ['projects']
symmetrical = True
| gpl-3.0 |
martinbede/second-sight | tensorflow/contrib/util/__init__.py | 7 | 1356 | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Utilities for dealing with Tensors.
## Miscellaneous Utility Functions
@@constant_value
@@make_tensor_proto
@@make_ndarray
@@stripped_op_list_for_graph
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.python.framework.tensor_util import constant_value
from tensorflow.python.framework.tensor_util import make_tensor_proto
from tensorflow.python.framework.tensor_util import MakeNdarray as make_ndarray
from tensorflow.python.training.saver import stripped_op_list_for_graph
from tensorflow.python.util.all_util import make_all
__all__ = make_all(__name__)
| apache-2.0 |
MortimerGoro/servo | tests/wpt/web-platform-tests/tools/webdriver/webdriver/__init__.py | 149 | 1055 | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
from client import Cookies, Element, Find, Session, Timeouts, Window
from error import (
ElementNotSelectableException,
ElementNotVisibleException,
InvalidArgumentException,
InvalidCookieDomainException,
InvalidElementCoordinatesException,
InvalidElementStateException,
InvalidSelectorException,
InvalidSessionIdException,
JavascriptErrorException,
MoveTargetOutOfBoundsException,
NoSuchAlertException,
NoSuchElementException,
NoSuchFrameException,
NoSuchWindowException,
ScriptTimeoutException,
SessionNotCreatedException,
StaleElementReferenceException,
TimeoutException,
UnableToSetCookieException,
UnexpectedAlertOpenException,
UnknownCommandException,
UnknownErrorException,
UnknownMethodException,
UnsupportedOperationException,
WebDriverException)
| mpl-2.0 |
kevinljw/ntulive_web | node_modules/node-gyp/gyp/pylib/gyp/MSVSSettings_test.py | 1446 | 65937 | #!/usr/bin/env python
# Copyright (c) 2012 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.
"""Unit tests for the MSVSSettings.py file."""
import StringIO
import unittest
import gyp.MSVSSettings as MSVSSettings
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
self.stderr = StringIO.StringIO()
def _ExpectedWarnings(self, expected):
"""Compares recorded lines to expected warnings."""
self.stderr.seek(0)
actual = self.stderr.read().split('\n')
actual = [line for line in actual if line]
self.assertEqual(sorted(expected), sorted(actual))
def testValidateMSVSSettings_tool_names(self):
"""Tests that only MSVS tool names are allowed."""
MSVSSettings.ValidateMSVSSettings(
{'VCCLCompilerTool': {},
'VCLinkerTool': {},
'VCMIDLTool': {},
'foo': {},
'VCResourceCompilerTool': {},
'VCLibrarianTool': {},
'VCManifestTool': {},
'ClCompile': {}},
self.stderr)
self._ExpectedWarnings([
'Warning: unrecognized tool foo',
'Warning: unrecognized tool ClCompile'])
def testValidateMSVSSettings_settings(self):
"""Tests that for invalid MSVS settings."""
MSVSSettings.ValidateMSVSSettings(
{'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': ['string1', 'string2'],
'AdditionalUsingDirectories': 'folder1;folder2',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': '0',
'BasicRuntimeChecks': '5',
'BrowseInformation': 'fdkslj',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': '-1',
'CompileAs': '1',
'DebugInformationFormat': '2',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'string1;string2',
'EnableEnhancedInstructionSet': '1',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'Enableprefast': 'bogus',
'ErrorReporting': '1',
'ExceptionHandling': '1',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '1',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2',
'ForcedUsingFiles': 'file1;file2',
'GeneratePreprocessedFile': '1',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '1',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '1',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderThrough': 'a_file_name',
'PreprocessorDefinitions': 'string1;string2',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': '1',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '1',
'UseUnicodeResponseFiles': 'true',
'WarnAsError': 'true',
'WarningLevel': '1',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name',
'ZZXYZ': 'bogus'},
'VCLinkerTool': {
'AdditionalDependencies': 'file1;file2',
'AdditionalDependencies_excluded': 'file3',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalManifestDependencies': 'file1;file2',
'AdditionalOptions': 'a string1',
'AddModuleNamesToAssembly': 'file1;file2',
'AllowIsolation': 'true',
'AssemblyDebug': '2',
'AssemblyLinkResource': 'file1;file2',
'BaseAddress': 'a string1',
'CLRImageType': '2',
'CLRThreadAttribute': '2',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '2',
'DelayLoadDLLs': 'file1;file2',
'DelaySign': 'true',
'Driver': '2',
'EmbedManagedResourceFile': 'file1;file2',
'EnableCOMDATFolding': '2',
'EnableUAC': 'true',
'EntryPointSymbol': 'a string1',
'ErrorReporting': '2',
'FixedBaseAddress': '2',
'ForceSymbolReferences': 'file1;file2',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a string1',
'HeapReserveSize': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'file1;file2',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': '2',
'LinkIncremental': '2',
'LinkLibraryDependencies': 'true',
'LinkTimeCodeGeneration': '2',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a string1',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'OptimizeForWindows98': '1',
'OptimizeReferences': '2',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': '2',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'true',
'ShowProgress': '2',
'StackCommitSize': 'a string1',
'StackReserveSize': 'a string1',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': '2',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '2',
'TerminalServerAware': '2',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': '2',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'true',
'UseUnicodeResponseFiles': 'true',
'Version': 'a string1'},
'VCMIDLTool': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'CPreprocessOptions': 'a string1',
'DefaultCharType': '1',
'DLLDataFileName': 'a_file_name',
'EnableErrorChecks': '1',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'notgood': 'bogus',
'OutputDirectory': 'a string1',
'PreprocessorDefinitions': 'string1;string2',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TargetEnvironment': '1',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'string1;string2',
'ValidateParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '1'},
'VCResourceCompilerTool': {
'AdditionalOptions': 'a string1',
'AdditionalIncludeDirectories': 'folder1;folder2',
'Culture': '1003',
'IgnoreStandardIncludePath': 'true',
'notgood2': 'bogus',
'PreprocessorDefinitions': 'string1;string2',
'ResourceOutputFileName': 'a string1',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2'},
'VCLibrarianTool': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'ExportNamedFunctions': 'string1;string2',
'ForceSymbolReferences': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2',
'LinkLibraryDependencies': 'true',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'file1;file2',
'AdditionalOptions': 'a string1',
'AssemblyIdentity': 'a string1',
'ComponentFileName': 'a_file_name',
'DependencyInformationFile': 'a_file_name',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a string1',
'ManifestResourceFile': 'a_file_name',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'truel',
'UpdateFileHashesSearchPath': 'a_file_name',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'true',
'VerboseOutput': 'true'}},
self.stderr)
self._ExpectedWarnings([
'Warning: for VCCLCompilerTool/BasicRuntimeChecks, '
'index value (5) not in expected range [0, 4)',
'Warning: for VCCLCompilerTool/BrowseInformation, '
"invalid literal for int() with base 10: 'fdkslj'",
'Warning: for VCCLCompilerTool/CallingConvention, '
'index value (-1) not in expected range [0, 4)',
'Warning: for VCCLCompilerTool/DebugInformationFormat, '
'converted value for 2 not specified.',
'Warning: unrecognized setting VCCLCompilerTool/Enableprefast',
'Warning: unrecognized setting VCCLCompilerTool/ZZXYZ',
'Warning: for VCLinkerTool/TargetMachine, '
'converted value for 2 not specified.',
'Warning: unrecognized setting VCMIDLTool/notgood',
'Warning: unrecognized setting VCResourceCompilerTool/notgood2',
'Warning: for VCManifestTool/UpdateFileHashes, '
"expected bool; got 'truel'"
''])
def testValidateMSBuildSettings_settings(self):
"""Tests that for invalid MSBuild settings."""
MSVSSettings.ValidateMSBuildSettings(
{'ClCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': ['string1', 'string2'],
'AdditionalUsingDirectories': 'folder1;folder2',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': 'NoListing',
'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
'BrowseInformation': 'false',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'BuildingInIDE': 'true',
'CallingConvention': 'Cdecl',
'CompileAs': 'CompileAsC',
'CompileAsManaged': 'true',
'CreateHotpatchableImage': 'true',
'DebugInformationFormat': 'ProgramDatabase',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'string1;string2',
'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'Enableprefast': 'bogus',
'ErrorReporting': 'Prompt',
'ExceptionHandling': 'SyncCThrow',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Neither',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Precise',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2',
'ForcedUsingFiles': 'file1;file2',
'FunctionLevelLinking': 'false',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'OnlyExplicitInline',
'IntrinsicFunctions': 'false',
'MinimalRebuild': 'true',
'MultiProcessorCompilation': 'true',
'ObjectFileName': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Disabled',
'PrecompiledHeader': 'NotUsing',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderOutputFile': 'a_file_name',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'string1;string2',
'PreprocessOutputPath': 'a string1',
'PreprocessSuppressLineNumbers': 'false',
'PreprocessToFile': 'false',
'ProcessorNumber': '33',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': 'MultiThreaded',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1Byte',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'TreatSpecificWarningsAsErrors': 'string1;string2',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'string1;string2',
'UseFullPaths': 'true',
'UseUnicodeForAssemblerListing': 'true',
'WarningLevel': 'TurnOffAllWarnings',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name',
'ZZXYZ': 'bogus'},
'Link': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalManifestDependencies': 'file1;file2',
'AdditionalOptions': 'a string1',
'AddModuleNamesToAssembly': 'file1;file2',
'AllowIsolation': 'true',
'AssemblyDebug': '',
'AssemblyLinkResource': 'file1;file2',
'BaseAddress': 'a string1',
'BuildingInIDE': 'true',
'CLRImageType': 'ForceIJWImage',
'CLRSupportLastError': 'Enabled',
'CLRThreadAttribute': 'MTAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'CreateHotPatchableImage': 'X86Image',
'DataExecutionPrevention': 'false',
'DelayLoadDLLs': 'file1;file2',
'DelaySign': 'true',
'Driver': 'NotSet',
'EmbedManagedResourceFile': 'file1;file2',
'EnableCOMDATFolding': 'false',
'EnableUAC': 'true',
'EntryPointSymbol': 'a string1',
'FixedBaseAddress': 'false',
'ForceFileOutput': 'Enabled',
'ForceSymbolReferences': 'file1;file2',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a string1',
'HeapReserveSize': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'a_file_list',
'ImageHasSafeExceptionHandlers': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': 'false',
'LinkDLL': 'true',
'LinkErrorReporting': 'SendErrorReport',
'LinkStatus': 'true',
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a string1',
'MidlCommandFile': 'a_file_name',
'MinimumRequiredVersion': 'a string1',
'ModuleDefinitionFile': 'a_file_name',
'MSDOSStubFileName': 'a_file_name',
'NoEntryPoint': 'true',
'OptimizeReferences': 'false',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'PreventDllBinding': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SectionAlignment': '33',
'SetChecksum': 'true',
'ShowProgress': 'LinkVerboseREF',
'SpecifySectionAttributes': 'a string1',
'StackCommitSize': 'a string1',
'StackReserveSize': 'a string1',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': 'Console',
'SupportNobindOfDelayLoadedDLL': 'true',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineX86',
'TerminalServerAware': 'false',
'TrackerLogDirectory': 'a_folder',
'TreatLinkerWarningAsErrors': 'true',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': 'AsInvoker',
'UACUIAccess': 'true',
'Version': 'a string1'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'Culture': '0x236',
'IgnoreStandardIncludePath': 'true',
'NullTerminateStrings': 'true',
'PreprocessorDefinitions': 'string1;string2',
'ResourceOutputFileName': 'a string1',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'UndefinePreprocessorDefinitions': 'string1;string2'},
'Midl': {
'AdditionalIncludeDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'ApplicationConfigurationMode': 'true',
'ClientStubFile': 'a_file_name',
'CPreprocessOptions': 'a string1',
'DefaultCharType': 'Signed',
'DllDataFileName': 'a_file_name',
'EnableErrorChecks': 'EnableCustom',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateClientFiles': 'Stub',
'GenerateServerFiles': 'None',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'LocaleID': '33',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a string1',
'PreprocessorDefinitions': 'string1;string2',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'ServerStubFile': 'a_file_name',
'StructMemberAlignment': 'NotSet',
'SuppressCompilerWarnings': 'true',
'SuppressStartupBanner': 'true',
'TargetEnvironment': 'Itanium',
'TrackerLogDirectory': 'a_folder',
'TypeLibFormat': 'NewFormat',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'string1;string2',
'ValidateAllParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '1'},
'Lib': {
'AdditionalDependencies': 'file1;file2',
'AdditionalLibraryDirectories': 'folder1;folder2',
'AdditionalOptions': 'a string1',
'DisplayLibrary': 'a string1',
'ErrorReporting': 'PromptImmediately',
'ExportNamedFunctions': 'string1;string2',
'ForceSymbolReferences': 'a string1',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2',
'LinkTimeCodeGeneration': 'true',
'MinimumRequiredVersion': 'a string1',
'ModuleDefinitionFile': 'a_file_name',
'Name': 'a_file_name',
'OutputFile': 'a_file_name',
'RemoveObjects': 'file1;file2',
'SubSystem': 'Console',
'SuppressStartupBanner': 'true',
'TargetMachine': 'MachineX86i',
'TrackerLogDirectory': 'a_folder',
'TreatLibWarningAsErrors': 'true',
'UseUnicodeResponseFiles': 'true',
'Verbose': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'file1;file2',
'AdditionalOptions': 'a string1',
'AssemblyIdentity': 'a string1',
'ComponentFileName': 'a_file_name',
'EnableDPIAwareness': 'fal',
'GenerateCatalogFiles': 'truel',
'GenerateCategoryTags': 'true',
'InputResourceManifests': 'a string1',
'ManifestFromManagedAssembly': 'a_file_name',
'notgood3': 'bogus',
'OutputManifestFile': 'a_file_name',
'OutputResourceManifests': 'a string1',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressDependencyElement': 'true',
'SuppressStartupBanner': 'true',
'TrackerLogDirectory': 'a_folder',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'VerboseOutput': 'true'},
'ProjectReference': {
'LinkLibraryDependencies': 'true',
'UseLibraryDependencyInputs': 'true'},
'ManifestResourceCompile': {
'ResourceOutputFileName': 'a_file_name'},
'': {
'EmbedManifest': 'true',
'GenerateManifest': 'true',
'IgnoreImportLibrary': 'true',
'LinkIncremental': 'false'}},
self.stderr)
self._ExpectedWarnings([
'Warning: unrecognized setting ClCompile/Enableprefast',
'Warning: unrecognized setting ClCompile/ZZXYZ',
'Warning: unrecognized setting Manifest/notgood3',
'Warning: for Manifest/GenerateCatalogFiles, '
"expected bool; got 'truel'",
'Warning: for Lib/TargetMachine, unrecognized enumerated value '
'MachineX86i',
"Warning: for Manifest/EnableDPIAwareness, expected bool; got 'fal'"])
def testConvertToMSBuildSettings_empty(self):
"""Tests an empty conversion."""
msvs_settings = {}
expected_msbuild_settings = {}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_minimal(self):
"""Tests a minimal conversion."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/foo',
'BasicRuntimeChecks': '0',
},
'VCLinkerTool': {
'LinkTimeCodeGeneration': '1',
'ErrorReporting': '1',
'DataExecutionPrevention': '2',
},
}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/foo',
'BasicRuntimeChecks': 'Default',
},
'Link': {
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'LinkErrorReporting': 'PromptImmediately',
'DataExecutionPrevention': 'true',
},
}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_warnings(self):
"""Tests conversion that generates warnings."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': '1',
'AdditionalOptions': '2',
# These are incorrect values:
'BasicRuntimeChecks': '12',
'BrowseInformation': '21',
'UsePrecompiledHeader': '13',
'GeneratePreprocessedFile': '14'},
'VCLinkerTool': {
# These are incorrect values:
'Driver': '10',
'LinkTimeCodeGeneration': '31',
'ErrorReporting': '21',
'FixedBaseAddress': '6'},
'VCResourceCompilerTool': {
# Custom
'Culture': '1003'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': '1',
'AdditionalOptions': '2'},
'Link': {},
'ResourceCompile': {
# Custom
'Culture': '0x03eb'}}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([
'Warning: while converting VCCLCompilerTool/BasicRuntimeChecks to '
'MSBuild, index value (12) not in expected range [0, 4)',
'Warning: while converting VCCLCompilerTool/BrowseInformation to '
'MSBuild, index value (21) not in expected range [0, 3)',
'Warning: while converting VCCLCompilerTool/UsePrecompiledHeader to '
'MSBuild, index value (13) not in expected range [0, 3)',
'Warning: while converting VCCLCompilerTool/GeneratePreprocessedFile to '
'MSBuild, value must be one of [0, 1, 2]; got 14',
'Warning: while converting VCLinkerTool/Driver to '
'MSBuild, index value (10) not in expected range [0, 4)',
'Warning: while converting VCLinkerTool/LinkTimeCodeGeneration to '
'MSBuild, index value (31) not in expected range [0, 5)',
'Warning: while converting VCLinkerTool/ErrorReporting to '
'MSBuild, index value (21) not in expected range [0, 3)',
'Warning: while converting VCLinkerTool/FixedBaseAddress to '
'MSBuild, index value (6) not in expected range [0, 3)',
])
def testConvertToMSBuildSettings_full_synthetic(self):
"""Tests conversion of all the MSBuild settings."""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'AdditionalUsingDirectories': 'folder1;folder2;folder3',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': '0',
'BasicRuntimeChecks': '1',
'BrowseInformation': '2',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': '0',
'CompileAs': '1',
'DebugInformationFormat': '4',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'd1;d2;d3',
'EnableEnhancedInstructionSet': '0',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'ErrorReporting': '1',
'ExceptionHandling': '2',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '0',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2;file3',
'ForcedUsingFiles': 'file1;file2;file3',
'GeneratePreprocessedFile': '1',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '2',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '3',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderThrough': 'a_file_name',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': '0',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1',
'SuppressStartupBanner': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '1',
'UseUnicodeResponseFiles': 'true',
'WarnAsError': 'true',
'WarningLevel': '2',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name'},
'VCLinkerTool': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3',
'AdditionalManifestDependencies': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AddModuleNamesToAssembly': 'file1;file2;file3',
'AllowIsolation': 'true',
'AssemblyDebug': '0',
'AssemblyLinkResource': 'file1;file2;file3',
'BaseAddress': 'a_string',
'CLRImageType': '1',
'CLRThreadAttribute': '2',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '0',
'DelayLoadDLLs': 'file1;file2;file3',
'DelaySign': 'true',
'Driver': '1',
'EmbedManagedResourceFile': 'file1;file2;file3',
'EnableCOMDATFolding': '0',
'EnableUAC': 'true',
'EntryPointSymbol': 'a_string',
'ErrorReporting': '0',
'FixedBaseAddress': '1',
'ForceSymbolReferences': 'file1;file2;file3',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a_string',
'HeapReserveSize': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'file1;file2;file3',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': '2',
'LinkIncremental': '1',
'LinkLibraryDependencies': 'true',
'LinkTimeCodeGeneration': '2',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a_string',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'OptimizeForWindows98': '1',
'OptimizeReferences': '0',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': '1',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'true',
'ShowProgress': '0',
'StackCommitSize': 'a_string',
'StackReserveSize': 'a_string',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': '2',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '3',
'TerminalServerAware': '2',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': '1',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'false',
'UseUnicodeResponseFiles': 'true',
'Version': 'a_string'},
'VCResourceCompilerTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'Culture': '1003',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'ResourceOutputFileName': 'a_string',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3'},
'VCMIDLTool': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'CPreprocessOptions': 'a_string',
'DefaultCharType': '0',
'DLLDataFileName': 'a_file_name',
'EnableErrorChecks': '2',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a_string',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '3',
'SuppressStartupBanner': 'true',
'TargetEnvironment': '1',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'ValidateParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '4'},
'VCLibrarianTool': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalLibraryDirectories_excluded': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'ExportNamedFunctions': 'd1;d2;d3',
'ForceSymbolReferences': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'LinkLibraryDependencies': 'true',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AssemblyIdentity': 'a_string',
'ComponentFileName': 'a_file_name',
'DependencyInformationFile': 'a_file_name',
'EmbedManifest': 'true',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a_string',
'ManifestResourceFile': 'my_name',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'true',
'VerboseOutput': 'true'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string /J',
'AdditionalUsingDirectories': 'folder1;folder2;folder3',
'AssemblerListingLocation': 'a_file_name',
'AssemblerOutput': 'NoListing',
'BasicRuntimeChecks': 'StackFrameRuntimeCheck',
'BrowseInformation': 'true',
'BrowseInformationFile': 'a_file_name',
'BufferSecurityCheck': 'true',
'CallingConvention': 'Cdecl',
'CompileAs': 'CompileAsC',
'DebugInformationFormat': 'EditAndContinue',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'd1;d2;d3',
'EnableEnhancedInstructionSet': 'NotSet',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'ErrorReporting': 'Prompt',
'ExceptionHandling': 'Async',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Neither',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Strict',
'ForceConformanceInForLoopScope': 'true',
'ForcedIncludeFiles': 'file1;file2;file3',
'ForcedUsingFiles': 'file1;file2;file3',
'FunctionLevelLinking': 'true',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'AnySuitable',
'IntrinsicFunctions': 'true',
'MinimalRebuild': 'true',
'ObjectFileName': 'a_file_name',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Full',
'PrecompiledHeader': 'Create',
'PrecompiledHeaderFile': 'a_file_name',
'PrecompiledHeaderOutputFile': 'a_file_name',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'PreprocessSuppressLineNumbers': 'false',
'PreprocessToFile': 'true',
'ProgramDataBaseFileName': 'a_file_name',
'RuntimeLibrary': 'MultiThreaded',
'RuntimeTypeInfo': 'true',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '1Byte',
'SuppressStartupBanner': 'true',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'true',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'UseFullPaths': 'true',
'WarningLevel': 'Level2',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': 'a_file_name'},
'Link': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalManifestDependencies': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AddModuleNamesToAssembly': 'file1;file2;file3',
'AllowIsolation': 'true',
'AssemblyDebug': '',
'AssemblyLinkResource': 'file1;file2;file3',
'BaseAddress': 'a_string',
'CLRImageType': 'ForceIJWImage',
'CLRThreadAttribute': 'STAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '',
'DelayLoadDLLs': 'file1;file2;file3',
'DelaySign': 'true',
'Driver': 'Driver',
'EmbedManagedResourceFile': 'file1;file2;file3',
'EnableCOMDATFolding': '',
'EnableUAC': 'true',
'EntryPointSymbol': 'a_string',
'FixedBaseAddress': 'false',
'ForceSymbolReferences': 'file1;file2;file3',
'FunctionOrder': 'a_file_name',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': 'a_string',
'HeapReserveSize': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'ImportLibrary': 'a_file_name',
'KeyContainer': 'a_file_name',
'KeyFile': 'a_file_name',
'LargeAddressAware': 'true',
'LinkErrorReporting': 'NoErrorReport',
'LinkTimeCodeGeneration': 'PGInstrument',
'ManifestFile': 'a_file_name',
'MapExports': 'true',
'MapFileName': 'a_file_name',
'MergedIDLBaseFileName': 'a_file_name',
'MergeSections': 'a_string',
'MidlCommandFile': 'a_file_name',
'ModuleDefinitionFile': 'a_file_name',
'NoEntryPoint': 'true',
'OptimizeReferences': '',
'OutputFile': 'a_file_name',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': 'a_file_name',
'ProgramDatabaseFile': 'a_file_name',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SetChecksum': 'true',
'ShowProgress': 'NotSet',
'StackCommitSize': 'a_string',
'StackReserveSize': 'a_string',
'StripPrivateSymbols': 'a_file_name',
'SubSystem': 'Windows',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'true',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineARM',
'TerminalServerAware': 'true',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'a_file_name',
'TypeLibraryResourceID': '33',
'UACExecutionLevel': 'HighestAvailable',
'UACUIAccess': 'true',
'Version': 'a_string'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'Culture': '0x03eb',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': 'd1;d2;d3',
'ResourceOutputFileName': 'a_string',
'ShowProgress': 'true',
'SuppressStartupBanner': 'true',
'UndefinePreprocessorDefinitions': 'd1;d2;d3'},
'Midl': {
'AdditionalIncludeDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'CPreprocessOptions': 'a_string',
'DefaultCharType': 'Unsigned',
'DllDataFileName': 'a_file_name',
'EnableErrorChecks': 'All',
'ErrorCheckAllocations': 'true',
'ErrorCheckBounds': 'true',
'ErrorCheckEnumRange': 'true',
'ErrorCheckRefPointers': 'true',
'ErrorCheckStubData': 'true',
'GenerateStublessProxies': 'true',
'GenerateTypeLibrary': 'true',
'HeaderFileName': 'a_file_name',
'IgnoreStandardIncludePath': 'true',
'InterfaceIdentifierFileName': 'a_file_name',
'MkTypLibCompatible': 'true',
'OutputDirectory': 'a_string',
'PreprocessorDefinitions': 'd1;d2;d3',
'ProxyFileName': 'a_file_name',
'RedirectOutputAndErrors': 'a_file_name',
'StructMemberAlignment': '4',
'SuppressStartupBanner': 'true',
'TargetEnvironment': 'Win32',
'TypeLibraryName': 'a_file_name',
'UndefinePreprocessorDefinitions': 'd1;d2;d3',
'ValidateAllParameters': 'true',
'WarnAsError': 'true',
'WarningLevel': '4'},
'Lib': {
'AdditionalDependencies': 'file1;file2;file3',
'AdditionalLibraryDirectories': 'folder1;folder2;folder3',
'AdditionalOptions': 'a_string',
'ExportNamedFunctions': 'd1;d2;d3',
'ForceSymbolReferences': 'a_string',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreSpecificDefaultLibraries': 'file1;file2;file3',
'ModuleDefinitionFile': 'a_file_name',
'OutputFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'UseUnicodeResponseFiles': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'file1;file2;file3',
'AdditionalOptions': 'a_string',
'AssemblyIdentity': 'a_string',
'ComponentFileName': 'a_file_name',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'a_string',
'OutputManifestFile': 'a_file_name',
'RegistrarScriptFile': 'a_file_name',
'ReplacementsFile': 'a_file_name',
'SuppressStartupBanner': 'true',
'TypeLibraryFile': 'a_file_name',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'a_file_name',
'VerboseOutput': 'true'},
'ManifestResourceCompile': {
'ResourceOutputFileName': 'my_name'},
'ProjectReference': {
'LinkLibraryDependencies': 'true',
'UseLibraryDependencyInputs': 'false'},
'': {
'EmbedManifest': 'true',
'GenerateManifest': 'true',
'IgnoreImportLibrary': 'true',
'LinkIncremental': 'false'}}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
def testConvertToMSBuildSettings_actual(self):
"""Tests the conversion of an actual project.
A VS2008 project with most of the options defined was created through the
VS2008 IDE. It was then converted to VS2010. The tool settings found in
the .vcproj and .vcxproj files were converted to the two dictionaries
msvs_settings and expected_msbuild_settings.
Note that for many settings, the VS2010 converter adds macros like
%(AdditionalIncludeDirectories) to make sure than inherited values are
included. Since the Gyp projects we generate do not use inheritance,
we removed these macros. They were:
ClCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)'
AdditionalOptions: ' %(AdditionalOptions)'
AdditionalUsingDirectories: ';%(AdditionalUsingDirectories)'
DisableSpecificWarnings: ';%(DisableSpecificWarnings)',
ForcedIncludeFiles: ';%(ForcedIncludeFiles)',
ForcedUsingFiles: ';%(ForcedUsingFiles)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
UndefinePreprocessorDefinitions:
';%(UndefinePreprocessorDefinitions)',
Link:
AdditionalDependencies: ';%(AdditionalDependencies)',
AdditionalLibraryDirectories: ';%(AdditionalLibraryDirectories)',
AdditionalManifestDependencies:
';%(AdditionalManifestDependencies)',
AdditionalOptions: ' %(AdditionalOptions)',
AddModuleNamesToAssembly: ';%(AddModuleNamesToAssembly)',
AssemblyLinkResource: ';%(AssemblyLinkResource)',
DelayLoadDLLs: ';%(DelayLoadDLLs)',
EmbedManagedResourceFile: ';%(EmbedManagedResourceFile)',
ForceSymbolReferences: ';%(ForceSymbolReferences)',
IgnoreSpecificDefaultLibraries:
';%(IgnoreSpecificDefaultLibraries)',
ResourceCompile:
AdditionalIncludeDirectories: ';%(AdditionalIncludeDirectories)',
AdditionalOptions: ' %(AdditionalOptions)',
PreprocessorDefinitions: ';%(PreprocessorDefinitions)',
Manifest:
AdditionalManifestFiles: ';%(AdditionalManifestFiles)',
AdditionalOptions: ' %(AdditionalOptions)',
InputResourceManifests: ';%(InputResourceManifests)',
"""
msvs_settings = {
'VCCLCompilerTool': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/more',
'AdditionalUsingDirectories': 'test',
'AssemblerListingLocation': '$(IntDir)\\a',
'AssemblerOutput': '1',
'BasicRuntimeChecks': '3',
'BrowseInformation': '1',
'BrowseInformationFile': '$(IntDir)\\e',
'BufferSecurityCheck': 'false',
'CallingConvention': '1',
'CompileAs': '1',
'DebugInformationFormat': '4',
'DefaultCharIsUnsigned': 'true',
'Detect64BitPortabilityProblems': 'true',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'abc',
'EnableEnhancedInstructionSet': '1',
'EnableFiberSafeOptimizations': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'EnablePREfast': 'true',
'ErrorReporting': '2',
'ExceptionHandling': '2',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': '2',
'FloatingPointExceptions': 'true',
'FloatingPointModel': '1',
'ForceConformanceInForLoopScope': 'false',
'ForcedIncludeFiles': 'def',
'ForcedUsingFiles': 'ge',
'GeneratePreprocessedFile': '2',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': '1',
'KeepComments': 'true',
'MinimalRebuild': 'true',
'ObjectFile': '$(IntDir)\\b',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMP': 'true',
'Optimization': '3',
'PrecompiledHeaderFile': '$(IntDir)\\$(TargetName).pche',
'PrecompiledHeaderThrough': 'StdAfx.hd',
'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE',
'ProgramDataBaseFileName': '$(IntDir)\\vc90b.pdb',
'RuntimeLibrary': '3',
'RuntimeTypeInfo': 'false',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '3',
'SuppressStartupBanner': 'false',
'TreatWChar_tAsBuiltInType': 'false',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'wer',
'UseFullPaths': 'true',
'UsePrecompiledHeader': '0',
'UseUnicodeResponseFiles': 'false',
'WarnAsError': 'true',
'WarningLevel': '3',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': '$(IntDir)\\c'},
'VCLinkerTool': {
'AdditionalDependencies': 'zx',
'AdditionalLibraryDirectories': 'asd',
'AdditionalManifestDependencies': 's2',
'AdditionalOptions': '/mor2',
'AddModuleNamesToAssembly': 'd1',
'AllowIsolation': 'false',
'AssemblyDebug': '1',
'AssemblyLinkResource': 'd5',
'BaseAddress': '23423',
'CLRImageType': '3',
'CLRThreadAttribute': '1',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '0',
'DelayLoadDLLs': 'd4',
'DelaySign': 'true',
'Driver': '2',
'EmbedManagedResourceFile': 'd2',
'EnableCOMDATFolding': '1',
'EnableUAC': 'false',
'EntryPointSymbol': 'f5',
'ErrorReporting': '2',
'FixedBaseAddress': '1',
'ForceSymbolReferences': 'd3',
'FunctionOrder': 'fssdfsd',
'GenerateDebugInformation': 'true',
'GenerateManifest': 'false',
'GenerateMapFile': 'true',
'HeapCommitSize': '13',
'HeapReserveSize': '12',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreDefaultLibraryNames': 'flob;flok',
'IgnoreEmbeddedIDL': 'true',
'IgnoreImportLibrary': 'true',
'ImportLibrary': 'f4',
'KeyContainer': 'f7',
'KeyFile': 'f6',
'LargeAddressAware': '2',
'LinkIncremental': '0',
'LinkLibraryDependencies': 'false',
'LinkTimeCodeGeneration': '1',
'ManifestFile':
'$(IntDir)\\$(TargetFileName).2intermediate.manifest',
'MapExports': 'true',
'MapFileName': 'd5',
'MergedIDLBaseFileName': 'f2',
'MergeSections': 'f5',
'MidlCommandFile': 'f1',
'ModuleDefinitionFile': 'sdsd',
'OptimizeForWindows98': '2',
'OptimizeReferences': '2',
'OutputFile': '$(OutDir)\\$(ProjectName)2.exe',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd',
'ProgramDatabaseFile': 'Flob.pdb',
'RandomizedBaseAddress': '1',
'RegisterOutput': 'true',
'ResourceOnlyDLL': 'true',
'SetChecksum': 'false',
'ShowProgress': '1',
'StackCommitSize': '15',
'StackReserveSize': '14',
'StripPrivateSymbols': 'd3',
'SubSystem': '1',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'false',
'SwapRunFromCD': 'true',
'SwapRunFromNet': 'true',
'TargetMachine': '1',
'TerminalServerAware': '1',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'f3',
'TypeLibraryResourceID': '12',
'UACExecutionLevel': '2',
'UACUIAccess': 'true',
'UseLibraryDependencyInputs': 'true',
'UseUnicodeResponseFiles': 'false',
'Version': '333'},
'VCResourceCompilerTool': {
'AdditionalIncludeDirectories': 'f3',
'AdditionalOptions': '/more3',
'Culture': '3084',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': '_UNICODE;UNICODE2',
'ResourceOutputFileName': '$(IntDir)/$(InputName)3.res',
'ShowProgress': 'true'},
'VCManifestTool': {
'AdditionalManifestFiles': 'sfsdfsd',
'AdditionalOptions': 'afdsdafsd',
'AssemblyIdentity': 'sddfdsadfsa',
'ComponentFileName': 'fsdfds',
'DependencyInformationFile': '$(IntDir)\\mt.depdfd',
'EmbedManifest': 'false',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'asfsfdafs',
'ManifestResourceFile':
'$(IntDir)\\$(TargetFileName).embed.manifest.resfdsf',
'OutputManifestFile': '$(TargetPath).manifestdfs',
'RegistrarScriptFile': 'sdfsfd',
'ReplacementsFile': 'sdffsd',
'SuppressStartupBanner': 'false',
'TypeLibraryFile': 'sfsd',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'sfsd',
'UseFAT32Workaround': 'true',
'UseUnicodeResponseFiles': 'false',
'VerboseOutput': 'true'}}
expected_msbuild_settings = {
'ClCompile': {
'AdditionalIncludeDirectories': 'dir1',
'AdditionalOptions': '/more /J',
'AdditionalUsingDirectories': 'test',
'AssemblerListingLocation': '$(IntDir)a',
'AssemblerOutput': 'AssemblyCode',
'BasicRuntimeChecks': 'EnableFastChecks',
'BrowseInformation': 'true',
'BrowseInformationFile': '$(IntDir)e',
'BufferSecurityCheck': 'false',
'CallingConvention': 'FastCall',
'CompileAs': 'CompileAsC',
'DebugInformationFormat': 'EditAndContinue',
'DisableLanguageExtensions': 'true',
'DisableSpecificWarnings': 'abc',
'EnableEnhancedInstructionSet': 'StreamingSIMDExtensions',
'EnableFiberSafeOptimizations': 'true',
'EnablePREfast': 'true',
'ErrorReporting': 'Queue',
'ExceptionHandling': 'Async',
'ExpandAttributedSource': 'true',
'FavorSizeOrSpeed': 'Size',
'FloatingPointExceptions': 'true',
'FloatingPointModel': 'Strict',
'ForceConformanceInForLoopScope': 'false',
'ForcedIncludeFiles': 'def',
'ForcedUsingFiles': 'ge',
'FunctionLevelLinking': 'true',
'GenerateXMLDocumentationFiles': 'true',
'IgnoreStandardIncludePath': 'true',
'InlineFunctionExpansion': 'OnlyExplicitInline',
'IntrinsicFunctions': 'true',
'MinimalRebuild': 'true',
'ObjectFileName': '$(IntDir)b',
'OmitDefaultLibName': 'true',
'OmitFramePointers': 'true',
'OpenMPSupport': 'true',
'Optimization': 'Full',
'PrecompiledHeader': 'NotUsing', # Actual conversion gives ''
'PrecompiledHeaderFile': 'StdAfx.hd',
'PrecompiledHeaderOutputFile': '$(IntDir)$(TargetName).pche',
'PreprocessKeepComments': 'true',
'PreprocessorDefinitions': 'WIN32;_DEBUG;_CONSOLE',
'PreprocessSuppressLineNumbers': 'true',
'PreprocessToFile': 'true',
'ProgramDataBaseFileName': '$(IntDir)vc90b.pdb',
'RuntimeLibrary': 'MultiThreadedDebugDLL',
'RuntimeTypeInfo': 'false',
'ShowIncludes': 'true',
'SmallerTypeCheck': 'true',
'StringPooling': 'true',
'StructMemberAlignment': '4Bytes',
'SuppressStartupBanner': 'false',
'TreatWarningAsError': 'true',
'TreatWChar_tAsBuiltInType': 'false',
'UndefineAllPreprocessorDefinitions': 'true',
'UndefinePreprocessorDefinitions': 'wer',
'UseFullPaths': 'true',
'WarningLevel': 'Level3',
'WholeProgramOptimization': 'true',
'XMLDocumentationFileName': '$(IntDir)c'},
'Link': {
'AdditionalDependencies': 'zx',
'AdditionalLibraryDirectories': 'asd',
'AdditionalManifestDependencies': 's2',
'AdditionalOptions': '/mor2',
'AddModuleNamesToAssembly': 'd1',
'AllowIsolation': 'false',
'AssemblyDebug': 'true',
'AssemblyLinkResource': 'd5',
'BaseAddress': '23423',
'CLRImageType': 'ForceSafeILImage',
'CLRThreadAttribute': 'MTAThreadingAttribute',
'CLRUnmanagedCodeCheck': 'true',
'DataExecutionPrevention': '',
'DelayLoadDLLs': 'd4',
'DelaySign': 'true',
'Driver': 'UpOnly',
'EmbedManagedResourceFile': 'd2',
'EnableCOMDATFolding': 'false',
'EnableUAC': 'false',
'EntryPointSymbol': 'f5',
'FixedBaseAddress': 'false',
'ForceSymbolReferences': 'd3',
'FunctionOrder': 'fssdfsd',
'GenerateDebugInformation': 'true',
'GenerateMapFile': 'true',
'HeapCommitSize': '13',
'HeapReserveSize': '12',
'IgnoreAllDefaultLibraries': 'true',
'IgnoreEmbeddedIDL': 'true',
'IgnoreSpecificDefaultLibraries': 'flob;flok',
'ImportLibrary': 'f4',
'KeyContainer': 'f7',
'KeyFile': 'f6',
'LargeAddressAware': 'true',
'LinkErrorReporting': 'QueueForNextLogin',
'LinkTimeCodeGeneration': 'UseLinkTimeCodeGeneration',
'ManifestFile': '$(IntDir)$(TargetFileName).2intermediate.manifest',
'MapExports': 'true',
'MapFileName': 'd5',
'MergedIDLBaseFileName': 'f2',
'MergeSections': 'f5',
'MidlCommandFile': 'f1',
'ModuleDefinitionFile': 'sdsd',
'NoEntryPoint': 'true',
'OptimizeReferences': 'true',
'OutputFile': '$(OutDir)$(ProjectName)2.exe',
'PerUserRedirection': 'true',
'Profile': 'true',
'ProfileGuidedDatabase': '$(TargetDir)$(TargetName).pgdd',
'ProgramDatabaseFile': 'Flob.pdb',
'RandomizedBaseAddress': 'false',
'RegisterOutput': 'true',
'SetChecksum': 'false',
'ShowProgress': 'LinkVerbose',
'StackCommitSize': '15',
'StackReserveSize': '14',
'StripPrivateSymbols': 'd3',
'SubSystem': 'Console',
'SupportUnloadOfDelayLoadedDLL': 'true',
'SuppressStartupBanner': 'false',
'SwapRunFromCD': 'true',
'SwapRunFromNET': 'true',
'TargetMachine': 'MachineX86',
'TerminalServerAware': 'false',
'TurnOffAssemblyGeneration': 'true',
'TypeLibraryFile': 'f3',
'TypeLibraryResourceID': '12',
'UACExecutionLevel': 'RequireAdministrator',
'UACUIAccess': 'true',
'Version': '333'},
'ResourceCompile': {
'AdditionalIncludeDirectories': 'f3',
'AdditionalOptions': '/more3',
'Culture': '0x0c0c',
'IgnoreStandardIncludePath': 'true',
'PreprocessorDefinitions': '_UNICODE;UNICODE2',
'ResourceOutputFileName': '$(IntDir)%(Filename)3.res',
'ShowProgress': 'true'},
'Manifest': {
'AdditionalManifestFiles': 'sfsdfsd',
'AdditionalOptions': 'afdsdafsd',
'AssemblyIdentity': 'sddfdsadfsa',
'ComponentFileName': 'fsdfds',
'GenerateCatalogFiles': 'true',
'InputResourceManifests': 'asfsfdafs',
'OutputManifestFile': '$(TargetPath).manifestdfs',
'RegistrarScriptFile': 'sdfsfd',
'ReplacementsFile': 'sdffsd',
'SuppressStartupBanner': 'false',
'TypeLibraryFile': 'sfsd',
'UpdateFileHashes': 'true',
'UpdateFileHashesSearchPath': 'sfsd',
'VerboseOutput': 'true'},
'ProjectReference': {
'LinkLibraryDependencies': 'false',
'UseLibraryDependencyInputs': 'true'},
'': {
'EmbedManifest': 'false',
'GenerateManifest': 'false',
'IgnoreImportLibrary': 'true',
'LinkIncremental': ''
},
'ManifestResourceCompile': {
'ResourceOutputFileName':
'$(IntDir)$(TargetFileName).embed.manifest.resfdsf'}
}
actual_msbuild_settings = MSVSSettings.ConvertToMSBuildSettings(
msvs_settings,
self.stderr)
self.assertEqual(expected_msbuild_settings, actual_msbuild_settings)
self._ExpectedWarnings([])
if __name__ == '__main__':
unittest.main()
| mit |
RichDijk/eXe | twisted/spread/refpath.py | 20 | 2880 | # Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
__version__ = "$Revision: 1.17 $"[11:-2]
"""
Path-based references for PB, and other reference-based protocols.
Maintainer: U{Glyph Lefkowitz<mailto:glyph@twistedmatrix.com>}
Stability: semi-stable
Future Plans: None at this point besides a final overview and finalization
pass.
"""
from twisted.python import log
from flavors import Referenceable, Viewable
from copy import copy
import os
### "Server"-side objects
class PathReferenceContext:
def __init__(self, path, root):
self.metadata = {}
self.path = path
self.root = root
def __setitem__(self, key, item):
self.metadata[key] = item
def __getitem__(self, key):
return self.metadata[key]
def getObject(self):
o = self.root
for p in self.path:
o = o.getChild(p, self)
return o
class PathReference:
def __init__(self):
self.children = {}
def getChild(self, child, ctx):
return self.children[child]
class PathReferenceDirectory(Referenceable):
def __init__(self, root, prefix="remote"):
self.root = root
self.prefix = prefix
def remote_callPath(self, path, name, *args, **kw):
ctx = PathReferenceContext(path, self)
obj = ctx.getObject()
return apply(getattr(obj, "%s_%s" % (self.prefix, name)), args, kw)
class PathReferenceContextDirectory(Referenceable):
def __init__(self, root, prefix="remote"):
self.root = root
self.prefix = prefix
def remote_callPath(self, path, name, *args, **kw):
ctx = PathReferenceContext(path, self)
obj = ctx.getObject()
return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
(ctx,)+args, kw)
class PathViewDirectory(Viewable):
def __init__(self, root, prefix="view"):
self.root = root
self.prefix = prefix
def view_callPath(self, perspective, path, name, *args, **kw):
ctx = PathReferenceContext(path, self)
obj = ctx.getObject()
return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
(perspective,)+args, kw)
class PathViewContextDirectory(Viewable):
def __init__(self, root, prefix="view"):
self.root = root
self.prefix = prefix
def view_callPath(self, perspective, path, name, *args, **kw):
ctx = PathReferenceContext(path, self)
obj = ctx.getObject()
return apply(getattr(obj, "%s_%s" % (self.prefix, name)),
(perspective,ctx)+args, kw)
### "Client"-side objects
class RemotePathReference:
def __init__(self, ref, path):
self.ref = ref
self.path = path
def callRemote(self, name, *args, **kw):
apply(self.ref.callRemote,
("callPath", self.path, name)+args, kw)
| gpl-2.0 |
badbear1727/E120LKERNEL | tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py | 12980 | 5411 | # SchedGui.py - Python extension for perf script, basic GUI code for
# traces drawing and overview.
#
# Copyright (C) 2010 by Frederic Weisbecker <fweisbec@gmail.com>
#
# This software is distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
try:
import wx
except ImportError:
raise ImportError, "You need to install the wxpython lib for this script"
class RootFrame(wx.Frame):
Y_OFFSET = 100
RECT_HEIGHT = 100
RECT_SPACE = 50
EVENT_MARKING_WIDTH = 5
def __init__(self, sched_tracer, title, parent = None, id = -1):
wx.Frame.__init__(self, parent, id, title)
(self.screen_width, self.screen_height) = wx.GetDisplaySize()
self.screen_width -= 10
self.screen_height -= 10
self.zoom = 0.5
self.scroll_scale = 20
self.sched_tracer = sched_tracer
self.sched_tracer.set_root_win(self)
(self.ts_start, self.ts_end) = sched_tracer.interval()
self.update_width_virtual()
self.nr_rects = sched_tracer.nr_rectangles() + 1
self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE))
# whole window panel
self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height))
# scrollable container
self.scroll = wx.ScrolledWindow(self.panel)
self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale)
self.scroll.EnableScrolling(True, True)
self.scroll.SetFocus()
# scrollable drawing area
self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2))
self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint)
self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
self.scroll.Bind(wx.EVT_PAINT, self.on_paint)
self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
self.scroll.Fit()
self.Fit()
self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING)
self.txt = None
self.Show(True)
def us_to_px(self, val):
return val / (10 ** 3) * self.zoom
def px_to_us(self, val):
return (val / self.zoom) * (10 ** 3)
def scroll_start(self):
(x, y) = self.scroll.GetViewStart()
return (x * self.scroll_scale, y * self.scroll_scale)
def scroll_start_us(self):
(x, y) = self.scroll_start()
return self.px_to_us(x)
def paint_rectangle_zone(self, nr, color, top_color, start, end):
offset_px = self.us_to_px(start - self.ts_start)
width_px = self.us_to_px(end - self.ts_start)
offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE))
width_py = RootFrame.RECT_HEIGHT
dc = self.dc
if top_color is not None:
(r, g, b) = top_color
top_color = wx.Colour(r, g, b)
brush = wx.Brush(top_color, wx.SOLID)
dc.SetBrush(brush)
dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH)
width_py -= RootFrame.EVENT_MARKING_WIDTH
offset_py += RootFrame.EVENT_MARKING_WIDTH
(r ,g, b) = color
color = wx.Colour(r, g, b)
brush = wx.Brush(color, wx.SOLID)
dc.SetBrush(brush)
dc.DrawRectangle(offset_px, offset_py, width_px, width_py)
def update_rectangles(self, dc, start, end):
start += self.ts_start
end += self.ts_start
self.sched_tracer.fill_zone(start, end)
def on_paint(self, event):
dc = wx.PaintDC(self.scroll_panel)
self.dc = dc
width = min(self.width_virtual, self.screen_width)
(x, y) = self.scroll_start()
start = self.px_to_us(x)
end = self.px_to_us(x + width)
self.update_rectangles(dc, start, end)
def rect_from_ypixel(self, y):
y -= RootFrame.Y_OFFSET
rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)
height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)
if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT:
return -1
return rect
def update_summary(self, txt):
if self.txt:
self.txt.Destroy()
self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50))
def on_mouse_down(self, event):
(x, y) = event.GetPositionTuple()
rect = self.rect_from_ypixel(y)
if rect == -1:
return
t = self.px_to_us(x) + self.ts_start
self.sched_tracer.mouse_down(rect, t)
def update_width_virtual(self):
self.width_virtual = self.us_to_px(self.ts_end - self.ts_start)
def __zoom(self, x):
self.update_width_virtual()
(xpos, ypos) = self.scroll.GetViewStart()
xpos = self.us_to_px(x) / self.scroll_scale
self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos)
self.Refresh()
def zoom_in(self):
x = self.scroll_start_us()
self.zoom *= 2
self.__zoom(x)
def zoom_out(self):
x = self.scroll_start_us()
self.zoom /= 2
self.__zoom(x)
def on_key_press(self, event):
key = event.GetRawKeyCode()
if key == ord("+"):
self.zoom_in()
return
if key == ord("-"):
self.zoom_out()
return
key = event.GetKeyCode()
(x, y) = self.scroll.GetViewStart()
if key == wx.WXK_RIGHT:
self.scroll.Scroll(x + 1, y)
elif key == wx.WXK_LEFT:
self.scroll.Scroll(x - 1, y)
elif key == wx.WXK_DOWN:
self.scroll.Scroll(x, y + 1)
elif key == wx.WXK_UP:
self.scroll.Scroll(x, y - 1)
| gpl-2.0 |
elkingtonmcb/django | tests/template_tests/filter_tests/test_urlize.py | 109 | 14303 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.template.defaultfilters import urlize
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class UrlizeTests(SimpleTestCase):
@setup({'urlize01': '{% autoescape off %}{{ a|urlize }} {{ b|urlize }}{% endautoescape %}'})
def test_urlize01(self):
output = self.engine.render_to_string(
'urlize01',
{'a': 'http://example.com/?x=&y=', 'b': mark_safe('http://example.com?x=&y=<2>')},
)
self.assertEqual(
output,
'<a href="http://example.com/?x=&y=" rel="nofollow">http://example.com/?x=&y=</a> '
'<a href="http://example.com?x=&y=%3C2%3E" rel="nofollow">http://example.com?x=&y=<2></a>'
)
@setup({'urlize02': '{{ a|urlize }} {{ b|urlize }}'})
def test_urlize02(self):
output = self.engine.render_to_string(
'urlize02',
{'a': "http://example.com/?x=&y=", 'b': mark_safe("http://example.com?x=&y=")},
)
self.assertEqual(
output,
'<a href="http://example.com/?x=&y=" rel="nofollow">http://example.com/?x=&y=</a> '
'<a href="http://example.com?x=&y=" rel="nofollow">http://example.com?x=&y=</a>'
)
@setup({'urlize03': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'})
def test_urlize03(self):
output = self.engine.render_to_string('urlize03', {'a': mark_safe("a & b")})
self.assertEqual(output, 'a & b')
@setup({'urlize04': '{{ a|urlize }}'})
def test_urlize04(self):
output = self.engine.render_to_string('urlize04', {'a': mark_safe("a & b")})
self.assertEqual(output, 'a & b')
# This will lead to a nonsense result, but at least it won't be
# exploitable for XSS purposes when auto-escaping is on.
@setup({'urlize05': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'})
def test_urlize05(self):
output = self.engine.render_to_string('urlize05', {'a': "<script>alert('foo')</script>"})
self.assertEqual(output, "<script>alert('foo')</script>")
@setup({'urlize06': '{{ a|urlize }}'})
def test_urlize06(self):
output = self.engine.render_to_string('urlize06', {'a': "<script>alert('foo')</script>"})
self.assertEqual(output, '<script>alert('foo')</script>')
# mailto: testing for urlize
@setup({'urlize07': '{{ a|urlize }}'})
def test_urlize07(self):
output = self.engine.render_to_string('urlize07', {'a': "Email me at me@example.com"})
self.assertEqual(
output,
'Email me at <a href="mailto:me@example.com">me@example.com</a>',
)
@setup({'urlize08': '{{ a|urlize }}'})
def test_urlize08(self):
output = self.engine.render_to_string('urlize08', {'a': "Email me at <me@example.com>"})
self.assertEqual(
output,
'Email me at <<a href="mailto:me@example.com">me@example.com</a>>',
)
@setup({'urlize09': '{% autoescape off %}{{ a|urlize }}{% endautoescape %}'})
def test_urlize09(self):
output = self.engine.render_to_string('urlize09', {'a': "http://example.com/?x=&y=<2>"})
self.assertEqual(
output,
'<a href="http://example.com/?x=&y=%3C2%3E" rel="nofollow">http://example.com/?x=&y=<2></a>',
)
class FunctionTests(SimpleTestCase):
def test_urls(self):
self.assertEqual(
urlize('http://google.com'),
'<a href="http://google.com" rel="nofollow">http://google.com</a>',
)
self.assertEqual(
urlize('http://google.com/'),
'<a href="http://google.com/" rel="nofollow">http://google.com/</a>',
)
self.assertEqual(
urlize('www.google.com'),
'<a href="http://www.google.com" rel="nofollow">www.google.com</a>',
)
self.assertEqual(
urlize('djangoproject.org'),
'<a href="http://djangoproject.org" rel="nofollow">djangoproject.org</a>',
)
self.assertEqual(
urlize('djangoproject.org/'),
'<a href="http://djangoproject.org/" rel="nofollow">djangoproject.org/</a>',
)
def test_url_split_chars(self):
# Quotes (single and double) and angle brackets shouldn't be considered
# part of URLs.
self.assertEqual(
urlize('www.server.com"abc'),
'<a href="http://www.server.com" rel="nofollow">www.server.com</a>"abc',
)
self.assertEqual(
urlize('www.server.com\'abc'),
'<a href="http://www.server.com" rel="nofollow">www.server.com</a>'abc',
)
self.assertEqual(
urlize('www.server.com<abc'),
'<a href="http://www.server.com" rel="nofollow">www.server.com</a><abc',
)
self.assertEqual(
urlize('www.server.com>abc'),
'<a href="http://www.server.com" rel="nofollow">www.server.com</a>>abc',
)
def test_email(self):
self.assertEqual(
urlize('info@djangoproject.org'),
'<a href="mailto:info@djangoproject.org">info@djangoproject.org</a>',
)
def test_word_with_dot(self):
self.assertEqual(urlize('some.organization'), 'some.organization'),
def test_https(self):
self.assertEqual(
urlize('https://google.com'),
'<a href="https://google.com" rel="nofollow">https://google.com</a>',
)
def test_quoting(self):
"""
#9655 - Check urlize doesn't overquote already quoted urls. The
teststring is the urlquoted version of 'http://hi.baidu.com/重新开始'
"""
self.assertEqual(
urlize('http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B'),
'<a href="http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B" rel="nofollow">'
'http://hi.baidu.com/%E9%87%8D%E6%96%B0%E5%BC%80%E5%A7%8B</a>',
)
def test_urlencoded(self):
self.assertEqual(
urlize('www.mystore.com/30%OffCoupons!'),
'<a href="http://www.mystore.com/30%25OffCoupons" rel="nofollow">'
'www.mystore.com/30%OffCoupons</a>!',
)
self.assertEqual(
urlize('https://en.wikipedia.org/wiki/Caf%C3%A9'),
'<a href="https://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">'
'https://en.wikipedia.org/wiki/Caf%C3%A9</a>',
)
def test_unicode(self):
self.assertEqual(
urlize('https://en.wikipedia.org/wiki/Café'),
'<a href="https://en.wikipedia.org/wiki/Caf%C3%A9" rel="nofollow">'
'https://en.wikipedia.org/wiki/Café</a>',
)
def test_parenthesis(self):
"""
#11911 - Check urlize keeps balanced parentheses
"""
self.assertEqual(
urlize('https://en.wikipedia.org/wiki/Django_(web_framework)'),
'<a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
'https://en.wikipedia.org/wiki/Django_(web_framework)</a>',
)
self.assertEqual(
urlize('(see https://en.wikipedia.org/wiki/Django_(web_framework))'),
'(see <a href="https://en.wikipedia.org/wiki/Django_(web_framework)" rel="nofollow">'
'https://en.wikipedia.org/wiki/Django_(web_framework)</a>)',
)
def test_nofollow(self):
"""
#12183 - Check urlize adds nofollow properly - see #12183
"""
self.assertEqual(
urlize('foo@bar.com or www.bar.com'),
'<a href="mailto:foo@bar.com">foo@bar.com</a> or '
'<a href="http://www.bar.com" rel="nofollow">www.bar.com</a>',
)
def test_idn(self):
"""
#13704 - Check urlize handles IDN correctly
"""
self.assertEqual(urlize('http://c✶.ws'), '<a href="http://xn--c-lgq.ws" rel="nofollow">http://c✶.ws</a>')
self.assertEqual(urlize('www.c✶.ws'), '<a href="http://www.xn--c-lgq.ws" rel="nofollow">www.c✶.ws</a>')
self.assertEqual(urlize('c✶.org'), '<a href="http://xn--c-lgq.org" rel="nofollow">c✶.org</a>')
self.assertEqual(urlize('info@c✶.org'), '<a href="mailto:info@xn--c-lgq.org">info@c✶.org</a>')
def test_malformed(self):
"""
#16395 - Check urlize doesn't highlight malformed URIs
"""
self.assertEqual(urlize('http:///www.google.com'), 'http:///www.google.com')
self.assertEqual(urlize('http://.google.com'), 'http://.google.com')
self.assertEqual(urlize('http://@foo.com'), 'http://@foo.com')
def test_tlds(self):
"""
#16656 - Check urlize accepts more TLDs
"""
self.assertEqual(urlize('usa.gov'), '<a href="http://usa.gov" rel="nofollow">usa.gov</a>')
def test_invalid_email(self):
"""
#17592 - Check urlize don't crash on invalid email with dot-starting
domain
"""
self.assertEqual(urlize('email@.stream.ru'), 'email@.stream.ru')
def test_uppercase(self):
"""
#18071 - Check urlize accepts uppercased URL schemes
"""
self.assertEqual(
urlize('HTTPS://github.com/'),
'<a href="https://github.com/" rel="nofollow">HTTPS://github.com/</a>',
)
def test_trailing_period(self):
"""
#18644 - Check urlize trims trailing period when followed by parenthesis
"""
self.assertEqual(
urlize('(Go to http://www.example.com/foo.)'),
'(Go to <a href="http://www.example.com/foo" rel="nofollow">http://www.example.com/foo</a>.)',
)
def test_brackets(self):
"""
#19070 - Check urlize handles brackets properly
"""
self.assertEqual(
urlize('[see www.example.com]'),
'[see <a href="http://www.example.com" rel="nofollow">www.example.com</a>]',
)
self.assertEqual(
urlize('see test[at[example.com'),
'see <a href="http://test[at[example.com" rel="nofollow">test[at[example.com</a>',
)
self.assertEqual(
urlize('[http://168.192.0.1](http://168.192.0.1)'),
'[<a href="http://168.192.0.1](http://168.192.0.1)" rel="nofollow">'
'http://168.192.0.1](http://168.192.0.1)</a>',
)
def test_ipv4(self):
self.assertEqual(
urlize('http://192.168.0.15/api/9'),
'<a href="http://192.168.0.15/api/9" rel="nofollow">http://192.168.0.15/api/9</a>',
)
def test_ipv6(self):
self.assertEqual(
urlize('http://[2001:db8:cafe::2]/api/9'),
'<a href="http://[2001:db8:cafe::2]/api/9" rel="nofollow">http://[2001:db8:cafe::2]/api/9</a>',
)
def test_quotation_marks(self):
"""
#20364 - Check urlize correctly include quotation marks in links
"""
self.assertEqual(
urlize('before "hi@example.com" afterwards', autoescape=False),
'before "<a href="mailto:hi@example.com">hi@example.com</a>" afterwards',
)
self.assertEqual(
urlize('before hi@example.com" afterwards', autoescape=False),
'before <a href="mailto:hi@example.com">hi@example.com</a>" afterwards',
)
self.assertEqual(
urlize('before "hi@example.com afterwards', autoescape=False),
'before "<a href="mailto:hi@example.com">hi@example.com</a> afterwards',
)
self.assertEqual(
urlize('before \'hi@example.com\' afterwards', autoescape=False),
'before \'<a href="mailto:hi@example.com">hi@example.com</a>\' afterwards',
)
self.assertEqual(
urlize('before hi@example.com\' afterwards', autoescape=False),
'before <a href="mailto:hi@example.com">hi@example.com</a>\' afterwards',
)
self.assertEqual(
urlize('before \'hi@example.com afterwards', autoescape=False),
'before \'<a href="mailto:hi@example.com">hi@example.com</a> afterwards',
)
def test_quote_commas(self):
"""
#20364 - Check urlize copes with commas following URLs in quotes
"""
self.assertEqual(
urlize('Email us at "hi@example.com", or phone us at +xx.yy', autoescape=False),
'Email us at "<a href="mailto:hi@example.com">hi@example.com</a>", or phone us at +xx.yy',
)
def test_exclamation_marks(self):
"""
#23715 - Check urlize correctly handles exclamation marks after TLDs
or query string
"""
self.assertEqual(
urlize('Go to djangoproject.com! and enjoy.'),
'Go to <a href="http://djangoproject.com" rel="nofollow">djangoproject.com</a>! and enjoy.',
)
self.assertEqual(
urlize('Search for google.com/?q=! and see.'),
'Search for <a href="http://google.com/?q=" rel="nofollow">google.com/?q=</a>! and see.',
)
self.assertEqual(
urlize('Search for google.com/?q=dj!`? and see.'),
'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a> and see.',
)
self.assertEqual(
urlize('Search for google.com/?q=dj!`?! and see.'),
'Search for <a href="http://google.com/?q=dj%21%60%3F" rel="nofollow">google.com/?q=dj!`?</a>! and see.',
)
def test_non_string_input(self):
self.assertEqual(urlize(123), '123')
def test_autoescape(self):
self.assertEqual(
urlize('foo<a href=" google.com ">bar</a>buz'),
'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz'
)
def test_autoescape_off(self):
self.assertEqual(
urlize('foo<a href=" google.com ">bar</a>buz', autoescape=False),
'foo<a href=" <a href="http://google.com" rel="nofollow">google.com</a> ">bar</a>buz',
)
| bsd-3-clause |
jhseu/tensorflow | tensorflow/lite/python/tflite_convert_test.py | 4 | 14396 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tflite_convert.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
from tensorflow.lite.python import tflite_convert
from tensorflow.python import keras
from tensorflow.python import tf2
from tensorflow.python.client import session
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.platform import gfile
from tensorflow.python.platform import resource_loader
from tensorflow.python.platform import test
from tensorflow.python.saved_model import saved_model
from tensorflow.python.saved_model.save import save
from tensorflow.python.training.tracking import tracking
from tensorflow.python.training.training_util import write_graph
class TestModels(test_util.TensorFlowTestCase):
def _getFilepath(self, filename):
return os.path.join(self.get_temp_dir(), filename)
def _run(self, flags_str, should_succeed):
output_file = os.path.join(self.get_temp_dir(), 'model.tflite')
tflite_bin = resource_loader.get_path_to_datafile('tflite_convert')
cmdline = '{0} --output_file={1} {2}'.format(tflite_bin, output_file,
flags_str)
exitcode = os.system(cmdline)
if exitcode == 0:
with gfile.Open(output_file, 'rb') as model_file:
content = model_file.read()
self.assertEqual(content is not None, should_succeed)
os.remove(output_file)
else:
self.assertFalse(should_succeed)
def _getKerasModelFile(self):
x = np.array([[1.], [2.]])
y = np.array([[2.], [4.]])
model = keras.models.Sequential([
keras.layers.Dropout(0.2, input_shape=(1,)),
keras.layers.Dense(1),
])
model.compile(optimizer='sgd', loss='mean_squared_error')
model.fit(x, y, epochs=1)
keras_file = self._getFilepath('model.h5')
keras.models.save_model(model, keras_file)
return keras_file
class TfLiteConvertV1Test(TestModels):
def _run(self, flags_str, should_succeed):
if tf2.enabled():
flags_str += ' --enable_v1_converter'
super(TfLiteConvertV1Test, self)._run(flags_str, should_succeed)
def testFrozenGraphDef(self):
with ops.Graph().as_default():
in_tensor = array_ops.placeholder(
shape=[1, 16, 16, 3], dtype=dtypes.float32)
_ = in_tensor + in_tensor
sess = session.Session()
# Write graph to file.
graph_def_file = self._getFilepath('model.pb')
write_graph(sess.graph_def, '', graph_def_file, False)
sess.close()
flags_str = ('--graph_def_file={0} --input_arrays={1} '
'--output_arrays={2}'.format(graph_def_file,
'Placeholder', 'add'))
self._run(flags_str, should_succeed=True)
os.remove(graph_def_file)
# Run `tflite_convert` explicitly with the legacy converter.
# Before the new converter is enabled by default, this flag has no real
# effects.
def testFrozenGraphDefWithLegacyConverter(self):
with ops.Graph().as_default():
in_tensor = array_ops.placeholder(
shape=[1, 16, 16, 3], dtype=dtypes.float32)
_ = in_tensor + in_tensor
sess = session.Session()
# Write graph to file.
graph_def_file = self._getFilepath('model.pb')
write_graph(sess.graph_def, '', graph_def_file, False)
sess.close()
flags_str = (
'--graph_def_file={0} --input_arrays={1} '
'--output_arrays={2} --experimental_new_converter=false'.format(
graph_def_file, 'Placeholder', 'add'))
self._run(flags_str, should_succeed=True)
os.remove(graph_def_file)
def testFrozenGraphDefNonPlaceholder(self):
with ops.Graph().as_default():
in_tensor = random_ops.random_normal(shape=[1, 16, 16, 3], name='random')
_ = in_tensor + in_tensor
sess = session.Session()
# Write graph to file.
graph_def_file = self._getFilepath('model.pb')
write_graph(sess.graph_def, '', graph_def_file, False)
sess.close()
flags_str = ('--graph_def_file={0} --input_arrays={1} '
'--output_arrays={2}'.format(graph_def_file,
'random', 'add'))
self._run(flags_str, should_succeed=True)
os.remove(graph_def_file)
def testSavedModel(self):
saved_model_dir = self._getFilepath('model')
with ops.Graph().as_default():
with session.Session() as sess:
in_tensor = array_ops.placeholder(
shape=[1, 16, 16, 3], dtype=dtypes.float32, name='inputB')
out_tensor = in_tensor + in_tensor
inputs = {'x': in_tensor}
outputs = {'z': out_tensor}
saved_model.simple_save(sess, saved_model_dir, inputs, outputs)
flags_str = '--saved_model_dir={}'.format(saved_model_dir)
self._run(flags_str, should_succeed=True)
def testKerasFile(self):
keras_file = self._getKerasModelFile()
flags_str = '--keras_model_file={}'.format(keras_file)
self._run(flags_str, should_succeed=True)
os.remove(keras_file)
def testKerasFileMLIR(self):
keras_file = self._getKerasModelFile()
flags_str = ('--keras_model_file={} --experimental_new_converter'
.format(keras_file))
self._run(flags_str, should_succeed=True)
os.remove(keras_file)
def testConversionSummary(self):
keras_file = self._getKerasModelFile()
log_dir = self.get_temp_dir()
flags_str = ('--keras_model_file={} --experimental_new_converter '
'--conversion_summary_dir={}'.format(keras_file, log_dir))
self._run(flags_str, should_succeed=True)
os.remove(keras_file)
num_items_conversion_summary = len(os.listdir(log_dir))
self.assertTrue(num_items_conversion_summary)
def testConversionSummaryWithOldConverter(self):
keras_file = self._getKerasModelFile()
log_dir = self.get_temp_dir()
flags_str = ('--keras_model_file={} --experimental_new_converter=false '
'--conversion_summary_dir={}'.format(keras_file, log_dir))
self._run(flags_str, should_succeed=True)
os.remove(keras_file)
num_items_conversion_summary = len(os.listdir(log_dir))
self.assertEqual(num_items_conversion_summary, 0)
def _initObjectDetectionArgs(self):
# Initializes the arguments required for the object detection model.
# Looks for the model file which is saved in a different location internally
# and externally.
filename = resource_loader.get_path_to_datafile('testdata/tflite_graph.pb')
if not os.path.exists(filename):
filename = os.path.join(
resource_loader.get_root_dir_with_all_resources(),
'../tflite_mobilenet_ssd_quant_protobuf/tflite_graph.pb')
if not os.path.exists(filename):
raise IOError("File '{0}' does not exist.".format(filename))
self._graph_def_file = filename
self._input_arrays = 'normalized_input_image_tensor'
self._output_arrays = (
'TFLite_Detection_PostProcess,TFLite_Detection_PostProcess:1,'
'TFLite_Detection_PostProcess:2,TFLite_Detection_PostProcess:3')
self._input_shapes = '1,300,300,3'
def testObjectDetection(self):
"""Tests object detection model through TOCO."""
self._initObjectDetectionArgs()
flags_str = ('--graph_def_file={0} --input_arrays={1} '
'--output_arrays={2} --input_shapes={3} '
'--allow_custom_ops'.format(self._graph_def_file,
self._input_arrays,
self._output_arrays,
self._input_shapes))
self._run(flags_str, should_succeed=True)
def testObjectDetectionMLIR(self):
"""Tests object detection model through MLIR converter."""
self._initObjectDetectionArgs()
custom_opdefs_str = (
'name: \'TFLite_Detection_PostProcess\' '
'input_arg: { name: \'raw_outputs/box_encodings\' type: DT_FLOAT } '
'input_arg: { name: \'raw_outputs/class_predictions\' type: DT_FLOAT } '
'input_arg: { name: \'anchors\' type: DT_FLOAT } '
'output_arg: { name: \'TFLite_Detection_PostProcess\' type: DT_FLOAT } '
'output_arg: { name: \'TFLite_Detection_PostProcess:1\' '
'type: DT_FLOAT } '
'output_arg: { name: \'TFLite_Detection_PostProcess:2\' '
'type: DT_FLOAT } '
'output_arg: { name: \'TFLite_Detection_PostProcess:3\' '
'type: DT_FLOAT } '
'attr : { name: \'h_scale\' type: \'float\'} '
'attr : { name: \'max_classes_per_detection\' type: \'int\'} '
'attr : { name: \'max_detections\' type: \'int\'} '
'attr : { name: \'nms_iou_threshold\' type: \'float\'} '
'attr : { name: \'nms_score_threshold\' type: \'float\'} '
'attr : { name: \'num_classes\' type: \'int\'} '
'attr : { name: \'w_scale\' type: \'int\'} '
'attr : { name: \'x_scale\' type: \'int\'} '
'attr : { name: \'y_scale\' type: \'int\'}')
flags_str = ('--graph_def_file={0} --input_arrays={1} '
'--output_arrays={2} --input_shapes={3} '
'--custom_opdefs="{4}"'.format(self._graph_def_file,
self._input_arrays,
self._output_arrays,
self._input_shapes,
custom_opdefs_str))
# Ensure --experimental_new_converter.
flags_str_final = ('{} --allow_custom_ops').format(flags_str)
self._run(flags_str_final, should_succeed=False)
# Ensure --allow_custom_ops.
flags_str_final = ('{} --experimental_new_converter').format(flags_str)
self._run(flags_str_final, should_succeed=False)
# Valid conversion.
flags_str_final = ('{} --allow_custom_ops '
'--experimental_new_converter').format(flags_str)
self._run(flags_str_final, should_succeed=True)
class TfLiteConvertV2Test(TestModels):
@test_util.run_v2_only
def testSavedModel(self):
input_data = constant_op.constant(1., shape=[1])
root = tracking.AutoTrackable()
root.f = def_function.function(lambda x: 2. * x)
to_save = root.f.get_concrete_function(input_data)
saved_model_dir = self._getFilepath('model')
save(root, saved_model_dir, to_save)
flags_str = '--saved_model_dir={}'.format(saved_model_dir)
self._run(flags_str, should_succeed=True)
@test_util.run_v2_only
def testKerasFile(self):
keras_file = self._getKerasModelFile()
flags_str = '--keras_model_file={}'.format(keras_file)
self._run(flags_str, should_succeed=True)
os.remove(keras_file)
@test_util.run_v2_only
def testKerasFileMLIR(self):
keras_file = self._getKerasModelFile()
flags_str = ('--keras_model_file={} --experimental_new_converter'
.format(keras_file))
self._run(flags_str, should_succeed=True)
os.remove(keras_file)
def testMissingRequired(self):
self._run('--invalid_args', should_succeed=False)
def testMutuallyExclusive(self):
self._run(
'--keras_model_file=model.h5 --saved_model_dir=/tmp/',
should_succeed=False)
class ArgParserTest(test_util.TensorFlowTestCase):
def test_without_experimental_new_converter(self):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
]
# V1 parser.
parser = tflite_convert._get_parser(False)
parsed_args = parser.parse_args(args)
self.assertFalse(parsed_args.experimental_new_converter)
# V2 parser.
parser = tflite_convert._get_parser(True)
parsed_args = parser.parse_args(args)
self.assertFalse(parsed_args.experimental_new_converter)
def test_experimental_new_converter(self):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
'--experimental_new_converter',
]
# V1 parser.
parser = tflite_convert._get_parser(False)
parsed_args = parser.parse_args(args)
self.assertTrue(parsed_args.experimental_new_converter)
# V2 parser.
parser = tflite_convert._get_parser(True)
parsed_args = parser.parse_args(args)
self.assertTrue(parsed_args.experimental_new_converter)
def test_experimental_new_converter_true(self):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
'--experimental_new_converter=true',
]
# V1 parser.
parser = tflite_convert._get_parser(False)
parsed_args = parser.parse_args(args)
self.assertTrue(parsed_args.experimental_new_converter)
# V2 parser.
parser = tflite_convert._get_parser(True)
parsed_args = parser.parse_args(args)
self.assertTrue(parsed_args.experimental_new_converter)
def test_experimental_new_converter_false(self):
args = [
'--saved_model_dir=/tmp/saved_model/',
'--output_file=/tmp/output.tflite',
'--experimental_new_converter=false',
]
# V1 parser.
parser = tflite_convert._get_parser(False)
parsed_args = parser.parse_args(args)
self.assertFalse(parsed_args.experimental_new_converter)
# V2 parser.
parser = tflite_convert._get_parser(True)
parsed_args = parser.parse_args(args)
self.assertFalse(parsed_args.experimental_new_converter)
if __name__ == '__main__':
test.main()
| apache-2.0 |
barbarubra/Don-t-know-What-i-m-doing. | python/src/Demo/sockets/telnet.py | 47 | 3010 | #! /usr/bin/env python
# Minimal interface to the Internet telnet protocol.
#
# It refuses all telnet options and does not recognize any of the other
# telnet commands, but can still be used to connect in line-by-line mode.
# It's also useful to play with a number of other services,
# like time, finger, smtp and even ftp.
#
# Usage: telnet host [port]
#
# The port may be a service name or a decimal port number;
# it defaults to 'telnet'.
import sys, posix, time
from socket import *
BUFSIZE = 1024
# Telnet protocol characters
IAC = chr(255) # Interpret as command
DONT = chr(254)
DO = chr(253)
WONT = chr(252)
WILL = chr(251)
def main():
host = sys.argv[1]
try:
hostaddr = gethostbyname(host)
except error:
sys.stderr.write(sys.argv[1] + ': bad host name\n')
sys.exit(2)
#
if len(sys.argv) > 2:
servname = sys.argv[2]
else:
servname = 'telnet'
#
if '0' <= servname[:1] <= '9':
port = eval(servname)
else:
try:
port = getservbyname(servname, 'tcp')
except error:
sys.stderr.write(servname + ': bad tcp service name\n')
sys.exit(2)
#
s = socket(AF_INET, SOCK_STREAM)
#
try:
s.connect((host, port))
except error, msg:
sys.stderr.write('connect failed: ' + repr(msg) + '\n')
sys.exit(1)
#
pid = posix.fork()
#
if pid == 0:
# child -- read stdin, write socket
while 1:
line = sys.stdin.readline()
s.send(line)
else:
# parent -- read socket, write stdout
iac = 0 # Interpret next char as command
opt = '' # Interpret next char as option
while 1:
data = s.recv(BUFSIZE)
if not data:
# EOF; kill child and exit
sys.stderr.write( '(Closed by remote host)\n')
posix.kill(pid, 9)
sys.exit(1)
cleandata = ''
for c in data:
if opt:
print ord(c)
s.send(opt + c)
opt = ''
elif iac:
iac = 0
if c == IAC:
cleandata = cleandata + c
elif c in (DO, DONT):
if c == DO: print '(DO)',
else: print '(DONT)',
opt = IAC + WONT
elif c in (WILL, WONT):
if c == WILL: print '(WILL)',
else: print '(WONT)',
opt = IAC + DONT
else:
print '(command)', ord(c)
elif c == IAC:
iac = 1
print '(IAC)',
else:
cleandata = cleandata + c
sys.stdout.write(cleandata)
sys.stdout.flush()
try:
main()
except KeyboardInterrupt:
pass
| apache-2.0 |
solashirai/edx-platform | common/lib/capa/capa/tests/test_correctmap.py | 107 | 7116 | """
Tests to verify that CorrectMap behaves correctly
"""
import unittest
from capa.correctmap import CorrectMap
import datetime
class CorrectMapTest(unittest.TestCase):
"""
Tests to verify that CorrectMap behaves correctly
"""
def setUp(self):
super(CorrectMapTest, self).setUp()
self.cmap = CorrectMap()
def test_set_input_properties(self):
# Set the correctmap properties for three inputs
self.cmap.set(
answer_id='1_2_1',
correctness='correct',
npoints=5,
msg='Test message',
hint='Test hint',
hintmode='always',
queuestate={
'key': 'secretstring',
'time': '20130228100026'
}
)
self.cmap.set(
answer_id='2_2_1',
correctness='incorrect',
npoints=None,
msg=None,
hint=None,
hintmode=None,
queuestate=None
)
self.cmap.set(
answer_id='3_2_1',
correctness='partially-correct',
npoints=3,
msg=None,
hint=None,
hintmode=None,
queuestate=None
)
# Assert that each input has the expected properties
self.assertTrue(self.cmap.is_correct('1_2_1'))
self.assertFalse(self.cmap.is_correct('2_2_1'))
self.assertTrue(self.cmap.is_correct('3_2_1'))
self.assertTrue(self.cmap.is_partially_correct('3_2_1'))
self.assertFalse(self.cmap.is_partially_correct('2_2_1'))
# Intentionally testing an item that's not in cmap.
self.assertFalse(self.cmap.is_partially_correct('9_2_1'))
self.assertEqual(self.cmap.get_correctness('1_2_1'), 'correct')
self.assertEqual(self.cmap.get_correctness('2_2_1'), 'incorrect')
self.assertEqual(self.cmap.get_correctness('3_2_1'), 'partially-correct')
self.assertEqual(self.cmap.get_npoints('1_2_1'), 5)
self.assertEqual(self.cmap.get_npoints('2_2_1'), 0)
self.assertEqual(self.cmap.get_npoints('3_2_1'), 3)
self.assertEqual(self.cmap.get_msg('1_2_1'), 'Test message')
self.assertEqual(self.cmap.get_msg('2_2_1'), None)
self.assertEqual(self.cmap.get_hint('1_2_1'), 'Test hint')
self.assertEqual(self.cmap.get_hint('2_2_1'), None)
self.assertEqual(self.cmap.get_hintmode('1_2_1'), 'always')
self.assertEqual(self.cmap.get_hintmode('2_2_1'), None)
self.assertTrue(self.cmap.is_queued('1_2_1'))
self.assertFalse(self.cmap.is_queued('2_2_1'))
self.assertEqual(self.cmap.get_queuetime_str('1_2_1'), '20130228100026')
self.assertEqual(self.cmap.get_queuetime_str('2_2_1'), None)
self.assertTrue(self.cmap.is_right_queuekey('1_2_1', 'secretstring'))
self.assertFalse(self.cmap.is_right_queuekey('1_2_1', 'invalidstr'))
self.assertFalse(self.cmap.is_right_queuekey('1_2_1', ''))
self.assertFalse(self.cmap.is_right_queuekey('1_2_1', None))
self.assertFalse(self.cmap.is_right_queuekey('2_2_1', 'secretstring'))
self.assertFalse(self.cmap.is_right_queuekey('2_2_1', 'invalidstr'))
self.assertFalse(self.cmap.is_right_queuekey('2_2_1', ''))
self.assertFalse(self.cmap.is_right_queuekey('2_2_1', None))
def test_get_npoints(self):
# Set the correctmap properties for 4 inputs
# 1) correct, 5 points
# 2) correct, None points
# 3) incorrect, 5 points
# 4) incorrect, None points
# 5) correct, 0 points
# 4) partially correct, 2.5 points
# 5) partially correct, None points
self.cmap.set(
answer_id='1_2_1',
correctness='correct',
npoints=5.3
)
self.cmap.set(
answer_id='2_2_1',
correctness='correct',
npoints=None
)
self.cmap.set(
answer_id='3_2_1',
correctness='incorrect',
npoints=5
)
self.cmap.set(
answer_id='4_2_1',
correctness='incorrect',
npoints=None
)
self.cmap.set(
answer_id='5_2_1',
correctness='correct',
npoints=0
)
self.cmap.set(
answer_id='6_2_1',
correctness='partially-correct',
npoints=2.5
)
self.cmap.set(
answer_id='7_2_1',
correctness='partially-correct',
npoints=None
)
# Assert that we get the expected points
# If points assigned --> npoints
# If no points assigned and correct --> 1 point
# If no points assigned and partially correct --> 1 point
# If no points assigned and incorrect --> 0 points
self.assertEqual(self.cmap.get_npoints('1_2_1'), 5.3)
self.assertEqual(self.cmap.get_npoints('2_2_1'), 1)
self.assertEqual(self.cmap.get_npoints('3_2_1'), 5)
self.assertEqual(self.cmap.get_npoints('4_2_1'), 0)
self.assertEqual(self.cmap.get_npoints('5_2_1'), 0)
self.assertEqual(self.cmap.get_npoints('6_2_1'), 2.5)
self.assertEqual(self.cmap.get_npoints('7_2_1'), 1)
def test_set_overall_message(self):
# Default is an empty string string
self.assertEqual(self.cmap.get_overall_message(), "")
# Set a message that applies to the whole question
self.cmap.set_overall_message("Test message")
# Retrieve the message
self.assertEqual(self.cmap.get_overall_message(), "Test message")
# Setting the message to None --> empty string
self.cmap.set_overall_message(None)
self.assertEqual(self.cmap.get_overall_message(), "")
def test_update_from_correctmap(self):
# Initialize a CorrectMap with some properties
self.cmap.set(
answer_id='1_2_1',
correctness='correct',
npoints=5,
msg='Test message',
hint='Test hint',
hintmode='always',
queuestate={
'key': 'secretstring',
'time': '20130228100026'
}
)
self.cmap.set_overall_message("Test message")
# Create a second cmap, then update it to have the same properties
# as the first cmap
other_cmap = CorrectMap()
other_cmap.update(self.cmap)
# Assert that it has all the same properties
self.assertEqual(
other_cmap.get_overall_message(),
self.cmap.get_overall_message()
)
self.assertEqual(
other_cmap.get_dict(),
self.cmap.get_dict()
)
def test_update_from_invalid(self):
# Should get an exception if we try to update() a CorrectMap
# with a non-CorrectMap value
invalid_list = [None, "string", 5, datetime.datetime.today()]
for invalid in invalid_list:
with self.assertRaises(Exception):
self.cmap.update(invalid)
| agpl-3.0 |
ccdale/cristel | lib/python/dvbsession.py | 1 | 12533 | # Copyright (c) 2015 Chris Allison chris.allison@hotmail.com
#
# This file is part of cristel.
#
# cristel 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.
#
# cristel 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 cristel. If not, see <http://www.gnu.org/licenses/>.
"""
Module to extend (and fix) the dvbstreamer Session class
"""
import time
import logging
import logging.handlers
from dvbstreamer.session import Session
from dvbstreamer.info import *
# log=logging.getLogger(__name__)
# # log.setLevel(logging.DEBUG)
# handler=logging.handlers.SysLogHandler(address = '/dev/log', facility=logging.handlers.SysLogHandler.LOG_DAEMON)
# log.addHandler(handler)
log=None
class DvbSession(Session):
"""Class represents an instance of a dvbstreamer server"""
def __init__(self, host, adaptor, username='dvbstreamer', password='control',logg=None):
global log
log=logg
Session.__init__(self,host,adaptor,username,password)
def execute_command(self, command, authenticate=True):
"""
Executes the specified command on the server.
@param command: The command to execute.
@param authenticate: Whether the connection needs to be authenticated
before running the command.
"""
log.debug("attempting command: %s" % command)
conn = self._get_connection(authenticate)
try:
result = conn.execute_command(command)
finally:
self.connections.append(conn)
return result
def get_service_filters(self):
"""
retrieve a list of active service filters
@returns: a list of ServiceFilterInfo objects
"""
error_message, lines = self.execute_command('lssfs')
sfs = []
if len(lines):
for sname in lines:
emsg, svc = self.execute_command('getsf %s' % sname)
if len(svc):
service=svc[0].split(" : ",1)
junk=service[1].split('"')
svc=junk[1]
emsg, url = self.execute_command('getsfmrl %s' % sname)
mrl=None
if len(url):
mrl=url[0]
sfs.append(ServiceFilterInfo(sname,mrl,svc))
return sfs
def find_free_sf(self):
"""finds the first free service filter"""
freesf=-1
count=-1
# print "in find_free_sf"
sfs=self.get_service_filters()
for sf in sfs:
count=count+1
# print "checking sf %d" % count
# print "testing sf.mrl: %s" % sf.mrl
if sf.mrl is None:
freesf=count
break
if sf.mrl == 'null://':
freesf=count
break
if freesf==-1:
count=count+1
newsf=self.add_sf(count)
if newsf == count:
freesf=newsf
return freesf
def add_sf(self,sfnum):
"""
adds a service filter name dvb<sfnum>
sfnum cannot be zero
@returns: the requested sf number or 0
"""
res=0
if (sfnum > -1) & (sfnum > 0):
emsg, res = self.execute_command('addsf dvb%d null://' % sfnum)
if emsg == "OK":
log.debug("Added filter dvb%d" % sfnum)
return sfnum
else:
log.warning("Failed to add filter dvb%d" % sfnum)
log.error("filter number: <%s> out of bounds" % sfnum)
return res
def set_sf(self,sfnum,service):
"""sets the service (channel) for the numbered service filter"""
if (sfnum == 0):
cmd='select "%s"' % service
else:
cmd='setsf dvb%d "%s"' % (sfnum,service)
emsg,res=self.execute_command(cmd)
if emsg == "OK":
if self.waitfortune():
log.debug("Tuned to %s for filter %d" % (service,sfnum))
return res
else:
log.error("Failed to tune to %s for filter %d" % (service,sfnum))
return False
else:
log.error("Failed to select service %s for filter %d" % (service,sfnum))
return False
def set_mrl_sf(self,sfnum,mrl):
"""sets the output for the numbered service filter"""
if sfnum == 0:
cmd='setmrl %s' % mrl
else:
cmd='setsfmrl dvb%d %s' % (sfnum,mrl)
emsg,res=self.execute_command(cmd)
if emsg == "OK":
log.debug("set output for filter %d to %s" % (sfnum,mrl))
return 1
else:
log.error("failed to set output for filter %d to %s" % (sfnum,mrl))
return 0
def clean_sf(self):
"""cleans up unused service filters"""
canclean=1
while canclean:
sfs=self.get_service_filters()
nsfs=len(sfs)
# start at the last service filter
if nsfs > 1:
nsfs=nsfs-1
if sfs[nsfs].mrl == "null://":
log.debug("removing filter dvb%d" % nsfs)
emsg,res=self.execute_command("rmsf dvb%d" % nsfs)
if emsg!="OK":
log.warning("Failed to remove filter dvb%d" % nsfs)
# filter failed to remove, so stop
canclean=0
else:
# the last service filter in the list is still in use, so stop
canclean=0
else:
log.debug("Nothing left to clean")
# there are no service filters other than <Primary>
canclean=0
def safe_to_record(self,channel):
"""checks that it is safe to tune to channel on a free service filter"""
freesf=self.find_free_sf()
# print "found %d as freesf" % freesf
if freesf > -1:
if freesf > 0:
# <Primary> is in use so check what mux it is using
sfs=self.get_service_filters()
# print "checking %s" % sfs[0].service
si=self.get_service_info(sfs[0].service)
nsi=self.get_service_info(channel)
if nsi.mux_uid != si.mux_uid:
log.warning("It is not safe to tune to %s at this time" % channel)
log.warning("Primary is tuned to %s and is in use" % sfs[0].service)
freesf=-1
else:
log.debug("Safe to tune to %s on free filter %d" % (channel,freesf))
else:
log.error("Not safe as no free filter is available")
return freesf
def get_service_info(self, service):
"""
Retrieve information about the specified service.
@param service: The service to retrieve information for. This can either
be a string descibing the name or id of the service or a Service object.
@returns: A ServiceInfo object.
"""
# print "getting service info: %s" % service
error_message, lines = self.execute_command('serviceinfo "%s"' % service)
return ServiceInfo(lines)
def recordprogramme(self,channel,filename):
"""makes a recording into the named file of the named channel"""
freesf=self.safe_to_record(channel)
if freesf > -1:
test=self.set_sf(freesf,channel)
if test:
test=self.set_mrl_sf(freesf,"file://%s" % filename)
if test:
log.debug("Recording %s into %s" % (channel,filename))
return 1
log.warning("Recording not starting for %s into %s" % (channel,filename))
return 0
def stoprecording(self,sfnum=None,filename=None):
"""stops a current recording
either supply the service filter number or the recording filename
both cannot be null
@returns: int: true if service filter was updated, false otherwise
"""
if sfnum==None:
if filename==None:
log.warning("Nothing to stop, no parameters supplied")
return 0
sfs=self.get_service_filters()
if sfnum > -1:
log.debug("stopping by filter number: %d" % sfnum)
res=self.set_mrl_sf(sfnum,"null://")
return res
count=0
for sf in sfs:
if ("file://%s" % filename)==sf.mrl:
log.debug("found filter for file: %s" % filename)
res=self.set_mrl_sf(count,"null://")
return res
count=count+1
return 0
def getstatus(self):
"""returns the front end status as a list"""
emsg,res=self.execute_command("festatus")
tmp=res[0].split("[")
t2=tmp[1].split("]")
s1=t2[0].split(",")
status=[]
for ss in s1:
status.append(ss.strip())
return status
def waitfortune(self,timeout=10):
count=0
status=self.getstatus()
while len(status)<5:
time.sleep(1)
count=count + 1
if count > timeout:
break;
status=self.getstatus()
if len(status)>4:
if status[4] == "Sync":
log.debug("Status: Sync")
return True
else:
log.error(status)
return False
def logicalchannels(self):
"""returns the logical channel ids (freeview channel numbers) as a dict"""
emsg,res=self.execute_command("lslcn")
lcn={}
for line in res:
tmp=line.split(":")
cn=tmp[0].strip()
name=tmp[1].strip()
lcn[cn]=name
return lcn
def logicalnames(self):
"""returns the logical channel ids (freeview channel numbers) as a dict keyed by name"""
emsg,res=self.execute_command("lslcn")
lcnames={}
for line in res:
tmp=line.split(":")
cn=tmp[0].strip()
name=tmp[1].strip()
lcnames[name]=cn
return lcnames
def lsmuxes(self):
"""returns a list of muxes"""
emsg,res=self.execute_command("lsmuxes")
muxes=[]
for line in res:
muxes.append(line.strip())
return muxes
def servicesformux(self,mux):
"""returns a list of services for the supplied muxid"""
emsg,res=self.execute_command("lsservices %s" % mux)
svcs=[]
for line in res:
svcs.append(line.strip())
return svcs
def lsservices(self):
"""returns the complete list of services available"""
emsg,res=self.execute_command("lsservices")
svcs=[]
for line in res:
svcs.append(line.strip())
return svcs
def serviceinfo(self,service):
"""returns a hash of the service info for a service"""
emsg,res=self.execute_command("serviceinfo '%s'" % service)
si={}
# for line in res.splitlines():
for line in res:
x=line.partition(':')
n=x[0].strip(" \"\t\r\n")
v=x[2].strip(" \"\t\r\n")
si[n]=v
return si
def canscan(self):
"""waits until no scan is running
scanning a non-existent mux will cause a generic command error
the error message tells you whether a scan is currently running
"""
while 1:
try:
emsg,res=self.execute_command("scan junk")
except GenericCommandError as e:
log.debug(e.msg)
if e.msg.strip() == "Scan in progress!":
time.sleep(10)
else:
log.debug("Scanning completed")
break
def scannet(self,net):
"""scans a net for services"""
self.canscan()
log.info("scanning: %s" % net)
emsg,res=self.execute_command("scan net '"+net+"'")
self.canscan()
log.info("Completed scan of %s" % net)
| gpl-3.0 |
benlaurie/certificate-transparency | python/demo/vdb/verifiable_log.py | 30 | 2096 | import hashlib, base64
# Basic verifiable log, for demo purposes only
class VerifiableLog:
def __init__(self):
self._entries = []
self._cache = {}
def append(self, val):
self._entries.append(val)
def get_entries(self, start, end):
return self._entries[start:end + 1]
def get_tree_head(self, seq=None):
if seq is None:
seq = len(self._entries)
if seq > len(self._entries):
raise
return {
'tree_size': seq,
'sha256_root_hash': base64.b64encode(self._calc_mth(0, seq)) if seq else None,
}
def consistency_proof(self, first, second):
return [base64.b64encode(self._calc_mth(a, b)) for a, b in self._subproof(first, 0, second, True)]
def inclusion_proof(self, m, n):
return [base64.b64encode(self._calc_mth(a, b)) for a, b in self._path(m, 0, n)]
def _calc_mth(self, start, end):
k = '%i-%i' % (start, end)
rv = self._cache.get(k, None)
if not rv:
stack = []
tree_size = end - start
for idx, leaf in enumerate(self._entries[start:end]):
stack.append(hashlib.sha256(chr(0) + leaf).digest())
for _ in range(bin(idx).replace('b', '')[::-1].index('0') if idx + 1 < tree_size else len(stack) - 1):
stack[-2:] = [hashlib.sha256(chr(1) + stack[-2] + stack[-1]).digest()]
rv = stack[0]
self._cache[k] = rv
return rv
def _subproof(self, m, start_n, end_n, b):
n = end_n - start_n
if m == n:
if b:
return []
else:
return [(start_n, end_n)]
else:
k = 1 << (len(bin(n - 1)) - 3)
if m <= k:
return self._subproof(m, start_n, start_n + k, b) + [(start_n + k, end_n)]
else:
return self._subproof(m - k, start_n + k, end_n, False) + [(start_n, start_n + k)]
def _path(self, m, start_n, end_n):
n = end_n - start_n
if n == 1:
return []
else:
k = 1 << (len(bin(n - 1)) - 3)
if m < k:
return self._path(m, start_n, start_n + k) + [(start_n + k, end_n)]
else:
return self._path(m - k, start_n + k, end_n) + [(start_n, start_n + k)]
| apache-2.0 |
gacarrillor/QGIS | tests/src/python/test_qgsserver_apicontext.py | 18 | 1891 | # -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsServerApiContext class.
From build dir, run: ctest -R PyQgsServerApiContext -V
.. note:: 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.
"""
__author__ = 'Alessandro Pasotti'
__date__ = '11/07/2019'
__copyright__ = 'Copyright 2019, The QGIS Project'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
import os
import json
import re
# Deterministic XML
os.environ['QT_HASH_SEED'] = '1'
from qgis.server import (
QgsBufferServerRequest,
QgsBufferServerResponse,
QgsServerApiContext
)
from qgis.testing import unittest
from utilities import unitTestDataPath
from urllib import parse
import tempfile
from test_qgsserver import QgsServerTestBase
class QgsServerApiContextsTest(QgsServerTestBase):
""" QGIS Server API context tests"""
def testMatchedPath(self):
"""Test path extraction"""
response = QgsBufferServerResponse()
request = QgsBufferServerRequest("http://www.qgis.org/services/wfs3")
context = QgsServerApiContext("/wfs3", request, response, None, None)
self.assertEqual(context.matchedPath(), "/services/wfs3")
request = QgsBufferServerRequest("http://www.qgis.org/services/wfs3/collections.hml")
context = QgsServerApiContext("/wfs3", request, response, None, None)
self.assertEqual(context.matchedPath(), "/services/wfs3")
request = QgsBufferServerRequest("http://www.qgis.org/services/wfs3/collections.hml")
context = QgsServerApiContext("/wfs4", request, response, None, None)
self.assertEqual(context.matchedPath(), "")
if __name__ == '__main__':
unittest.main()
| gpl-2.0 |
ChristinaZografou/sympy | sympy/solvers/ode.py | 3 | 330808 | r"""
This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper
functions that it uses.
:py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations.
See the docstring on the various functions for their uses. Note that partial
differential equations support is in ``pde.py``. Note that hint functions
have docstrings describing their various methods, but they are intended for
internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a
specific hint. See also the docstring on
:py:meth:`~sympy.solvers.ode.dsolve`.
**Functions in this module**
These are the user functions in this module:
- :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs.
- :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into
possible hints for :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the
solution to an ODE.
- :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the
homogeneous order of an expression.
- :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals
of the Lie group of point transformations of an ODE, such that it is
invariant.
- :py:meth:`~sympy.solvers.ode_checkinfsol` - Checks if the given infinitesimals
are the actual infinitesimals of a first order ODE.
These are the non-solver helper functions that are for internal use. The
user should use the various options to
:py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided
by these functions:
- :py:meth:`~sympy.solvers.ode.odesimp` - Does all forms of ODE
simplification.
- :py:meth:`~sympy.solvers.ode.ode_sol_simplicity` - A key function for
comparing solutions by simplicity.
- :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary
constants.
- :py:meth:`~sympy.solvers.ode.constant_renumber` - Renumber arbitrary
constants.
- :py:meth:`~sympy.solvers.ode._handle_Integral` - Evaluate unevaluated
Integrals.
See also the docstrings of these functions.
**Currently implemented solver methods**
The following methods are implemented for solving ordinary differential
equations. See the docstrings of the various hint functions for more
information on each (run ``help(ode)``):
- 1st order separable differential equations.
- 1st order differential equations whose coefficients or `dx` and `dy` are
functions homogeneous of the same order.
- 1st order exact differential equations.
- 1st order linear differential equations.
- 1st order Bernoulli differential equations.
- Power series solutions for first order differential equations.
- Lie Group method of solving first order differential equations.
- 2nd order Liouville differential equations.
- Power series solutions for second order differential equations
at ordinary and regular singular points.
- `n`\th order linear homogeneous differential equation with constant
coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of undetermined coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of variation of parameters.
**Philosophy behind this module**
This module is designed to make it easy to add new ODE solving methods without
having to mess with the solving code for other methods. The idea is that
there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in
an ODE and tells you what hints, if any, will solve the ODE. It does this
without attempting to solve the ODE, so it is fast. Each solving method is a
hint, and it has its own function, named ``ode_<hint>``. That function takes
in the ODE and any match expression gathered by
:py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If
this result has any integrals in it, the hint function will return an
unevaluated :py:class:`~sympy.integrals.Integral` class.
:py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function
around all of this, will then call :py:meth:`~sympy.solvers.ode.odesimp` on
the result, which, among other things, will attempt to solve the equation for
the dependent variable (the function we are solving for), simplify the
arbitrary constants in the expression, and evaluate any integrals, if the hint
allows it.
**How to add new solution methods**
If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be
able to solve, try to avoid adding special case code here. Instead, try
finding a general method that will solve your ODE, as well as others. This
way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and
unhindered by special case hacks. WolphramAlpha and Maple's
DETools[odeadvisor] function are two resources you can use to classify a
specific ODE. It is also better for a method to work with an `n`\th order ODE
instead of only with specific orders, if possible.
To add a new method, there are a few things that you need to do. First, you
need a hint name for your method. Try to name your hint so that it is
unambiguous with all other methods, including ones that may not be implemented
yet. If your method uses integrals, also include a ``hint_Integral`` hint.
If there is more than one way to solve ODEs with your method, include a hint
for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()``
function should choose the best using min with ``ode_sol_simplicity`` as the
key argument. See
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_best`, for example.
The function that uses your method will be called ``ode_<hint>()``, so the
hint must only use characters that are allowed in a Python function name
(alphanumeric characters and the underscore '``_``' character). Include a
function for every hint, except for ``_Integral`` hints
(:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically).
Hint names should be all lowercase, unless a word is commonly capitalized
(such as Integral or Bernoulli). If you have a hint that you do not want to
run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such
as a best hint that would defeat the purpose of ``all_Integral``), you will
need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
guidelines on writing a hint name.
Determine *in general* how the solutions returned by your method compare with
other methods that can potentially solve the same ODEs. Then, put your hints
in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they
should be called. The ordering of this tuple determines which hints are
default. Note that exceptions are ok, because it is easy for the user to
choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In
general, ``_Integral`` variants should go at the end of the list, and
``_best`` variants should go before the various hints they apply to. For
example, the ``undetermined_coefficients`` hint comes before the
``variation_of_parameters`` hint because, even though variation of parameters
is more general than undetermined coefficients, undetermined coefficients
generally returns cleaner results for the ODEs that it can solve than
variation of parameters does, and it does not require integration, so it is
much faster.
Next, you need to have a match expression or a function that matches the type
of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode`
(if the match function is more than just a few lines, like
:py:meth:`~sympy.solvers.ode._undetermined_coefficients_match`, it should go
outside of :py:meth:`~sympy.solvers.ode.classify_ode`). It should match the
ODE without solving for it as much as possible, so that
:py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by
bugs in solving code. Be sure to consider corner cases. For example, if your
solution method involves dividing by something, make sure you exclude the case
where that division will be 0.
In most cases, the matching of the ODE will also give you the various parts
that you need to solve it. You should put that in a dictionary (``.match()``
will do this for you), and add that as ``matching_hints['hint'] = matchdict``
in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`.
:py:meth:`~sympy.solvers.ode.classify_ode` will then send this to
:py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as
the ``match`` argument. Your function should be named ``ode_<hint>(eq, func,
order, match)`. If you need to send more information, put it in the ``match``
dictionary. For example, if you had to substitute in a dummy variable in
:py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to
pass it to your function using the `match` dict to access it. You can access
the independent variable using ``func.args[0]``, and the dependent variable
(the function you are trying to solve for) as ``func.func``. If, while trying
to solve the ODE, you find that you cannot, raise ``NotImplementedError``.
:py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all``
meta-hint, rather than causing the whole routine to fail.
Add a docstring to your function that describes the method employed. Like
with anything else in SymPy, you will need to add a doctest to the docstring,
in addition to real tests in ``test_ode.py``. Try to maintain consistency
with the other hint functions' docstrings. Add your method to the list at the
top of this docstring. Also, add your method to ``ode.rst`` in the
``docs/src`` directory, so that the Sphinx docs will pull its docstring into
the main SymPy documentation. Be sure to make the Sphinx documentation by
running ``make html`` from within the doc directory to verify that the
docstring formats correctly.
If your solution method involves integrating, use :py:meth:`Integral()
<sympy.integrals.integrals.Integral>` instead of
:py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass
hard/slow integration by using the ``_Integral`` variant of your hint. In
most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your
solution. If this is not the case, you will need to write special code in
:py:meth:`~sympy.solvers.ode._handle_Integral`. Arbitrary constants should be
symbols named ``C1``, ``C2``, and so on. All solution methods should return
an equality instance. If you need an arbitrary number of arbitrary constants,
you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``.
If it is possible to solve for the dependent function in a general way, do so.
Otherwise, do as best as you can, but do not call solve in your
``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.odesimp` will attempt
to solve the solution for you, so you do not need to do that. Lastly, if your
ODE has a common simplification that can be applied to your solutions, you can
add a special case in :py:meth:`~sympy.solvers.ode.odesimp` for it. For
example, solutions returned from the ``1st_homogeneous_coeff`` hints often
have many :py:meth:`~sympy.functions.log` terms, so
:py:meth:`~sympy.solvers.ode.odesimp` calls
:py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write
the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also
consider common ways that you can rearrange your solution to have
:py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is
better to put simplification in :py:meth:`~sympy.solvers.ode.odesimp` than in
your method, because it can then be turned off with the simplify flag in
:py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous
simplification in your function, be sure to only run it using ``if
match.get('simplify', True):``, especially if it can be slow or if it can
reduce the domain of the solution.
Finally, as with every contribution to SymPy, your method will need to be
tested. Add a test for each method in ``test_ode.py``. Follow the
conventions there, i.e., test the solver using ``dsolve(eq, f(x),
hint=your_hint)``, and also test the solution using
:py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate
tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your
hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test
won't be broken simply by the introduction of another matching hint. If your
method works for higher order (>1) ODEs, you will need to run ``sol =
constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is
the order of the ODE. This is because ``constant_renumber`` renumbers the
arbitrary constants by printing order, which is platform dependent. Try to
test every corner case of your solver, including a range of orders if it is a
`n`\th order solver, but if your solver is slow, such as if it involves hard
integration, try to keep the test run time down.
Feel free to refactor existing hints to avoid duplicating code or creating
inconsistencies. If you can show that your method exactly duplicates an
existing method, including in the simplicity and speed of obtaining the
solutions, then you can remove the old, less general method. The existing
code is tested extensively in ``test_ode.py``, so if anything is broken, one
of those tests will surely fail.
"""
from __future__ import print_function, division
from collections import defaultdict
from itertools import islice
from sympy.core import Add, S, Mul, Pow, oo
from sympy.core.compatibility import ordered, iterable, is_sequence, range
from sympy.core.containers import Tuple
from sympy.core.exprtools import factor_terms
from sympy.core.expr import AtomicExpr, Expr
from sympy.core.function import (Function, Derivative, AppliedUndef, diff,
expand, expand_mul, Subs, _mexpand)
from sympy.core.multidimensional import vectorize
from sympy.core.numbers import NaN, zoo, I, Number
from sympy.core.relational import Equality, Eq
from sympy.core.symbol import Symbol, Wild, Dummy, symbols
from sympy.core.sympify import sympify
from sympy.logic.boolalg import BooleanAtom
from sympy.functions import cos, exp, im, log, re, sin, tan, sqrt, \
atan2, conjugate
from sympy.functions.combinatorial.factorials import factorial
from sympy.integrals.integrals import Integral, integrate
from sympy.matrices import wronskian, Matrix, eye, zeros
from sympy.polys import (Poly, RootOf, rootof, terms_gcd,
PolynomialError, lcm)
from sympy.polys.polyroots import roots_quartic
from sympy.polys.polytools import cancel, degree, div
from sympy.series import Order
from sympy.series.series import series
from sympy.simplify import collect, logcombine, powsimp, separatevars, \
simplify, trigsimp, denom, posify, cse
from sympy.simplify.powsimp import powdenest
from sympy.simplify.radsimp import collect_const
from sympy.solvers import solve
from sympy.solvers.pde import pdsolve
from sympy.utilities import numbered_symbols, default_sort_key, sift
from sympy.solvers.deutils import _preprocess, ode_order, _desolve
#: This is a list of hints in the order that they should be preferred by
#: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the
#: list should produce simpler solutions than those later in the list (for
#: ODEs that fit both). For now, the order of this list is based on empirical
#: observations by the developers of SymPy.
#:
#: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE
#: can be overridden (see the docstring).
#:
#: In general, ``_Integral`` hints are grouped at the end of the list, unless
#: there is a method that returns an unevaluable integral most of the time
#: (which go near the end of the list anyway). ``default``, ``all``,
#: ``best``, and ``all_Integral`` meta-hints should not be included in this
#: list, but ``_best`` and ``_Integral`` hints should be included.
allhints = (
"separable",
"1st_exact",
"1st_linear",
"Bernoulli",
"Riccati_special_minus2",
"1st_homogeneous_coeff_best",
"1st_homogeneous_coeff_subs_indep_div_dep",
"1st_homogeneous_coeff_subs_dep_div_indep",
"almost_linear",
"linear_coefficients",
"separable_reduced",
"1st_power_series",
"lie_group",
"nth_linear_constant_coeff_homogeneous",
"nth_linear_euler_eq_homogeneous",
"nth_linear_constant_coeff_undetermined_coefficients",
"nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
"nth_linear_constant_coeff_variation_of_parameters",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
"Liouville",
"2nd_power_series_ordinary",
"2nd_power_series_regular",
"separable_Integral",
"1st_exact_Integral",
"1st_linear_Integral",
"Bernoulli_Integral",
"1st_homogeneous_coeff_subs_indep_div_dep_Integral",
"1st_homogeneous_coeff_subs_dep_div_indep_Integral",
"almost_linear_Integral",
"linear_coefficients_Integral",
"separable_reduced_Integral",
"nth_linear_constant_coeff_variation_of_parameters_Integral",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral",
"Liouville_Integral",
)
lie_heuristics = (
"abaco1_simple",
"abaco1_product",
"abaco2_similar",
"abaco2_unique_unknown",
"abaco2_unique_general",
"linear",
"function_sum",
"bivariate",
"chi"
)
def sub_func_doit(eq, func, new):
r"""
When replacing the func with something else, we usually want the
derivative evaluated, so this function helps in making that happen.
To keep subs from having to look through all derivatives, we mask them off
with dummy variables, do the func sub, and then replace masked-off
derivatives with their doit values.
Examples
========
>>> from sympy import Derivative, symbols, Function
>>> from sympy.solvers.ode import sub_func_doit
>>> x, z = symbols('x, z')
>>> y = Function('y')
>>> sub_func_doit(3*Derivative(y(x), x) - 1, y(x), x)
2
>>> sub_func_doit(x*Derivative(y(x), x) - y(x)**2 + y(x), y(x),
... 1/(x*(z + 1/x)))
x*(-1/(x**2*(z + 1/x)) + 1/(x**3*(z + 1/x)**2)) + 1/(x*(z + 1/x))
...- 1/(x**2*(z + 1/x)**2)
"""
reps = {}
repu = {}
for d in eq.atoms(Derivative):
u = Dummy('u')
repu[u] = d.subs(func, new).doit()
reps[d] = u
return eq.subs(reps).subs(func, new).subs(repu)
def get_numbered_constants(eq, num=1, start=1, prefix='C'):
"""
Returns a list of constants that do not occur
in eq already.
"""
if isinstance(eq, Expr):
eq = [eq]
elif not iterable(eq):
raise ValueError("Expected Expr or iterable but got %s" % eq)
atom_set = set().union(*[i.free_symbols for i in eq])
ncs = numbered_symbols(start=start, prefix=prefix, exclude=atom_set)
Cs = [next(ncs) for i in range(num)]
return (Cs[0] if num == 1 else tuple(Cs))
def dsolve(eq, func=None, hint="default", simplify=True,
ics= None, xi=None, eta=None, x0=0, n=6, **kwargs):
r"""
Solves any (supported) kind of ordinary differential equation and
system of ordinary differential equations.
For single ordinary differential equation
=========================================
It is classified under this when number of equation in ``eq`` is one.
**Usage**
``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation
``eq`` for function ``f(x)``, using method ``hint``.
**Details**
``eq`` can be any supported ordinary differential equation (see the
:py:mod:`~sympy.solvers.ode` docstring for supported methods).
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``f(x)`` is a function of one variable whose derivatives in that
variable make up the ordinary differential equation ``eq``. In
many cases it is not necessary to provide this; it will be
autodetected (and an error raised if it couldn't be detected).
``hint`` is the solving method that you want dsolve to use. Use
``classify_ode(eq, f(x))`` to get all of the possible hints for an
ODE. The default hint, ``default``, will use whatever hint is
returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See
Hints below for more options that you can use for hint.
``simplify`` enables simplification by
:py:meth:`~sympy.solvers.ode.odesimp`. See its docstring for more
information. Turn this off, for example, to disable solving of
solutions for ``func`` or simplification of arbitrary constants.
It will still integrate with this hint. Note that the solution may
contain more arbitrary constants than the order of the ODE with
this option enabled.
``xi`` and ``eta`` are the infinitesimal functions of an ordinary
differential equation. They are the infinitesimals of the Lie group
of point transformations for which the differential equation is
invariant. The user can specify values for the infinitesimals. If
nothing is specified, ``xi`` and ``eta`` are calculated using
:py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various
heuristics.
``ics`` is the set of boundary conditions for the differential equation.
It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2):
x3}`` and so on. For now initial conditions are implemented only for
power series solutions of first-order differential equations which should
be given in the form of ``{f(x0): x1}`` (See issue 4720). If nothing is
specified for this case ``f(0)`` is assumed to be ``C0`` and the power
series solution is calculated about 0.
``x0`` is the point about which the power series solution of a differential
equation is to be evaluated.
``n`` gives the exponent of the dependent variable up to which the power series
solution of a differential equation is to be evaluated.
**Hints**
Aside from the various solving methods, there are also some meta-hints
that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`:
``default``:
This uses whatever hint is returned first by
:py:meth:`~sympy.solvers.ode.classify_ode`. This is the
default argument to :py:meth:`~sympy.solvers.ode.dsolve`.
``all``:
To make :py:meth:`~sympy.solvers.ode.dsolve` apply all
relevant classification hints, use ``dsolve(ODE, func,
hint="all")``. This will return a dictionary of
``hint:solution`` terms. If a hint causes dsolve to raise the
``NotImplementedError``, value of that hint's key will be the
exception object raised. The dictionary will also include
some special keys:
- ``order``: The order of the ODE. See also
:py:meth:`~sympy.solvers.deutils.ode_order` in
``deutils.py``.
- ``best``: The simplest hint; what would be returned by
``best`` below.
- ``best_hint``: The hint that would produce the solution
given by ``best``. If more than one hint produces the best
solution, the first one in the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode` is chosen.
- ``default``: The solution that would be returned by default.
This is the one produced by the hint that appears first in
the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode`.
``all_Integral``:
This is the same as ``all``, except if a hint also has a
corresponding ``_Integral`` hint, it only returns the
``_Integral`` hint. This is useful if ``all`` causes
:py:meth:`~sympy.solvers.ode.dsolve` to hang because of a
difficult or impossible integral. This meta-hint will also be
much faster than ``all``, because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive
routine.
``best``:
To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods
and return the simplest one. This takes into account whether
the solution is solvable in the function, whether it contains
any Integral classes (i.e. unevaluatable integrals), and
which one is the shortest in size.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for
a list of all supported hints.
**Tips**
- You can declare the derivative of an unknown function this way:
>>> from sympy import Function, Derivative
>>> from sympy.abc import x # x is the independent variable
>>> f = Function("f")(x) # f is a function of x
>>> # f_ will be the derivative of f with respect to x
>>> f_ = Derivative(f, x)
- See ``test_ode.py`` for many tests, which serves also as a set of
examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.dsolve` always returns an
:py:class:`~sympy.core.relational.Equality` class (except for the
case when the hint is ``all`` or ``all_Integral``). If possible, it
solves the solution explicitly for the function being solved for.
Otherwise, it returns an implicit solution.
- Arbitrary constants are symbols named ``C1``, ``C2``, and so on.
- Because all solutions should be mathematically equivalent, some
hints may return the exact same result for an ODE. Often, though,
two different hints will return the same solution formatted
differently. The two should be equivalent. Also note that sometimes
the values of the arbitrary constants in two different solutions may
not be the same, because one constant may have "absorbed" other
constants into it.
- Do ``help(ode.ode_<hintname>)`` to get help more information on a
specific hint, where ``<hintname>`` is the name of a hint without
``_Integral``.
For system of ordinary differential equations
=============================================
**Usage**
``dsolve(eq, func)`` -> Solve a system of ordinary differential
equations ``eq`` for ``func`` being list of functions including
`x(t)`, `y(t)`, `z(t)` where number of functions in the list depends
upon the number of equations provided in ``eq``.
**Details**
``eq`` can be any supported system of ordinary differential equations
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which
together with some of their derivatives make up the system of ordinary
differential equation ``eq``. It is not necessary to provide this; it
will be autodetected (and an error raised if it couldn't be detected).
**Hints**
The hints are formed by parameters returned by classify_sysode, combining
them give hints name used later for forming method name.
Examples
========
>>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x))
Eq(f(x), C1*sin(3*x) + C2*cos(3*x))
>>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
>>> dsolve(eq, hint='1st_exact')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> dsolve(eq, hint='almost_linear')
[Eq(f(x), -acos(C1/sqrt(-cos(x)**2)) + 2*pi), Eq(f(x), acos(C1/sqrt(-cos(x)**2)))]
>>> t = symbols('t')
>>> x, y = symbols('x, y', function=True)
>>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t)))
>>> dsolve(eq)
[Eq(x(t), C1*x0 + C2*x0*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0**2, t)),
Eq(y(t), C1*y0 + C2(y0*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0**2, t) +
exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0))]
>>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t)))
>>> dsolve(eq)
set([Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))])
"""
if iterable(eq):
match = classify_sysode(eq, func)
eq = match['eq']
order = match['order']
func = match['func']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
# keep highest order term coefficient positive
for i in range(len(eq)):
for func_ in func:
if isinstance(func_, list):
pass
else:
if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative:
eq[i] = -eq[i]
match['eq'] = eq
if len(set(order.values()))!=1:
raise ValueError("It solves only those systems of equations whose orders are equal")
match['order'] = list(order.values())[0]
def recur_len(l):
return sum(recur_len(item) if isinstance(item,list) else 1 for item in l)
if recur_len(func) != len(eq):
raise ValueError("dsolve() and classify_sysode() work with "
"number of functions being equal to number of equations")
if match['type_of_equation'] is None:
raise NotImplementedError
else:
if match['is_linear'] == True:
if match['no_of_equation'] > 3:
solvefunc = globals()['sysode_linear_neq_order%(order)s' % match]
else:
solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match]
else:
solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match]
sols = solvefunc(match)
return sols
else:
given_hint = hint # hint given by the user
# See the docstring of _desolve for more details.
hints = _desolve(eq, func=func,
hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics,
x0=x0, n=n, **kwargs)
eq = hints.pop('eq', eq)
all_ = hints.pop('all', False)
if all_:
retdict = {}
failed_hints = {}
gethints = classify_ode(eq, dict=True)
orderedhints = gethints['ordered_hints']
for hint in hints:
try:
rv = _helper_simplify(eq, hint, hints[hint], simplify)
except NotImplementedError as detail:
failed_hints[hint] = detail
else:
retdict[hint] = rv
func = hints[hint]['func']
retdict['best'] = min(list(retdict.values()), key=lambda x:
ode_sol_simplicity(x, func, trysolving=not simplify))
if given_hint == 'best':
return retdict['best']
for i in orderedhints:
if retdict['best'] == retdict.get(i, None):
retdict['best_hint'] = i
break
retdict['default'] = gethints['default']
retdict['order'] = gethints['order']
retdict.update(failed_hints)
return retdict
else:
# The key 'hint' stores the hint needed to be solved for.
hint = hints['hint']
return _helper_simplify(eq, hint, hints, simplify)
def _helper_simplify(eq, hint, match, simplify=True, **kwargs):
r"""
Helper function of dsolve that calls the respective
:py:mod:`~sympy.solvers.ode` functions to solve for the ordinary
differential equations. This minimises the computation in calling
:py:meth:`~sympy.solvers.deutils._desolve` multiple times.
"""
r = match
if hint.endswith('_Integral'):
solvefunc = globals()['ode_' + hint[:-len('_Integral')]]
else:
solvefunc = globals()['ode_' + hint]
func = r['func']
order = r['order']
match = r[hint]
if simplify:
# odesimp() will attempt to integrate, if necessary, apply constantsimp(),
# attempt to solve for func, and apply any other hint specific
# simplifications
sols = solvefunc(eq, func, order, match)
free = eq.free_symbols
cons = lambda s: s.free_symbols.difference(free)
if isinstance(sols, Expr):
return odesimp(sols, func, order, cons(sols), hint)
return [odesimp(s, func, order, cons(s), hint) for s in sols]
else:
# We still want to integrate (you can disable it separately with the hint)
match['simplify'] = False # Some hints can take advantage of this option
rv = _handle_Integral(solvefunc(eq, func, order, match),
func, order, hint)
return rv
def classify_ode(eq, func=None, dict=False, ics=None, **kwargs):
r"""
Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve`
classifications for an ODE.
The tuple is ordered so that first item is the classification that
:py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In
general, classifications at the near the beginning of the list will
produce better solutions faster than those near the end, thought there are
always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a
different classification, use ``dsolve(ODE, func,
hint=<classification>)``. See also the
:py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints
you can use.
If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will
return a dictionary of ``hint:match`` expression terms. This is intended
for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that
because dictionaries are ordered arbitrarily, this will most likely not be
in the same order as the tuple.
You can get help on different hints by executing
``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint
without ``_Integral``.
See :py:data:`~sympy.solvers.ode.allhints` or the
:py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints
that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`.
Notes
=====
These are remarks on hint names.
``_Integral``
If a classification has ``_Integral`` at the end, it will return the
expression with an unevaluated :py:class:`~sympy.integrals.Integral`
class in it. Note that a hint may do this anyway if
:py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral,
though just using an ``_Integral`` will do so much faster. Indeed, an
``_Integral`` hint will always be faster than its corresponding hint
without ``_Integral`` because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine.
If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because
:py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or
impossible integral. Try using an ``_Integral`` hint or
``all_Integral`` to get it return something.
Note that some hints do not have ``_Integral`` counterparts. This is
because :py:meth:`~sympy.solvers.ode.integrate` is not used in solving
the ODE for those method. For example, `n`\th order linear homogeneous
ODEs with constant coefficients do not require integration to solve,
so there is no ``nth_linear_homogeneous_constant_coeff_Integrate``
hint. You can easily evaluate any unevaluated
:py:class:`~sympy.integrals.Integral`\s in an expression by doing
``expr.doit()``.
Ordinals
Some hints contain an ordinal such as ``1st_linear``. This is to help
differentiate them from other hints, as well as from other methods
that may not be implemented yet. If a hint has ``nth`` in it, such as
the ``nth_linear`` hints, this means that the method used to applies
to ODEs of any order.
``indep`` and ``dep``
Some hints contain the words ``indep`` or ``dep``. These reference
the independent variable and the dependent function, respectively. For
example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to
`x` and ``dep`` will refer to `f`.
``subs``
If a hints has the word ``subs`` in it, it means the the ODE is solved
by substituting the expression given after the word ``subs`` for a
single dummy variable. This is usually in terms of ``indep`` and
``dep`` as above. The substituted expression will be written only in
characters allowed for names of Python objects, meaning operators will
be spelled out. For example, ``indep``/``dep`` will be written as
``indep_div_dep``.
``coeff``
The word ``coeff`` in a hint refers to the coefficients of something
in the ODE, usually of the derivative terms. See the docstring for
the individual methods for more info (``help(ode)``). This is
contrast to ``coefficients``, as in ``undetermined_coefficients``,
which refers to the common name of a method.
``_best``
Methods that have more than one fundamental way to solve will have a
hint for each sub-method and a ``_best`` meta-classification. This
will evaluate all hints and return the best, using the same
considerations as the normal ``best`` meta-hint.
Examples
========
>>> from sympy import Function, classify_ode, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> classify_ode(Eq(f(x).diff(x), 0), f(x))
('separable', '1st_linear', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_homogeneous',
'separable_Integral', '1st_linear_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
>>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4)
('nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
"""
prep = kwargs.pop('prep', True)
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_ode() only "
"work with functions of one variable, not %s" % func)
if prep or func is None:
eq, func_ = _preprocess(eq, func)
if func is None:
func = func_
x = func.args[0]
f = func.func
y = Dummy('y')
xi = kwargs.get('xi')
eta = kwargs.get('eta')
terms = kwargs.get('n')
if isinstance(eq, Equality):
if eq.rhs != 0:
return classify_ode(eq.lhs - eq.rhs, func, ics=ics, xi=xi,
n=terms, eta=eta, prep=False)
eq = eq.lhs
order = ode_order(eq, f(x))
# hint:matchdict or hint:(tuple of matchdicts)
# Also will contain "default":<default hint> and "order":order items.
matching_hints = {"order": order}
if not order:
if dict:
matching_hints["default"] = None
return matching_hints
else:
return ()
df = f(x).diff(x)
a = Wild('a', exclude=[f(x)])
b = Wild('b', exclude=[f(x)])
c = Wild('c', exclude=[f(x)])
d = Wild('d', exclude=[df, f(x).diff(x, 2)])
e = Wild('e', exclude=[df])
k = Wild('k', exclude=[df])
n = Wild('n', exclude=[f(x)])
c1 = Wild('c1', exclude=[x])
a2 = Wild('a2', exclude=[x, f(x), df])
b2 = Wild('b2', exclude=[x, f(x), df])
c2 = Wild('c2', exclude=[x, f(x), df])
d2 = Wild('d2', exclude=[x, f(x), df])
a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)])
b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)])
c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)])
r3 = {'xi': xi, 'eta': eta} # Used for the lie_group hint
boundary = {} # Used to extract initial conditions
C1 = Symbol("C1")
eq = expand(eq)
# Preprocessing to get the initial conditions out
if ics is not None:
for funcarg in ics:
# Separating derivatives
if isinstance(funcarg, Subs):
deriv = funcarg.expr
old = funcarg.variables[0]
new = funcarg.point[0]
if isinstance(deriv, Derivative) and isinstance(deriv.args[0],
AppliedUndef) and deriv.args[0].func == f and old == x and not new.has(x):
dorder = ode_order(deriv, x)
temp = 'f' + str(dorder)
boundary.update({temp: new, temp + 'val': ics[funcarg]})
else:
raise ValueError("Enter valid boundary conditions for Derivatives")
# Separating functions
elif isinstance(funcarg, AppliedUndef):
if funcarg.func == f and len(funcarg.args) == 1 and \
not funcarg.args[0].has(x):
boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]})
else:
raise ValueError("Enter valid boundary conditions for Function")
else:
raise ValueError("Enter boundary conditions of the form ics "
" = {f(point}: value, f(point).diff(point, order).subs(arg, point) "
":value")
# Precondition to try remove f(x) from highest order derivative
reduced_eq = None
if eq.is_Add:
deriv_coef = eq.coeff(f(x).diff(x, order))
if deriv_coef not in (1, 0):
r = deriv_coef.match(a*f(x)**c1)
if r and r[c1]:
den = f(x)**r[c1]
reduced_eq = Add(*[arg/den for arg in eq.args])
if not reduced_eq:
reduced_eq = eq
if order == 1:
## Linear case: a(x)*y'+b(x)*y+c(x) == 0
if eq.is_Add:
ind, dep = reduced_eq.as_independent(f)
else:
u = Dummy('u')
ind, dep = (reduced_eq + u).as_independent(f)
ind, dep = [tmp.subs(u, 0) for tmp in [ind, dep]]
r = {a: dep.coeff(df),
b: dep.coeff(f(x)),
c: ind}
# double check f[a] since the preconditioning may have failed
if not r[a].has(f) and not r[b].has(f) and (
r[a]*df + r[b]*f(x) + r[c]).expand() - reduced_eq == 0:
r['a'] = a
r['b'] = b
r['c'] = c
matching_hints["1st_linear"] = r
matching_hints["1st_linear_Integral"] = r
## Bernoulli case: a(x)*y'+b(x)*y+c(x)*y**n == 0
r = collect(
reduced_eq, f(x), exact=True).match(a*df + b*f(x) + c*f(x)**n)
if r and r[c] != 0 and r[n] != 1: # See issue 4676
r['a'] = a
r['b'] = b
r['c'] = c
r['n'] = n
matching_hints["Bernoulli"] = r
matching_hints["Bernoulli_Integral"] = r
## Riccati special n == -2 case: a2*y'+b2*y**2+c2*y/x+d2/x**2 == 0
r = collect(reduced_eq,
f(x), exact=True).match(a2*df + b2*f(x)**2 + c2*f(x)/x + d2/x**2)
if r and r[b2] != 0 and (r[c2] != 0 or r[d2] != 0):
r['a2'] = a2
r['b2'] = b2
r['c2'] = c2
r['d2'] = d2
matching_hints["Riccati_special_minus2"] = r
# NON-REDUCED FORM OF EQUATION matches
r = collect(eq, df, exact=True).match(d + e * df)
if r:
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = r[d].subs(f(x), y)
r[e] = r[e].subs(f(x), y)
# FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS
# TODO: Hint first order series should match only if d/e is analytic.
# For now, only d/e and (d/e).diff(arg) is checked for existence at
# at a given point.
# This is currently done internally in ode_1st_power_series.
point = boundary.get('f0', 0)
value = boundary.get('f0val', C1)
check = cancel(r[d]/r[e])
check1 = check.subs({x: point, y: value})
if not check1.has(oo) and not check1.has(zoo) and \
not check1.has(NaN) and not check1.has(-oo):
check2 = (check1.diff(x)).subs({x: point, y: value})
if not check2.has(oo) and not check2.has(zoo) and \
not check2.has(NaN) and not check2.has(-oo):
rseries = r.copy()
rseries.update({'terms': terms, 'f0': point, 'f0val': value})
matching_hints["1st_power_series"] = rseries
r3.update(r)
## Exact Differential Equation: P(x, y) + Q(x, y)*y' = 0 where
# dP/dy == dQ/dx
try:
if r[d] != 0:
numerator = simplify(r[d].diff(y) - r[e].diff(x))
# The following few conditions try to convert a non-exact
# differential equation into an exact one.
# References : Differential equations with applications
# and historical notes - George E. Simmons
if numerator:
# If (dP/dy - dQ/dx) / Q = f(x)
# then exp(integral(f(x))*equation becomes exact
factor = simplify(numerator/r[e])
variables = factor.free_symbols
if len(variables) == 1 and x == variables.pop():
factor = exp(Integral(factor).doit())
r[d] *= factor
r[e] *= factor
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
else:
# If (dP/dy - dQ/dx) / -P = f(y)
# then exp(integral(f(y))*equation becomes exact
factor = simplify(-numerator/r[d])
variables = factor.free_symbols
if len(variables) == 1 and y == variables.pop():
factor = exp(Integral(factor).doit())
r[d] *= factor
r[e] *= factor
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
else:
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
except NotImplementedError:
# Differentiating the coefficients might fail because of things
# like f(2*x).diff(x). See issue 4624 and issue 4719.
pass
# Any first order ODE can be ideally solved by the Lie Group
# method
matching_hints["lie_group"] = r3
# This match is used for several cases below; we now collect on
# f(x) so the matching works.
r = collect(reduced_eq, df, exact=True).match(d + e*df)
if r:
# Using r[d] and r[e] without any modification for hints
# linear-coefficients and separable-reduced.
num, den = r[d], r[e] # ODE = d/e + df
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = num.subs(f(x), y)
r[e] = den.subs(f(x), y)
## Separable Case: y' == P(y)*Q(x)
r[d] = separatevars(r[d])
r[e] = separatevars(r[e])
# m1[coeff]*m1[x]*m1[y] + m2[coeff]*m2[x]*m2[y]*y'
m1 = separatevars(r[d], dict=True, symbols=(x, y))
m2 = separatevars(r[e], dict=True, symbols=(x, y))
if m1 and m2:
r1 = {'m1': m1, 'm2': m2, 'y': y}
matching_hints["separable"] = r1
matching_hints["separable_Integral"] = r1
## First order equation with homogeneous coefficients:
# dy/dx == F(y/x) or dy/dx == F(x/y)
ordera = homogeneous_order(r[d], x, y)
if ordera is not None:
orderb = homogeneous_order(r[e], x, y)
if ordera == orderb:
# u1=y/x and u2=x/y
u1 = Dummy('u1')
u2 = Dummy('u2')
s = "1st_homogeneous_coeff_subs"
s1 = s + "_dep_div_indep"
s2 = s + "_indep_div_dep"
if simplify((r[d] + u1*r[e]).subs({x: 1, y: u1})) != 0:
matching_hints[s1] = r
matching_hints[s1 + "_Integral"] = r
if simplify((r[e] + u2*r[d]).subs({x: u2, y: 1})) != 0:
matching_hints[s2] = r
matching_hints[s2 + "_Integral"] = r
if s1 in matching_hints and s2 in matching_hints:
matching_hints["1st_homogeneous_coeff_best"] = r
## Linear coefficients of the form
# y'+ F((a*x + b*y + c)/(a'*x + b'y + c')) = 0
# that can be reduced to homogeneous form.
F = num/den
params = _linear_coeff_match(F, func)
if params:
xarg, yarg = params
u = Dummy('u')
t = Dummy('t')
# Dummy substitution for df and f(x).
dummy_eq = reduced_eq.subs(((df, t), (f(x), u)))
reps = ((x, x + xarg), (u, u + yarg), (t, df), (u, f(x)))
dummy_eq = simplify(dummy_eq.subs(reps))
# get the re-cast values for e and d
r2 = collect(expand(dummy_eq), [df, f(x)]).match(e*df + d)
if r2:
orderd = homogeneous_order(r2[d], x, f(x))
if orderd is not None:
ordere = homogeneous_order(r2[e], x, f(x))
if orderd == ordere:
# Match arguments are passed in such a way that it
# is coherent with the already existing homogeneous
# functions.
r2[d] = r2[d].subs(f(x), y)
r2[e] = r2[e].subs(f(x), y)
r2.update({'xarg': xarg, 'yarg': yarg,
'd': d, 'e': e, 'y': y})
matching_hints["linear_coefficients"] = r2
matching_hints["linear_coefficients_Integral"] = r2
## Equation of the form y' + (y/x)*H(x^n*y) = 0
# that can be reduced to separable form
factor = simplify(x/f(x)*num/den)
# Try representing factor in terms of x^n*y
# where n is lowest power of x in factor;
# first remove terms like sqrt(2)*3 from factor.atoms(Mul)
u = None
for mul in ordered(factor.atoms(Mul)):
if mul.has(x):
_, u = mul.as_independent(x, f(x))
break
if u and u.has(f(x)):
h = x**(degree(Poly(u.subs(f(x), y), gen=x)))*f(x)
p = Wild('p')
if (u/h == 1) or ((u/h).simplify().match(x**p)):
t = Dummy('t')
r2 = {'t': t}
xpart, ypart = u.as_independent(f(x))
test = factor.subs(((u, t), (1/u, 1/t)))
free = test.free_symbols
if len(free) == 1 and free.pop() == t:
r2.update({'power': xpart.as_base_exp()[1], 'u': test})
matching_hints["separable_reduced"] = r2
matching_hints["separable_reduced_Integral"] = r2
## Almost-linear equation of the form f(x)*g(y)*y' + k(x)*l(y) + m(x) = 0
r = collect(eq, [df, f(x)]).match(e*df + d)
if r:
r2 = r.copy()
r2[c] = S.Zero
if r2[d].is_Add:
# Separate the terms having f(x) to r[d] and
# remaining to r[c]
no_f, r2[d] = r2[d].as_independent(f(x))
r2[c] += no_f
factor = simplify(r2[d].diff(f(x))/r[e])
if factor and not factor.has(f(x)):
r2[d] = factor_terms(r2[d])
u = r2[d].as_independent(f(x), as_Add=False)[1]
r2.update({'a': e, 'b': d, 'c': c, 'u': u})
r2[d] /= u
r2[e] /= u.diff(f(x))
matching_hints["almost_linear"] = r2
matching_hints["almost_linear_Integral"] = r2
elif order == 2:
# Liouville ODE in the form
# f(x).diff(x, 2) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98
s = d*f(x).diff(x, 2) + e*df**2 + k*df
r = reduced_eq.match(s)
if r and r[d] != 0:
y = Dummy('y')
g = simplify(r[e]/r[d]).subs(f(x), y)
h = simplify(r[k]/r[d])
if h.has(f(x)) or g.has(x):
pass
else:
r = {'g': g, 'h': h, 'y': y}
matching_hints["Liouville"] = r
matching_hints["Liouville_Integral"] = r
# Homogeneous second order differential equation of the form
# a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3, where
# for simplicity, a3, b3 and c3 are assumed to be polynomials.
# It has a definite power series solution at point x0 if, b3/a3 and c3/a3
# are analytic at x0.
deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x)
r = collect(reduced_eq,
[f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
ordinary = False
if r and r[a3] != 0:
if all([r[key].is_polynomial() for key in r]):
p = cancel(r[b3]/r[a3]) # Used below
q = cancel(r[c3]/r[a3]) # Used below
point = kwargs.get('x0', 0)
check = p.subs(x, point)
if not check.has(oo) and not check.has(NaN) and \
not check.has(zoo) and not check.has(-oo):
check = q.subs(x, point)
if not check.has(oo) and not check.has(NaN) and \
not check.has(zoo) and not check.has(-oo):
ordinary = True
r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms})
matching_hints["2nd_power_series_ordinary"] = r
# Checking if the differential equation has a regular singular point
# at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0)
# and (c3/a3)*((x - x0)**2) are analytic at x0.
if not ordinary:
p = cancel((x - point)*p)
check = p.subs(x, point)
if not check.has(oo) and not check.has(NaN) and \
not check.has(zoo) and not check.has(-oo):
q = cancel(((x - point)**2)*q)
check = q.subs(x, point)
if not check.has(oo) and not check.has(NaN) and \
not check.has(zoo) and not check.has(-oo):
coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms}
matching_hints["2nd_power_series_regular"] = coeff_dict
if order > 0:
# nth order linear ODE
# a_n(x)y^(n) + ... + a_1(x)y' + a_0(x)y = F(x) = b
r = _nth_linear_match(reduced_eq, func, order)
# Constant coefficient case (a_i is constant for all i)
if r and not any(r[i].has(x) for i in r if i >= 0):
# Inhomogeneous case: F(x) is not identically 0
if r[-1]:
undetcoeff = _undetermined_coefficients_match(r[-1], x)
s = "nth_linear_constant_coeff_variation_of_parameters"
matching_hints[s] = r
matching_hints[s + "_Integral"] = r
if undetcoeff['test']:
r['trialset'] = undetcoeff['trialset']
matching_hints[
"nth_linear_constant_coeff_undetermined_coefficients"
] = r
# Homogeneous case: F(x) is identically 0
else:
matching_hints["nth_linear_constant_coeff_homogeneous"] = r
# nth order Euler equation a_n*x**n*y^(n) + ... + a_1*x*y' + a_0*y = F(x)
#In case of Homogeneous euler equation F(x) = 0
def _test_term(coeff, order):
r"""
Linear Euler ODEs have the form K*x**order*diff(y(x),x,order) = F(x),
where K is independent of x and y(x), order>= 0.
So we need to check that for each term, coeff == K*x**order from
some K. We have a few cases, since coeff may have several
different types.
"""
if order < 0:
raise ValueError("order should be greater than 0")
if coeff == 0:
return True
if order == 0:
if x in coeff.free_symbols:
return False
return True
if coeff.is_Mul:
if coeff.has(f(x)):
return False
return x**order in coeff.args
elif coeff.is_Pow:
return coeff.as_base_exp() == (x, order)
elif order == 1:
return x == coeff
return False
if r and not any(not _test_term(r[i], i) for i in r if i >= 0):
if not r[-1]:
matching_hints["nth_linear_euler_eq_homogeneous"] = r
else:
matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"] = r
matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral"] = r
e, re = posify(r[-1].subs(x, exp(x)))
undetcoeff = _undetermined_coefficients_match(e.subs(re), x)
if undetcoeff['test']:
r['trialset'] = undetcoeff['trialset']
matching_hints["nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"] = r
# Order keys based on allhints.
retlist = [i for i in allhints if i in matching_hints]
if dict:
# Dictionaries are ordered arbitrarily, so make note of which
# hint would come first for dsolve(). Use an ordered dict in Py 3.
matching_hints["default"] = retlist[0] if retlist else None
matching_hints["ordered_hints"] = tuple(retlist)
return matching_hints
else:
return tuple(retlist)
def classify_sysode(eq, funcs=None, **kwargs):
r"""
Returns a dictionary of parameter names and values that define the system
of ordinary differential equations in ``eq``.
The parameters are further used in
:py:meth:`~sympy.solvers.ode.dsolve` for solving that system.
The parameter names and values are:
'is_linear' (boolean), which tells whether the given system is linear.
Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are
nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators.
'func' (list) contains the :py:class:`~sympy.core.function.Function`s that
appear with a derivative in the ODE, i.e. those that we are trying to solve
the ODE for.
'order' (dict) with the maximum derivative for each element of the 'func'
parameter.
'func_coeff' (dict) with the coefficient for each triple ``(equation number,
function, order)```. The coefficients are those subexpressions that do not
appear in 'func', and hence can be considered constant for purposes of ODE
solving.
'eq' (list) with the equations from ``eq``, sympified and transformed into
expressions (we are solving for these expressions to be zero).
'no_of_equations' (int) is the number of equations (same as ``len(eq)``).
'type_of_equation' (string) is an internal classification of the type of
ODE.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm
-A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists
Examples
========
>>> from sympy import Function, Eq, symbols, diff
>>> from sympy.solvers.ode import classify_sysode
>>> from sympy.abc import t
>>> f, x, y = symbols('f, x, y', function=True)
>>> k, l, m, n = symbols('k, l, m, n', Integer=True)
>>> x1 = diff(x(t), t) ; y1 = diff(y(t), t)
>>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t)
>>> eq = (Eq(5*x1, 12*x(t) - 6*y(t)), Eq(2*y1, 11*x(t) + 3*y(t)))
>>> classify_sysode(eq)
{'eq': [-12*x(t) + 6*y(t) + 5*Derivative(x(t), t), -11*x(t) - 3*y(t) + 2*Derivative(y(t), t)],
'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 5, (0, y(t), 0): 6,
(0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 2},
'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': 'type1'}
>>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
>>> classify_sysode(eq)
{'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t), t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)],
'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2,
(0, y(t), 1): 0, (1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1},
'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': 'type4'}
"""
# Sympify equations and convert iterables of equations into
# a list of equations
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eq, funcs = (_sympify(w) for w in [eq, funcs])
for i, fi in enumerate(eq):
if isinstance(fi, Equality):
eq[i] = fi.lhs - fi.rhs
matching_hints = {"no_of_equation":i+1}
matching_hints['eq'] = eq
if i==0:
raise ValueError("classify_sysode() works for systems of ODEs. "
"For scalar ODEs, classify_ode should be used")
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
# find all the functions if not given
order = dict()
if funcs==[None]:
funcs = []
for eqs in eq:
derivs = eqs.atoms(Derivative)
func = set().union(*[d.atoms(AppliedUndef) for d in derivs])
for func_ in func:
order[func_] = 0
funcs.append(func_)
funcs = list(set(funcs))
if len(funcs) < len(eq):
raise ValueError("Number of functions given is less than number of equations %s" % funcs)
func_dict = dict()
for func in funcs:
if not order[func]:
max_order = 0
for i, eqs_ in enumerate(eq):
order_ = ode_order(eqs_,func)
if max_order < order_:
max_order = order_
eq_no = i
if eq_no in func_dict:
list_func = []
list_func.append(func_dict[eq_no])
list_func.append(func)
func_dict[eq_no] = list_func
else:
func_dict[eq_no] = func
order[func] = max_order
funcs = [func_dict[i] for i in range(len(func_dict))]
matching_hints['func'] = funcs
for func in funcs:
if isinstance(func, list):
for func_elem in func:
if len(func_elem.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
else:
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
# find the order of all equation in system of odes
matching_hints["order"] = order
# find coefficients of terms f(t), diff(f(t),t) and higher derivatives
# and similarly for other functions g(t), diff(g(t),t) in all equations.
# Here j denotes the equation number, funcs[l] denotes the function about
# which we are talking about and k denotes the order of function funcs[l]
# whose coefficient we are calculating.
def linearity_check(eqs, j, func, is_linear_):
for k in range(order[func]+1):
func_coef[j,func,k] = collect(eqs.expand(),[diff(func,t,k)]).coeff(diff(func,t,k))
if is_linear_ == True:
if func_coef[j,func,k]==0:
if k==0:
coef = eqs.as_independent(func)[1]
for xr in range(1, ode_order(eqs,func)+1):
coef -= eqs.as_independent(diff(func,t,xr))[1]
if coef != 0:
is_linear_ = False
else:
if eqs.as_independent(diff(func,t,k))[1]:
is_linear_ = False
else:
for func_ in funcs:
if isinstance(func_, list):
for elem_func_ in func_:
dep = func_coef[j,func,k].as_independent(elem_func_)[1]
if dep!=1 and dep!=0:
is_linear_ = False
else:
dep = func_coef[j,func,k].as_independent(func_)[1]
if dep!=1 and dep!=0:
is_linear_ = False
return is_linear_
func_coef = {}
is_linear = True
for j, eqs in enumerate(eq):
for func in funcs:
if isinstance(func, list):
for func_elem in func:
is_linear = linearity_check(eqs, j, func_elem, is_linear)
else:
is_linear = linearity_check(eqs, j, func, is_linear)
matching_hints['func_coeff'] = func_coef
matching_hints['is_linear'] = is_linear
if len(set(order.values()))==1:
order_eq = list(matching_hints['order'].values())[0]
if matching_hints['is_linear'] == True:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef)
elif order_eq == 2:
type_of_equation = check_linear_2eq_order2(eq, funcs, func_coef)
else:
type_of_equation = None
elif matching_hints['no_of_equation'] == 3:
if order_eq == 1:
type_of_equation = check_linear_3eq_order1(eq, funcs, func_coef)
if type_of_equation==None:
type_of_equation = check_linear_neq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
if order_eq == 1:
type_of_equation = check_linear_neq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
elif matching_hints['no_of_equation'] == 3:
if order_eq == 1:
type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
type_of_equation = None
else:
type_of_equation = None
matching_hints['type_of_equation'] = type_of_equation
return matching_hints
def check_linear_2eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
# for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1)
# and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2)
r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1]
r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S(0),S(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
# We can handle homogeneous case and simple constant forcings
r['d1'] = forcing[0]
r['d2'] = forcing[1]
else:
# Issue #9244: nonhomogeneous linear systems are not supported
return None
# Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and
# Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t))
p = 0
q = 0
p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0]))
p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0]))
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q and n==0:
if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j:
p = 1
elif q and n==1:
if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j:
p = 2
# End of condition for type 6
if r['d1']!=0 or r['d2']!=0:
if not r['d1'].has(t) and not r['d2'].has(t):
if all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()):
# Equations for type 2 are Eq(a1*diff(x(t),t),b1*x(t)+c1*y(t)+d1) and Eq(a2*diff(y(t),t),b2*x(t)+c2*y(t)+d2)
return "type2"
else:
return None
else:
if all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()):
# Equations for type 1 are Eq(a1*diff(x(t),t),b1*x(t)+c1*y(t)) and Eq(a2*diff(y(t),t),b2*x(t)+c2*y(t))
return "type1"
else:
r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2']
r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2']
if (r['b1'] == r['c2']) and (r['c1'] == r['b2']):
# Equation for type 3 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), g(t)*x(t) + f(t)*y(t))
return "type3"
elif (r['b1'] == r['c2']) and (r['c1'] == -r['b2']) or (r['b1'] == -r['c2']) and (r['c1'] == r['b2']):
# Equation for type 4 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), -g(t)*x(t) + f(t)*y(t))
return "type4"
elif (not cancel(r['b2']/r['c1']).has(t) and not cancel((r['c2']-r['b1'])/r['c1']).has(t)) \
or (not cancel(r['b1']/r['c2']).has(t) and not cancel((r['c1']-r['b2'])/r['c2']).has(t)):
# Equations for type 5 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), a*g(t)*x(t) + [f(t) + b*g(t)]*y(t)
return "type5"
elif p:
return "type6"
else:
# Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t))
return "type7"
def check_linear_2eq_order2(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
a = Wild('a', exclude=[1/t])
b = Wild('b', exclude=[1/t**2])
u = Wild('u', exclude=[t, t**2])
v = Wild('v', exclude=[t, t**2])
w = Wild('w', exclude=[t, t**2])
p = Wild('p', exclude=[t, t**2])
r['a1'] = fc[0,x(t),2] ; r['a2'] = fc[1,y(t),2]
r['b1'] = fc[0,x(t),1] ; r['b2'] = fc[1,x(t),1]
r['c1'] = fc[0,y(t),1] ; r['c2'] = fc[1,y(t),1]
r['d1'] = fc[0,x(t),0] ; r['d2'] = fc[1,x(t),0]
r['e1'] = fc[0,y(t),0] ; r['e2'] = fc[1,y(t),0]
const = [S(0), S(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not (j.has(x(t)) or j.has(y(t))):
const[i] += j
r['f1'] = const[0]
r['f2'] = const[1]
if r['f1']!=0 or r['f2']!=0:
if all(not r[k].has(t) for k in 'a1 a2 d1 d2 e1 e2 f1 f2'.split()) \
and r['b1']==r['c1']==r['b2']==r['c2']==0:
return "type2"
elif all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2 d1 d2 e1 e1'.split()):
p = [S(0), S(0)] ; q = [S(0), S(0)]
for n, e in enumerate([r['f1'], r['f2']]):
if e.has(t):
tpart = e.as_independent(t, Mul)[1]
for i in Mul.make_args(tpart):
if i.has(exp):
b, e = i.as_base_exp()
co = e.coeff(t)
if co and not co.has(t) and co.has(I):
p[n] = 1
else:
q[n] = 1
else:
q[n] = 1
else:
q[n] = 1
if p[0]==1 and p[1]==1 and q[0]==0 and q[1]==0:
return "type4"
else:
return None
else:
return None
else:
if r['b1']==r['b2']==r['c1']==r['c2']==0 and all(not r[k].has(t) \
for k in 'a1 a2 d1 d2 e1 e2'.split()):
return "type1"
elif r['b1']==r['e1']==r['c2']==r['d2']==0 and all(not r[k].has(t) \
for k in 'a1 a2 b2 c1 d1 e2'.split()) and r['c1'] == -r['b2'] and \
r['d1'] == r['e2']:
return "type3"
elif cancel(-r['b2']/r['d2'])==t and cancel(-r['c1']/r['e1'])==t and not \
(r['d2']/r['a2']).has(t) and not (r['e1']/r['a1']).has(t) and \
r['b1']==r['d1']==r['c2']==r['e2']==0:
return "type5"
elif ((r['a1']/r['d1']).expand()).match((p*(u*t**2+v*t+w)**2).expand()) and not \
(cancel(r['a1']*r['d2']/(r['a2']*r['d1']))).has(t) and not (r['d1']/r['e1']).has(t) and not \
(r['d2']/r['e2']).has(t) and r['b1'] == r['b2'] == r['c1'] == r['c2'] == 0:
return "type10"
elif not cancel(r['d1']/r['e1']).has(t) and not cancel(r['d2']/r['e2']).has(t) and not \
cancel(r['d1']*r['a2']/(r['d2']*r['a1'])).has(t) and r['b1']==r['b2']==r['c1']==r['c2']==0:
return "type6"
elif not cancel(r['b1']/r['c1']).has(t) and not cancel(r['b2']/r['c2']).has(t) and not \
cancel(r['b1']*r['a2']/(r['b2']*r['a1'])).has(t) and r['d1']==r['d2']==r['e1']==r['e2']==0:
return "type7"
elif cancel(-r['b2']/r['d2'])==t and cancel(-r['c1']/r['e1'])==t and not \
cancel(r['e1']*r['a2']/(r['d2']*r['a1'])).has(t) and r['e1'].has(t) \
and r['b1']==r['d1']==r['c2']==r['e2']==0:
return "type8"
elif (r['b1']/r['a1']).match(a/t) and (r['b2']/r['a2']).match(a/t) and not \
(r['b1']/r['c1']).has(t) and not (r['b2']/r['c2']).has(t) and \
(r['d1']/r['a1']).match(b/t**2) and (r['d2']/r['a2']).match(b/t**2) \
and not (r['d1']/r['e1']).has(t) and not (r['d2']/r['e2']).has(t):
return "type9"
elif -r['b1']/r['d1']==-r['c1']/r['e1']==-r['b2']/r['d2']==-r['c2']/r['e2']==t:
return "type11"
else:
return None
def check_linear_3eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
r['a1'] = fc[0,x(t),1]; r['a2'] = fc[1,y(t),1]; r['a3'] = fc[2,z(t),1]
r['b1'] = fc[0,x(t),0]; r['b2'] = fc[1,x(t),0]; r['b3'] = fc[2,x(t),0]
r['c1'] = fc[0,y(t),0]; r['c2'] = fc[1,y(t),0]; r['c3'] = fc[2,y(t),0]
r['d1'] = fc[0,z(t),0]; r['d2'] = fc[1,z(t),0]; r['d3'] = fc[2,z(t),0]
forcing = [S(0), S(0), S(0)]
for i in range(3):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t), z(t)):
forcing[i] += j
if forcing[0].has(t) or forcing[1].has(t) or forcing[2].has(t):
# We can handle homogeneous case and simple constant forcings.
# Issue #9244: nonhomogeneous linear systems are not supported
return None
if all(not r[k].has(t) for k in 'a1 a2 a3 b1 b2 b3 c1 c2 c3 d1 d2 d3'.split()):
if r['c1']==r['d1']==r['d2']==0:
return 'type1'
elif r['c1'] == -r['b2'] and r['d1'] == -r['b3'] and r['d2'] == -r['c3'] \
and r['b1'] == r['c2'] == r['d3'] == 0:
return 'type2'
elif r['b1'] == r['c2'] == r['d3'] == 0 and r['c1']/r['a1'] == -r['d1']/r['a1'] \
and r['d2']/r['a2'] == -r['b2']/r['a2'] and r['b3']/r['a3'] == -r['c3']/r['a3']:
return 'type3'
else:
return None
else:
for k1 in 'c1 d1 b2 d2 b3 c3'.split():
if r[k1] == 0:
continue
else:
if all(not cancel(r[k1]/r[k]).has(t) for k in 'd1 b2 d2 b3 c3'.split() if r[k]!=0) \
and all(not cancel(r[k1]/(r['b1'] - r[k])).has(t) for k in 'b1 c2 d3'.split() if r['b1']!=r[k]):
return 'type4'
else:
break
return None
def check_linear_neq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
n = len(eq)
for i in range(n):
for j in range(n):
if (fc[i,func[j],0]/fc[i,func[i],1]).has(t):
return None
if len(eq)==3:
return 'type6'
return 'type1'
def check_nonlinear_2eq_order1(eq, func, func_coef):
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
f = Wild('f')
g = Wild('g')
u, v = symbols('u, v', cls=Dummy)
def check_type(x, y):
r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \
or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)):
return 'type5'
else:
return None
for func_ in func:
if isinstance(func_, list):
x = func[0][0].func
y = func[0][1].func
eq_type = check_type(x, y)
if not eq_type:
eq_type = check_type(y, x)
return eq_type
x = func[0].func
y = func[1].func
fc = func_coef
n = Wild('n', exclude=[x(t),y(t)])
f1 = Wild('f1', exclude=[v,t])
f2 = Wild('f2', exclude=[v,t])
g1 = Wild('g1', exclude=[u,t])
g2 = Wild('g2', exclude=[u,t])
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
r = eq[0].match(diff(x(t),t) - x(t)**n*f)
if r:
g = (diff(y(t),t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
return 'type1'
r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
if r:
g = (diff(y(t),t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
return 'type2'
g = Wild('g')
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \
r2[g].subs(x(t),u).subs(y(t),v).has(t)):
return 'type3'
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
num, den = (
(r1[f].subs(x(t),u).subs(y(t),v))/
(r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
if R1 and R2:
return 'type4'
return None
def check_nonlinear_2eq_order2(eq, func, func_coef):
return None
def check_nonlinear_3eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
u, v, w = symbols('u, v, w', cls=Dummy)
a = Wild('a', exclude=[x(t), y(t), z(t), t])
b = Wild('b', exclude=[x(t), y(t), z(t), t])
c = Wild('c', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
F1 = Wild('F1')
F2 = Wild('F2')
F3 = Wild('F3')
for i in range(3):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t))
r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t))
r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
return 'type1'
r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f)
if r:
r1 = collect_const(r[f]).match(a*f)
r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t))
r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
return 'type2'
r = eq[0].match(diff(x(t),t) - (F2-F3))
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1)
if r2:
r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2])
if r1 and r2 and r3:
return 'type3'
r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1)
if r2:
r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2])
if r1 and r2 and r3:
return 'type4'
r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3))
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1))
if r2:
r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2]))
if r1 and r2 and r3:
return 'type5'
return None
def check_nonlinear_3eq_order2(eq, func, func_coef):
return None
def checksysodesol(eqs, sols, func=None):
r"""
Substitutes corresponding ``sols`` for each functions into each ``eqs`` and
checks that the result of substitutions for each equation is ``0``. The
equations and solutions passed can be any iterable.
This only works when each ``sols`` have one function only, like `x(t)` or `y(t)`.
For each function, ``sols`` can have a single solution or a list of solutions.
In most cases it will not be necessary to explicitly identify the function,
but if the function cannot be inferred from the original equation it
can be supplied through the ``func`` argument.
When a sequence of equations is passed, the same sequence is used to return
the result for each equation with each function substitued with corresponding
solutions.
It tries the following method to find zero equivalence for each equation:
Substitute the solutions for functions, like `x(t)` and `y(t)` into the
original equations containing those functions.
This function returns a tuple. The first item in the tuple is ``True`` if
the substitution results for each equation is ``0``, and ``False`` otherwise.
The second item in the tuple is what the substitution results in. Each element
of the ``list`` should always be ``0`` corresponding to each equation if the
first item is ``True``. Note that sometimes this function may return ``False``,
but with an expression that is identically equal to ``0``, instead of returning
``True``. This is because :py:meth:`~sympy.simplify.simplify.simplify` cannot
reduce the expression to ``0``. If an expression returned by each function
vanishes identically, then ``sols`` really is a solution to ``eqs``.
If this function seems to hang, it is probably because of a difficult simplification.
Examples
========
>>> from sympy import Eq, diff, symbols, sin, cos, exp, sqrt, S
>>> from sympy.solvers.ode import checksysodesol
>>> C1, C2 = symbols('C1:3')
>>> t = symbols('t')
>>> x, y = symbols('x, y', function=True)
>>> eq = (Eq(diff(x(t),t), x(t) + y(t) + 17), Eq(diff(y(t),t), -2*x(t) + y(t) + 12))
>>> sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - S(5)/3),
... Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - S(46)/3)]
>>> checksysodesol(eq, sol)
(True, [0, 0])
>>> eq = (Eq(diff(x(t),t),x(t)*y(t)**4), Eq(diff(y(t),t),y(t)**3))
>>> sol = [Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), -sqrt(2)*sqrt(-1/(C2 + t))/2),
... Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), sqrt(2)*sqrt(-1/(C2 + t))/2)]
>>> checksysodesol(eq, sol)
(True, [0, 0])
"""
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eqs = _sympify(eqs)
for i in range(len(eqs)):
if isinstance(eqs[i], Equality):
eqs[i] = eqs[i].lhs - eqs[i].rhs
if func is None:
funcs = []
for eq in eqs:
derivs = eq.atoms(Derivative)
func = set().union(*[d.atoms(AppliedUndef) for d in derivs])
for func_ in func:
funcs.append(func_)
funcs = list(set(funcs))
if not all(isinstance(func, AppliedUndef) and len(func.args) == 1 for func in funcs)\
and len({func.args for func in funcs})!=1:
raise ValueError("func must be a function of one variable, not %s" % func)
for sol in sols:
if len(sol.atoms(AppliedUndef)) != 1:
raise ValueError("solutions should have one function only")
if len(funcs) != len({sol.lhs for sol in sols}):
raise ValueError("number of solutions provided does not match the number of equations")
t = funcs[0].args[0]
dictsol = dict()
for sol in sols:
func = list(sol.atoms(AppliedUndef))[0]
if sol.rhs == func:
sol = sol.reversed
solved = sol.lhs == func and not sol.rhs.has(func)
if not solved:
rhs = solve(sol, func)
if not rhs:
raise NotImplementedError
else:
rhs = sol.rhs
dictsol[func] = rhs
checkeq = []
for eq in eqs:
for func in funcs:
eq = sub_func_doit(eq, func, dictsol[func])
ss = simplify(eq)
if ss != 0:
eq = ss.expand(force=True)
else:
eq = 0
checkeq.append(eq)
if len(set(checkeq)) == 1 and list(set(checkeq))[0] == 0:
return (True, checkeq)
else:
return (False, checkeq)
@vectorize(0)
def odesimp(eq, func, order, constants, hint):
r"""
Simplifies ODEs, including trying to solve for ``func`` and running
:py:meth:`~sympy.solvers.ode.constantsimp`.
It may use knowledge of the type of solution that the hint returns to
apply additional simplifications.
It also attempts to integrate any :py:class:`~sympy.integrals.Integral`\s
in the expression, if the hint is not an ``_Integral`` hint.
This function should have no effect on expressions returned by
:py:meth:`~sympy.solvers.ode.dsolve`, as
:py:meth:`~sympy.solvers.ode.dsolve` already calls
:py:meth:`~sympy.solvers.ode.odesimp`, but the individual hint functions
do not call :py:meth:`~sympy.solvers.ode.odesimp` (because the
:py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this
function is designed for mainly internal use.
Examples
========
>>> from sympy import sin, symbols, dsolve, pprint, Function
>>> from sympy.solvers.ode import odesimp
>>> x , u2, C1= symbols('x,u2,C1')
>>> f = Function('f')
>>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral',
... simplify=False)
>>> pprint(eq, wrap_line=False)
x
----
f(x)
/
|
| / 1 \
| -|u2 + -------|
| | /1 \|
| | sin|--||
| \ \u2//
log(f(x)) = log(C1) + | ---------------- d(u2)
| 2
| u2
|
/
>>> pprint(odesimp(eq, f(x), 1, set([C1]),
... hint='1st_homogeneous_coeff_subs_indep_div_dep'
... )) #doctest: +SKIP
x
--------- = C1
/f(x)\
tan|----|
\2*x /
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
# First, integrate if the hint allows it.
eq = _handle_Integral(eq, func, order, hint)
if hint.startswith("nth_linear_euler_eq_nonhomogeneous"):
eq = simplify(eq)
if not isinstance(eq, Equality):
raise TypeError("eq should be an instance of Equality")
# Second, clean up the arbitrary constants.
# Right now, nth linear hints can put as many as 2*order constants in an
# expression. If that number grows with another hint, the third argument
# here should be raised accordingly, or constantsimp() rewritten to handle
# an arbitrary number of constants.
eq = constantsimp(eq, constants)
# Lastly, now that we have cleaned up the expression, try solving for func.
# When CRootOf is implemented in solve(), we will want to return a CRootOf
# everytime instead of an Equality.
# Get the f(x) on the left if possible.
if eq.rhs == func and not eq.lhs.has(func):
eq = [Eq(eq.rhs, eq.lhs)]
# make sure we are working with lists of solutions in simplified form.
if eq.lhs == func and not eq.rhs.has(func):
# The solution is already solved
eq = [eq]
# special simplification of the rhs
if hint.startswith("nth_linear_constant_coeff"):
# Collect terms to make the solution look nice.
# This is also necessary for constantsimp to remove unnecessary
# terms from the particular solution from variation of parameters
#
# Collect is not behaving reliably here. The results for
# some linear constant-coefficient equations with repeated
# roots do not properly simplify all constants sometimes.
# 'collectterms' gives different orders sometimes, and results
# differ in collect based on that order. The
# sort-reverse trick fixes things, but may fail in the
# future. In addition, collect is splitting exponentials with
# rational powers for no reason. We have to do a match
# to fix this using Wilds.
global collectterms
try:
collectterms.sort(key=default_sort_key)
collectterms.reverse()
except Exception:
pass
assert len(eq) == 1 and eq[0].lhs == f(x)
sol = eq[0].rhs
sol = expand_mul(sol)
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x))
del collectterms
# Collect is splitting exponentials with rational powers for
# no reason. We call powsimp to fix.
sol = powsimp(sol)
eq[0] = Eq(f(x), sol)
else:
# The solution is not solved, so try to solve it
try:
floats = any(i.is_Float for i in eq.atoms(Number))
eqsol = solve(eq, func, force=True, rational=False if floats else None)
if not eqsol:
raise NotImplementedError
except (NotImplementedError, PolynomialError):
eq = [eq]
else:
def _expand(expr):
numer, denom = expr.as_numer_denom()
if denom.is_Add:
return expr
else:
return powsimp(expr.expand(), combine='exp', deep=True)
# XXX: the rest of odesimp() expects each ``t`` to be in a
# specific normal form: rational expression with numerator
# expanded, but with combined exponential functions (at
# least in this setup all tests pass).
eq = [Eq(f(x), _expand(t)) for t in eqsol]
# special simplification of the lhs.
if hint.startswith("1st_homogeneous_coeff"):
for j, eqi in enumerate(eq):
newi = logcombine(eqi, force=True)
if newi.lhs.func is log and newi.rhs == 0:
newi = Eq(newi.lhs.args[0]/C1, C1)
eq[j] = newi
# We cleaned up the constants before solving to help the solve engine with
# a simpler expression, but the solved expression could have introduced
# things like -C1, so rerun constantsimp() one last time before returning.
for i, eqi in enumerate(eq):
eq[i] = constantsimp(eqi, constants)
eq[i] = constant_renumber(eq[i], 'C', 1, 2*order)
# If there is only 1 solution, return it;
# otherwise return the list of solutions.
if len(eq) == 1:
eq = eq[0]
return eq
def checkodesol(ode, sol, func=None, order='auto', solve_for_func=True):
r"""
Substitutes ``sol`` into ``ode`` and checks that the result is ``0``.
This only works when ``func`` is one function, like `f(x)`. ``sol`` can
be a single solution or a list of solutions. Each solution may be an
:py:class:`~sympy.core.relational.Equality` that the solution satisfies,
e.g. ``Eq(f(x), C1), Eq(f(x) + C1, 0)``; or simply an
:py:class:`~sympy.core.expr.Expr`, e.g. ``f(x) - C1``. In most cases it
will not be necessary to explicitly identify the function, but if the
function cannot be inferred from the original equation it can be supplied
through the ``func`` argument.
If a sequence of solutions is passed, the same sort of container will be
used to return the result for each solution.
It tries the following methods, in order, until it finds zero equivalence:
1. Substitute the solution for `f` in the original equation. This only
works if ``ode`` is solved for `f`. It will attempt to solve it first
unless ``solve_for_func == False``.
2. Take `n` derivatives of the solution, where `n` is the order of
``ode``, and check to see if that is equal to the solution. This only
works on exact ODEs.
3. Take the 1st, 2nd, ..., `n`\th derivatives of the solution, each time
solving for the derivative of `f` of that order (this will always be
possible because `f` is a linear operator). Then back substitute each
derivative into ``ode`` in reverse order.
This function returns a tuple. The first item in the tuple is ``True`` if
the substitution results in ``0``, and ``False`` otherwise. The second
item in the tuple is what the substitution results in. It should always
be ``0`` if the first item is ``True``. Note that sometimes this function
will ``False``, but with an expression that is identically equal to ``0``,
instead of returning ``True``. This is because
:py:meth:`~sympy.simplify.simplify.simplify` cannot reduce the expression
to ``0``. If an expression returned by this function vanishes
identically, then ``sol`` really is a solution to ``ode``.
If this function seems to hang, it is probably because of a hard
simplification.
To use this function to test, test the first item of the tuple.
Examples
========
>>> from sympy import Eq, Function, checkodesol, symbols
>>> x, C1 = symbols('x,C1')
>>> f = Function('f')
>>> checkodesol(f(x).diff(x), Eq(f(x), C1))
(True, 0)
>>> assert checkodesol(f(x).diff(x), C1)[0]
>>> assert not checkodesol(f(x).diff(x), x)[0]
>>> checkodesol(f(x).diff(x, 2), x**2)
(False, 2)
"""
if not isinstance(ode, Equality):
ode = Eq(ode, 0)
if func is None:
try:
_, func = _preprocess(ode.lhs)
except ValueError:
funcs = [s.atoms(AppliedUndef) for s in (
sol if is_sequence(sol, set) else [sol])]
funcs = set().union(*funcs)
if len(funcs) != 1:
raise ValueError(
'must pass func arg to checkodesol for this case.')
func = funcs.pop()
if not isinstance(func, AppliedUndef) or len(func.args) != 1:
raise ValueError(
"func must be a function of one variable, not %s" % func)
if is_sequence(sol, set):
return type(sol)([checkodesol(ode, i, order=order, solve_for_func=solve_for_func) for i in sol])
if not isinstance(sol, Equality):
sol = Eq(func, sol)
elif sol.rhs == func:
sol = sol.reversed
if order == 'auto':
order = ode_order(ode, func)
solved = sol.lhs == func and not sol.rhs.has(func)
if solve_for_func and not solved:
rhs = solve(sol, func)
if rhs:
eqs = [Eq(func, t) for t in rhs]
if len(rhs) == 1:
eqs = eqs[0]
return checkodesol(ode, eqs, order=order,
solve_for_func=False)
s = True
testnum = 0
x = func.args[0]
while s:
if testnum == 0:
# First pass, try substituting a solved solution directly into the
# ODE. This has the highest chance of succeeding.
ode_diff = ode.lhs - ode.rhs
if sol.lhs == func:
s = sub_func_doit(ode_diff, func, sol.rhs)
else:
testnum += 1
continue
ss = simplify(s)
if ss:
# with the new numer_denom in power.py, if we do a simple
# expansion then testnum == 0 verifies all solutions.
s = ss.expand(force=True)
else:
s = 0
testnum += 1
elif testnum == 1:
# Second pass. If we cannot substitute f, try seeing if the nth
# derivative is equal, this will only work for odes that are exact,
# by definition.
s = simplify(
trigsimp(diff(sol.lhs, x, order) - diff(sol.rhs, x, order)) -
trigsimp(ode.lhs) + trigsimp(ode.rhs))
# s2 = simplify(
# diff(sol.lhs, x, order) - diff(sol.rhs, x, order) - \
# ode.lhs + ode.rhs)
testnum += 1
elif testnum == 2:
# Third pass. Try solving for df/dx and substituting that into the
# ODE. Thanks to Chris Smith for suggesting this method. Many of
# the comments below are his, too.
# The method:
# - Take each of 1..n derivatives of the solution.
# - Solve each nth derivative for d^(n)f/dx^(n)
# (the differential of that order)
# - Back substitute into the ODE in decreasing order
# (i.e., n, n-1, ...)
# - Check the result for zero equivalence
if sol.lhs == func and not sol.rhs.has(func):
diffsols = {0: sol.rhs}
elif sol.rhs == func and not sol.lhs.has(func):
diffsols = {0: sol.lhs}
else:
diffsols = {}
sol = sol.lhs - sol.rhs
for i in range(1, order + 1):
# Differentiation is a linear operator, so there should always
# be 1 solution. Nonetheless, we test just to make sure.
# We only need to solve once. After that, we automatically
# have the solution to the differential in the order we want.
if i == 1:
ds = sol.diff(x)
try:
sdf = solve(ds, func.diff(x, i))
if not sdf:
raise NotImplementedError
except NotImplementedError:
testnum += 1
break
else:
diffsols[i] = sdf[0]
else:
# This is what the solution says df/dx should be.
diffsols[i] = diffsols[i - 1].diff(x)
# Make sure the above didn't fail.
if testnum > 2:
continue
else:
# Substitute it into ODE to check for self consistency.
lhs, rhs = ode.lhs, ode.rhs
for i in range(order, -1, -1):
if i == 0 and 0 not in diffsols:
# We can only substitute f(x) if the solution was
# solved for f(x).
break
lhs = sub_func_doit(lhs, func.diff(x, i), diffsols[i])
rhs = sub_func_doit(rhs, func.diff(x, i), diffsols[i])
ode_or_bool = Eq(lhs, rhs)
ode_or_bool = simplify(ode_or_bool)
if isinstance(ode_or_bool, (bool, BooleanAtom)):
if ode_or_bool:
lhs = rhs = S.Zero
else:
lhs = ode_or_bool.lhs
rhs = ode_or_bool.rhs
# No sense in overworking simplify -- just prove that the
# numerator goes to zero
num = trigsimp((lhs - rhs).as_numer_denom()[0])
# since solutions are obtained using force=True we test
# using the same level of assumptions
## replace function with dummy so assumptions will work
_func = Dummy('func')
num = num.subs(func, _func)
## posify the expression
num, reps = posify(num)
s = simplify(num).xreplace(reps).xreplace({_func: func})
testnum += 1
else:
break
if not s:
return (True, s)
elif s is True: # The code above never was able to change s
raise NotImplementedError("Unable to test if " + str(sol) +
" is a solution to " + str(ode) + ".")
else:
return (False, s)
def ode_sol_simplicity(sol, func, trysolving=True):
r"""
Returns an extended integer representing how simple a solution to an ODE
is.
The following things are considered, in order from most simple to least:
- ``sol`` is solved for ``func``.
- ``sol`` is not solved for ``func``, but can be if passed to solve (e.g.,
a solution returned by ``dsolve(ode, func, simplify=False``).
- If ``sol`` is not solved for ``func``, then base the result on the
length of ``sol``, as computed by ``len(str(sol))``.
- If ``sol`` has any unevaluated :py:class:`~sympy.integrals.Integral`\s,
this will automatically be considered less simple than any of the above.
This function returns an integer such that if solution A is simpler than
solution B by above metric, then ``ode_sol_simplicity(sola, func) <
ode_sol_simplicity(solb, func)``.
Currently, the following are the numbers returned, but if the heuristic is
ever improved, this may change. Only the ordering is guaranteed.
+----------------------------------------------+-------------------+
| Simplicity | Return |
+==============================================+===================+
| ``sol`` solved for ``func`` | ``-2`` |
+----------------------------------------------+-------------------+
| ``sol`` not solved for ``func`` but can be | ``-1`` |
+----------------------------------------------+-------------------+
| ``sol`` is not solved nor solvable for | ``len(str(sol))`` |
| ``func`` | |
+----------------------------------------------+-------------------+
| ``sol`` contains an | ``oo`` |
| :py:class:`~sympy.integrals.Integral` | |
+----------------------------------------------+-------------------+
``oo`` here means the SymPy infinity, which should compare greater than
any integer.
If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve
``sol``, you can use ``trysolving=False`` to skip that step, which is the
only potentially slow step. For example,
:py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag
should do this.
If ``sol`` is a list of solutions, if the worst solution in the list
returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``,
that is, the length of the string representation of the whole list.
Examples
========
This function is designed to be passed to ``min`` as the key argument,
such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i,
f(x)))``.
>>> from sympy import symbols, Function, Eq, tan, cos, sqrt, Integral
>>> from sympy.solvers.ode import ode_sol_simplicity
>>> x, C1, C2 = symbols('x, C1, C2')
>>> f = Function('f')
>>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x))
-2
>>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x))
-1
>>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x))
oo
>>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1)
>>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2)
>>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]]
[28, 35]
>>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x)))
Eq(f(x)/tan(f(x)/(2*x)), C1)
"""
# TODO: if two solutions are solved for f(x), we still want to be
# able to get the simpler of the two
# See the docstring for the coercion rules. We check easier (faster)
# things here first, to save time.
if iterable(sol):
# See if there are Integrals
for i in sol:
if ode_sol_simplicity(i, func, trysolving=trysolving) == oo:
return oo
return len(str(sol))
if sol.has(Integral):
return oo
# Next, try to solve for func. This code will change slightly when CRootOf
# is implemented in solve(). Probably a CRootOf solution should fall
# somewhere between a normal solution and an unsolvable expression.
# First, see if they are already solved
if sol.lhs == func and not sol.rhs.has(func) or \
sol.rhs == func and not sol.lhs.has(func):
return -2
# We are not so lucky, try solving manually
if trysolving:
try:
sols = solve(sol, func)
if not sols:
raise NotImplementedError
except NotImplementedError:
pass
else:
return -1
# Finally, a naive computation based on the length of the string version
# of the expression. This may favor combined fractions because they
# will not have duplicate denominators, and may slightly favor expressions
# with fewer additions and subtractions, as those are separated by spaces
# by the printer.
# Additional ideas for simplicity heuristics are welcome, like maybe
# checking if a equation has a larger domain, or if constantsimp has
# introduced arbitrary constants numbered higher than the order of a
# given ODE that sol is a solution of.
return len(str(sol))
def _get_constant_subexpressions(expr, Cs):
Cs = set(Cs)
Ces = []
def _recursive_walk(expr):
expr_syms = expr.free_symbols
if len(expr_syms) > 0 and expr_syms.issubset(Cs):
Ces.append(expr)
else:
if expr.func == exp:
expr = expr.expand(mul=True)
if expr.func in (Add, Mul):
d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs))
if len(d[True]) > 1:
x = expr.func(*d[True])
if not x.is_number:
Ces.append(x)
elif isinstance(expr, Integral):
if expr.free_symbols.issubset(Cs) and \
all(len(x) == 3 for x in expr.limits):
Ces.append(expr)
for i in expr.args:
_recursive_walk(i)
return
_recursive_walk(expr)
return Ces
def __remove_linear_redundancies(expr, Cs):
cnts = {i: expr.count(i) for i in Cs}
Cs = [i for i in Cs if cnts[i] > 0]
def _linear(expr):
if expr.func is Add:
xs = [i for i in Cs if expr.count(i)==cnts[i] \
and 0 == expr.diff(i, 2)]
d = {}
for x in xs:
y = expr.diff(x)
if y not in d:
d[y]=[]
d[y].append(x)
for y in d:
if len(d[y]) > 1:
d[y].sort(key=str)
for x in d[y][1:]:
expr = expr.subs(x, 0)
return expr
def _recursive_walk(expr):
if len(expr.args) != 0:
expr = expr.func(*[_recursive_walk(i) for i in expr.args])
expr = _linear(expr)
return expr
if expr.func is Equality:
lhs, rhs = [_recursive_walk(i) for i in expr.args]
f = lambda i: isinstance(i, Number) or i in Cs
if lhs.func is Symbol and lhs in Cs:
rhs, lhs = lhs, rhs
if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f)
for i in [True, False]:
for hs in [dlhs, drhs]:
if i not in hs:
hs[i] = [0]
# this calculation can be simplified
lhs = Add(*dlhs[False]) - Add(*drhs[False])
rhs = Add(*drhs[True]) - Add(*dlhs[True])
elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
if True in dlhs:
if False not in dlhs:
dlhs[False] = [1]
lhs = Mul(*dlhs[False])
rhs = rhs/Mul(*dlhs[True])
return Eq(lhs, rhs)
else:
return _recursive_walk(expr)
@vectorize(0)
def constantsimp(expr, constants):
r"""
Simplifies an expression with arbitrary constants in it.
This function is written specifically to work with
:py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use.
Simplification is done by "absorbing" the arbitrary constants into other
arbitrary constants, numbers, and symbols that they are not independent
of.
The symbols must all have the same name with numbers after it, for
example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be
'``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3.
If the arbitrary constants are independent of the variable ``x``, then the
independent symbol would be ``x``. There is no need to specify the
dependent function, such as ``f(x)``, because it already has the
independent symbol, ``x``, in it.
Because terms are "absorbed" into arbitrary constants and because
constants are renumbered after simplifying, the arbitrary constants in
expr are not necessarily equal to the ones of the same name in the
returned result.
If two or more arbitrary constants are added, multiplied, or raised to the
power of each other, they are first absorbed together into a single
arbitrary constant. Then the new constant is combined into other terms if
necessary.
Absorption of constants is done with limited assistance:
1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join
constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x
C_1 \cos(x)`;
2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are
expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`.
Use :py:meth:`~sympy.solvers.ode.constant_renumber` to renumber constants
after simplification or else arbitrary numbers on constants may appear,
e.g. `C_1 + C_3 x`.
In rare cases, a single constant can be "simplified" into two constants.
Every differential equation solution should have as many arbitrary
constants as the order of the differential equation. The result here will
be technically correct, but it may, for example, have `C_1` and `C_2` in
an expression, when `C_1` is actually equal to `C_2`. Use your discretion
in such situations, and also take advantage of the ability to use hints in
:py:meth:`~sympy.solvers.ode.dsolve`.
Examples
========
>>> from sympy import symbols
>>> from sympy.solvers.ode import constantsimp
>>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y')
>>> constantsimp(2*C1*x, set([C1, C2, C3]))
C1*x
>>> constantsimp(C1 + 2 + x, set([C1, C2, C3]))
C1 + x
>>> constantsimp(C1*C2 + 2 + C2 + C3*x, set([C1, C2, C3]))
C1 + C3*x
"""
# This function works recursively. The idea is that, for Mul,
# Add, Pow, and Function, if the class has a constant in it, then
# we can simplify it, which we do by recursing down and
# simplifying up. Otherwise, we can skip that part of the
# expression.
Cs = constants
orig_expr = expr
constant_subexprs = _get_constant_subexpressions(expr, Cs)
for xe in constant_subexprs:
xes = list(xe.free_symbols)
if not xes:
continue
if all([expr.count(c) == xe.count(c) for c in xes]):
xes.sort(key=str)
expr = expr.subs(xe, xes[0])
# try to perform common sub-expression elimination of constant terms
try:
commons, rexpr = cse(expr)
commons.reverse()
rexpr = rexpr[0]
for s in commons:
cs = list(s[1].atoms(Symbol))
if len(cs) == 1 and cs[0] in Cs:
rexpr = rexpr.subs(s[0], cs[0])
else:
rexpr = rexpr.subs(*s)
expr = rexpr
except Exception:
pass
expr = __remove_linear_redundancies(expr, Cs)
def _conditional_term_factoring(expr):
new_expr = terms_gcd(expr, clear=False, deep=True, expand=False)
# we do not want to factor exponentials, so handle this separately
if new_expr.is_Mul:
infac = False
asfac = False
for m in new_expr.args:
if m.func is exp:
asfac = True
elif m.is_Add:
infac = any(fi.func is exp for t in m.args
for fi in Mul.make_args(t))
if asfac and infac:
new_expr = expr
break
return new_expr
expr = _conditional_term_factoring(expr)
# call recursively if more simplification is possible
if orig_expr != expr:
return constantsimp(expr, Cs)
return expr
def constant_renumber(expr, symbolname, startnumber, endnumber):
r"""
Renumber arbitrary constants in ``expr`` to have numbers 1 through `N`
where `N` is ``endnumber - startnumber + 1`` at most.
In the process, this reorders expression terms in a standard way.
This is a simple function that goes through and renumbers any
:py:class:`~sympy.core.symbol.Symbol` with a name in the form ``symbolname
+ num`` where ``num`` is in the range from ``startnumber`` to
``endnumber``.
Symbols are renumbered based on ``.sort_key()``, so they should be
numbered roughly in the order that they appear in the final, printed
expression. Note that this ordering is based in part on hashes, so it can
produce different results on different machines.
The structure of this function is very similar to that of
:py:meth:`~sympy.solvers.ode.constantsimp`.
Examples
========
>>> from sympy import symbols, Eq, pprint
>>> from sympy.solvers.ode import constant_renumber
>>> x, C0, C1, C2, C3, C4 = symbols('x,C:5')
Only constants in the given range (inclusive) are renumbered;
the renumbering always starts from 1:
>>> constant_renumber(C1 + C3 + C4, 'C', 1, 3)
C1 + C2 + C4
>>> constant_renumber(C0 + C1 + C3 + C4, 'C', 2, 4)
C0 + 2*C1 + C2
>>> constant_renumber(C0 + 2*C1 + C2, 'C', 0, 1)
C1 + 3*C2
>>> pprint(C2 + C1*x + C3*x**2)
2
C1*x + C2 + C3*x
>>> pprint(constant_renumber(C2 + C1*x + C3*x**2, 'C', 1, 3))
2
C1 + C2*x + C3*x
"""
if type(expr) in (set, list, tuple):
return type(expr)(
[constant_renumber(i, symbolname=symbolname, startnumber=startnumber, endnumber=endnumber)
for i in expr]
)
global newstartnumber
newstartnumber = 1
constants_found = [None]*(endnumber + 2)
constantsymbols = [Symbol(
symbolname + "%d" % t) for t in range(startnumber,
endnumber + 1)]
# make a mapping to send all constantsymbols to S.One and use
# that to make sure that term ordering is not dependent on
# the indexed value of C
C_1 = [(ci, S.One) for ci in constantsymbols]
sort_key=lambda arg: default_sort_key(arg.subs(C_1))
def _constant_renumber(expr):
r"""
We need to have an internal recursive function so that
newstartnumber maintains its values throughout recursive calls.
"""
global newstartnumber
if isinstance(expr, Equality):
return Eq(
_constant_renumber(expr.lhs),
_constant_renumber(expr.rhs))
if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \
not expr.has(*constantsymbols):
# Base case, as above. Hope there aren't constants inside
# of some other class, because they won't be renumbered.
return expr
elif expr.is_Piecewise:
return expr
elif expr in constantsymbols:
if expr not in constants_found:
constants_found[newstartnumber] = expr
newstartnumber += 1
return expr
elif expr.is_Function or expr.is_Pow or isinstance(expr, Tuple):
return expr.func(
*[_constant_renumber(x) for x in expr.args])
else:
sortedargs = list(expr.args)
sortedargs.sort(key=sort_key)
return expr.func(*[_constant_renumber(x) for x in sortedargs])
expr = _constant_renumber(expr)
# Renumbering happens here
newconsts = symbols('C1:%d' % newstartnumber)
expr = expr.subs(zip(constants_found[1:], newconsts), simultaneous=True)
return expr
def _handle_Integral(expr, func, order, hint):
r"""
Converts a solution with Integrals in it into an actual solution.
For most hints, this simply runs ``expr.doit()``.
"""
global y
x = func.args[0]
f = func.func
if hint == "1st_exact":
sol = (expr.doit()).subs(y, f(x))
del y
elif hint == "1st_exact_Integral":
sol = expr.subs(y, f(x))
del y
elif hint == "nth_linear_constant_coeff_homogeneous":
sol = expr
elif not hint.endswith("_Integral"):
sol = expr.doit()
else:
sol = expr
return sol
# FIXME: replace the general solution in the docstring with
# dsolve(equation, hint='1st_exact_Integral'). You will need to be able
# to have assumptions on P and Q that dP/dy = dQ/dx.
def ode_1st_exact(eq, func, order, match):
r"""
Solves 1st order exact ordinary differential equations.
A 1st order differential equation is called exact if it is the total
differential of a function. That is, the differential equation
.. math:: P(x, y) \,\partial{}x + Q(x, y) \,\partial{}y = 0
is exact if there is some function `F(x, y)` such that `P(x, y) =
\partial{}F/\partial{}x` and `Q(x, y) = \partial{}F/\partial{}y`. It can
be shown that a necessary and sufficient condition for a first order ODE
to be exact is that `\partial{}P/\partial{}y = \partial{}Q/\partial{}x`.
Then, the solution will be as given below::
>>> from sympy import Function, Eq, Integral, symbols, pprint
>>> x, y, t, x0, y0, C1= symbols('x,y,t,x0,y0,C1')
>>> P, Q, F= map(Function, ['P', 'Q', 'F'])
>>> pprint(Eq(Eq(F(x, y), Integral(P(t, y), (t, x0, x)) +
... Integral(Q(x0, t), (t, y0, y))), C1))
x y
/ /
| |
F(x, y) = | P(t, y) dt + | Q(x0, t) dt = C1
| |
/ /
x0 y0
Where the first partials of `P` and `Q` exist and are continuous in a
simply connected region.
A note: SymPy currently has no way to represent inert substitution on an
expression, so the hint ``1st_exact_Integral`` will return an integral
with `dy`. This is supposed to represent the function that you are
solving for.
Examples
========
>>> from sympy import Function, dsolve, cos, sin
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
... f(x), hint='1st_exact')
Eq(x*cos(f(x)) + f(x)**3/3, C1)
References
==========
- http://en.wikipedia.org/wiki/Exact_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 73
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match # d+e*diff(f(x),x)
e = r[r['e']]
d = r[r['d']]
global y # This is the only way to pass dummy y to _handle_Integral
y = r['y']
C1 = get_numbered_constants(eq, num=1)
# Refer Joel Moses, "Symbolic Integration - The Stormy Decade",
# Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558
# which gives the method to solve an exact differential equation.
sol = Integral(d, x) + Integral((e - (Integral(d, x).diff(y))), y)
return Eq(sol, C1)
def ode_1st_homogeneous_coeff_best(eq, func, order, match):
r"""
Returns the best solution to an ODE from the two hints
``1st_homogeneous_coeff_subs_dep_div_indep`` and
``1st_homogeneous_coeff_subs_indep_div_dep``.
This is as determined by :py:meth:`~sympy.solvers.ode.ode_sol_simplicity`.
See the
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
and
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
docstrings for more information on these hints. Note that there is no
``ode_1st_homogeneous_coeff_best_Integral`` hint.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_best', simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- http://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
# There are two substitutions that solve the equation, u1=y/x and u2=x/y
# They produce different integrals, so try them both and see which
# one is easier.
sol1 = ode_1st_homogeneous_coeff_subs_indep_div_dep(eq,
func, order, match)
sol2 = ode_1st_homogeneous_coeff_subs_dep_div_indep(eq,
func, order, match)
simplify = match.get('simplify', True)
if simplify:
# why is odesimp called here? Should it be at the usual spot?
constants = sol1.free_symbols.difference(eq.free_symbols)
sol1 = odesimp(
sol1, func, order, constants,
"1st_homogeneous_coeff_subs_indep_div_dep")
constants = sol2.free_symbols.difference(eq.free_symbols)
sol2 = odesimp(
sol2, func, order, constants,
"1st_homogeneous_coeff_subs_dep_div_indep")
return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, func,
trysolving=not simplify))
def ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_1 = \frac{\text{<dependent
variable>}}{\text{<independent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential
equation into an equation separable in the variables `x` and `u`. If
`h(u_1)` is the function that results from making the substitution `u_1 =
f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is::
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x)
>>> pprint(genform)
/f(x)\ /f(x)\ d
g|----| + h|----|*--(f(x))
\ x / \ x / dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral'))
f(x)
----
x
/
|
| -h(u1)
log(x) = C1 + | ---------------- d(u1)
| u1*h(u1) + g(u1)
|
/
Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`.
See also the docstrings of
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_best` and
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`.
Examples
========
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False))
/ 3 \
|3*f(x) f (x)|
log|------ + -----|
| x 3 |
\ x /
log(x) = log(C1) - -------------------
3
References
==========
- http://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u1 = Dummy('u1') # u1 == f(x)/x
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0)
yarg = match.get('yarg', 0)
int = Integral(
(-r[r['e']]/(r[r['d']] + u1*r[r['e']])).subs({x: 1, r['y']: u1}),
(u1, None, f(x)/x))
sol = logcombine(Eq(log(x), int + log(C1)), force=True)
sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
def ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_2 = \frac{\text{<independent
variable>}}{\text{<dependent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential
equation into an equation separable in the variables `y` and `u_2`. If
`h(u_2)` is the function that results from making the substitution `u_2 =
x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is:
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x)
>>> pprint(genform)
/ x \ / x \ d
g|----| + h|----|*--(f(x))
\f(x)/ \f(x)/ dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral'))
x
----
f(x)
/
|
| -g(u2)
| ---------------- d(u2)
| u2*g(u2) + h(u2)
|
/
<BLANKLINE>
f(x) = C1*e
Where `u_2 g(u_2) + h(u_2) \ne 0` and `f(x) \ne 0`.
See also the docstrings of
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_best` and
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`.
Examples
========
>>> from sympy import Function, pprint, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep',
... simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- http://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u2 = Dummy('u2') # u2 == x/f(x)
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0) # If xarg present take xarg, else zero
yarg = match.get('yarg', 0) # If yarg present take yarg, else zero
int = Integral(
simplify(
(-r[r['d']]/(r[r['e']] + u2*r[r['d']])).subs({x: u2, r['y']: 1})),
(u2, None, x/f(x)))
sol = logcombine(Eq(log(f(x)), int + log(C1)), force=True)
sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
# XXX: Should this function maybe go somewhere else?
def homogeneous_order(eq, *symbols):
r"""
Returns the order `n` if `g` is homogeneous and ``None`` if it is not
homogeneous.
Determines if a function is homogeneous and if so of what order. A
function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y,
\cdots) = t^n f(x, y, \cdots)`.
If the function is of two variables, `F(x, y)`, then `f` being homogeneous
of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)`
or `H(y/x)`. This fact is used to solve 1st order ordinary differential
equations whose coefficients are homogeneous of the same order (see the
docstrings of
:py:meth:`~solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` and
:py:meth:`~solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`).
Symbols can be functions, but every argument of the function must be a
symbol, and the arguments of the function that appear in the expression
must match those given in the list of symbols. If a declared function
appears with different arguments than given in the list of symbols,
``None`` is returned.
Examples
========
>>> from sympy import Function, homogeneous_order, sqrt
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> homogeneous_order(f(x), f(x)) is None
True
>>> homogeneous_order(f(x,y), f(y, x), x, y) is None
True
>>> homogeneous_order(f(x), f(x), x)
1
>>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x))
2
>>> homogeneous_order(x**2+f(x), x, f(x)) is None
True
"""
if not symbols:
raise ValueError("homogeneous_order: no symbols were given.")
symset = set(symbols)
eq = sympify(eq)
# The following are not supported
if eq.has(Order, Derivative):
return None
# These are all constants
if (eq.is_Number or
eq.is_NumberSymbol or
eq.is_number
):
return S.Zero
# Replace all functions with dummy variables
dum = numbered_symbols(prefix='d', cls=Dummy)
newsyms = set()
for i in [j for j in symset if getattr(j, 'is_Function')]:
iargs = set(i.args)
if iargs.difference(symset):
return None
else:
dummyvar = next(dum)
eq = eq.subs(i, dummyvar)
symset.remove(i)
newsyms.add(dummyvar)
symset.update(newsyms)
if not eq.free_symbols & symset:
return None
# assuming order of a nested function can only be equal to zero
if isinstance(eq, Function):
return None if homogeneous_order(
eq.args[0], *tuple(symset)) != 0 else S.Zero
# make the replacement of x with x*t and see if t can be factored out
t = Dummy('t', positive=True) # It is sufficient that t > 0
eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t]
if eqs is S.One:
return S.Zero # there was no term with only t
i, d = eqs.as_independent(t, as_Add=False)
b, e = d.as_base_exp()
if b == t:
return e
def ode_1st_linear(eq, func, order, match):
r"""
Solves 1st order linear differential equations.
These are differential equations of the form
.. math:: dy/dx + P(x) y = Q(x)\text{.}
These kinds of differential equations can be solved in a general way. The
integrating factor `e^{\int P(x) \,dx}` will turn the equation into a
separable equation. The general solution is::
>>> from sympy import Function, dsolve, Eq, pprint, diff, sin
>>> from sympy.abc import x
>>> f, P, Q = map(Function, ['f', 'P', 'Q'])
>>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x))
>>> pprint(genform)
d
P(x)*f(x) + --(f(x)) = Q(x)
dx
>>> pprint(dsolve(genform, f(x), hint='1st_linear_Integral'))
/ / \
| | |
| | / | /
| | | | |
| | | P(x) dx | - | P(x) dx
| | | | |
| | / | /
f(x) = |C1 + | Q(x)*e dx|*e
| | |
\ / /
Examples
========
>>> f = Function('f')
>>> pprint(dsolve(Eq(x*diff(f(x), x) - f(x), x**2*sin(x)),
... f(x), '1st_linear'))
f(x) = x*(C1 - cos(x))
References
==========
- http://en.wikipedia.org/wiki/Linear_differential_equation#First_order_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 92
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match # a*diff(f(x),x) + b*f(x) + c
C1 = get_numbered_constants(eq, num=1)
t = exp(Integral(r[r['b']]/r[r['a']], x))
tt = Integral(t*(-r[r['c']]/r[r['a']]), x)
f = match.get('u', f(x)) # take almost-linear u if present, else f(x)
return Eq(f, (tt + C1)/t)
def ode_Bernoulli(eq, func, order, match):
r"""
Solves Bernoulli differential equations.
These are equations of the form
.. math:: dy/dx + P(x) y = Q(x) y^n\text{, }n \ne 1`\text{.}
The substitution `w = 1/y^{1-n}` will transform an equation of this form
into one that is linear (see the docstring of
:py:meth:`~sympy.solvers.ode.ode_1st_linear`). The general solution is::
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x, n
>>> f, P, Q = map(Function, ['f', 'P', 'Q'])
>>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)**n)
>>> pprint(genform)
d n
P(x)*f(x) + --(f(x)) = Q(x)*f (x)
dx
>>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral')) #doctest: +SKIP
1
----
1 - n
// / \ \
|| | | |
|| | / | / |
|| | | | | |
|| | (1 - n)* | P(x) dx | (-1 + n)* | P(x) dx|
|| | | | | |
|| | / | / |
f(x) = ||C1 + (-1 + n)* | -Q(x)*e dx|*e |
|| | | |
\\ / / /
Note that the equation is separable when `n = 1` (see the docstring of
:py:meth:`~sympy.solvers.ode.ode_separable`).
>>> pprint(dsolve(Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)), f(x),
... hint='separable_Integral'))
f(x)
/
| /
| 1 |
| - dy = C1 + | (-P(x) + Q(x)) dx
| y |
| /
/
Examples
========
>>> from sympy import Function, dsolve, Eq, pprint, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(Eq(x*f(x).diff(x) + f(x), log(x)*f(x)**2),
... f(x), hint='Bernoulli'))
1
f(x) = -------------------
/ log(x) 1\
x*|C1 + ------ + -|
\ x x/
References
==========
- http://en.wikipedia.org/wiki/Bernoulli_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 95
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match # a*diff(f(x),x) + b*f(x) + c*f(x)**n, n != 1
C1 = get_numbered_constants(eq, num=1)
t = exp((1 - r[r['n']])*Integral(r[r['b']]/r[r['a']], x))
tt = (r[r['n']] - 1)*Integral(t*r[r['c']]/r[r['a']], x)
return Eq(f(x), ((tt + C1)/t)**(1/(1 - r[r['n']])))
def ode_Riccati_special_minus2(eq, func, order, match):
r"""
The general Riccati equation has the form
.. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.}
While it does not have a general solution [1], the "special" form, `dy/dx
= a y^2 - b x^c`, does have solutions in many cases [2]. This routine
returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained
by using a suitable change of variables to reduce it to the special form
and is valid when neither `a` nor `b` are zero and either `c` or `d` is
zero.
>>> from sympy.abc import x, y, a, b, c, d
>>> from sympy.solvers.ode import dsolve, checkodesol
>>> from sympy import pprint, Function
>>> f = Function('f')
>>> y = f(x)
>>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2)
>>> sol = dsolve(genform, y)
>>> pprint(sol, wrap_line=False)
/ / __________________ \\
| __________________ | / 2 ||
| / 2 | \/ 4*b*d - (a + c) *log(x)||
-|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------||
\ \ 2*a //
f(x) = ------------------------------------------------------------------------
2*b*x
>>> checkodesol(genform, sol, order=1)[0]
True
References
==========
1. http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati
2. http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf -
http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf
"""
x = func.args[0]
f = func.func
r = match # a2*diff(f(x),x) + b2*f(x) + c2*f(x)/x + d2/x**2
a2, b2, c2, d2 = [r[r[s]] for s in 'a2 b2 c2 d2'.split()]
C1 = get_numbered_constants(eq, num=1)
mu = sqrt(4*d2*b2 - (a2 - c2)**2)
return Eq(f(x), (a2 - c2 - mu*tan(mu/(2*a2)*log(x) + C1))/(2*b2*x))
def ode_Liouville(eq, func, order, match):
r"""
Solves 2nd order Liouville differential equations.
The general form of a Liouville ODE is
.. math:: \frac{d^2 y}{dx^2} + g(y) \left(\!
\frac{dy}{dx}\!\right)^2 + h(x)
\frac{dy}{dx}\text{.}
The general solution is:
>>> from sympy import Function, dsolve, Eq, pprint, diff
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = Eq(diff(f(x),x,x) + g(f(x))*diff(f(x),x)**2 +
... h(x)*diff(f(x),x), 0)
>>> pprint(genform)
2 2
/d \ d d
g(f(x))*|--(f(x))| + h(x)*--(f(x)) + ---(f(x)) = 0
\dx / dx 2
dx
>>> pprint(dsolve(genform, f(x), hint='Liouville_Integral'))
f(x)
/ /
| |
| / | /
| | | |
| - | h(x) dx | | g(y) dy
| | | |
| / | /
C1 + C2* | e dx + | e dy = 0
| |
/ /
Examples
========
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(diff(f(x), x, x) + diff(f(x), x)**2/f(x) +
... diff(f(x), x)/x, f(x), hint='Liouville'))
________________ ________________
[f(x) = -\/ C1 + C2*log(x) , f(x) = \/ C1 + C2*log(x) ]
References
==========
- Goldstein and Braun, "Advanced Methods for the Solution of Differential
Equations", pp. 98
- http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Liouville
# indirect doctest
"""
# Liouville ODE:
# f(x).diff(x, 2) + g(f(x))*(f(x).diff(x, 2))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98, as well as
# http://www.maplesoft.com/support/help/view.aspx?path=odeadvisor/Liouville
x = func.args[0]
f = func.func
r = match # f(x).diff(x, 2) + g*f(x).diff(x)**2 + h*f(x).diff(x)
y = r['y']
C1, C2 = get_numbered_constants(eq, num=2)
int = Integral(exp(Integral(r['g'], y)), (y, None, f(x)))
sol = Eq(int + C1*Integral(exp(-Integral(r['h'], x)), x) + C2, 0)
return sol
def ode_2nd_power_series_ordinary(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at an ordinary point. A homogenous
differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0
For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials,
it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at
`x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`,
in the differential equation, and equating the nth term. Using this relation
various terms can be generated.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x, y
>>> f = Function("f")
>>> eq = f(x).diff(x, 2) + f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_ordinary'))
/ 4 2 \ / 2 \
|x x | | x | / 6\
f(x) = C2*|-- - -- + 1| + C1*x*|- -- + 1| + O\x /
\24 2 / \ 6 /
References
==========
- http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = Dummy("n", integer=True)
s = Wild("s")
k = Wild("k", exclude=[x])
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match[match['a3']]
q = match[match['b3']]
r = match[match['c3']]
seriesdict = {}
recurr = Function("r")
# Generating the recurrence relation which works this way:
# for the second order term the summation begins at n = 2. The coefficients
# p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that
# the exponent of x becomes n.
# For example, if p is x, then the second degree recurrence term is
# an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to
# an+1*n*(n - 1)*x**n.
# A similar process is done with the first order and zeroth order term.
coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)]
for index, coeff in enumerate(coefflist):
if coeff[1]:
f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0)))
if f2.is_Add:
addargs = f2.args
else:
addargs = [f2]
for arg in addargs:
powm = arg.match(s*x**k)
term = coeff[0]*powm[s]
if not powm[k].is_Symbol:
term = term.subs(n, n - powm[k].as_independent(n)[0])
startind = powm[k].subs(n, index)
# Seeing if the startterm can be reduced further.
# If it vanishes for n lesser than startind, it is
# equal to summation from n.
if startind:
for i in reversed(range(startind)):
if not term.subs(n, i):
seriesdict[term] = i
else:
seriesdict[term] = i + 1
break
else:
seriesdict[term] = S(0)
# Stripping of terms so that the sum starts with the same number.
teq = S(0)
suminit = seriesdict.values()
rkeys = seriesdict.keys()
req = Add(*rkeys)
if any(suminit):
maxval = max(suminit)
for term in seriesdict:
val = seriesdict[term]
if val != maxval:
for i in range(val, maxval):
teq += term.subs(n, val)
finaldict = {}
if teq:
fargs = teq.atoms(AppliedUndef)
if len(fargs) == 1:
finaldict[fargs.pop()] = 0
else:
maxf = max(fargs, key = lambda x: x.args[0])
sol = solve(teq, maxf)
if isinstance(sol, list):
sol = sol[0]
finaldict[maxf] = sol
# Finding the recurrence relation in terms of the largest term.
fargs = req.atoms(AppliedUndef)
maxf = max(fargs, key = lambda x: x.args[0])
minf = min(fargs, key = lambda x: x.args[0])
if minf.args[0].is_Symbol:
startiter = 0
else:
startiter = -minf.args[0].as_independent(n)[0]
lhs = maxf
rhs = solve(req, maxf)
if isinstance(rhs, list):
rhs = rhs[0]
# Checking how many values are already present
tcounter = len([t for t in finaldict.values() if t])
for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary
check = rhs.subs(n, startiter)
nlhs = lhs.subs(n, startiter)
nrhs = check.subs(finaldict)
finaldict[nlhs] = nrhs
startiter += 1
# Post processing
series = C0 + C1*(x - x0)
for term in finaldict:
if finaldict[term]:
fact = term.args[0]
series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*(
x - x0)**fact)
series = collect(expand_mul(series), [C0, C1]) + Order(x**terms)
return Eq(f(x), series)
def ode_2nd_power_series_regular(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at a regular point. A second order
homogenous differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0
A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}`
and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity
`P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for
finding the power series solutions is:
1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series
solutions about x0. Find `p0` and `q0` which are the constants of the
power series expansions.
2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the
roots `m1` and `m2` of the indicial equation.
3. If `m1 - m2` is a non integer there exists two series solutions. If
`m1 = m2`, there exists only one solution. If `m1 - m2` is an integer,
then the existence of one solution is confirmed. The other solution may
or may not exist.
The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The
coefficients are determined by the following recurrence relation.
`a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case
in which `m1 - m2` is an integer, it can be seen from the recurrence relation
that for the lower root `m`, when `n` equals the difference of both the
roots, the denominator becomes zero. So if the numerator is not equal to zero,
a second series solution exists.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x, y
>>> f = Function("f")
>>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x)
>>> pprint(dsolve(eq))
/ 6 4 2 \
| x x x |
/ 4 2 \ C1*|- --- + -- - -- + 1|
| x x | \ 720 24 2 / / 6\
f(x) = C2*|--- - -- + 1| + ------------------------ + O\x /
\120 6 / x
References
==========
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = Dummy("n")
m = Dummy("m") # for solving the indicial equation
s = Wild("s")
k = Wild("k", exclude=[x])
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match['p']
q = match['q']
# Generating the indicial equation
indicial = []
for term in [p, q]:
if not term.has(x):
indicial.append(term)
else:
term = series(term, n=1, x0=x0)
if isinstance(term, Order):
indicial.append(S(0))
else:
for arg in term.args:
if not arg.has(x):
indicial.append(arg)
break
p0, q0 = indicial
sollist = solve(m*(m - 1) + m*p0 + q0, m)
if sollist and isinstance(sollist, list) and all(
[sol.is_real for sol in sollist]):
serdict1 = {}
serdict2 = {}
if len(sollist) == 1:
# Only one series solution exists in this case.
m1 = m2 = sollist.pop()
if terms-m1-1 <= 0:
return Eq(f(x), Order(terms))
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
else:
m1 = sollist[0]
m2 = sollist[1]
if m1 < m2:
m1, m2 = m2, m1
# Irrespective of whether m1 - m2 is an integer or not, one
# Frobenius series solution exists.
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
if not (m1 - m2).is_integer:
# Second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1)
else:
# Check if second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1)
if serdict1:
finalseries1 = C0
for key in serdict1:
power = int(key.name[1:])
finalseries1 += serdict1[key]*(x - x0)**power
finalseries1 = (x - x0)**m1*finalseries1
finalseries2 = S(0)
if serdict2:
for key in serdict2:
power = int(key.name[1:])
finalseries2 += serdict2[key]*(x - x0)**power
finalseries2 += C1
finalseries2 = (x - x0)**m2*finalseries2
return Eq(f(x), collect(finalseries1 + finalseries2,
[C0, C1]) + Order(x**terms))
def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None):
r"""
Returns a dict with keys as coefficients and values as their values in terms of C0
"""
n = int(n)
# In cases where m1 - m2 is not an integer
m2 = check
d = Dummy("d")
numsyms = numbered_symbols("C", start=0)
numsyms = [next(numsyms) for i in range(n + 1)]
C0 = Symbol("C0")
serlist = []
for ser in [p, q]:
# Order term not present
if ser.is_polynomial(x) and Poly(ser, x).degree() <= n:
if x0:
ser = ser.subs(x, x + x0)
dict_ = Poly(ser, x).as_dict()
# Order term present
else:
tseries = series(ser, x=x0, n=n+1)
# Removing order
dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict()
# Fill in with zeros, if coefficients are zero.
for i in range(n + 1):
if (i,) not in dict_:
dict_[(i,)] = S(0)
serlist.append(dict_)
pseries = serlist[0]
qseries = serlist[1]
indicial = d*(d - 1) + d*p0 + q0
frobdict = {}
for i in range(1, n + 1):
num = c*(m*pseries[(i,)] + qseries[(i,)])
for j in range(1, i):
sym = Symbol("C" + str(j))
num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)])
# Checking for cases when m1 - m2 is an integer. If num equals zero
# then a second Frobenius series solution cannot be found. If num is not zero
# then set constant as zero and proceed.
if m2 is not None and i == m2 - m:
if num:
return False
else:
frobdict[numsyms[i]] = S(0)
else:
frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i))
return frobdict
def _nth_linear_match(eq, func, order):
r"""
Matches a differential equation to the linear form:
.. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0
Returns a dict of order:coeff terms, where order is the order of the
derivative on each term, and coeff is the coefficient of that derivative.
The key ``-1`` holds the function `B(x)`. Returns ``None`` if the ODE is
not linear. This function assumes that ``func`` has already been checked
to be good.
Examples
========
>>> from sympy import Function, cos, sin
>>> from sympy.abc import x
>>> from sympy.solvers.ode import _nth_linear_match
>>> f = Function('f')
>>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) +
... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(x), f(x), 3)
{-1: x - sin(x), 0: -1, 1: cos(x) + 2, 2: x, 3: 1}
>>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) +
... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(f(x)), f(x), 3) == None
True
"""
x = func.args[0]
one_x = {x}
terms = {i: S.Zero for i in range(-1, order + 1)}
for i in Add.make_args(eq):
if not i.has(func):
terms[-1] += i
else:
c, f = i.as_independent(func)
if not ((isinstance(f, Derivative) and set(f.variables) == one_x) \
or f == func):
return None
else:
terms[len(f.args[1:])] += c
return terms
def ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear homogeneous variable-coefficient
Cauchy-Euler equidimensional ordinary differential equation.
This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `f(x) = x^r`, and deriving a characteristic equation
for `r`. When there are repeated roots, we include extra terms of the
form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration
constant, `r` is a root of the characteristic equation, and `k` ranges
over the multiplicity of `r`. In the cases where the roots are complex,
solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))`
are returned, based on expansions with Eulers formula. The general
solution is the sum of the terms found. If SymPy cannot find exact roots
to the characteristic equation, a
:py:class:`~sympy.polys.rootoftools.CRootOf` instance will be returned
instead.
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(4*x**2*f(x).diff(x, 2) + f(x), f(x),
... hint='nth_linear_euler_eq_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), sqrt(x)*(C1 + C2*log(x)))
Note that because this method does not involve integration, there is no
``nth_linear_euler_eq_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
corresponding to the fundamental solution set, for use with non
homogeneous solution methods like variation of parameters and
undetermined coefficients. Note that, though the solutions should be
linearly independent, this function does not explicitly check that. You
can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear
independence. Also, ``assert len(sollist) == order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x, 2)*x**2 - 4*f(x).diff(x)*x + 6*f(x)
>>> pprint(dsolve(eq, f(x),
... hint='nth_linear_euler_eq_homogeneous'))
2
f(x) = x *(C1 + C2*x)
References
==========
- http://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation
- C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and
Engineers", Springer 1999, pp. 12
# indirect doctest
"""
global collectterms
collectterms = []
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = S.Zero, Dummy('x')
for i in r.keys():
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
chareq = Poly(chareq, symbol)
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
constants.reverse()
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
gsol = S(0)
# We need keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
ln = log
for root, multiplicity in charroots.items():
for i in range(multiplicity):
if isinstance(root, RootOf):
gsol += (x**root) * constants.pop()
if multiplicity != 1:
raise ValueError("Value should be 1")
collectterms = [(0, root, 0)] + collectterms
elif root.is_real:
gsol += ln(x)**i*(x**root) * constants.pop()
collectterms = [(i, root, 0)] + collectterms
else:
reroot = re(root)
imroot = im(root)
gsol += ln(x)**i * (x**reroot) * (
constants.pop() * sin(abs(imroot)*ln(x))
+ constants.pop() * cos(imroot*ln(x)))
# Preserve ordering (multiplicity, real part, imaginary part)
# It will be assumed implicitly when constructing
# fundamental solution sets.
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'sol':
return Eq(f(x), gsol)
elif returns in ('list' 'both'):
# HOW TO TEST THIS CODE? (dsolve does not pass 'returns' through)
# Create a list of (hopefully) linearly independent solutions
gensols = []
# Keep track of when to use sin or cos for nonzero imroot
for i, reroot, imroot in collectterms:
if imroot == 0:
gensols.append(ln(x)**i*x**reroot)
else:
sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
if sin_form in gensols:
cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
gensols.append(cos_form)
else:
gensols.append(sin_form)
if returns == 'list':
return gensols
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using undetermined coefficients.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `x = exp(t)`, and deriving a characteristic equation
of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can
be then solved by nth_linear_constant_coeff_undetermined_coefficients if
g(exp(t)) has finite number of lineary independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
After replacement of x by exp(t), this method works by creating a trial function
from the expression and all of its linear independent derivatives and
substituting them into the original ODE. The coefficients for each term
will be a system of linear equations, which are be solved for and
substituted, giving the solution. If any of the trial functions are linearly
dependent on the solution to the homogeneous equation, they are multiplied
by sufficient `x` to make them linearly independent.
Examples
========
>>> from sympy import dsolve, Function, Derivative, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x)
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients').expand()
Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4)
"""
x = func.args[0]
f = func.func
r = match
chareq, eq, symbol = S.Zero, S.Zero, Dummy('x')
for i in r.keys():
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
for i in range(1,degree(Poly(chareq, symbol))+1):
eq += chareq.coeff(symbol**i)*diff(f(x), x, i)
if chareq.as_coeff_add(symbol)[0]:
eq += chareq.as_coeff_add(symbol)[0]*f(x)
e, re = posify(r[-1].subs(x, exp(x)))
eq += e.subs(re)
match = _nth_linear_match(eq, f(x), ode_order(eq, f(x)))
match['trialset'] = r['trialset']
return ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match).subs(x, log(x)).subs(f(log(x)), f(x)).expand()
def ode_nth_linear_euler_eq_nonhomogeneous_variation_of_parameters(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using variation of parameters.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by multiplying eq given below with `a_n x^{n}`
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left (x \right )}]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation, but sometimes SymPy cannot simplify the
Wronskian well enough to integrate it. If this method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, Derivative
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand()
Eq(f(x), C1*x + C2*x**2 + x**4/6)
"""
x = func.args[0]
f = func.func
r = match
gensol = ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='both')
match.update(gensol)
r[-1] = r[-1]/r[ode_order(eq, f(x))]
sol = _solve_variation_of_parameters(eq, func, order, match)
return Eq(f(x), r['sol'].rhs + (sol.rhs - r['sol'].rhs)*r[ode_order(eq, f(x))])
def ode_almost_linear(eq, func, order, match):
r"""
Solves an almost-linear differential equation.
The general form of an almost linear differential equation is
.. math:: f(x) g(y) y + k(x) l(y) + m(x) = 0
\text{where} l'(y) = g(y)\text{.}
This can be solved by substituting `l(y) = u(y)`. Making the given
substitution reduces it to a linear differential equation of the form `u'
+ P(x) u + Q(x) = 0`.
The general solution is
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x, y, n
>>> f, g, k, l = map(Function, ['f', 'g', 'k', 'l'])
>>> genform = Eq(f(x)*(l(y).diff(y)) + k(x)*l(y) + g(x))
>>> pprint(genform)
d
f(x)*--(l(y)) + g(x) + k(x)*l(y) = 0
dy
>>> pprint(dsolve(genform, hint = 'almost_linear'))
/ // -y*g(x) \\
| || -------- for k(x) = 0||
| || f(x) || -y*k(x)
| || || --------
| || y*k(x) || f(x)
l(y) = |C1 + |< ------ ||*e
| || f(x) ||
| ||-g(x)*e ||
| ||-------------- otherwise ||
| || k(x) ||
\ \\ //
See Also
========
:meth:`sympy.solvers.ode.ode_1st_linear`
Examples
========
>>> from sympy import Function, Derivative, pprint
>>> from sympy.solvers.ode import dsolve, classify_ode
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = x*d + x*f(x) + 1
>>> dsolve(eq, f(x), hint='almost_linear')
Eq(f(x), (C1 - Ei(x))*exp(-x))
>>> pprint(dsolve(eq, f(x), hint='almost_linear'))
-x
f(x) = (C1 - Ei(x))*e
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
# Since ode_1st_linear has already been implemented, and the
# coefficients have been modified to the required form in
# classify_ode, just passing eq, func, order and match to
# ode_1st_linear will give the required output.
return ode_1st_linear(eq, func, order, match)
def _linear_coeff_match(expr, func):
r"""
Helper function to match hint ``linear_coefficients``.
Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2
f(x) + c_2)` where the following conditions hold:
1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals;
2. `c_1` or `c_2` are not equal to zero;
3. `a_2 b_1 - a_1 b_2` is not equal to zero.
Return ``xarg``, ``yarg`` where
1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)`
2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)`
Examples
========
>>> from sympy import Function
>>> from sympy.abc import x
>>> from sympy.solvers.ode import _linear_coeff_match
>>> from sympy.functions.elementary.trigonometric import sin
>>> f = Function('f')
>>> _linear_coeff_match((
... (-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11)), f(x))
(1/9, 22/9)
>>> _linear_coeff_match(
... sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1)), f(x))
(19/27, 2/27)
>>> _linear_coeff_match(sin(f(x)/x), f(x))
"""
f = func.func
x = func.args[0]
def abc(eq):
r'''
Internal function of _linear_coeff_match
that returns Rationals a, b, c
if eq is a*x + b*f(x) + c, else None.
'''
eq = _mexpand(eq)
c = eq.as_independent(x, f(x), as_Add=True)[0]
if not c.is_Rational:
return
a = eq.coeff(x)
if not a.is_Rational:
return
b = eq.coeff(f(x))
if not b.is_Rational:
return
if eq == a*x + b*f(x) + c:
return a, b, c
def match(arg):
r'''
Internal function of _linear_coeff_match that returns Rationals a1,
b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x)
+ c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is
non-zero, else None.
'''
n, d = arg.together().as_numer_denom()
m = abc(n)
if m is not None:
a1, b1, c1 = m
m = abc(d)
if m is not None:
a2, b2, c2 = m
d = a2*b1 - a1*b2
if (c1 or c2) and d:
return a1, b1, c1, a2, b2, c2, d
m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and
len(fi.args) == 1 and not fi.args[0].is_Function] or {expr}
m1 = match(m.pop())
if m1 and all(match(mi) == m1 for mi in m):
a1, b1, c1, a2, b2, c2, denom = m1
return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom
def ode_linear_coefficients(eq, func, order, match):
r"""
Solves a differential equation with linear coefficients.
The general form of a differential equation with linear coefficients is
.. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y +
c_2}\!\right) = 0\text{,}
where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2
- a_2 b_1 \ne 0`.
This can be solved by substituting:
.. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2}
y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1
b_2}\text{.}
This substitution reduces the equation to a homogeneous differential
equation.
See Also
========
:meth:`sympy.solvers.ode.ode_1st_homogeneous_coeff_best`
:meth:`sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
:meth:`sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
Examples
========
>>> from sympy import Function, Derivative, pprint
>>> from sympy.solvers.ode import dsolve, classify_ode
>>> from sympy.abc import x
>>> f = Function('f')
>>> df = f(x).diff(x)
>>> eq = (x + f(x) + 1)*df + (f(x) - 6*x + 1)
>>> dsolve(eq, hint='linear_coefficients')
[Eq(f(x), -x - sqrt(C1 + 7*x**2) - 1), Eq(f(x), -x + sqrt(C1 + 7*x**2) - 1)]
>>> pprint(dsolve(eq, hint='linear_coefficients'))
___________ ___________
/ 2 / 2
[f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1]
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
return ode_1st_homogeneous_coeff_best(eq, func, order, match)
def ode_separable_reduced(eq, func, order, match):
r"""
Solves a differential equation that can be reduced to the separable form.
The general form of this equation is
.. math:: y' + (y/x) H(x^n y) = 0\text{}.
This can be solved by substituting `u(y) = x^n y`. The equation then
reduces to the separable form `\frac{u'}{u (\mathrm{power} - H(u))} -
\frac{1}{x} = 0`.
The general solution is:
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x, n
>>> f, g = map(Function, ['f', 'g'])
>>> genform = f(x).diff(x) + (f(x)/x)*g(x**n*f(x))
>>> pprint(genform)
/ n \
d f(x)*g\x *f(x)/
--(f(x)) + ---------------
dx x
>>> pprint(dsolve(genform, hint='separable_reduced'))
n
x *f(x)
/
|
| 1
| ------------ dy = C1 + log(x)
| y*(n - g(y))
|
/
See Also
========
:meth:`sympy.solvers.ode.ode_separable`
Examples
========
>>> from sympy import Function, Derivative, pprint
>>> from sympy.solvers.ode import dsolve, classify_ode
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = (x - x**2*f(x))*d - f(x)
>>> dsolve(eq, hint='separable_reduced')
[Eq(f(x), (-sqrt(C1*x**2 + 1) + 1)/x), Eq(f(x), (sqrt(C1*x**2 + 1) + 1)/x)]
>>> pprint(dsolve(eq, hint='separable_reduced'))
___________ ___________
/ 2 / 2
- \/ C1*x + 1 + 1 \/ C1*x + 1 + 1
[f(x) = --------------------, f(x) = ------------------]
x x
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
# Arguments are passed in a way so that they are coherent with the
# ode_separable function
x = func.args[0]
f = func.func
y = Dummy('y')
u = match['u'].subs(match['t'], y)
ycoeff = 1/(y*(match['power'] - u))
m1 = {y: 1, x: -1/x, 'coeff': 1}
m2 = {y: ycoeff, x: 1, 'coeff': 1}
r = {'m1': m1, 'm2': m2, 'y': y, 'hint': x**match['power']*f(x)}
return ode_separable(eq, func, order, r)
def ode_1st_power_series(eq, func, order, match):
r"""
The power series solution is a method which gives the Taylor series expansion
to the solution of a differential equation.
For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power
series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`.
The solution is given by
.. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!},
where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`.
To compute the values of the `F_{n}(x_{0},b)` the following algorithm is
followed, until the required number of terms are generated.
1. `F_1 = h(x_{0}, b)`
2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}`
Examples
========
>>> from sympy import Function, Derivative, pprint, exp
>>> from sympy.solvers.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = exp(x)*(f(x).diff(x)) - f(x)
>>> pprint(dsolve(eq, hint='1st_power_series'))
3 4 5
C1*x C1*x C1*x / 6\
f(x) = C1 + C1*x - ----- + ----- + ----- + O\x /
6 24 60
References
==========
- Travis W. Walker, Analytic power series technique for solving first-order
differential equations, p.p 17, 18
"""
x = func.args[0]
y = match['y']
f = func.func
h = -match[match['d']]/match[match['e']]
point = match.get('f0')
value = match.get('f0val')
terms = match.get('terms')
# First term
F = h
if not h:
return Eq(f(x), value)
# Initialisation
series = value
if terms > 1:
hc = h.subs({x: point, y: value})
if hc.has(oo) or hc.has(NaN) or hc.has(zoo):
# Derivative does not exist, not analytic
return Eq(f(x), oo)
elif hc:
series += hc*(x - point)
for factcount in range(2, terms):
Fnew = F.diff(x) + F.diff(y)*h
Fnewc = Fnew.subs({x: point, y: value})
# Same logic as above
if Fnewc.has(oo) or Fnewc.has(NaN) or Fnewc.has(-oo) or Fnewc.has(zoo):
return Eq(f(x), oo)
series += Fnewc*((x - point)**factcount)/factorial(factcount)
F = Fnew
series += Order(x**terms)
return Eq(f(x), series)
def ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='sol'):
r"""
Solves an `n`\th order linear homogeneous differential equation with
constant coefficients.
This is an equation of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = 0\text{.}
These equations can be solved in a general manner, by taking the roots of
the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m +
a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms,
for each where `C_n` is an arbitrary constant, `r` is a root of the
characteristic equation and `i` is one of each from 0 to the multiplicity
of the root - 1 (for example, a root 3 of multiplicity 2 would create the
terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded
for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`.
Complex roots always come in conjugate pairs in polynomials with real
coefficients, so the two roots will be represented (after simplifying the
constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`.
If SymPy cannot find exact roots to the characteristic equation, a
:py:class:`~sympy.polys.rootoftools.CRootOf` instance will be return
instead.
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C1*exp(x*CRootOf(_x**5 + 10*_x - 2, 0)) +
C2*exp(x*CRootOf(_x**5 + 10*_x - 2, 1)) +
C3*exp(x*CRootOf(_x**5 + 10*_x - 2, 2)) +
C4*exp(x*CRootOf(_x**5 + 10*_x - 2, 3)) +
C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 4)))
Note that because this method does not involve integration, there is no
``nth_linear_constant_coeff_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
for use with non homogeneous solution methods like variation of
parameters and undetermined coefficients. Note that, though the
solutions should be linearly independent, this function does not
explicitly check that. You can do ``assert simplify(wronskian(sollist))
!= 0`` to check for linear independence. Also, ``assert len(sollist) ==
order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) -
... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous'))
x -2*x
f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e
References
==========
- http://en.wikipedia.org/wiki/Linear_differential_equation section:
Nonhomogeneous_equation_with_constant_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 211
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = S.Zero, Dummy('x')
for i in r.keys():
if type(i) == str or i < 0:
pass
else:
chareq += r[i]*symbol**i
chareq = Poly(chareq, symbol)
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
chareq_is_complex = not all([i.is_real for i in chareq.all_coeffs()])
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
gsol = S(0)
# We need to keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
global collectterms
collectterms = []
gensols = []
conjugate_roots = [] # used to prevent double-use of conjugate roots
for root, multiplicity in charroots.items():
for i in range(multiplicity):
if isinstance(root, RootOf):
gensols.append(exp(root*x))
if multiplicity != 1:
raise ValueError("Value should be 1")
# This ordering is important
collectterms = [(0, root, 0)] + collectterms
else:
if chareq_is_complex:
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
continue
reroot = re(root)
imroot = im(root)
if imroot.has(atan2) and reroot.has(atan2):
# Remove this condition when re and im stop returning
# circular atan2 usages.
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
else:
if root in conjugate_roots:
collectterms = [(i, reroot, imroot)] + collectterms
continue
if imroot == 0:
gensols.append(x**i*exp(reroot*x))
collectterms = [(i, reroot, 0)] + collectterms
continue
conjugate_roots.append(conjugate(root))
gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x))
gensols.append(x**i*exp(reroot*x) * cos( imroot * x))
# This ordering is important
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'list':
return gensols
elif returns in ('sol' 'both'):
gsol = Add(*[i*j for (i,j) in zip(constants, gensols)])
if returns == 'sol':
return Eq(f(x), gsol)
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of undetermined coefficients.
This method works on differential equations of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = P(x)\text{,}
where `P(x)` is a function that has a finite number of linearly
independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
This method works by creating a trial function from the expression and all
of its linear independent derivatives and substituting them into the
original ODE. The coefficients for each term will be a system of linear
equations, which are be solved for and substituted, giving the solution.
If any of the trial functions are linearly dependent on the solution to
the homogeneous equation, they are multiplied by sufficient `x` to make
them linearly independent.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) -
... 4*exp(-x)*x**2 + cos(2*x), f(x),
... hint='nth_linear_constant_coeff_undetermined_coefficients'))
/ 4\
| x | -x 4*sin(2*x) 3*cos(2*x)
f(x) = |C1 + C2*x + --|*e - ---------- + ----------
\ 3 / 25 25
References
==========
- http://en.wikipedia.org/wiki/Method_of_undetermined_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 221
# indirect doctest
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_undetermined_coefficients(eq, func, order, match)
def _solve_undetermined_coefficients(eq, func, order, match):
r"""
Helper function for the method of undetermined coefficients.
See the
:py:meth:`~sympy.solvers.ode.ode_nth_linear_constant_coeff_undetermined_coefficients`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
``trialset``
The set of trial functions as returned by
``_undetermined_coefficients_match()['trialset']``.
"""
x = func.args[0]
f = func.func
r = match
coeffs = numbered_symbols('a', cls=Dummy)
coefflist = []
gensols = r['list']
gsol = r['sol']
trialset = r['trialset']
notneedset = set([])
newtrialset = set([])
global collectterms
if len(gensols) != order:
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation necessary to apply" +
" undetermined coefficients to " + str(eq) +
" (number of terms != order)")
usedsin = set([])
mult = 0 # The multiplicity of the root
getmult = True
for i, reroot, imroot in collectterms:
if getmult:
mult = i + 1
getmult = False
if i == 0:
getmult = True
if imroot:
# Alternate between sin and cos
if (i, reroot) in usedsin:
check = x**i*exp(reroot*x)*cos(imroot*x)
else:
check = x**i*exp(reroot*x)*sin(abs(imroot)*x)
usedsin.add((i, reroot))
else:
check = x**i*exp(reroot*x)
if check in trialset:
# If an element of the trial function is already part of the
# homogeneous solution, we need to multiply by sufficient x to
# make it linearly independent. We also don't need to bother
# checking for the coefficients on those elements, since we
# already know it will be 0.
while True:
if check*x**mult in trialset:
mult += 1
else:
break
trialset.add(check*x**mult)
notneedset.add(check)
newtrialset = trialset - notneedset
trialfunc = 0
for i in newtrialset:
c = next(coeffs)
coefflist.append(c)
trialfunc += c*i
eqs = sub_func_doit(eq, f(x), trialfunc)
coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1))))
eqs = _mexpand(eqs)
for i in Add.make_args(eqs):
s = separatevars(i, dict=True, symbols=[x])
coeffsdict[s[x]] += s['coeff']
coeffvals = solve(list(coeffsdict.values()), coefflist)
if not coeffvals:
raise NotImplementedError(
"Could not solve `%s` using the "
"method of undetermined coefficients "
"(unable to solve for coefficients)." % eq)
psol = trialfunc.subs(coeffvals)
return Eq(f(x), gsol.rhs + psol)
def _undetermined_coefficients_match(expr, x):
r"""
Returns a trial function match if undetermined coefficients can be applied
to ``expr``, and ``None`` otherwise.
A trial expression can be found for an expression for use with the method
of undetermined coefficients if the expression is an
additive/multiplicative combination of constants, polynomials in `x` (the
independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
`e^{a x}` terms (in other words, it has a finite number of linearly
independent derivatives).
Note that you may still need to multiply each term returned here by
sufficient `x` to make it linearly independent with the solutions to the
homogeneous equation.
This is intended for internal use by ``undetermined_coefficients`` hints.
SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
for example, you will need to manually convert `\sin^2(x)` into `[1 +
\cos(2 x)]/2` to properly apply the method of undetermined coefficients on
it.
Examples
========
>>> from sympy import log, exp
>>> from sympy.solvers.ode import _undetermined_coefficients_match
>>> from sympy.abc import x
>>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
{'test': True, 'trialset': set([x*exp(x), exp(-x), exp(x)])}
>>> _undetermined_coefficients_match(log(x), x)
{'test': False}
"""
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
retdict = {}
def _test_term(expr, x):
r"""
Test if ``expr`` fits the proper form for undetermined coefficients.
"""
if expr.is_Add:
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Mul:
if expr.has(sin, cos):
foundtrig = False
# Make sure that there is only one trig function in the args.
# See the docstring.
for i in expr.args:
if i.has(sin, cos):
if foundtrig:
return False
else:
foundtrig = True
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Function:
if expr.func in (sin, cos, exp):
if expr.args[0].match(a*x + b):
return True
else:
return False
else:
return False
elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
expr.exp >= 0:
return True
elif expr.is_Pow and expr.base.is_number:
if expr.exp.match(a*x + b):
return True
else:
return False
elif expr.is_Symbol or expr.is_number:
return True
else:
return False
def _get_trial_set(expr, x, exprs=set([])):
r"""
Returns a set of trial terms for undetermined coefficients.
The idea behind undetermined coefficients is that the terms expression
repeat themselves after a finite number of derivatives, except for the
coefficients (they are linearly dependent). So if we collect these,
we should have the terms of our trial function.
"""
def _remove_coefficient(expr, x):
r"""
Returns the expression without a coefficient.
Similar to expr.as_independent(x)[1], except it only works
multiplicatively.
"""
term = S.One
if expr.is_Mul:
for i in expr.args:
if i.has(x):
term *= i
elif expr.has(x):
term = expr
return term
expr = expand_mul(expr)
if expr.is_Add:
for term in expr.args:
if _remove_coefficient(term, x) in exprs:
pass
else:
exprs.add(_remove_coefficient(term, x))
exprs = exprs.union(_get_trial_set(term, x, exprs))
else:
term = _remove_coefficient(expr, x)
tmpset = exprs.union({term})
oldset = set([])
while tmpset != oldset:
# If you get stuck in this loop, then _test_term is probably
# broken
oldset = tmpset.copy()
expr = expr.diff(x)
term = _remove_coefficient(expr, x)
if term.is_Add:
tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
else:
tmpset.add(term)
exprs = tmpset
return exprs
retdict['test'] = _test_term(expr, x)
if retdict['test']:
# Try to generate a list of trial solutions that will have the
# undetermined coefficients. Note that if any of these are not linearly
# independent with any of the solutions to the homogeneous equation,
# then they will need to be multiplied by sufficient x to make them so.
# This function DOES NOT do that (it doesn't even look at the
# homogeneous equation).
retdict['trialset'] = _get_trial_set(expr, x)
return retdict
def ode_nth_linear_constant_coeff_variation_of_parameters(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of variation of parameters.
This method works on any differential equations of the form
.. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0
f(x) = P(x)\text{.}
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, P(x)]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation with constant coefficients, but sometimes
SymPy cannot simplify the Wronskian well enough to integrate it. If this
method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) +
... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x),
... hint='nth_linear_constant_coeff_variation_of_parameters'))
/ 3 \
| 2 x *(6*log(x) - 11)| x
f(x) = |C1 + C2*x + C3*x + ------------------|*e
\ 36 /
References
==========
- http://en.wikipedia.org/wiki/Variation_of_parameters
- http://planetmath.org/VariationOfParameters
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 233
# indirect doctest
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_variation_of_parameters(eq, func, order, match)
def _solve_variation_of_parameters(eq, func, order, match):
r"""
Helper function for the method of variation of parameters and nonhomogeneous euler eq.
See the
:py:meth:`~sympy.solvers.ode.ode_nth_linear_constant_coeff_variation_of_parameters`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
"""
x = func.args[0]
f = func.func
r = match
psol = 0
gensols = r['list']
gsol = r['sol']
wr = wronskian(gensols, x)
if r.get('simplify', True):
wr = simplify(wr) # We need much better simplification for
# some ODEs. See issue 4662, for example.
# To reduce commonly occuring sin(x)**2 + cos(x)**2 to 1
wr = trigsimp(wr, deep=True, recursive=True)
if not wr:
# The wronskian will be 0 iff the solutions are not linearly
# independent.
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation nessesary to apply " +
"variation of parameters to " + str(eq) + " (Wronskian == 0)")
if len(gensols) != order:
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation nessesary to apply " +
"variation of parameters to " +
str(eq) + " (number of terms != order)")
negoneterm = (-1)**(order)
for i in gensols:
psol += negoneterm*Integral(wronskian([sol for sol in gensols if sol != i], x)*r[-1]/wr, x)*i/r[order]
negoneterm *= -1
if r.get('simplify', True):
psol = simplify(psol)
psol = trigsimp(psol, deep=True)
return Eq(f(x), gsol.rhs + psol)
def ode_separable(eq, func, order, match):
r"""
Solves separable 1st order differential equations.
This is any differential equation that can be written as `P(y)
\tfrac{dy}{dx} = Q(x)`. The solution can then just be found by
rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`.
This hint uses :py:meth:`sympy.simplify.simplify.separatevars` as its back
end, so if a separable equation is not caught by this solver, it is most
likely the fault of that function.
:py:meth:`~sympy.simplify.simplify.separatevars` is
smart enough to do most expansion and factoring necessary to convert a
separable equation `F(x, y)` into the proper form `P(x)\cdot{}Q(y)`. The
general solution is::
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x
>>> a, b, c, d, f = map(Function, ['a', 'b', 'c', 'd', 'f'])
>>> genform = Eq(a(x)*b(f(x))*f(x).diff(x), c(x)*d(f(x)))
>>> pprint(genform)
d
a(x)*b(f(x))*--(f(x)) = c(x)*d(f(x))
dx
>>> pprint(dsolve(genform, f(x), hint='separable_Integral'))
f(x)
/ /
| |
| b(y) | c(x)
| ---- dy = C1 + | ---- dx
| d(y) | a(x)
| |
/ /
Examples
========
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(Eq(f(x)*f(x).diff(x) + x, 3*x*f(x)**2), f(x),
... hint='separable', simplify=False))
/ 2 \ 2
log\3*f (x) - 1/ x
---------------- = C1 + --
6 2
References
==========
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 52
# indirect doctest
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
r = match # {'m1':m1, 'm2':m2, 'y':y}
u = r.get('hint', f(x)) # get u from separable_reduced else get f(x)
return Eq(Integral(r['m2']['coeff']*r['m2'][r['y']]/r['m1'][r['y']],
(r['y'], None, u)), Integral(-r['m1']['coeff']*r['m1'][x]/
r['m2'][x], x) + C1)
def checkinfsol(eq, infinitesimals, func=None, order=None):
r"""
This function is used to check if the given infinitesimals are the
actual infinitesimals of the given first order differential equation.
This method is specific to the Lie Group Solver of ODEs.
As of now, it simply checks, by substituting the infinitesimals in the
partial differential equation.
.. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x}\right)*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0
where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}`
The infinitesimals should be given in the form of a list of dicts
``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the
output of the function infinitesimals. It returns a list
of values of the form ``[(True/False, sol)]`` where ``sol`` is the value
obtained after substituting the infinitesimals in the PDE. If it
is ``True``, then ``sol`` would be 0.
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Lie groups solver has been implemented "
"only for first order differential equations")
else:
df = func.diff(x)
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy('y')
h = h.subs(func, y)
xi = Function('xi')(x, y)
eta = Function('eta')(x, y)
dxi = Function('xi')(x, func)
deta = Function('eta')(x, func)
pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h -
(xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)))
soltup = []
for sol in infinitesimals:
tsol = {xi: S(sol[dxi]).subs(func, y),
eta: S(sol[deta]).subs(func, y)}
sol = simplify(pde.subs(tsol).doit())
if sol:
soltup.append((False, sol.subs(y, func)))
else:
soltup.append((True, 0))
return soltup
def ode_lie_group(eq, func, order, match):
r"""
This hint implements the Lie group method of solving first order differential
equations. The aim is to convert the given differential equation from the
given coordinate given system into another coordinate system where it becomes
invariant under the one-parameter Lie group of translations. The converted ODE is
quadrature and can be solved easily. It makes use of the
:py:meth:`sympy.solvers.ode.infinitesimals` function which returns the
infinitesimals of the transformation.
The coordinates `r` and `s` can be found by solving the following Partial
Differential Equations.
.. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y}
= 0
.. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y}
= 1
The differential equation becomes separable in the new coordinate system
.. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} +
h(x, y)\frac{\partial s}{\partial y}}{
\frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}}
After finding the solution by integration, it is then converted back to the original
coordinate system by subsituting `r` and `s` in terms of `x` and `y` again.
Examples
========
>>> from sympy import Function, dsolve, Eq, exp, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x),
... hint='lie_group'))
/ 2\ 2
| x | -x
f(x) = |C1 + --|*e
\ 2 /
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
heuristics = lie_heuristics
inf = {}
f = func.func
x = func.args[0]
df = func.diff(x)
xi = Function("xi")
eta = Function("eta")
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
xis = match.pop('xi')
etas = match.pop('eta')
if match:
h = -simplify(match[match['d']]/match[match['e']])
y = match['y']
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Unable to solve the differential equation " +
str(eq) + " by the lie group method")
else:
y = Dummy("y")
h = sol[0].subs(func, y)
if xis is not None and etas is not None:
inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}]
if not checkinfsol(eq, inf, func=f(x), order=1)[0][0]:
raise ValueError("The given infinitesimals xi and eta"
" are not the infinitesimals to the given equation")
else:
heuristics = ["user_defined"]
match = {'h': h, 'y': y}
# This is done so that if:
# a] solve raises a NotImplementedError.
# b] any heuristic raises a ValueError
# another heuristic can be used.
tempsol = [] # Used by solve below
for heuristic in heuristics:
try:
if not inf:
inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match)
except ValueError:
continue
else:
for infsim in inf:
xiinf = (infsim[xi(x, func)]).subs(func, y)
etainf = (infsim[eta(x, func)]).subs(func, y)
# This condition creates recursion while using pdsolve.
# Since the first step while solving a PDE of form
# a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0
# is to solve the ODE dy/dx = b/a
if simplify(etainf/xiinf) == h:
continue
rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf
r = pdsolve(rpde, func=f(x, y)).rhs
s = pdsolve(rpde - 1, func=f(x, y)).rhs
newcoord = [_lie_group_remove(coord) for coord in [r, s]]
r = Dummy("r")
s = Dummy("s")
C1 = Symbol("C1")
rcoord = newcoord[0]
scoord = newcoord[-1]
try:
sol = solve([r - rcoord, s - scoord], x, y, dict=True)
except NotImplementedError:
continue
else:
sol = sol[0]
xsub = sol[x]
ysub = sol[y]
num = simplify(scoord.diff(x) + scoord.diff(y)*h)
denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h)
if num and denom:
diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)]))
sep = separatevars(diffeq, symbols=[r, s], dict=True)
if sep:
# Trying to separate, r and s coordinates
deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r)
# Substituting and reverting back to original coordinates
deq = deq.subs([(r, rcoord), (s, scoord)])
try:
sdeq = solve(deq, y)
except NotImplementedError:
tempsol.append(deq)
else:
if len(sdeq) == 1:
return Eq(f(x), sdeq.pop())
else:
return [Eq(f(x), sol) for sol in sdeq]
elif denom: # (ds/dr) is zero which means s is constant
return Eq(f(x), solve(scoord - C1, y)[0])
elif num: # (dr/ds) is zero which means r is constant
return Eq(f(x), solve(rcoord - C1, y)[0])
# If nothing works, return solution as it is, without solving for y
if tempsol:
if len(tempsol) == 1:
return Eq(tempsol.pop().subs(y, f(x)), 0)
else:
return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol]
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the lie group method")
def _lie_group_remove(coords):
r"""
This function is strictly meant for internal use by the Lie group ODE solving
method. It replaces arbitrary functions returned by pdsolve with either 0 or 1 or the
args of the arbitrary function.
The algorithm used is:
1] If coords is an instance of an Undefined Function, then the args are returned
2] If the arbitrary function is present in an Add object, it is replaced by zero.
3] If the arbitrary function is present in an Mul object, it is replaced by one.
4] If coords has no Undefined Function, it is returned as it is.
Examples
========
>>> from sympy.solvers.ode import _lie_group_remove
>>> from sympy import Function
>>> from sympy.abc import x, y
>>> F = Function("F")
>>> eq = x**2*y
>>> _lie_group_remove(eq)
x**2*y
>>> eq = F(x**2*y)
>>> _lie_group_remove(eq)
x**2*y
>>> eq = y**2*x + F(x**3)
>>> _lie_group_remove(eq)
x*y**2
>>> eq = (F(x**3) + y)*x**4
>>> _lie_group_remove(eq)
x**4*y
"""
if isinstance(coords, AppliedUndef):
return coords.args[0]
elif coords.is_Add:
subfunc = coords.atoms(AppliedUndef)
if subfunc:
for func in subfunc:
coords = coords.subs(func, 0)
return coords
elif coords.is_Pow:
base, expr = coords.as_base_exp()
base = _lie_group_remove(base)
expr = _lie_group_remove(expr)
return base**expr
elif coords.is_Mul:
mulargs = []
coordargs = coords.args
for arg in coordargs:
if not isinstance(coords, AppliedUndef):
mulargs.append(_lie_group_remove(arg))
return Mul(*mulargs)
return coords
def infinitesimals(eq, func=None, order=None, hint='default', match=None):
r"""
The infinitesimal functions of an ordinary differential equation, `\xi(x,y)`
and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations
for which the differential equation is invariant. So, the ODE `y'=f(x,y)`
would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`,
`y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`.
A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group
becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`.
They are tangents to the coordinate curves of the new system.
Consider the transformation `(x, y) \to (X, Y)` such that the
differential equation remains invariant. `\xi` and `\eta` are the tangents to
the transformed coordinates `X` and `Y`, at `\varepsilon=0`.
.. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \xi,
\left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \eta,
The infinitesimals can be found by solving the following PDE:
>>> from sympy import Function, diff, Eq, pprint
>>> from sympy.abc import x, y
>>> xi, eta, h = map(Function, ['xi', 'eta', 'h'])
>>> h = h(x, y) # dy/dx = h
>>> eta = eta(x, y)
>>> xi = xi(x, y)
>>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h
... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0)
>>> pprint(genform)
/d d \ d 2 d
|--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(x
\dy dx / dy dy
<BLANKLINE>
d d
i(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0
dx dx
Solving the above mentioned PDE is not trivial, and can be solved only by
making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an
infinitesimal is found, the attempt to find more heuristics stops. This is done to
optimise the speed of solving the differential equation. If a list of all the
infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives
the complete list of infinitesimals. If the infinitesimals for a particular
heuristic needs to be found, it can be passed as a flag to ``hint``.
Examples
========
>>> from sympy import Function, diff
>>> from sympy.solvers.ode import infinitesimals
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x) - x**2*f(x)
>>> infinitesimals(eq)
[{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}]
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Infinitesimals for only "
"first order ODE's have been implemented")
else:
df = func.diff(x)
# Matching differential equation of the form a*df + b
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
if match: # Used by lie_group hint
h = match['h']
y = match['y']
else:
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy("y")
h = h.subs(func, y)
u = Dummy("u")
hx = h.diff(x)
hy = h.diff(y)
hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE
match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv}
if hint == 'all':
xieta = []
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
inflist = function(match, comp=True)
if inflist:
xieta.extend([inf for inf in inflist if inf not in xieta])
if xieta:
return xieta
else:
raise NotImplementedError("Infinitesimals could not be found for "
"the given ODE")
elif hint == 'default':
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
xieta = function(match, comp=False)
if xieta:
return xieta
raise NotImplementedError("Infinitesimals could not be found for"
" the given ODE")
elif hint not in lie_heuristics:
raise ValueError("Heuristic not recognized: " + hint)
else:
function = globals()['lie_heuristic_' + hint]
xieta = function(match, comp=True)
if xieta:
return xieta
else:
raise ValueError("Infinitesimals could not be found using the"
" given heuristic")
def lie_heuristic_abaco1_simple(match, comp=False):
r"""
The first heuristic uses the following four sets of
assumptions on `\xi` and `\eta`
.. math:: \xi = 0, \eta = f(x)
.. math:: \xi = 0, \eta = f(y)
.. math:: \xi = f(x), \eta = 0
.. math:: \xi = f(y), \eta = 0
The success of this heuristic is determined by algebraic factorisation.
For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE
.. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x})*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0
reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0`
If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually
be integrated easily. A similar idea is applied to the other 3 assumptions as well.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
xieta = []
y = match['y']
h = match['h']
func = match['func']
x = func.args[0]
hx = match['hx']
hy = match['hy']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
hysym = hy.free_symbols
if y not in hysym:
try:
fx = exp(integrate(hy, x))
except NotImplementedError:
pass
else:
inf = {xi: S(0), eta: fx}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = hy/h
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: S(0), eta: fy.subs(y, func)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/h
facsym = factor.free_symbols
if y not in facsym:
try:
fx = exp(integrate(factor, x))
except NotImplementedError:
pass
else:
inf = {xi: fx, eta: S(0)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/(h**2)
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: fy.subs(y, func), eta: S(0)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco1_product(match, comp=False):
r"""
The second heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x)*g(y)
.. math:: \eta = f(x)*g(y), \xi = 0
The first assumption of this heuristic holds good if
`\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is
separable in `x` and `y`, then the separated factors containing `x`
is `f(x)`, and `g(y)` is obtained by
.. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy}
provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function
of `y` only.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisifes. After obtaining `f(x)` and `g(y)`, the coordinates are again
interchanged, to get `\eta` as `f(x)*g(y)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
y = match['y']
h = match['h']
hinv = match['hinv']
func = match['func']
x = func.args[0]
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*h)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
inf = {eta: S(0), xi: (fx*gy).subs(y, func)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
u1 = Dummy("u1")
inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*hinv)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
etaval = fx*gy
etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y)
inf = {eta: etaval.subs(y, func), xi: S(0)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_bivariate(match, comp=False):
r"""
The third heuristic assumes the infinitesimals `\xi` and `\eta`
to be bi-variate polynomials in `x` and `y`. The assumption made here
for the logic below is that `h` is a rational function in `x` and `y`
though that may not be necessary for the infinitesimals to be
bivariate polynomials. The coefficients of the infinitesimals
are found out by substituting them in the PDE and grouping similar terms
that are polynomials and since they form a linear system, solve and check
for non trivial solutions. The degree of the assumed bivariates
are increased till a certain maximum value.
References
==========
- Lie Groups and Differential Equations
pp. 327 - pp. 329
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
# The maximum degree that the infinitesimals can take is
# calculated by this technique.
etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid")
ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy
num, denom = cancel(ipde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
deta = Function('deta')(x, y)
dxi = Function('dxi')(x, y)
ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2
- dxi*hx - deta*hy)
xieq = Symbol("xi0")
etaeq = Symbol("eta0")
for i in range(deg + 1):
if i:
xieq += Add(*[
Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
etaeq += Add(*[
Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom()
pden = expand(pden)
# If the individual terms are monomials, the coefficients
# are grouped
if pden.is_polynomial(x, y) and pden.is_Add:
polyy = Poly(pden, x, y).as_dict()
if polyy:
symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y}
soldict = solve(polyy.values(), *symset)
if isinstance(soldict, list):
soldict = soldict[0]
if any(x for x in soldict.values()):
xired = xieq.subs(soldict)
etared = etaeq.subs(soldict)
# Scaling is done by substituting one for the parameters
# This can be any number except zero.
dict_ = dict((sym, 1) for sym in symset)
inf = {eta: etared.subs(dict_).subs(y, func),
xi: xired.subs(dict_).subs(y, func)}
return [inf]
def lie_heuristic_chi(match, comp=False):
r"""
The aim of the fourth heuristic is to find the function `\chi(x, y)`
that satisifies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx}
- \frac{\partial h}{\partial y}\chi = 0`.
This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intution,
`h` should be a rational function in `x` and `y`. The method used here is
to substitute a general binomial for `\chi` up to a certain maximum degree
is reached. The coefficients of the polynomials, are calculated by by collecting
terms of the same order in `x` and `y`.
After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to
determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h`
which would give `-\xi` as the quotient and `\eta` as the remainder.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
schi, schix, schiy = symbols("schi, schix, schiy")
cpde = schix + h*schiy - hy*schi
num, denom = cancel(cpde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
chi = Function('chi')(x, y)
chix = chi.diff(x)
chiy = chi.diff(y)
cpde = chix + h*chiy - hy*chi
chieq = Symbol("chi")
for i in range(1, deg + 1):
chieq += Add(*[
Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom()
cnum = expand(cnum)
if cnum.is_polynomial(x, y) and cnum.is_Add:
cpoly = Poly(cnum, x, y).as_dict()
if cpoly:
solsyms = chieq.free_symbols - {x, y}
soldict = solve(cpoly.values(), *solsyms)
if isinstance(soldict, list):
soldict = soldict[0]
if any(x for x in soldict.values()):
chieq = chieq.subs(soldict)
dict_ = dict((sym, 1) for sym in solsyms)
chieq = chieq.subs(dict_)
# After finding chi, the main aim is to find out
# eta, xi by the equation eta = xi*h + chi
# One method to set xi, would be rearranging it to
# (eta/h) - xi = (chi/h). This would mean dividing
# chi by h would give -xi as the quotient and eta
# as the remainder. Thanks to Sean Vig for suggesting
# this method.
xic, etac = div(chieq, h)
inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)}
return [inf]
def lie_heuristic_function_sum(match, comp=False):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x) + g(y)
.. math:: \eta = f(x) + g(y), \xi = 0
The first assumption of this heuristic holds good if
.. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{
\partial x^{2}}(h^{-1}))^{-1}]
is separable in `x` and `y`,
1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`.
From this `g(y)` can be determined.
2. The separated factors containing `x` is `f''(x)`.
3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals
`\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first
assumption satisifes. After obtaining `f(x)` and `g(y)`, the coordinates
are again interchanged, to get `\eta` as `f(x) + g(y)`.
For both assumptions, the constant factors are separated among `g(y)`
and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that
obtained from 2]. If not possible, then this heuristic fails.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
for odefac in [h, hinv]:
factor = odefac*((1/odefac).diff(x, 2))
sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y])
if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y):
k = Dummy("k")
try:
gy = k*integrate(sep[y], y)
except NotImplementedError:
pass
else:
fdd = 1/(k*sep[x]*sep['coeff'])
fx = simplify(fdd/factor - gy)
check = simplify(fx.diff(x, 2) - fdd)
if fx:
if not check:
fx = fx.subs(k, 1)
gy = (gy/k)
else:
sol = solve(check, k)
if sol:
sol = sol[0]
fx = fx.subs(k, sol)
gy = (gy/k)*sol
else:
continue
if odefac == hinv: # Inverse ODE
fx = fx.subs(x, y)
gy = gy.subs(y, x)
etaval = factor_terms(fx + gy)
if etaval.is_Mul:
etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)])
if odefac == hinv: # Inverse ODE
inf = {eta: etaval.subs(y, func), xi : S(0)}
else:
inf = {xi: etaval.subs(y, func), eta : S(0)}
if not comp:
return [inf]
else:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco2_similar(match, comp=False):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = g(x), \xi = f(x)
.. math:: \eta = f(y), \xi = g(y)
For the first assumption,
1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{
\partial yy}}` is calculated. Let us say this value is A
2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{
\frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)`
and `A(x)*f(x)` gives `g(x)`
3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{
\partial Y}} = \gamma` is calculated. If
a] `\gamma` is a function of `x` alone
b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{
\partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone.
then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)`
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisifes. After obtaining `f(x)` and `g(x)`, the coordinates are again
interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
factor = cancel(h.diff(y)/h.diff(y, 2))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{xi: tau, eta: gx}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{xi: tau, eta: gx}]
factor = cancel(hinv.diff(y)/hinv.diff(y, 2))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/(
hinv + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
def lie_heuristic_abaco2_unique_unknown(match, comp=False):
r"""
This heuristic assumes the presence of unknown functions or known functions
with non-integer powers.
1. A list of all functions and non-integer powers containing x and y
2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{
\frac{\partial f}{\partial x}} = R`
If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then
a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return
`\xi` and `\eta`
b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE.
If yes, then return `\xi` and `\eta`
If not, then check if
a] :math:`\xi = -R,\eta = 1`
b] :math:`\xi = 1, \eta = -\frac{1}{R}`
are solutions.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
funclist = []
for atom in h.atoms(Pow):
base, exp = atom.as_base_exp()
if base.has(x) and base.has(y):
if not exp.is_Integer:
funclist.append(atom)
for function in h.atoms(AppliedUndef):
syms = function.free_symbols
if x in syms and y in syms:
funclist.append(function)
for f in funclist:
frac = cancel(f.diff(y)/f.diff(x))
sep = separatevars(frac, dict=True, symbols=[x, y])
if sep and sep['coeff']:
xitry1 = sep[x]
etatry1 = -1/(sep[y]*sep['coeff'])
pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy
if not simplify(pde1):
return [{xi: xitry1, eta: etatry1.subs(y, func)}]
xitry2 = 1/etatry1
etatry2 = 1/xitry1
pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy
if not simplify(expand(pde2)):
return [{xi: xitry2.subs(y, func), eta: etatry2}]
else:
etatry = -1/frac
pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy
if not simplify(pde):
return [{xi: S(1), eta: etatry.subs(y, func)}]
xitry = -frac
pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy
if not simplify(expand(pde)):
return [{xi: xitry.subs(y, func), eta: S(1)}]
def lie_heuristic_abaco2_unique_general(match, comp=False):
r"""
This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)`
without making any assumptions on `h`.
The complete sequence of steps is given in the paper mentioned below.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
C = S(0)
A = hx.diff(y)
B = hy.diff(y) + hy**2
C = hx.diff(x) - hx**2
if not (A and B and C):
return
Ax = A.diff(x)
Ay = A.diff(y)
Axy = Ax.diff(y)
Axx = Ax.diff(x)
Ayy = Ay.diff(y)
D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay
if not D:
E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A)
if E1:
E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
if not E2:
E3 = simplify(
E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4)
if not E3:
etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1))
if x not in etaval:
try:
etaval = exp(integrate(etaval, y))
except NotImplementedError:
pass
else:
xival = -4*A**3*etaval/E1
if y not in xival:
return [{xi: xival, eta: etaval.subs(y, func)}]
else:
E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
if E1:
E2 = simplify(
4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2))
if not E2:
E3 = simplify(
-(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D +
(A*hx - 3*Ax)*E1)*E1)
if not E3:
etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D))
if x not in etaval:
try:
etaval = exp(integrate(etaval, y))
except NotImplementedError:
pass
else:
xival = -E1*etaval/D
if y not in xival:
return [{xi: xival, eta: etaval.subs(y, func)}]
def lie_heuristic_linear(match, comp=False):
r"""
This heuristic assumes
1. `\xi = ax + by + c` and
2. `\eta = fx + gy + h`
After substituting the following assumptions in the determining PDE, it
reduces to
.. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x}
- (fx + gy + c)\frac{\partial h}{\partial y}
Solving the reduced PDE obtained, using the method of characteristics, becomes
impractical. The method followed is grouping similar terms and solving the system
of linear equations obtained. The difference between the bivariate heuristic is that
`h` need not be a rational function in this case.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
coeffdict = {}
symbols = numbered_symbols("c", cls=Dummy)
symlist = [next(symbols) for i in islice(symbols, 6)]
C0, C1, C2, C3, C4, C5 = symlist
pde = C3 + (C4 - C0)*h -(C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2
pde, denom = pde.as_numer_denom()
pde = powsimp(expand(pde))
if pde.is_Add:
terms = pde.args
for term in terms:
if term.is_Mul:
rem = Mul(*[m for m in term.args if not m.has(x, y)])
xypart = term/rem
if xypart not in coeffdict:
coeffdict[xypart] = rem
else:
coeffdict[xypart] += rem
else:
if term not in coeffdict:
coeffdict[term] = S(1)
else:
coeffdict[term] += S(1)
sollist = coeffdict.values()
soldict = solve(sollist, symlist)
if soldict:
if isinstance(soldict, list):
soldict = soldict[0]
subval = soldict.values()
if any(t for t in subval):
onedict = dict(zip(symlist, [1]*6))
xival = C0*x + C1*func + C2
etaval = C3*x + C4*func + C5
xival = xival.subs(soldict)
etaval = etaval.subs(soldict)
xival = xival.subs(onedict)
etaval = etaval.subs(onedict)
return [{xi: xival, eta: etaval}]
def sysode_linear_2eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r = dict()
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
# for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1)
# and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2)
r['a'] = -fc[0,x(t),0]/fc[0,x(t),1]
r['c'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['b'] = -fc[0,y(t),0]/fc[0,x(t),1]
r['d'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S(0),S(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
r['k1'] = forcing[0]
r['k2'] = forcing[1]
else:
raise NotImplementedError("Only homogeneous problems are supported" +
" (and constant inhomogeneity)")
if match_['type_of_equation'] == 'type1':
sol = _linear_2eq_order1_type1(x, y, t, r, eq)
if match_['type_of_equation'] == 'type2':
gsol = _linear_2eq_order1_type1(x, y, t, r, eq)
psol = _linear_2eq_order1_type2(x, y, t, r, eq)
sol = [Eq(x(t), gsol[0].rhs+psol[0]), Eq(y(t), gsol[1].rhs+psol[1])]
if match_['type_of_equation'] == 'type3':
sol = _linear_2eq_order1_type3(x, y, t, r, eq)
if match_['type_of_equation'] == 'type4':
sol = _linear_2eq_order1_type4(x, y, t, r, eq)
if match_['type_of_equation'] == 'type5':
sol = _linear_2eq_order1_type5(x, y, t, r, eq)
if match_['type_of_equation'] == 'type6':
sol = _linear_2eq_order1_type6(x, y, t, r, eq)
if match_['type_of_equation'] == 'type7':
sol = _linear_2eq_order1_type7(x, y, t, r, eq)
return sol
def _linear_2eq_order1_type1(x, y, t, r, eq):
r"""
It is classified under system of two linear homogeneous first-order constant-coefficient
ordinary differential equations.
The equations which come under this type are
.. math:: x' = ax + by,
.. math:: y' = cx + dy
The characteristics equation is written as
.. math:: \lambda^{2} + (a+d) \lambda + ad - bc = 0
and its discriminant is `D = (a-d)^{2} + 4bc`. There are several cases
1. Case when `ad - bc \neq 0`. The origin of coordinates, `x = y = 0`,
is the only stationary point; it is
- a node if `D = 0`
- a node if `D > 0` and `ad - bc > 0`
- a saddle if `D > 0` and `ad - bc < 0`
- a focus if `D < 0` and `a + d \neq 0`
- a centre if `D < 0` and `a + d \neq 0`.
1.1. If `D > 0`. The characteristic equation has two distinct real roots
`\lambda_1` and `\lambda_ 2` . The general solution of the system in question is expressed as
.. math:: x = C_1 b e^{\lambda_1 t} + C_2 b e^{\lambda_2 t}
.. math:: y = C_1 (\lambda_1 - a) e^{\lambda_1 t} + C_2 (\lambda_2 - a) e^{\lambda_2 t}
where `C_1` and `C_2` being arbitary constants
1.2. If `D < 0`. The characteristics equation has two conjugate
roots, `\lambda_1 = \sigma + i \beta` and `\lambda_2 = \sigma - i \beta`.
The general solution of the system is given by
.. math:: x = b e^{\sigma t} (C_1 \sin(\beta t) + C_2 \cos(\beta t))
.. math:: y = e^{\sigma t} ([(\sigma - a) C_1 - \beta C_2] \sin(\beta t) + [\beta C_1 + (\sigma - a) C_2 \cos(\beta t)])
1.3. If `D = 0` and `a \neq d`. The characteristic equation has
two equal roots, `\lambda_1 = \lambda_2`. The general solution of the system is written as
.. math:: x = 2b (C_1 + \frac{C_2}{a-d} + C_2 t) e^{\frac{a+d}{2} t}
.. math:: y = [(d - a) C_1 + C_2 + (d - a) C_2 t] e^{\frac{a+d}{2} t}
1.4. If `D = 0` and `a = d \neq 0` and `b = 0`
.. math:: x = C_1 e^{a t} , y = (c C_1 t + C_2) e^{a t}
1.5. If `D = 0` and `a = d \neq 0` and `c = 0`
.. math:: x = (b C_1 t + C_2) e^{a t} , y = C_1 e^{a t}
2. Case when `ad - bc = 0` and `a^{2} + b^{2} > 0`. The whole straight
line `ax + by = 0` consists of singular points. The orginal system of differential
equaitons can be rewritten as
.. math:: x' = ax + by , y' = k (ax + by)
2.1 If `a + bk \neq 0`, solution will be
.. math:: x = b C_1 + C_2 e^{(a + bk) t} , y = -a C_1 + k C_2 e^{(a + bk) t}
2.2 If `a + bk = 0`, solution will be
.. math:: x = C_1 (bk t - 1) + b C_2 t , y = k^{2} b C_1 t + (b k^{2} t + 1) C_2
"""
# FIXME: at least some of these can fail to give two linearly
# independent solutions e.g., because they make assumptions about
# zero/nonzero of certain coefficients. I've "fixed" one and
# raised NotImplementedError in another. I think this should probably
# just be re-written in terms of eigenvectors...
l = Dummy('l')
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
l1 = rootof(l**2 - (r['a']+r['d'])*l + r['a']*r['d'] - r['b']*r['c'], l, 0)
l2 = rootof(l**2 - (r['a']+r['d'])*l + r['a']*r['d'] - r['b']*r['c'], l, 1)
D = (r['a'] - r['d'])**2 + 4*r['b']*r['c']
if (r['a']*r['d'] - r['b']*r['c']) != 0:
if D > 0:
if r['b'].is_zero:
# tempting to use this in all cases, but does not guarantee linearly independent eigenvectors
gsol1 = C1*(l1 - r['d'] + r['b'])*exp(l1*t) + C2*(l2 - r['d'] + r['b'])*exp(l2*t)
gsol2 = C1*(l1 - r['a'] + r['c'])*exp(l1*t) + C2*(l2 - r['a'] + r['c'])*exp(l2*t)
else:
gsol1 = C1*r['b']*exp(l1*t) + C2*r['b']*exp(l2*t)
gsol2 = C1*(l1 - r['a'])*exp(l1*t) + C2*(l2 - r['a'])*exp(l2*t)
if D < 0:
sigma = re(l1)
if im(l1).is_positive:
beta = im(l1)
else:
beta = im(l2)
if r['b'].is_zero:
raise NotImplementedError('b == 0 case not implemented')
gsol1 = r['b']*exp(sigma*t)*(C1*sin(beta*t)+C2*cos(beta*t))
gsol2 = exp(sigma*t)*(((C1*(sigma-r['a'])-C2*beta)*sin(beta*t)+(C1*beta+(sigma-r['a'])*C2)*cos(beta*t)))
if D == 0:
if r['a']!=r['d']:
gsol1 = 2*r['b']*(C1 + C2/(r['a']-r['d'])+C2*t)*exp((r['a']+r['d'])*t/2)
gsol2 = ((r['d']-r['a'])*C1+C2+(r['d']-r['a'])*C2*t)*exp((r['a']+r['d'])*t/2)
if r['a']==r['d'] and r['a']!=0 and r['b']==0:
gsol1 = C1*exp(r['a']*t)
gsol2 = (r['c']*C1*t+C2)*exp(r['a']*t)
if r['a']==r['d'] and r['a']!=0 and r['c']==0:
gsol1 = (r['b']*C1*t+C2)*exp(r['a']*t)
gsol2 = C1*exp(r['a']*t)
elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2+r['b']**2) > 0:
k = r['c']/r['a']
if r['a']+r['b']*k != 0:
gsol1 = r['b']*C1 + C2*exp((r['a']+r['b']*k)*t)
gsol2 = -r['a']*C1 + k*C2*exp((r['a']+r['b']*k)*t)
else:
gsol1 = C1*(r['b']*k*t-1)+r['b']*C2*t
gsol2 = k**2*r['b']*C1*t+(r['b']*k**2*t+1)*C2
return [Eq(x(t), gsol1), Eq(y(t), gsol2)]
def _linear_2eq_order1_type2(x, y, t, r, eq):
r"""
The equations of this type are
.. math:: x' = ax + by + k1 , y' = cx + dy + k2
The general solution of this system is given by sum of its particular solution and the
general solution of the corresponding homogeneous system is obtained from type1.
1. When `ad - bc \neq 0`. The particular solution will be
`x = x_0` and `y = y_0` where `x_0` and `y_0` are determined by solving linear system of equations
.. math:: a x_0 + b y_0 + k1 = 0 , c x_0 + d y_0 + k2 = 0
2. When `ad - bc = 0` and `a^{2} + b^{2} > 0`. In this case, the system of equation becomes
.. math:: x' = ax + by + k_1 , y' = k (ax + by) + k_2
2.1 If `\sigma = a + bk \neq 0`, particular solution is given by
.. math:: x = b \sigma^{-1} (c_1 k - c_2) t - \sigma^{-2} (a c_1 + b c_2)
.. math:: y = kx + (c_2 - c_1 k) t
2.2 If `\sigma = a + bk = 0`, particular solution is given by
.. math:: x = \frac{1}{2} b (c_2 - c_1 k) t^{2} + c_1 t
.. math:: y = kx + (c_2 - c_1 k) t
"""
r['k1'] = -r['k1']; r['k2'] = -r['k2']
if (r['a']*r['d'] - r['b']*r['c']) != 0:
x0, y0 = symbols('x0, y0', cls=Dummy)
sol = solve((r['a']*x0+r['b']*y0+r['k1'], r['c']*x0+r['d']*y0+r['k2']), x0, y0)
psol = [sol[x0], sol[y0]]
elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2+r['b']**2) > 0:
k = r['c']/r['a']
sigma = r['a'] + r['b']*k
if sigma != 0:
sol1 = r['b']*sigma**-1*(r['k1']*k-r['k2'])*t - sigma**-2*(r['a']*r['k1']+r['b']*r['k2'])
sol2 = k*sol1 + (r['k2']-r['k1']*k)*t
else:
# FIXME: a previous typo fix shows this is not covered by tests
sol1 = r['b']*(r['k2']-r['k1']*k)*t**2 + r['k1']*t
sol2 = k*sol1 + (r['k2']-r['k1']*k)*t
psol = [sol1, sol2]
return psol
def _linear_2eq_order1_type3(x, y, t, r, eq):
r"""
The equations of this type of ode are
.. math:: x' = f(t) x + g(t) y
.. math:: y' = g(t) x + f(t) y
The solution of such equations is given by
.. math:: x = e^{F} (C_1 e^{G} + C_2 e^{-G}) , y = e^{F} (C_1 e^{G} - C_2 e^{-G})
where `C_1` and `C_2` are arbitary constants, and
.. math:: F = \int f(t) \,dt , G = \int g(t) \,dt
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
F = Integral(r['a'], t)
G = Integral(r['b'], t)
sol1 = exp(F)*(C1*exp(G) + C2*exp(-G))
sol2 = exp(F)*(C1*exp(G) - C2*exp(-G))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type4(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = -g(t) x + f(t) y
The solution is given by
.. math:: x = F (C_1 \cos(G) + C_2 \sin(G)), y = F (-C_1 \sin(G) + C_2 \cos(G))
where `C_1` and `C_2` are arbitary constants, and
.. math:: F = \int f(t) \,dt , G = \int g(t) \,dt
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
if r['b'] == -r['c']:
F = exp(Integral(r['a'], t))
G = Integral(r['b'], t)
sol1 = F*(C1*cos(G) + C2*sin(G))
sol2 = F*(-C1*sin(G) + C2*cos(G))
elif r['d'] == -r['a']:
F = exp(Integral(r['c'], t))
G = Integral(r['d'], t)
sol1 = F*(-C1*sin(G) + C2*cos(G))
sol2 = F*(C1*cos(G) + C2*sin(G))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type5(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = a g(t) x + [f(t) + b g(t)] y
The transformation of
.. math:: x = e^{\int f(t) \,dt} u , y = e^{\int f(t) \,dt} v , T = \int g(t) \,dt
leads to a system of constant coefficient linear differential equations
.. math:: u'(T) = v , v'(T) = au + bv
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', function=True)
T = Symbol('T')
if not cancel(r['c']/r['b']).has(t):
p = cancel(r['c']/r['b'])
q = cancel((r['d']-r['a'])/r['b'])
eq = (Eq(diff(u(T),T), v(T)), Eq(diff(v(T),T), p*u(T)+q*v(T)))
sol = dsolve(eq)
sol1 = exp(Integral(r['a'], t))*sol[0].rhs.subs(T, Integral(r['b'],t))
sol2 = exp(Integral(r['a'], t))*sol[1].rhs.subs(T, Integral(r['b'],t))
if not cancel(r['a']/r['d']).has(t):
p = cancel(r['a']/r['d'])
q = cancel((r['b']-r['c'])/r['d'])
sol = dsolve(Eq(diff(u(T),T), v(T)), Eq(diff(v(T),T), p*u(T)+q*v(T)))
sol1 = exp(Integral(r['c'], t))*sol[1].rhs.subs(T, Integral(r['d'],t))
sol2 = exp(Integral(r['c'], t))*sol[0].rhs.subs(T, Integral(r['d'],t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type6(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y
This is solved by first multiplying the first equation by `-a` and adding
it to the second equation to obtain
.. math:: y' - a x' = -a h(t) (y - a x)
Setting `U = y - ax` and integrating the equation we arrive at
.. math:: y - ax = C_1 e^{-a \int h(t) \,dt}
and on substituing the value of y in first equation give rise to first order ODEs. After solving for
`x`, we can obtain `y` by substituting the value of `x` in second equation.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
p = 0
q = 0
p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0])
p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0])
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q!=0 and n==0:
if ((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j:
p = 1
s = j
break
if q!=0 and n==1:
if ((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j:
p = 2
s = j
break
if p == 1:
equ = diff(x(t),t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t)))
hint1 = classify_ode(equ)[1]
sol1 = dsolve(equ, hint=hint1+'_Integral').rhs
sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t))
elif p ==2:
equ = diff(y(t),t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
hint1 = classify_ode(equ)[1]
sol2 = dsolve(equ, hint=hint1+'_Integral').rhs
sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type7(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = h(t) x + p(t) y
Differentiating the first equation and substituting the value of `y`
from second equation will give a second-order linear equation
.. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0
This above equation can be easily integrated if following conditions are satisfied.
1. `fgp - g^{2} h + f g' - f' g = 0`
2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg`
If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes
a constant cofficient differential equation which is also solved by current solver.
Otherwise if the above condition fails then,
a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)`
Then the general solution is expressed as
.. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt
.. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt]
where C1 and C2 are arbitary constants and
.. math:: F(t) = e^{\int f(t) \,dt} , P(t) = e^{\int p(t) \,dt}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'],t) - diff(r['a'],t)*r['b']
e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'],t)*r['d'] - r['c']*diff(r['d'],t)
m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'],t)
m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'],t)
if e1 == 0:
sol1 = dsolve(r['b']*diff(x(t),t,t) - m1*diff(x(t),t)).rhs
sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs
elif e2 == 0:
sol2 = dsolve(r['c']*diff(y(t),t,t) - m2*diff(y(t),t)).rhs
sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs
elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t):
sol1 = dsolve(diff(x(t),t,t) - (m1/r['b'])*diff(x(t),t) - (e1/r['b'])*x(t)).rhs
sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs
elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t):
sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs
sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs
else:
x0, y0 = symbols('x0, y0') #x0 and y0 being particular solutions
F = exp(Integral(r['a'],t))
P = exp(Integral(r['d'],t))
sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t)
sol2 = C1*y0 + C2(F*P/x0 + y0*Integral(r['b']*F*P/x0**2, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def sysode_linear_2eq_order2(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r = dict()
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eqs = []
for terms in Add.make_args(eq[i]):
eqs.append(terms/fc[i,func[i],2])
eq[i] = Add(*eqs)
# for equations Eq(diff(x(t),t,t), a1*diff(x(t),t)+b1*diff(y(t),t)+c1*x(t)+d1*y(t)+e1)
# and Eq(a2*diff(y(t),t,t), a2*diff(x(t),t)+b2*diff(y(t),t)+c2*x(t)+d2*y(t)+e2)
r['a1'] = -fc[0,x(t),1]/fc[0,x(t),2] ; r['a2'] = -fc[1,x(t),1]/fc[1,y(t),2]
r['b1'] = -fc[0,y(t),1]/fc[0,x(t),2] ; r['b2'] = -fc[1,y(t),1]/fc[1,y(t),2]
r['c1'] = -fc[0,x(t),0]/fc[0,x(t),2] ; r['c2'] = -fc[1,x(t),0]/fc[1,y(t),2]
r['d1'] = -fc[0,y(t),0]/fc[0,x(t),2] ; r['d2'] = -fc[1,y(t),0]/fc[1,y(t),2]
const = [S(0), S(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not (j.has(x(t)) or j.has(y(t))):
const[i] += j
r['e1'] = -const[0]
r['e2'] = -const[1]
if match_['type_of_equation'] == 'type1':
sol = _linear_2eq_order2_type1(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type2':
gsol = _linear_2eq_order2_type1(x, y, t, r, eq)
psol = _linear_2eq_order2_type2(x, y, t, r, eq)
sol = [Eq(x(t), gsol[0].rhs+psol[0]), Eq(y(t), gsol[1].rhs+psol[1])]
elif match_['type_of_equation'] == 'type3':
sol = _linear_2eq_order2_type3(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type4':
sol = _linear_2eq_order2_type4(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type5':
sol = _linear_2eq_order2_type5(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type6':
sol = _linear_2eq_order2_type6(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type7':
sol = _linear_2eq_order2_type7(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type8':
sol = _linear_2eq_order2_type8(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type9':
sol = _linear_2eq_order2_type9(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type10':
sol = _linear_2eq_order2_type10(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type11':
sol = _linear_2eq_order2_type11(x, y, t, r, eq)
return sol
def _linear_2eq_order2_type1(x, y, t, r, eq):
r"""
System of two constant-coefficient second-order linear homogeneous differential equations
.. math:: x'' = ax + by
.. math:: y'' = cx + dy
The charecteristic equation for above equations
.. math:: \lambda^4 - (a + d) \lambda^2 + ad - bc = 0
whose discriminant is `D = (a - d)^2 + 4bc \neq 0`
1. When `ad - bc \neq 0`
1.1. If `D \neq 0`. The characteristic equation has four distict roots, `\lambda_1, \lambda_2, \lambda_3, \lambda_4`.
The general solution of the system is
.. math:: x = C_1 b e^{\lambda_1 t} + C_2 b e^{\lambda_2 t} + C_3 b e^{\lambda_3 t} + C_4 b e^{\lambda_4 t}
.. math:: y = C_1 (\lambda_1^{2} - a) e^{\lambda_1 t} + C_2 (\lambda_2^{2} - a) e^{\lambda_2 t} + C_3 (\lambda_3^{2} - a) e^{\lambda_3 t} + C_4 (\lambda_4^{2} - a) e^{\lambda_4 t}
where `C_1,..., C_4` are arbitary constants.
1.2. If `D = 0` and `a \neq d`:
.. math:: x = 2 C_1 (bt + \frac{2bk}{a - d}) e^{\frac{kt}{2}} + 2 C_2 (bt + \frac{2bk}{a - d}) e^{\frac{-kt}{2}} + 2b C_3 t e^{\frac{kt}{2}} + 2b C_4 t e^{\frac{-kt}{2}}
.. math:: y = C_1 (d - a) t e^{\frac{kt}{2}} + C_2 (d - a) t e^{\frac{-kt}{2}} + C_3 [(d - a) t + 2k] e^{\frac{kt}{2}} + C_4 [(d - a) t - 2k] e^{\frac{-kt}{2}}
where `C_1,..., C_4` are arbitary constants and `k = \sqrt{2 (a + d)}`
1.3. If `D = 0` and `a = d \neq 0` and `b = 0`:
.. math:: x = 2 \sqrt{a} C_1 e^{\sqrt{a} t} + 2 \sqrt{a} C_2 e^{-\sqrt{a} t}
.. math:: y = c C_1 t e^{\sqrt{a} t} - c C_2 t e^{-\sqrt{a} t} + C_3 e^{\sqrt{a} t} + C_4 e^{-\sqrt{a} t}
1.4. If `D = 0` and `a = d \neq 0` and `c = 0`:
.. math:: x = b C_1 t e^{\sqrt{a} t} - b C_2 t e^{-\sqrt{a} t} + C_3 e^{\sqrt{a} t} + C_4 e^{-\sqrt{a} t}
.. math:: y = 2 \sqrt{a} C_1 e^{\sqrt{a} t} + 2 \sqrt{a} C_2 e^{-\sqrt{a} t}
2. When `ad - bc = 0` and `a^2 + b^2 > 0`. Then the original system becomes
.. math:: x'' = ax + by
.. math:: y'' = k (ax + by)
2.1. If `a + bk \neq 0`:
.. math:: x = C_1 e^{t \sqrt{a + bk}} + C_2 e^{-t \sqrt{a + bk}} + C_3 bt + C_4 b
.. math:: y = C_1 k e^{t \sqrt{a + bk}} + C_2 k e^{-t \sqrt{a + bk}} - C_3 at - C_4 a
2.2. If `a + bk = 0`:
.. math:: x = C_1 b t^3 + C_2 b t^2 + C_3 t + C_4
.. math:: y = kx + 6 C_1 t + 2 C_2
"""
r['a'] = r['c1']
r['b'] = r['d1']
r['c'] = r['c2']
r['d'] = r['d2']
l = Symbol('l')
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
chara_eq = l**4 - (r['a']+r['d'])*l**2 + r['a']*r['d'] - r['b']*r['c']
l1 = rootof(chara_eq, 0)
l2 = rootof(chara_eq, 1)
l3 = rootof(chara_eq, 2)
l4 = rootof(chara_eq, 3)
D = (r['a'] - r['d'])**2 + 4*r['b']*r['c']
if (r['a']*r['d'] - r['b']*r['c']) != 0:
if D != 0:
gsol1 = C1*r['b']*exp(l1*t) + C2*r['b']*exp(l2*t) + C3*r['b']*exp(l3*t) \
+ C4*r['b']*exp(l4*t)
gsol2 = C1*(l1**2-r['a'])*exp(l1*t) + C2*(l2**2-r['a'])*exp(l2*t) + \
C3*(l3**2-r['a'])*exp(l3*t) + C4*(l4**2-r['a'])*exp(l4*t)
else:
if r['a'] != r['d']:
k = sqrt(2*(r['a']+r['d']))
mid = r['b']*t+2*r['b']*k/(r['a']-r['d'])
gsol1 = 2*C1*mid*exp(k*t/2) + 2*C2*mid*exp(-k*t/2) + \
2*r['b']*C3*t*exp(k*t/2) + 2*r['b']*C4*t*exp(-k*t/2)
gsol2 = C1*(r['d']-r['a'])*t*exp(k*t/2) + C2*(r['d']-r['a'])*t*exp(-k*t/2) + \
C3*((r['d']-r['a'])*t+2*k)*exp(k*t/2) + C4*((r['d']-r['a'])*t-2*k)*exp(-k*t/2)
elif r['a'] == r['d'] != 0 and r['b'] == 0:
sa = sqrt(r['a'])
gsol1 = 2*sa*C1*exp(sa*t) + 2*sa*C2*exp(-sa*t)
gsol2 = r['c']*C1*t*exp(sa*t)-r['c']*C2*t*exp(-sa*t)+C3*exp(sa*t)+C4*exp(-sa*t)
elif r['a'] == r['d'] != 0 and r['c'] == 0:
sa = sqrt(r['a'])
gsol1 = r['b']*C1*t*exp(sa*t)-r['b']*C2*t*exp(-sa*t)+C3*exp(sa*t)+C4*exp(-sa*t)
gsol2 = 2*sa*C1*exp(sa*t) + 2*sa*C2*exp(-sa*t)
elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2 + r['b']**2) > 0:
k = r['c']/r['a']
if r['a'] + r['b']*k != 0:
mid = sqrt(r['a'] + r['b']*k)
gsol1 = C1*exp(mid*t) + C2*exp(-mid*t) + C3*r['b']*t + C4*r['b']
gsol2 = C1*k*exp(mid*t) + C2*k*exp(-mid*t) - C3*r['a']*t - C4*r['a']
else:
gsol1 = C1*r['b']*t**3 + C2*r['b']*t**2 + C3*t + C4
gsol2 = k*gsol1 + 6*C1*t + 2*C2
return [Eq(x(t), gsol1), Eq(y(t), gsol2)]
def _linear_2eq_order2_type2(x, y, t, r, eq):
r"""
The equations in this type are
.. math:: x'' = a_1 x + b_1 y + c_1
.. math:: y'' = a_2 x + b_2 y + c_2
The general solution of this system is given by the sum of its particular solution
and the general solution of the homogeneous system. The general solution is given
by the linear system of 2 equation of order 2 and type 1
1. If `a_1 b_2 - a_2 b_1 \neq 0`. A particular solution will be `x = x_0` and `y = y_0`
where the constants `x_0` and `y_0` are determined by solving the linear algebraic system
.. math:: a_1 x_0 + b_1 y_0 + c_1 = 0, a_2 x_0 + b_2 y_0 + c_2 = 0
2. If `a_1 b_2 - a_2 b_1 = 0` and `a_1^2 + b_1^2 > 0`. In this case, the system in question becomes
.. math:: x'' = ax + by + c_1, y'' = k (ax + by) + c_2
2.1. If `\sigma = a + bk \neq 0`, the particular solution will be
.. math:: x = \frac{1}{2} b \sigma^{-1} (c_1 k - c_2) t^2 - \sigma^{-2} (a c_1 + b c_2)
.. math:: y = kx + \frac{1}{2} (c_2 - c_1 k) t^2
2.2. If `\sigma = a + bk = 0`, the particular solution will be
.. math:: x = \frac{1}{24} b (c_2 - c_1 k) t^4 + \frac{1}{2} c_1 t^2
.. math:: y = kx + \frac{1}{2} (c_2 - c_1 k) t^2
"""
x0, y0 = symbols('x0, y0')
if r['c1']*r['d2'] - r['c2']*r['d1'] != 0:
sol = solve((r['c1']*x0+r['d1']*y0+r['e1'], r['c2']*x0+r['d2']*y0+r['e2']), x0, y0)
psol = [sol[x0], sol[y0]]
elif r['c1']*r['d2'] - r['c2']*r['d1'] == 0 and (r['c1']**2 + r['d1']**2) > 0:
k = r['c2']/r['c1']
sig = r['c1'] + r['d1']*k
if sig != 0:
psol1 = r['d1']*sig**-1*(r['e1']*k-r['e2'])*t**2/2 - \
sig**-2*(r['c1']*r['e1']+r['d1']*r['e2'])
psol2 = k*psol1 + (r['e2'] - r['e1']*k)*t**2/2
psol = [psol1, psol2]
else:
psol1 = r['d1']*(r['e2']-r['e1']*k)*t**4/24 + r['e1']*t**2/2
psol2 = k*psol1 + (r['e2']-r['e1']*k)*t**2/2
psol = [psol1, psol2]
return psol
def _linear_2eq_order2_type3(x, y, t, r, eq):
r"""
These type of equation is used for describing the horizontal motion of a pendulum
taking into account the Earth rotation.
The solution is given with `a^2 + 4b > 0`:
.. math:: x = C_1 \cos(\alpha t) + C_2 \sin(\alpha t) + C_3 \cos(\beta t) + C_4 \sin(\beta t)
.. math:: y = -C_1 \sin(\alpha t) + C_2 \cos(\alpha t) - C_3 \sin(\beta t) + C_4 \cos(\beta t)
where `C_1,...,C_4` and
.. math:: \alpha = \frac{1}{2} a + \frac{1}{2} \sqrt{a^2 + 4b}, \beta = \frac{1}{2} a - \frac{1}{2} \sqrt{a^2 + 4b}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
if r['b1']**2 - 4*r['c1'] > 0:
r['a'] = r['b1'] ; r['b'] = -r['c1']
alpha = r['a']/2 + sqrt(r['a']**2 + 4*r['b'])/2
beta = r['a']/2 - sqrt(r['a']**2 + 4*r['b'])/2
sol1 = C1*cos(alpha*t) + C2*sin(alpha*t) + C3*cos(beta*t) + C4*sin(beta*t)
sol2 = -C1*sin(alpha*t) + C2*cos(alpha*t) - C3*sin(beta*t) + C4*cos(beta*t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type4(x, y, t, r, eq):
r"""
These equations are found in the theory of oscillations
.. math:: x'' + a_1 x' + b_1 y' + c_1 x + d_1 y = k_1 e^{i \omega t}
.. math:: y'' + a_2 x' + b_2 y' + c_2 x + d_2 y = k_2 e^{i \omega t}
The general solution of this linear nonhomogeneous system of constant-coefficient
differential equations is given by the sum of its particular solution and the
general solution of the corresponding homogeneous system (with `k_1 = k_2 = 0`)
1. A particular solution is obtained by the method of undetermined coefficients:
.. math:: x = A_* e^{i \omega t}, y = B_* e^{i \omega t}
On substituting these expressions into the original system of differential equations,
one arrive at a linear nonhomogeneous system of algebraic equations for the
coefficients `A` and `B`.
2. The general solution of the homogeneous system of differential equations is determined
by a linear combination of linearly independent particular solutions determined by
the method of undetermined coefficients in the form of exponentials:
.. math:: x = A e^{\lambda t}, y = B e^{\lambda t}
On substituting these expressions into the original system and colleting the
coefficients of the unknown `A` and `B`, one obtains
.. math:: (\lambda^{2} + a_1 \lambda + c_1) A + (b_1 \lambda + d_1) B = 0
.. math:: (a_2 \lambda + c_2) A + (\lambda^{2} + b_2 \lambda + d_2) B = 0
The determinant of this system must vanish for nontrivial solutions A, B to exist.
This requirement results in the following characteristic equation for `\lambda`
.. math:: (\lambda^2 + a_1 \lambda + c_1) (\lambda^2 + b_2 \lambda + d_2) - (b_1 \lambda + d_1) (a_2 \lambda + c_2) = 0
If all roots `k_1,...,k_4` of this equation are distict, the general solution of the original
system of the differential equations has the form
.. math:: x = C_1 (b_1 \lambda_1 + d_1) e^{\lambda_1 t} - C_2 (b_1 \lambda_2 + d_1) e^{\lambda_2 t} - C_3 (b_1 \lambda_3 + d_1) e^{\lambda_3 t} - C_4 (b_1 \lambda_4 + d_1) e^{\lambda_4 t}
.. math:: y = C_1 (\lambda_1^{2} + a_1 \lambda_1 + c_1) e^{\lambda_1 t} + C_2 (\lambda_2^{2} + a_1 \lambda_2 + c_1) e^{\lambda_2 t} + C_3 (\lambda_3^{2} + a_1 \lambda_3 + c_1) e^{\lambda_3 t} + C_4 (\lambda_4^{2} + a_1 \lambda_4 + c_1) e^{\lambda_4 t}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
Ra, Ca, Rb, Cb = symbols('Ra, Ca, Rb, Cb')
a1 = r['a1'] ; a2 = r['a2']
b1 = r['b1'] ; b2 = r['b2']
c1 = r['c1'] ; c2 = r['c2']
d1 = r['d1'] ; d2 = r['d2']
k1 = r['e1'].expand().as_independent(t)[0]
k2 = r['e2'].expand().as_independent(t)[0]
ew1 = r['e1'].expand().as_independent(t)[1]
ew2 = powdenest(ew1).as_base_exp()[1]
ew3 = collect(ew2, t).coeff(t)
w = cancel(ew3/I)
# The particular solution is assumed to be (Ra+I*Ca)*exp(I*w*t) and
# (Rb+I*Cb)*exp(I*w*t) for x(t) and y(t) respectively
peq1 = (-w**2+c1)*Ra - a1*w*Ca + d1*Rb - b1*w*Cb - k1
peq2 = a1*w*Ra + (-w**2+c1)*Ca + b1*w*Rb + d1*Cb
peq3 = c2*Ra - a2*w*Ca + (-w**2+d2)*Rb - b2*w*Cb - k2
peq4 = a2*w*Ra + c2*Ca + b2*w*Rb + (-w**2+d2)*Cb
# FIXME: solve for what in what? Ra, Rb, etc I guess
# but then psol not used for anything?
psol = solve([peq1, peq2, peq3, peq4])
chareq = (k**2+a1*k+c1)*(k**2+b2*k+d2) - (b1*k+d1)*(a2*k+c2)
[k1, k2, k3, k4] = roots_quartic(Poly(chareq))
sol1 = -C1*(b1*k1+d1)*exp(k1*t) - C2*(b1*k2+d1)*exp(k2*t) - \
C3*(b1*k3+d1)*exp(k3*t) - C4*(b1*k4+d1)*exp(k4*t) + (Ra+I*Ca)*exp(I*w*t)
a1_ = (a1-1)
sol2 = C1*(k1**2+a1_*k1+c1)*exp(k1*t) + C2*(k2**2+a1_*k2+c1)*exp(k2*t) + \
C3*(k3**2+a1_*k3+c1)*exp(k3*t) + C4*(k4**2+a1_*k4+c1)*exp(k4*t) + (Rb+I*Cb)*exp(I*w*t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type5(x, y, t, r, eq):
r"""
The equation which come under this catagory are
.. math:: x'' = a (t y' - y)
.. math:: y'' = b (t x' - x)
The transformation
.. math:: u = t x' - x, b = t y' - y
leads to the first-order system
.. math:: u' = atv, v' = btu
The general solution of this system is given by
If `ab > 0`:
.. math:: u = C_1 a e^{\frac{1}{2} \sqrt{ab} t^2} + C_2 a e^{-\frac{1}{2} \sqrt{ab} t^2}
.. math:: v = C_1 \sqrt{ab} e^{\frac{1}{2} \sqrt{ab} t^2} - C_2 \sqrt{ab} e^{-\frac{1}{2} \sqrt{ab} t^2}
If `ab < 0`:
.. math:: u = C_1 a \cos(\frac{1}{2} \sqrt{\left|ab\right|} t^2) + C_2 a \sin(-\frac{1}{2} \sqrt{\left|ab\right|} t^2)
.. math:: v = C_1 \sqrt{\left|ab\right|} \sin(\frac{1}{2} \sqrt{\left|ab\right|} t^2) + C_2 \sqrt{\left|ab\right|} \cos(-\frac{1}{2} \sqrt{\left|ab\right|} t^2)
where `C_1` and `C_2` are arbitary constants. On substituting the value of `u` and `v`
in above equations and integrating the resulting expressions, the general solution will become
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt, y = C_4 t + t \int \frac{u}{t^2} \,dt
where `C_3` and `C_4` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r['a'] = -r['d1'] ; r['b'] = -r['c2']
mul = sqrt(abs(r['a']*r['b']))
if r['a']*r['b'] > 0:
u = C1*r['a']*exp(mul*t**2/2) + C2*r['a']*exp(-mul*t**2/2)
v = C1*mul*exp(mul*t**2/2) - C2*mul*exp(-mul*t**2/2)
else:
u = C1*r['a']*cos(mul*t**2/2) + C2*r['a']*sin(mul*t**2/2)
v = -C1*mul*sin(mul*t**2/2) + C2*mul*cos(mul*t**2/2)
sol1 = C3*t + t*Integral(u/t**2, t)
sol2 = C4*t + t*Integral(v/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type6(x, y, t, r, eq):
r"""
The equations are
.. math:: x'' = f(t) (a_1 x + b_1 y)
.. math:: y'' = f(t) (a_2 x + b_2 y)
If `k_1` and `k_2` are roots of the quadratic equation
.. math:: k^2 - (a_1 + b_2) k + a_1 b_2 - a_2 b_1 = 0
Then by multiplying appropriate constants and adding together original equations
we obtain two independent equations:
.. math:: z_1'' = k_1 f(t) z_1, z_1 = a_2 x + (k_1 - a_1) y
.. math:: z_2'' = k_2 f(t) z_2, z_2 = a_2 x + (k_2 - a_1) y
Solving the equations will give the values of `x` and `y` after obtaining the value
of `z_1` and `z_2` by solving the differential equation and substuting the result.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
z = Function('z')
num, den = cancel(
(r['c1']*x(t) + r['d1']*y(t))/
(r['c2']*x(t) + r['d2']*y(t))).as_numer_denom()
f = r['c1']/num.coeff(x(t))
a1 = num.coeff(x(t))
b1 = num.coeff(y(t))
a2 = den.coeff(x(t))
b2 = den.coeff(y(t))
chareq = k**2 - (a1 + b2)*k + a1*b2 - a2*b1
k1, k2 = [rootof(chareq, k) for k in range(Poly(chareq).degree())]
z1 = dsolve(diff(z(t),t,t) - k1*f*z(t)).rhs
z2 = dsolve(diff(z(t),t,t) - k2*f*z(t)).rhs
sol1 = (k1*z2 - k2*z1 + a1*(z1 - z2))/(a2*(k1-k2))
sol2 = (z1 - z2)/(k1 - k2)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type7(x, y, t, r, eq):
r"""
The equations are given as
.. math:: x'' = f(t) (a_1 x' + b_1 y')
.. math:: y'' = f(t) (a_2 x' + b_2 y')
If `k_1` and 'k_2` are roots of the quadratic equation
.. math:: k^2 - (a_1 + b_2) k + a_1 b_2 - a_2 b_1 = 0
Then the system can be reduced by adding together the two equations multiplied
by appropriate constants give following two independent equations:
.. math:: z_1'' = k_1 f(t) z_1', z_1 = a_2 x + (k_1 - a_1) y
.. math:: z_2'' = k_2 f(t) z_2', z_2 = a_2 x + (k_2 - a_1) y
Integrating these and returning to the original variables, one arrives at a linear
algebraic system for the unknowns `x` and `y`:
.. math:: a_2 x + (k_1 - a_1) y = C_1 \int e^{k_1 F(t)} \,dt + C_2
.. math:: a_2 x + (k_2 - a_1) y = C_3 \int e^{k_2 F(t)} \,dt + C_4
where `C_1,...,C_4` are arbitrary constants and `F(t) = \int f(t) \,dt`
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
num, den = cancel(
(r['a1']*x(t) + r['b1']*y(t))/
(r['a2']*x(t) + r['b2']*y(t))).as_numer_denom()
f = r['a1']/num.coeff(x(t))
a1 = num.coeff(x(t))
b1 = num.coeff(y(t))
a2 = den.coeff(x(t))
b2 = den.coeff(y(t))
chareq = k**2 - (a1 + b2)*k + a1*b2 - a2*b1
[k1, k2] = [rootof(chareq, k) for k in range(Poly(chareq).degree())]
F = Integral(f, t)
z1 = C1*Integral(exp(k1*F), t) + C2
z2 = C3*Integral(exp(k2*F), t) + C4
sol1 = (k1*z2 - k2*z1 + a1*(z1 - z2))/(a2*(k1-k2))
sol2 = (z1 - z2)/(k1 - k2)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type8(x, y, t, r, eq):
r"""
The equation of this catagory are
.. math:: x'' = a f(t) (t y' - y)
.. math:: y'' = b f(t) (t x' - x)
The transformation
.. math:: u = t x' - x, v = t y' - y
leads to the system of first-order equations
.. math:: u' = a t f(t) v, v' = b t f(t) u
The general solution of this system has the form
If `ab > 0`:
.. math:: u = C_1 a e^{\sqrt{ab} \int t f(t) \,dt} + C_2 a e^{-\sqrt{ab} \int t f(t) \,dt}
.. math:: v = C_1 \sqrt{ab} e^{\sqrt{ab} \int t f(t) \,dt} - C_2 \sqrt{ab} e^{-\sqrt{ab} \int t f(t) \,dt}
If `ab < 0`:
.. math:: u = C_1 a \cos(\sqrt{\left|ab\right|} \int t f(t) \,dt) + C_2 a \sin(-\sqrt{\left|ab\right|} \int t f(t) \,dt)
.. math:: v = C_1 \sqrt{\left|ab\right|} \sin(\sqrt{\left|ab\right|} \int t f(t) \,dt) + C_2 \sqrt{\left|ab\right|} \cos(-\sqrt{\left|ab\right|} \int t f(t) \,dt)
where `C_1` and `C_2` are arbitary constants. On substituting the value of `u` and `v`
in above equations and integrating the resulting expressions, the general solution will become
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt, y = C_4 t + t \int \frac{u}{t^2} \,dt
where `C_3` and `C_4` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
num, den = cancel(r['d1']/r['c2']).as_numer_denom()
f = -r['d1']/num
a = num
b = den
mul = sqrt(abs(a*b))
Igral = Integral(t*f, t)
if a*b > 0:
u = C1*a*exp(mul*Igral) + C2*a*exp(-mul*Igral)
v = C1*mul*exp(mul*Igral) - C2*mul*exp(-mul*Igral)
else:
u = C1*a*cos(mul*Igral) + C2*a*sin(mul*Igral)
v = -C1*mul*sin(mul*Igral) + C2*mul*cos(mul*Igral)
sol1 = C3*t + t*Integral(u/t**2, t)
sol2 = C4*t + t*Integral(v/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type9(x, y, t, r, eq):
r"""
.. math:: t^2 x'' + a_1 t x' + b_1 t y' + c_1 x + d_1 y = 0
.. math:: t^2 y'' + a_2 t x' + b_2 t y' + c_2 x + d_2 y = 0
These system of equations are euler type.
The substitution of `t = \sigma e^{\tau} (\sigma \neq 0)` leads to the system of constant
coefficient linear differential equations
.. math:: x'' + (a_1 - 1) x' + b_1 y' + c_1 x + d_1 y = 0
.. math:: y'' + a_2 x' + (b_2 - 1) y' + c_2 x + d_2 y = 0
The general solution of the homogeneous system of differential equations is determined
by a linear combination of linearly independent particular solutions determined by
the method of undetermined coefficients in the form of exponentials
.. math:: x = A e^{\lambda t}, y = B e^{\lambda t}
On substituting these expressions into the original system and colleting the
coefficients of the unknown `A` and `B`, one obtains
.. math:: (\lambda^{2} + (a_1 - 1) \lambda + c_1) A + (b_1 \lambda + d_1) B = 0
.. math:: (a_2 \lambda + c_2) A + (\lambda^{2} + (b_2 - 1) \lambda + d_2) B = 0
The determinant of this system must vanish for nontrivial solutions A, B to exist.
This requirement results in the following characteristic equation for `\lambda`
.. math:: (\lambda^2 + (a_1 - 1) \lambda + c_1) (\lambda^2 + (b_2 - 1) \lambda + d_2) - (b_1 \lambda + d_1) (a_2 \lambda + c_2) = 0
If all roots `k_1,...,k_4` of this equation are distict, the general solution of the original
system of the differential equations has the form
.. math:: x = C_1 (b_1 \lambda_1 + d_1) e^{\lambda_1 t} - C_2 (b_1 \lambda_2 + d_1) e^{\lambda_2 t} - C_3 (b_1 \lambda_3 + d_1) e^{\lambda_3 t} - C_4 (b_1 \lambda_4 + d_1) e^{\lambda_4 t}
.. math:: y = C_1 (\lambda_1^{2} + (a_1 - 1) \lambda_1 + c_1) e^{\lambda_1 t} + C_2 (\lambda_2^{2} + (a_1 - 1) \lambda_2 + c_1) e^{\lambda_2 t} + C_3 (\lambda_3^{2} + (a_1 - 1) \lambda_3 + c_1) e^{\lambda_3 t} + C_4 (\lambda_4^{2} + (a_1 - 1) \lambda_4 + c_1) e^{\lambda_4 t}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
a1 = -r['a1']*t; a2 = -r['a2']*t
b1 = -r['b1']*t; b2 = -r['b2']*t
c1 = -r['c1']*t**2; c2 = -r['c2']*t**2
d1 = -r['d1']*t**2; d2 = -r['d2']*t**2
eq = (k**2+(a1-1)*k+c1)*(k**2+(b2-1)*k+d2)-(b1*k+d1)*(a2*k+c2)
[k1, k2, k3, k4] = roots_quartic(Poly(eq))
sol1 = -C1*(b1*k1+d1)*exp(k1*log(t)) - C2*(b1*k2+d1)*exp(k2*log(t)) - \
C3*(b1*k3+d1)*exp(k3*log(t)) - C4*(b1*k4+d1)*exp(k4*log(t))
a1_ = (a1-1)
sol2 = C1*(k1**2+a1_*k1+c1)*exp(k1*log(t)) + C2*(k2**2+a1_*k2+c1)*exp(k2*log(t)) \
+ C3*(k3**2+a1_*k3+c1)*exp(k3*log(t)) + C4*(k4**2+a1_*k4+c1)*exp(k4*log(t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type10(x, y, t, r, eq):
r"""
The equation of this catagory are
.. math:: (\alpha t^2 + \beta t + \gamma)^{2} x'' = ax + by
.. math:: (\alpha t^2 + \beta t + \gamma)^{2} y'' = cx + dy
The transformation
.. math:: \tau = \int \frac{1}{\alpha t^2 + \beta t + \gamma} \,dt , u = \frac{x}{\sqrt{\left|\alpha t^2 + \beta t + \gamma\right|}} , v = \frac{y}{\sqrt{\left|\alpha t^2 + \beta t + \gamma\right|}}
leads to a constant coefficient linear system of equations
.. math:: u'' = (a - \alpha \gamma + \frac{1}{4} \beta^{2}) u + b v
.. math:: v'' = c u + (d - \alpha \gamma + \frac{1}{4} \beta^{2}) v
These system of equations obtained can be solved by type1 of System of two
constant-coefficient second-order linear homogeneous differential equations.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', function=True)
T = Symbol('T')
p = Wild('p', exclude=[t, t**2])
q = Wild('q', exclude=[t, t**2])
s = Wild('s', exclude=[t, t**2])
n = Wild('n', exclude=[t, t**2])
num, den = r['c1'].as_numer_denom()
dic = den.match((n*(p*t**2+q*t+s)**2).expand())
eqz = dic[p]*t**2 + dic[q]*t + dic[s]
a = num/dic[n]
b = cancel(r['d1']*eqz**2)
c = cancel(r['c2']*eqz**2)
d = cancel(r['d2']*eqz**2)
[msol1, msol2] = dsolve([Eq(diff(u(t), t, t), (a - dic[p]*dic[s] + dic[q]**2/4)*u(t) \
+ b*v(t)), Eq(diff(v(t),t,t), c*u(t) + (d - dic[p]*dic[s] + dic[q]**2/4)*v(t))])
sol1 = (msol1.rhs*sqrt(abs(eqz))).subs(t, Integral(1/eqz, t))
sol2 = (msol2.rhs*sqrt(abs(eqz))).subs(t, Integral(1/eqz, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type11(x, y, t, r, eq):
r"""
The equations which comes under this type are
.. math:: x'' = f(t) (t x' - x) + g(t) (t y' - y)
.. math:: y'' = h(t) (t x' - x) + p(t) (t y' - y)
The transformation
.. math:: u = t x' - x, v = t y' - y
leads to the linear system of first-order equations
.. math:: u' = t f(t) u + t g(t) v, v' = t h(t) u + t p(t) v
On substituting the value of `u` and `v` in transformed equation gives value of `x` and `y` as
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt , y = C_4 t + t \int \frac{v}{t^2} \,dt.
where `C_3` and `C_4` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', function=True)
f = -r['c1'] ; g = -r['d1']
h = -r['c2'] ; p = -r['d2']
[msol1, msol2] = dsolve([Eq(diff(u(t),t), t*f*u(t) + t*g*v(t)), Eq(diff(v(t),t), t*h*u(t) + t*p*v(t))])
sol1 = C3*t + t*Integral(msol1.rhs/t**2, t)
sol2 = C4*t + t*Integral(msol2.rhs/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def sysode_linear_3eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
z = match_['func'][2].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r = dict()
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(3):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
# for equations:
# Eq(g1*diff(x(t),t), a1*x(t)+b1*y(t)+c1*z(t)+d1),
# Eq(g2*diff(y(t),t), a2*x(t)+b2*y(t)+c2*z(t)+d2), and
# Eq(g3*diff(z(t),t), a3*x(t)+b3*y(t)+c3*z(t)+d3)
r['a1'] = fc[0,x(t),0]/fc[0,x(t),1]; r['a2'] = fc[1,x(t),0]/fc[1,y(t),1];
r['a3'] = fc[2,x(t),0]/fc[2,z(t),1]
r['b1'] = fc[0,y(t),0]/fc[0,x(t),1]; r['b2'] = fc[1,y(t),0]/fc[1,y(t),1];
r['b3'] = fc[2,y(t),0]/fc[2,z(t),1]
r['c1'] = fc[0,z(t),0]/fc[0,x(t),1]; r['c2'] = fc[1,z(t),0]/fc[1,y(t),1];
r['c3'] = fc[2,z(t),0]/fc[2,z(t),1]
for i in range(3):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t), z(t)):
raise NotImplementedError("Only homogeneous problems are supported, non-homogenous are not supported currently.")
if match_['type_of_equation'] == 'type1':
sol = _linear_3eq_order1_type1(x, y, z, t, r, eq)
if match_['type_of_equation'] == 'type2':
sol = _linear_3eq_order1_type2(x, y, z, t, r, eq)
if match_['type_of_equation'] == 'type3':
sol = _linear_3eq_order1_type3(x, y, z, t, r, eq)
if match_['type_of_equation'] == 'type4':
sol = _linear_3eq_order1_type4(x, y, z, t, r, eq)
if match_['type_of_equation'] == 'type6':
sol = _linear_neq_order1_type1(match_)
return sol
def _linear_3eq_order1_type1(x, y, z, t, r, eq):
r"""
.. math:: x' = ax
.. math:: y' = bx + cy
.. math:: z' = dx + ky + pz
Solution of such equations are forward substitution. Solving first equations
gives the value of `x`, substituting it in second and third equation and
solving second equation gives `y` and similarly substituting `y` in third
equation give `z`.
.. math:: x = C_1 e^{at}
.. math:: y = \frac{b C_1}{a - c} e^{at} + C_2 e^{ct}
.. math:: z = \frac{C_1}{a - p} (d + \frac{bk}{a - c}) e^{at} + \frac{k C_2}{c - p} e^{ct} + C_3 e^{pt}
where `C_1, C_2` and `C_3` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
a = -r['a1']; b = -r['a2']; c = -r['b2']
d = -r['a3']; k = -r['b3']; p = -r['c3']
sol1 = C1*exp(a*t)
sol2 = b*C1*exp(a*t)/(a-c) + C2*exp(c*t)
sol3 = C1*(d+b*k/(a-c))*exp(a*t)/(a-p) + k*C2*exp(c*t)/(c-p) + C3*exp(p*t)
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _linear_3eq_order1_type2(x, y, z, t, r, eq):
r"""
The equations of this type are
.. math:: x' = cy - bz
.. math:: y' = az - cx
.. math:: z' = bx - ay
1. First integral:
.. math:: ax + by + cz = A \qquad - (1)
.. math:: x^2 + y^2 + z^2 = B^2 \qquad - (2)
where `A` and `B` are arbitrary constants. It follows from these integrals
that the integral lines are circles formed by the intersection of the planes
`(1)` and sphere `(2)`
2. Solution:
.. math:: x = a C_0 + k C_1 \cos(kt) + (c C_2 - b C_3) \sin(kt)
.. math:: y = b C_0 + k C_2 \cos(kt) + (a C_2 - c C_3) \sin(kt)
.. math:: z = c C_0 + k C_3 \cos(kt) + (b C_2 - a C_3) \sin(kt)
where `k = \sqrt{a^2 + b^2 + c^2}` and the four constants of integration,
`C_1,...,C_4` are constrained by a single relation,
.. math:: a C_1 + b C_2 + c C_3 = 0
"""
C0, C1, C2, C3 = get_numbered_constants(eq, num=4, start=0)
a = -r['c2']; b = -r['a3']; c = -r['b1']
k = sqrt(a**2 + b**2 + c**2)
C3 = (-a*C1 - b*C2)/c
sol1 = a*C0 + k*C1*cos(k*t) + (c*C2-b*C3)*sin(k*t)
sol2 = b*C0 + k*C2*cos(k*t) + (a*C3-c*C1)*sin(k*t)
sol3 = c*C0 + k*C3*cos(k*t) + (b*C1-a*C2)*sin(k*t)
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _linear_3eq_order1_type3(x, y, z, t, r, eq):
r"""
Equations of this system of ODEs
.. math:: a x' = bc (y - z)
.. math:: b y' = ac (z - x)
.. math:: c z' = ab (x - y)
1. First integral:
.. math:: a^2 x + b^2 y + c^2 z = A
where A is an arbitary constant. It follows that the integral lines are plane curves.
2. Solution:
.. math:: x = C_0 + k C_1 \cos(kt) + a^{-1} bc (C_2 - C_3) \sin(kt)
.. math:: y = C_0 + k C_2 \cos(kt) + a b^{-1} c (C_3 - C_1) \sin(kt)
.. math:: z = C_0 + k C_3 \cos(kt) + ab c^{-1} (C_1 - C_2) \sin(kt)
where `k = \sqrt{a^2 + b^2 + c^2}` and the four constants of integration,
`C_1,...,C_4` are constrained by a single relation
.. math:: a^2 C_1 + b^2 C_2 + c^2 C_3 = 0
"""
C0, C1, C2, C3 = get_numbered_constants(eq, num=4, start=0)
c = sqrt(r['b1']*r['c2'])
b = sqrt(r['b1']*r['a3'])
a = sqrt(r['c2']*r['a3'])
C3 = (-a**2*C1-b**2*C2)/c**2
k = sqrt(a**2 + b**2 + c**2)
sol1 = C0 + k*C1*cos(k*t) + a**-1*b*c*(C2-C3)*sin(k*t)
sol2 = C0 + k*C2*cos(k*t) + a*b**-1*c*(C3-C1)*sin(k*t)
sol3 = C0 + k*C3*cos(k*t) + a*b*c**-1*(C1-C2)*sin(k*t)
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _linear_3eq_order1_type4(x, y, z, t, r, eq):
r"""
Equations:
.. math:: x' = (a_1 f(t) + g(t)) x + a_2 f(t) y + a_3 f(t) z
.. math:: y' = b_1 f(t) x + (b_2 f(t) + g(t)) y + b_3 f(t) z
.. math:: z' = c_1 f(t) x + c_2 f(t) y + (c_3 f(t) + g(t)) z
The transformation
.. math:: x = e^{\int g(t) \,dt} u, y = e^{\int g(t) \,dt} v, z = e^{\int g(t) \,dt} w, \tau = \int f(t) \,dt
leads to the system of constant coefficient linear differential equations
.. math:: u' = a_1 u + a_2 v + a_3 w
.. math:: v' = b_1 u + b_2 v + b_3 w
.. math:: w' = c_1 u + c_2 v + c_3 w
These system of equations are solved by homogeneous linear system of constant
coefficients of `n` equations of first order. Then substituting the value of
`u, v` and `w` in transformed equation gives value of `x, y` and `z`.
"""
u, v, w = symbols('u, v, w', function=True)
a2, a3 = cancel(r['b1']/r['c1']).as_numer_denom()
f = cancel(r['b1']/a2)
b1 = cancel(r['a2']/f); b3 = cancel(r['c2']/f)
c1 = cancel(r['a3']/f); c2 = cancel(r['b3']/f)
a1, g = div(r['a1'],f)
b2 = div(r['b2'],f)[0]
c3 = div(r['c3'],f)[0]
trans_eq = (diff(u(t),t)-a1*u(t)-a2*v(t)-a3*w(t), diff(v(t),t)-b1*u(t)-\
b2*v(t)-b3*w(t), diff(w(t),t)-c1*u(t)-c2*v(t)-c3*w(t))
sol = dsolve(trans_eq)
sol1 = exp(Integral(g,t))*((sol[0].rhs).subs(t, Integral(f,t)))
sol2 = exp(Integral(g,t))*((sol[1].rhs).subs(t, Integral(f,t)))
sol3 = exp(Integral(g,t))*((sol[2].rhs).subs(t, Integral(f,t)))
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def sysode_linear_neq_order1(match_):
sol = _linear_neq_order1_type1(match_)
def _linear_neq_order1_type1(match_):
r"""
System of n first-order constant-coefficient linear nonhomogeneous differential equation
.. math:: y'_k = a_{k1} y_1 + a_{k2} y_2 +...+ a_{kn} y_n; k = 1,2,...,n
or that can be written as `\vec{y'} = A . \vec{y}`
where `\vec{y}` is matrix of `y_k` for `k = 1,2,...n` and `A` is a `n \times n` matrix.
Since these equations are equivalent to a first order homogeneous linear
differential equation. So the general solution will contain `n` linearly
independent parts and solution will consist some type of exponential
functions. Assuming `y = \vec{v} e^{rt}` is a solution of the system where
`\vec{v}` is a vector of coefficients of `y_1,...,y_n`. Substituting `y` and
`y' = r v e^{r t}` into the equation `\vec{y'} = A . \vec{y}`, we get
.. math:: r \vec{v} e^{rt} = A \vec{v} e^{rt}
.. math:: r \vec{v} = A \vec{v}
where `r` comes out to be eigenvalue of `A` and vector `\vec{v}` is the eigenvector
of `A` corresponding to `r`. There are three possiblities of eigenvalues of `A`
- `n` distinct real eigenvalues
- complex conjugate eigenvalues
- eigenvalues with multiplicity `k`
1. When all eigenvalues `r_1,..,r_n` are distinct with `n` different eigenvectors
`v_1,...v_n` then the solution is given by
.. math:: \vec{y} = C_1 e^{r_1 t} \vec{v_1} + C_2 e^{r_2 t} \vec{v_2} +...+ C_n e^{r_n t} \vec{v_n}
where `C_1,C_2,...,C_n` are arbitrary constants.
2. When some eigenvalues are complex then in order to make the solution real,
we take a llinear combination: if `r = a + bi` has an eigenvector
`\vec{v} = \vec{w_1} + i \vec{w_2}` then to obtain real-valued solutions to
the system, replace the complex-valued solutions `e^{rx} \vec{v}`
with real-valued solution `e^{ax} (\vec{w_1} \cos(bx) - \vec{w_2} \sin(bx))`
and for `r = a - bi` replace the solution `e^{-r x} \vec{v}` with
`e^{ax} (\vec{w_1} \sin(bx) + \vec{w_2} \cos(bx))`
3. If some eigenvalues are repeated. Then we get fewer than `n` linearly
independent eigenvectors, we miss some of the solutions and need to
construct the missing ones. We do this via generalized eigenvectors, vectors
which are not eigenvectors but are close enough that we can use to write
down the remaining solutions. For a eigenvalue `r` with eigenvector `\vec{w}`
we obtain `\vec{w_2},...,\vec{w_k}` using
.. math:: (A - r I) . \vec{w_2} = \vec{w}
.. math:: (A - r I) . \vec{w_3} = \vec{w_2}
.. math:: \vdots
.. math:: (A - r I) . \vec{w_k} = \vec{w_{k-1}}
Then the solutions to the system for the eigenspace are `e^{rt} [\vec{w}],
e^{rt} [t \vec{w} + \vec{w_2}], e^{rt} [\frac{t^2}{2} \vec{w} + t \vec{w_2} + \vec{w_3}],
...,e^{rt} [\frac{t^{k-1}}{(k-1)!} \vec{w} + \frac{t^{k-2}}{(k-2)!} \vec{w_2} +...+ t \vec{w_{k-1}}
+ \vec{w_k}]`
So, If `\vec{y_1},...,\vec{y_n}` are `n` solution of obtained from three
categories of `A`, then general solution to the system `\vec{y'} = A . \vec{y}`
.. math:: \vec{y} = C_1 \vec{y_1} + C_2 \vec{y_2} + \cdots + C_n \vec{y_n}
"""
eq = match_['eq']
func = match_['func']
fc = match_['func_coeff']
n = len(eq)
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
constants = numbered_symbols(prefix='C', cls=Symbol, start=1)
M = Matrix(n,n,lambda i,j:-fc[i,func[j],0])
evector = M.eigenvects(simplify=True)
def is_complex(mat, root):
return Matrix(n, 1, lambda i,j: re(mat[i])*cos(im(root)*t) - im(mat[i])*sin(im(root)*t))
def is_complex_conjugate(mat, root):
return Matrix(n, 1, lambda i,j: re(mat[i])*sin(abs(im(root))*t) + im(mat[i])*cos(im(root)*t)*abs(im(root))/im(root))
conjugate_root = []
e_vector = zeros(n,1)
for evects in evector:
if evects[0] not in conjugate_root:
# If number of column of an eigenvector is not equal to the multiplicity
# of its eigenvalue then the legt eigenvectors are calculated
if len(evects[2])!=evects[1]:
var_mat = Matrix(n, 1, lambda i,j: Symbol('x'+str(i)))
Mnew = (M - evects[0]*eye(evects[2][-1].rows))*var_mat
w = [0 for i in range(evects[1])]
w[0] = evects[2][-1]
for r in range(1, evects[1]):
w_ = Mnew - w[r-1]
sol_dict = solve(list(w_), var_mat[1:])
sol_dict[var_mat[0]] = var_mat[0]
for key, value in sol_dict.items():
sol_dict[key] = value.subs(var_mat[0],1)
w[r] = Matrix(n, 1, lambda i,j: sol_dict[var_mat[i]])
evects[2].append(w[r])
for i in range(evects[1]):
C = next(constants)
for j in range(i+1):
if evects[0].has(I):
evects[2][j] = simplify(evects[2][j])
e_vector += C*is_complex(evects[2][j], evects[0])*t**(i-j)*exp(re(evects[0])*t)/factorial(i-j)
C = next(constants)
e_vector += C*is_complex_conjugate(evects[2][j], evects[0])*t**(i-j)*exp(re(evects[0])*t)/factorial(i-j)
else:
e_vector += C*evects[2][j]*t**(i-j)*exp(evects[0]*t)/factorial(i-j)
if evects[0].has(I):
conjugate_root.append(conjugate(evects[0]))
sol = []
for i in range(len(eq)):
sol.append(Eq(func[i],e_vector[i]))
return sol
def sysode_nonlinear_2eq_order1(match_):
func = match_['func']
eq = match_['eq']
fc = match_['func_coeff']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
if match_['type_of_equation'] == 'type5':
sol = _nonlinear_2eq_order1_type5(func, t, eq)
return sol
x = func[0].func
y = func[1].func
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
if match_['type_of_equation'] == 'type1':
sol = _nonlinear_2eq_order1_type1(x, y, t, eq)
elif match_['type_of_equation'] == 'type2':
sol = _nonlinear_2eq_order1_type2(x, y, t, eq)
elif match_['type_of_equation'] == 'type3':
sol = _nonlinear_2eq_order1_type3(x, y, t, eq)
elif match_['type_of_equation'] == 'type4':
sol = _nonlinear_2eq_order1_type4(x, y, t, eq)
return sol
def _nonlinear_2eq_order1_type1(x, y, t, eq):
r"""
Equations:
.. math:: x' = x^n F(x,y)
.. math:: y' = g(y) F(x,y)
Solution:
.. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
where
if `n \neq 1`
.. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}}
if `n = 1`
.. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy}
where `C_1` and `C_2` are arbitrary constants.
"""
C1, C2 = get_numbered_constants(eq, num=2)
n = Wild('n', exclude=[x(t),y(t)])
f = Wild('f')
u, v, phi = symbols('u, v, phi', function=True)
r = eq[0].match(diff(x(t),t) - x(t)**n*f)
g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v)
F = r[f].subs(x(t),u).subs(y(t),v)
n = r[n]
if n!=1:
phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n))
else:
phi = C1*exp(Integral(1/g, v))
phi = phi.doit()
sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v)
sol = []
for sols in sol2:
sol.append(Eq(x(t),phi.subs(v, sols)))
sol.append(Eq(y(t), sols))
return sol
def _nonlinear_2eq_order1_type2(x, y, t, eq):
r"""
Equations:
.. math:: x' = e^{\lambda x} F(x,y)
.. math:: y' = g(y) F(x,y)
Solution:
.. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
where
if `\lambda \neq 0`
.. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy)
if `\lambda = 0`
.. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy
where `C_1` and `C_2` are arbitrary constants.
"""
C1, C2 = get_numbered_constants(eq, num=2)
n = Wild('n', exclude=[x(t),y(t)])
f = Wild('f')
u, v, phi = symbols('u, v, phi', function=True)
r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v)
F = r[f].subs(x(t),u).subs(y(t),v)
n = r[n]
if n:
phi = -1/n*log(C1 - n*Integral(1/g, v))
else:
phi = C1 + Integral(1/g, v)
phi = phi.doit()
sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v)
sol = []
for sols in sol2:
sol.append(Eq(x(t),phi.subs(v, sols)))
sol.append(Eq(y(t), sols))
return sol
def _nonlinear_2eq_order1_type3(x, y, t, eq):
r"""
Autonomous system of general form
.. math:: x' = F(x,y)
.. math:: y' = G(x,y)
Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general
solution of the first-order equation
.. math:: F(x,y) y'_x = G(x,y)
Then the general solution of the original system of equations has the form
.. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', function=True)
f = Wild('f')
g = Wild('g')
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
F = r1[f].subs(x(t),u).subs(y(t),v)
G = r2[g].subs(x(t),u).subs(y(t),v)
sol2r = dsolve(Eq(diff(v(u),u), G.subs(v,v(u))/F.subs(v,v(u))))
for sol2s in sol2r:
sol1 = solve(Integral(1/F.subs(v, sol2s.rhs), u).doit() - t - C2, u)
sol = []
for sols in sol1:
sol.append(Eq(x(t), sols))
sol.append(Eq(y(t), (sol2s.rhs).subs(u, sols)))
return sol
def _nonlinear_2eq_order1_type4(x, y, t, eq):
r"""
Equation:
.. math:: x' = f_1(x) g_1(y) \phi(x,y,t)
.. math:: y' = f_2(x) g_2(y) \phi(x,y,t)
First integral:
.. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C
where `C` is an arbitrary constant.
On solving the first integral for `x` (resp., `y` ) and on substituting the
resulting expression into either equation of the original solution, one
arrives at a firs-order equation for determining `y` (resp., `x` ).
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v = symbols('u, v')
f = Wild('f')
g = Wild('g')
f1 = Wild('f1', exclude=[v,t])
f2 = Wild('f2', exclude=[v,t])
g1 = Wild('g1', exclude=[u,t])
g2 = Wild('g2', exclude=[u,t])
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
num, den = (
(r1[f].subs(x(t),u).subs(y(t),v))/
(r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
F1 = R1[f1]; F2 = R2[f2]
G1 = R1[g1]; G2 = R2[g2]
sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u)
sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v)
sol = []
for sols in sol1r:
sol.append(Eq(y(t), dsolve(diff(v(t),t) - F2.subs(u,sols).subs(v,v(t))*G2.subs(v,v(t))*phi.subs(u,sols).subs(v,v(t))).rhs))
for sols in sol2r:
sol.append(Eq(x(t), dsolve(diff(u(t),t) - F1.subs(u,u(t))*G1.subs(v,sols).subs(u,u(t))*phi.subs(v,sols).subs(u,u(t))).rhs))
return set(sol)
def _nonlinear_2eq_order1_type5(func, t, eq):
r"""
Clairaut system of ODEs
.. math:: x = t x' + F(x',y')
.. math:: y = t y' + G(x',y')
The following are solutions of the system
`(i)` straight lines:
.. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2)
where `C_1` and `C_2` are arbitrary constants;
`(ii)` envelopes of the above lines;
`(iii)` continuously differentiable lines made up from segments of the lines
`(i)` and `(ii)`.
"""
C1, C2 = get_numbered_constants(eq, num=2)
f = Wild('f')
g = Wild('g')
def check_type(x, y):
r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
return [r1, r2]
for func_ in func:
if isinstance(func_, list):
x = func[0][0].func
y = func[0][1].func
[r1, r2] = check_type(x, y)
if not (r1 and r2):
[r1, r2] = check_type(y, x)
x, y = y, x
x1 = diff(x(t),t); y1 = diff(y(t),t)
return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))}
def sysode_nonlinear_3eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
z = match_['func'][2].func
eq = match_['eq']
fc = match_['func_coeff']
func = match_['func']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
if match_['type_of_equation'] == 'type1':
sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq)
if match_['type_of_equation'] == 'type2':
sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq)
if match_['type_of_equation'] == 'type3':
sol = _nonlinear_3eq_order1_type3(x, y, z, t, eq)
if match_['type_of_equation'] == 'type4':
sol = _nonlinear_3eq_order1_type4(x, y, z, t, eq)
if match_['type_of_equation'] == 'type5':
sol = _nonlinear_3eq_order1_type5(x, y, z, t, eq)
return sol
def _nonlinear_3eq_order1_type1(x, y, z, t, eq):
r"""
Equations:
.. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y
First Integrals:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
.. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
`z` and on substituting the resulting expressions into the first equation of the
system, we arrives at a separable first-order equation on `x`. Similarly doing that
for other two equations, we will arrive at first order equation on `y` and `z` too.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
r = (diff(x(t),t) - eq[0]).match(p*y(t)*z(t))
r.update((diff(y(t),t) - eq[1]).match(q*z(t)*x(t)))
r.update((diff(z(t),t) - eq[2]).match(s*x(t)*y(t)))
n1, d1 = r[p].as_numer_denom()
n2, d2 = r[q].as_numer_denom()
n3, d3 = r[s].as_numer_denom()
val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w],[u,v])
vals = [val[v], val[u]]
c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
b = vals[0].subs(w,c)
a = vals[1].subs(w,c)
y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
try:
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x).rhs
except:
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x, hint='separable_Integral')
try:
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y).rhs
except:
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y, hint='separable_Integral')
try:
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z).rhs
except:
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z, hint='separable_Integral')
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type2(x, y, z, t, eq):
r"""
Equations:
.. math:: a x' = (b - c) y z f(x, y, z, t)
.. math:: b y' = (c - a) z x f(x, y, z, t)
.. math:: c z' = (a - b) x y f(x, y, z, t)
First Integrals:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
.. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
`z` and on substituting the resulting expressions into the first equation of the
system, we arrives at a first-order differential equations on `x`. Similarly doing
that for other two equations we will arrive at first order equation on `y` and `z`.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
r1 = (diff(x(t),t) - eq[0]).match(y(t)*z(t)*f)
r = collect_const(r1[f]).match(p*f)
r.update(((diff(y(t),t) - eq[1])/r[f]).match(q*z(t)*x(t)))
r.update(((diff(z(t),t) - eq[2])/r[f]).match(s*x(t)*y(t)))
n1, d1 = r[p].as_numer_denom()
n2, d2 = r[q].as_numer_denom()
n3, d3 = r[s].as_numer_denom()
val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, -d3*u+d3*v+n3*w],[u,v])
vals = [val[v], val[u]]
c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
a = vals[0].subs(w,c)
b = vals[1].subs(w,c)
y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
try:
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f]).rhs
except:
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f], hint='separable_Integral')
try:
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f]).rhs
except:
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f], hint='separable_Integral')
try:
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f]).rhs
except:
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f], hint='separable_Integral')
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type3(x, y, z, t, eq):
r"""
Equations:
.. math:: x' = c F_2 - b F_3, \enspace y' = a F_3 - c F_1, \enspace z' = b F_1 - a F_2
where `F_n = F_n(x, y, z, t)`.
1. First Integral:
.. math:: a x + b y + c z = C_1,
where C is an arbitrary constant.
2. If we assume function `F_n` to be independent of `t`,i.e, `F_n` = `F_n (x, y, z)`
Then, on eliminating `t` and `z` from the first two equation of the system, one
arrives at the first-order equation
.. math:: \frac{dy}{dx} = \frac{a F_3 (x, y, z) - c F_1 (x, y, z)}{c F_2 (x, y, z) -
b F_3 (x, y, z)}
where `z = \frac{1}{c} (C_1 - a x - b y)`
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0404.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = (diff(x(t),t) - eq[0]).match(F2-F3)
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t),t) - eq[1]).match(p*r[F3] - r[s]*F1))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w)
z_xy = (C1-a*u-b*v)/c
y_zx = (C1-a*u-c*w)/b
x_yz = (C1-b*v-c*w)/a
y_x = dsolve(diff(v(u),u) - ((a*F3-c*F1)/(c*F2-b*F3)).subs(w,z_xy).subs(v,v(u))).rhs
z_x = dsolve(diff(w(u),u) - ((b*F1-a*F2)/(c*F2-b*F3)).subs(v,y_zx).subs(w,w(u))).rhs
z_y = dsolve(diff(w(v),v) - ((b*F1-a*F2)/(a*F3-c*F1)).subs(u,x_yz).subs(w,w(v))).rhs
x_y = dsolve(diff(u(v),v) - ((c*F2-b*F3)/(a*F3-c*F1)).subs(w,z_xy).subs(u,u(v))).rhs
y_z = dsolve(diff(v(w),w) - ((a*F3-c*F1)/(b*F1-a*F2)).subs(u,x_yz).subs(v,v(w))).rhs
x_z = dsolve(diff(u(w),w) - ((c*F2-b*F3)/(b*F1-a*F2)).subs(v,y_zx).subs(u,u(w))).rhs
sol1 = dsolve(diff(u(t),t) - (c*F2 - b*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs
sol2 = dsolve(diff(v(t),t) - (a*F3 - c*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs
sol3 = dsolve(diff(w(t),t) - (b*F1 - a*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type4(x, y, z, t, eq):
r"""
Equations:
.. math:: x' = c z F_2 - b y F_3, \enspace y' = a x F_3 - c z F_1, \enspace z' = b y F_1 - a x F_2
where `F_n = F_n (x, y, z, t)`
1. First integral:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
where `C` is an arbitrary constant.
2. Assuming the function `F_n` is independent of `t`: `F_n = F_n (x, y, z)`. Then on
eliminating `t` and `z` from the first two equations of the system, one arrives at
the first-order equation
.. math:: \frac{dy}{dx} = \frac{a x F_3 (x, y, z) - c z F_1 (x, y, z)}
{c z F_2 (x, y, z) - b y F_3 (x, y, z)}
where `z = \pm \sqrt{\frac{1}{c} (C_1 - a x^{2} - b y^{2})}`
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0405.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w)
x_yz = sqrt((C1 - b*v**2 - c*w**2)/a)
y_zx = sqrt((C1 - c*w**2 - a*u**2)/b)
z_xy = sqrt((C1 - a*u**2 - b*v**2)/c)
y_x = dsolve(diff(v(u),u) - ((a*u*F3-c*w*F1)/(c*w*F2-b*v*F3)).subs(w,z_xy).subs(v,v(u))).rhs
z_x = dsolve(diff(w(u),u) - ((b*v*F1-a*u*F2)/(c*w*F2-b*v*F3)).subs(v,y_zx).subs(w,w(u))).rhs
z_y = dsolve(diff(w(v),v) - ((b*v*F1-a*u*F2)/(a*u*F3-c*w*F1)).subs(u,x_yz).subs(w,w(v))).rhs
x_y = dsolve(diff(u(v),v) - ((c*w*F2-b*v*F3)/(a*u*F3-c*w*F1)).subs(w,z_xy).subs(u,u(v))).rhs
y_z = dsolve(diff(v(w),w) - ((a*u*F3-c*w*F1)/(b*v*F1-a*u*F2)).subs(u,x_yz).subs(v,v(w))).rhs
x_z = dsolve(diff(u(w),w) - ((c*w*F2-b*v*F3)/(b*v*F1-a*u*F2)).subs(v,y_zx).subs(u,u(w))).rhs
sol1 = dsolve(diff(u(t),t) - (c*w*F2 - b*v*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs
sol2 = dsolve(diff(v(t),t) - (a*u*F3 - c*w*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs
sol3 = dsolve(diff(w(t),t) - (b*v*F1 - a*u*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type5(x, y, t, eq):
r"""
.. math:: x' = x (c F_2 - b F_3), \enspace y' = y (a F_3 - c F_1), \enspace z' = z (b F_1 - a F_2)
where `F_n = F_n (x, y, z, t)` and are arbitrary functions.
First Integral:
.. math:: \left|x\right|^{a} \left|y\right|^{b} \left|z\right|^{c} = C_1
where `C` is an arbitrary constant. If the function `F_n` is independent of `t`,
then, by eliminating `t` and `z` from the first two equations of the system, one
arrives at a first-order equation.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0406.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = eq[0].match(diff(x(t),t) - x(t)*(F2 - F3))
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t),t) - eq[1]).match(y(t)*(a*r[F3] - r[c]*F1)))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w)
x_yz = (C1*v**-b*w**-c)**-a
y_zx = (C1*w**-c*u**-a)**-b
z_xy = (C1*u**-a*v**-b)**-c
y_x = dsolve(diff(v(u),u) - ((v*(a*F3-c*F1))/(u*(c*F2-b*F3))).subs(w,z_xy).subs(v,v(u))).rhs
z_x = dsolve(diff(w(u),u) - ((w*(b*F1-a*F2))/(u*(c*F2-b*F3))).subs(v,y_zx).subs(w,w(u))).rhs
z_y = dsolve(diff(w(v),v) - ((w*(b*F1-a*F2))/(v*(a*F3-c*F1))).subs(u,x_yz).subs(w,w(v))).rhs
x_y = dsolve(diff(u(v),v) - ((u*(c*F2-b*F3))/(v*(a*F3-c*F1))).subs(w,z_xy).subs(u,u(v))).rhs
y_z = dsolve(diff(v(w),w) - ((v*(a*F3-c*F1))/(w*(b*F1-a*F2))).subs(u,x_yz).subs(v,v(w))).rhs
x_z = dsolve(diff(u(w),w) - ((u*(c*F2-b*F3))/(w*(b*F1-a*F2))).subs(v,y_zx).subs(u,u(w))).rhs
sol1 = dsolve(diff(u(t),t) - (u*(c*F2-b*F3)).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs
sol2 = dsolve(diff(v(t),t) - (v*(a*F3-c*F1)).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs
sol3 = dsolve(diff(w(t),t) - (w*(b*F1-a*F2)).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
| bsd-3-clause |
t00m/KB4IT | setup.py | 1 | 2639 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Setup KB4IT project.
# File: setup.py.
# Author: Tomás Vírseda
# License: GPL v3
# Description: setup.py tells you that the module/package you are about
# to install has been packaged and distributed with Distutils, which is
# the standard for distributing Python Modules.
"""
import os
import glob
from setuptools import setup
from kb4it.core.env import APP
with open('pypi/README.rst', 'r') as f:
LONG_DESCRIPTION = f.read()
def add_data(root_data):
"""Add data files from a given directory."""
dir_files = []
resdirs = set()
for root, dirs, files in os.walk(root_data):
resdirs.add(os.path.realpath(root))
resdirs.remove(os.path.realpath(root_data))
for directory in resdirs:
files = glob.glob(directory+'/*')
relfiles = []
for thisfile in files:
if not os.path.isdir(thisfile):
relfiles.append(os.path.relpath(thisfile))
num_files = len(files)
if num_files > 0:
dir_files.append((os.path.relpath(directory), relfiles))
return dir_files
DATA_FILES = add_data('kb4it/resources')
setup(
name=APP['shortname'],
version=APP['version'],
author=APP['author'],
author_email=APP['author_email'],
url=APP['website'],
description='A static website generator based on Asciidoctor sources.',
long_description=LONG_DESCRIPTION,
download_url='https://github.com/t00m/KB4IT/archive/master.zip',
license=APP['license'],
packages=['kb4it', 'kb4it.core', 'kb4it.services'],
# distutils does not support install_requires, but pip needs it to be
# able to automatically install dependencies
install_requires=['mako==1.1.3'],
include_package_data=True,
data_files=DATA_FILES,
zip_safe=False,
platforms='any',
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'Intended Audience :: System Administrators',
'Intended Audience :: Other Audience',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3',
'Topic :: Documentation',
'Topic :: Software Development :: Documentation',
'Topic :: Utilities'
],
entry_points={
'console_scripts': [
'kb4it = kb4it.kb4it:main',
],
},
)
| gpl-3.0 |
sarantapichos/faircoop-market | addons/purchase/partner.py | 210 | 2566 | # -*- 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 res_partner(osv.osv):
_name = 'res.partner'
_inherit = 'res.partner'
def _purchase_invoice_count(self, cr, uid, ids, field_name, arg, context=None):
PurchaseOrder = self.pool['purchase.order']
Invoice = self.pool['account.invoice']
return {
partner_id: {
'purchase_order_count': PurchaseOrder.search_count(cr,uid, [('partner_id', 'child_of', partner_id)], context=context),
'supplier_invoice_count': Invoice.search_count(cr,uid, [('partner_id', 'child_of', partner_id), ('type','=','in_invoice')], context=context)
}
for partner_id in ids
}
def _commercial_fields(self, cr, uid, context=None):
return super(res_partner, self)._commercial_fields(cr, uid, context=context) + ['property_product_pricelist_purchase']
_columns = {
'property_product_pricelist_purchase': fields.property(
type='many2one',
relation='product.pricelist',
domain=[('type','=','purchase')],
string="Purchase Pricelist",
help="This pricelist will be used, instead of the default one, for purchases from the current partner"),
'purchase_order_count': fields.function(_purchase_invoice_count, string='# of Purchase Order', type='integer', multi="count"),
'supplier_invoice_count': fields.function(_purchase_invoice_count, string='# Supplier Invoices', type='integer', multi="count"),
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
bnoi/scikit-tracker | sktracker/detection/tests/test_nuclei_detector.py | 1 | 2695 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import os
from sktracker import data
from sktracker.io import StackIO
from sktracker.detection import nuclei_detector
from nose import with_setup
def setup():
global stack_iter
global metadata
image_path_list = data.stack_list()
metadata = {"PhysicalSizeX": 0.42,
"PhysicalSizeY": 0.42,
"PhysicalSizeZ": 1.5,
"TimeIncrement": 3,
"FileName": '',
"Shape": [1, 1, 512, 512],
"DimensionOrder": "TZYX"}
metadata['FileName'] = image_path_list[0]
stack_io = StackIO(image_path_list=image_path_list,
metadata=metadata)
im0 = stack_io.get_tif().asarray()
correct_metadata = {'FileName': os.path.basename(image_path_list[0]),
'SizeX': im0.shape[2],
'SizeY': im0.shape[1],
'SizeZ': im0.shape[0],
'SizeT': len(image_path_list),
'Shape': (len(image_path_list),
im0.shape[2],
im0.shape[1],
im0.shape[0])}
stack_io.metadata.update(correct_metadata)
metadata = stack_io.metadata
stack_iter = stack_io.list_iterator()
@with_setup(setup)
def test_nuclei_detector_naive():
parameters = {'segment_method': 'naive',
'correction': 0.1,
'nuc_distance': 2.,
'min_z_size': 0.}
cell_positions = nuclei_detector(stack_iter(),
metadata=metadata,
parameters=parameters)
assert cell_positions.shape == (11, 6)
@with_setup(setup)
def test_nuclei_detector_otsu():
parameters = {'segment_method': 'otsu',
'correction': 0.7,
'nuc_distance': 2.,
'min_z_size': 0.}
cell_positions = nuclei_detector(stack_iter(),
metadata=metadata,
parameters=parameters)
assert cell_positions.shape == (9, 6)
@with_setup(setup)
def test_nuclei_detector_none():
parameters = {'segment_method': 'naive',
'correction': 1.,
'min_z_size': 100}
cell_positions = nuclei_detector(stack_iter(),
metadata=metadata,
parameters=parameters)
assert cell_positions.empty is True
| bsd-3-clause |
anbangr/trusted-nova | nova/scheduler/host_manager.py | 7 | 13254 | # Copyright (c) 2011 OpenStack, LLC.
# 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.
"""
Manage hosts in the current zone.
"""
import datetime
import UserDict
from nova import db
from nova import exception
from nova import flags
from nova import log as logging
from nova.openstack.common import cfg
from nova.scheduler import filters
from nova import utils
host_manager_opts = [
cfg.IntOpt('reserved_host_disk_mb',
default=0,
help='Amount of disk in MB to reserve for host/dom0'),
cfg.IntOpt('reserved_host_memory_mb',
default=512,
help='Amount of memory in MB to reserve for host/dom0'),
cfg.MultiStrOpt('scheduler_available_filters',
default=['nova.scheduler.filters.standard_filters'],
help='Filter classes available to the scheduler which may '
'be specified more than once. An entry of '
'"nova.scheduler.filters.standard_filters" '
'maps to all filters included with nova.'),
cfg.ListOpt('scheduler_default_filters',
default=[
'AvailabilityZoneFilter',
'RamFilter',
'ComputeFilter'
],
help='Which filter class names to use for filtering hosts '
'when not specified in the request.'),
]
FLAGS = flags.FLAGS
FLAGS.register_opts(host_manager_opts)
LOG = logging.getLogger(__name__)
class ReadOnlyDict(UserDict.IterableUserDict):
"""A read-only dict."""
def __init__(self, source=None):
self.data = {}
self.update(source)
def __setitem__(self, key, item):
raise TypeError
def __delitem__(self, key):
raise TypeError
def clear(self):
raise TypeError
def pop(self, key, *args):
raise TypeError
def popitem(self):
raise TypeError
def update(self, source=None):
if source is None:
return
elif isinstance(source, UserDict.UserDict):
self.data = source.data
elif isinstance(source, type({})):
self.data = source
else:
raise TypeError
class HostState(object):
"""Mutable and immutable information tracked for a host.
This is an attempt to remove the ad-hoc data structures
previously used and lock down access.
"""
def __init__(self, host, topic, capabilities=None, service=None):
self.host = host
self.topic = topic
# Read-only capability dicts
if capabilities is None:
capabilities = {}
self.capabilities = ReadOnlyDict(capabilities.get(topic, None))
if service is None:
service = {}
self.service = ReadOnlyDict(service)
# Mutable available resources.
# These will change as resources are virtually "consumed".
self.free_ram_mb = 0
self.free_disk_mb = 0
self.vcpus_total = 0
self.vcpus_used = 0
def update_from_compute_node(self, compute):
"""Update information about a host from its compute_node info."""
all_disk_mb = compute['local_gb'] * 1024
all_ram_mb = compute['memory_mb']
vcpus_total = compute['vcpus']
if FLAGS.reserved_host_disk_mb > 0:
all_disk_mb -= FLAGS.reserved_host_disk_mb
if FLAGS.reserved_host_memory_mb > 0:
all_ram_mb -= FLAGS.reserved_host_memory_mb
self.free_ram_mb = all_ram_mb
self.free_disk_mb = all_disk_mb
self.vcpus_total = vcpus_total
def consume_from_instance(self, instance):
"""Update information about a host from instance info."""
disk_mb = (instance['root_gb'] + instance['ephemeral_gb']) * 1024
ram_mb = instance['memory_mb']
vcpus = instance['vcpus']
self.free_ram_mb -= ram_mb
self.free_disk_mb -= disk_mb
self.vcpus_used += vcpus
def passes_filters(self, filter_fns, filter_properties):
"""Return whether or not this host passes filters."""
if self.host in filter_properties.get('ignore_hosts', []):
LOG.debug(_('Host filter fails for ignored host %(host)s'),
{'host': self.host})
return False
force_hosts = filter_properties.get('force_hosts', [])
if force_hosts:
if not self.host in force_hosts:
LOG.debug(_('Host filter fails for non-forced host %(host)s'),
{'host': self.host})
return self.host in force_hosts
for filter_fn in filter_fns:
if not filter_fn(self, filter_properties):
LOG.debug(_('Host filter function %(func)s failed for '
'%(host)s'),
{'func': repr(filter_fn),
'host': self.host})
return False
LOG.debug(_('Host filter passes for %(host)s'), {'host': self.host})
return True
def __repr__(self):
return ("host '%s': free_ram_mb:%s free_disk_mb:%s" %
(self.host, self.free_ram_mb, self.free_disk_mb))
class HostManager(object):
"""Base HostManager class."""
# Can be overriden in a subclass
host_state_cls = HostState
def __init__(self):
self.service_states = {} # { <host> : { <service> : { cap k : v }}}
self.filter_classes = filters.get_filter_classes(
FLAGS.scheduler_available_filters)
def _choose_host_filters(self, filters):
"""Since the caller may specify which filters to use we need
to have an authoritative list of what is permissible. This
function checks the filter names against a predefined set
of acceptable filters.
"""
if filters is None:
filters = FLAGS.scheduler_default_filters
if not isinstance(filters, (list, tuple)):
filters = [filters]
good_filters = []
bad_filters = []
for filter_name in filters:
found_class = False
for cls in self.filter_classes:
if cls.__name__ == filter_name:
found_class = True
filter_instance = cls()
# Get the filter function
filter_func = getattr(filter_instance,
'host_passes', None)
if filter_func:
good_filters.append(filter_func)
break
if not found_class:
bad_filters.append(filter_name)
if bad_filters:
msg = ", ".join(bad_filters)
raise exception.SchedulerHostFilterNotFound(filter_name=msg)
return good_filters
def filter_hosts(self, hosts, filter_properties, filters=None):
"""Filter hosts and return only ones passing all filters"""
filtered_hosts = []
filter_fns = self._choose_host_filters(filters)
for host in hosts:
if host.passes_filters(filter_fns, filter_properties):
filtered_hosts.append(host)
return filtered_hosts
def get_host_list(self):
"""Returns a list of dicts for each host that the Zone Manager
knows about. Each dict contains the host_name and the service
for that host.
"""
all_hosts = self.service_states.keys()
ret = []
for host in self.service_states:
for svc in self.service_states[host]:
ret.append({"service": svc, "host_name": host})
return ret
def get_service_capabilities(self):
"""Roll up all the individual host info to generic 'service'
capabilities. Each capability is aggregated into
<cap>_min and <cap>_max values."""
hosts_dict = self.service_states
# TODO(sandy) - be smarter about fabricating this structure.
# But it's likely to change once we understand what the Best-Match
# code will need better.
combined = {} # { <service>_<cap> : (min, max), ... }
stale_host_services = {} # { host1 : [svc1, svc2], host2 :[svc1]}
for host, host_dict in hosts_dict.iteritems():
for service_name, service_dict in host_dict.iteritems():
if not service_dict.get("enabled", True):
# Service is disabled; do no include it
continue
# Check if the service capabilities became stale
if self.host_service_caps_stale(host, service_name):
if host not in stale_host_services:
stale_host_services[host] = [] # Adding host key once
stale_host_services[host].append(service_name)
continue
for cap, value in service_dict.iteritems():
if cap == "timestamp": # Timestamp is not needed
continue
key = "%s_%s" % (service_name, cap)
min_value, max_value = combined.get(key, (value, value))
min_value = min(min_value, value)
max_value = max(max_value, value)
combined[key] = (min_value, max_value)
# Delete the expired host services
self.delete_expired_host_services(stale_host_services)
return combined
def update_service_capabilities(self, service_name, host, capabilities):
"""Update the per-service capabilities based on this notification."""
LOG.debug(_("Received %(service_name)s service update from "
"%(host)s.") % locals())
service_caps = self.service_states.get(host, {})
# Copy the capabilities, so we don't modify the original dict
capab_copy = dict(capabilities)
capab_copy["timestamp"] = utils.utcnow() # Reported time
service_caps[service_name] = capab_copy
self.service_states[host] = service_caps
def host_service_caps_stale(self, host, service):
"""Check if host service capabilites are not recent enough."""
allowed_time_diff = FLAGS.periodic_interval * 3
caps = self.service_states[host][service]
if ((utils.utcnow() - caps["timestamp"]) <=
datetime.timedelta(seconds=allowed_time_diff)):
return False
return True
def delete_expired_host_services(self, host_services_dict):
"""Delete all the inactive host services information."""
for host, services in host_services_dict.iteritems():
service_caps = self.service_states[host]
for service in services:
del service_caps[service]
if len(service_caps) == 0: # Delete host if no services
del self.service_states[host]
def get_all_host_states(self, context, topic):
"""Returns a dict of all the hosts the HostManager
knows about. Also, each of the consumable resources in HostState
are pre-populated and adjusted based on data in the db.
For example:
{'192.168.1.100': HostState(), ...}
Note: this can be very slow with a lot of instances.
InstanceType table isn't required since a copy is stored
with the instance (in case the InstanceType changed since the
instance was created)."""
if topic != 'compute':
raise NotImplementedError(_(
"host_manager only implemented for 'compute'"))
host_state_map = {}
# Make a compute node dict with the bare essential metrics.
compute_nodes = db.compute_node_get_all(context)
for compute in compute_nodes:
service = compute['service']
if not service:
LOG.warn(_("No service for compute ID %s") % compute['id'])
continue
host = service['host']
capabilities = self.service_states.get(host, None)
host_state = self.host_state_cls(host, topic,
capabilities=capabilities,
service=dict(service.iteritems()))
host_state.update_from_compute_node(compute)
host_state_map[host] = host_state
# "Consume" resources from the host the instance resides on.
instances = db.instance_get_all(context)
for instance in instances:
host = instance['host']
if not host:
continue
host_state = host_state_map.get(host, None)
if not host_state:
continue
host_state.consume_from_instance(instance)
return host_state_map
| apache-2.0 |
zhujzhuo/Sahara | sahara/service/edp/binary_retrievers/internal_swift.py | 10 | 3423 | # Copyright (c) 2013 Mirantis 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 functools
from oslo_config import cfg
import six
import swiftclient
import sahara.context as context
import sahara.exceptions as ex
from sahara.i18n import _
from sahara.swift import utils as su
from sahara.utils.openstack import swift as sw
CONF = cfg.CONF
def _get_names_from_url(url):
parse = six.moves.urllib.parse.urlparse(url)
return (parse.netloc + parse.path).split('/', 1)
def _get_raw_data(job_binary, conn):
names = _get_names_from_url(job_binary.url)
container, obj = names
# if container name has '.sahara' suffix we need to strip it
if container.endswith(su.SWIFT_URL_SUFFIX):
container = container[:-len(su.SWIFT_URL_SUFFIX)]
try:
# First check the size
headers = conn.head_object(container, obj)
total_KB = int(headers.get('content-length', 0)) / 1024.0
if total_KB > CONF.job_binary_max_KB:
raise ex.DataTooBigException(
round(total_KB, 1), CONF.job_binary_max_KB,
_("Size of swift object (%(size)sKB) is greater "
"than maximum (%(maximum)sKB)"))
headers, body = conn.get_object(container, obj)
except swiftclient.ClientException as e:
raise ex.SwiftClientException(six.text_type(e))
return body
def _validate_job_binary_url(f):
@functools.wraps(f)
def wrapper(job_binary, *args, **kwargs):
if not (job_binary.url.startswith(su.SWIFT_INTERNAL_PREFIX)):
# This should have been guaranteed already,
# but we'll check just in case.
raise ex.BadJobBinaryException(
_("Url for binary in internal swift must start with %s")
% su.SWIFT_INTERNAL_PREFIX)
names = _get_names_from_url(job_binary.url)
if len(names) == 1:
# a container has been requested, this is currently unsupported
raise ex.BadJobBinaryException(
_('Url for binary in internal swift must specify an object '
'not a container'))
return f(job_binary, *args, **kwargs)
return wrapper
@_validate_job_binary_url
def get_raw_data(job_binary, proxy_configs=None):
conn_kwargs = {}
if proxy_configs:
conn_kwargs.update(username=proxy_configs.get('proxy_username'),
password=proxy_configs.get('proxy_password'),
trust_id=proxy_configs.get('proxy_trust_id'))
else:
conn_kwargs.update(username=job_binary.extra.get('user'),
password=job_binary.extra.get('password'))
conn = sw.client(**conn_kwargs)
return _get_raw_data(job_binary, conn)
@_validate_job_binary_url
def get_raw_data_with_context(job_binary):
conn = sw.client_from_token(context.ctx().auth_token)
return _get_raw_data(job_binary, conn)
| apache-2.0 |
leki75/ansible | lib/ansible/module_utils/database.py | 108 | 5859 | # This code is part of Ansible, but is an independent component.
# This particular file snippet, and this file snippet only, is BSD licensed.
# Modules you write using this snippet, which is embedded dynamically by Ansible
# still belong to the author of the module, and may assign their own license
# to the complete work.
#
# Copyright (c) 2014, Toshio Kuratomi <tkuratomi@ansible.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:
#
# * 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.
#
# 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.
class SQLParseError(Exception):
pass
class UnclosedQuoteError(SQLParseError):
pass
# maps a type of identifier to the maximum number of dot levels that are
# allowed to specify that identifier. For example, a database column can be
# specified by up to 4 levels: database.schema.table.column
_PG_IDENTIFIER_TO_DOT_LEVEL = dict(database=1, schema=2, table=3, column=4, role=1)
_MYSQL_IDENTIFIER_TO_DOT_LEVEL = dict(database=1, table=2, column=3, role=1, vars=1)
def _find_end_quote(identifier, quote_char):
accumulate = 0
while True:
try:
quote = identifier.index(quote_char)
except ValueError:
raise UnclosedQuoteError
accumulate = accumulate + quote
try:
next_char = identifier[quote + 1]
except IndexError:
return accumulate
if next_char == quote_char:
try:
identifier = identifier[quote + 2:]
accumulate = accumulate + 2
except IndexError:
raise UnclosedQuoteError
else:
return accumulate
def _identifier_parse(identifier, quote_char):
if not identifier:
raise SQLParseError('Identifier name unspecified or unquoted trailing dot')
already_quoted = False
if identifier.startswith(quote_char):
already_quoted = True
try:
end_quote = _find_end_quote(identifier[1:], quote_char=quote_char) + 1
except UnclosedQuoteError:
already_quoted = False
else:
if end_quote < len(identifier) - 1:
if identifier[end_quote + 1] == '.':
dot = end_quote + 1
first_identifier = identifier[:dot]
next_identifier = identifier[dot + 1:]
further_identifiers = _identifier_parse(next_identifier, quote_char)
further_identifiers.insert(0, first_identifier)
else:
raise SQLParseError('User escaped identifiers must escape extra quotes')
else:
further_identifiers = [identifier]
if not already_quoted:
try:
dot = identifier.index('.')
except ValueError:
identifier = identifier.replace(quote_char, quote_char * 2)
identifier = ''.join((quote_char, identifier, quote_char))
further_identifiers = [identifier]
else:
if dot == 0 or dot >= len(identifier) - 1:
identifier = identifier.replace(quote_char, quote_char * 2)
identifier = ''.join((quote_char, identifier, quote_char))
further_identifiers = [identifier]
else:
first_identifier = identifier[:dot]
next_identifier = identifier[dot + 1:]
further_identifiers = _identifier_parse(next_identifier, quote_char)
first_identifier = first_identifier.replace(quote_char, quote_char * 2)
first_identifier = ''.join((quote_char, first_identifier, quote_char))
further_identifiers.insert(0, first_identifier)
return further_identifiers
def pg_quote_identifier(identifier, id_type):
identifier_fragments = _identifier_parse(identifier, quote_char='"')
if len(identifier_fragments) > _PG_IDENTIFIER_TO_DOT_LEVEL[id_type]:
raise SQLParseError('PostgreSQL does not support %s with more than %i dots' % (id_type, _PG_IDENTIFIER_TO_DOT_LEVEL[id_type]))
return '.'.join(identifier_fragments)
def mysql_quote_identifier(identifier, id_type):
identifier_fragments = _identifier_parse(identifier, quote_char='`')
if len(identifier_fragments) > _MYSQL_IDENTIFIER_TO_DOT_LEVEL[id_type]:
raise SQLParseError('MySQL does not support %s with more than %i dots' % (id_type, _MYSQL_IDENTIFIER_TO_DOT_LEVEL[id_type]))
special_cased_fragments = []
for fragment in identifier_fragments:
if fragment == '`*`':
special_cased_fragments.append('*')
else:
special_cased_fragments.append(fragment)
return '.'.join(special_cased_fragments)
| gpl-3.0 |
aam-at/tensorflow | tensorflow/python/eager/def_function_xla_jit_test.py | 2 | 22355 | # Copyright 2019 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.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.compiler.tests import xla_test
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import control_flow_util
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
class DefFunctionTest(xla_test.XLATestCase):
def testAutoclusteringWithTfFunction(self):
if 'tpu' in self.device.lower():
self.skipTest('Autoclustering does not run on TPU')
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=False)
def outer(a, b, c):
return a * inner(b, c) + c
@def_function.function(experimental_compile=True)
def inner(b, c):
return b + c * b
i1 = constant_op.constant([1.0, 2.0, 3.0, 4.0, 5.0])
i2 = constant_op.constant([1.0, 2.0, 3.0, 4.0, 5.0])
i3 = constant_op.constant([1.0, 2.0, 3.0, 4.0, 5.0])
with context.collect_graphs(optimized=True) as graphs:
outer(i1, i2, i3)
if test_util.is_xla_enabled():
self.assertIn('_XlaRun', [n.op for n in graphs[0].node])
else:
self.assertNotIn('_XlaRun', [n.op for n in graphs[0].node])
def testBasic(self):
with ops.device('device:{}:0'.format(self.device)):
def fn(x, a):
return x + a
func = def_function.function(fn, experimental_compile=False)
xla_func = def_function.function(fn, experimental_compile=True)
inputs = constant_op.constant([1, 2, 2, 3, 3])
self.assertAllClose([2, 3, 3, 4, 4], func(inputs, 1))
self.assertAllClose([2, 3, 3, 4, 4], xla_func(inputs, 1))
def testBasicInt32(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def fn(x, a):
return x + a
inputs = constant_op.constant([1, 2, 2, 3, 3], dtype=dtypes.int32)
self.assertAllClose([2, 3, 3, 4, 4], fn(inputs, 1))
def testDerivative(self):
with ops.device('device:{}:0'.format(self.device)):
def fn(x, a):
return 2 * x + a
xla_func = def_function.function(fn, experimental_compile=True)
with backprop.GradientTape() as tape:
inputs = constant_op.constant([1., 2., 2., 3., 3.])
tape.watch(inputs)
outputs = xla_func(inputs, 1)
self.assertAllClose([2, 2, 2, 2, 2], tape.gradient(outputs, inputs))
# pylint: disable=protected-access
(forward, backward) = xla_func.get_concrete_function(
inputs, 1)._delayed_rewrite_functions.forward_backward()
# Check that the must-compile attribute gets correctly propagated to the
# created derivatives.
self.assertTrue(backward.function_def.attr['_XlaMustCompile'])
self.assertTrue(forward.definition.attr['_XlaMustCompile'])
# Calling function with experimental_compile=True from
# experimental_compile=False should compile the inner func.
def testNestedCall(self):
if 'tpu' in self.device.lower():
self.skipTest('b/162800687: Inner function runs on host')
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def fn(x, a):
return x + a
@def_function.function(experimental_compile=False)
def fn2(x, a):
return fn(x, a)
inputs = constant_op.constant([1, 2, 2, 3, 3])
self.assertAllClose([2, 3, 3, 4, 4], fn2(inputs, 1))
@test_util.disable_mlir_bridge('TODO(b/162272821): MLIR bridge returns'
' wrong status type')
def testNestedCallUnsupportedOps(self):
with ops.device('device:{}:0'.format(self.device)):
def fn(x):
return array_ops.unique(x).y
xla_func = def_function.function(fn, experimental_compile=True)
def fn2(x):
return xla_func(x)
func = def_function.function(fn2, experimental_compile=False)
inputs = constant_op.constant([1, 2, 2, 3, 3])
with self.assertRaisesRegex(errors.InvalidArgumentError,
'not compilable'):
func(inputs)
@test_util.disable_mlir_bridge('TODO(b/162272821): MLIR bridge returns'
' wrong status type')
def testUnsupportedOps(self):
with ops.device('device:{}:0'.format(self.device)):
def fn(x):
return array_ops.unique(x).y # Unique is not supported by XLA
func = def_function.function(fn, experimental_compile=False)
xla_func = def_function.function(fn, experimental_compile=True)
inputs = constant_op.constant([1, 2, 2, 3, 3])
self.assertAllClose([1, 2, 3], func(inputs))
with self.assertRaisesRegex(errors.InvalidArgumentError,
'not compilable'):
xla_func(inputs)
def testFunctionGradient(self):
with ops.device('device:{}:0'.format(self.device)):
v = resource_variable_ops.ResourceVariable(2.0)
def fn(x):
return v * x
func = def_function.function(fn, experimental_compile=False)
xla_func = def_function.function(fn, experimental_compile=True)
def run_and_check(test_func):
x = constant_op.constant(3.0)
with backprop.GradientTape() as tape:
y = test_func(x)
dy = tape.gradient(y, v)
self.assertAllClose(6.0, y)
self.assertAllClose(3.0, dy)
run_and_check(func)
run_and_check(xla_func)
@test_util.disable_mlir_bridge('TODO(b/162521846): MLIR bridge fails'
' msan, function library not found')
def testControlFlow(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f(x):
assert control_flow_util.GraphOrParentsInXlaContext(
ops.get_default_graph())
x = ops.convert_to_tensor(x)
def body(i, a):
return i + 1, control_flow_ops.cond(i > 2, lambda: a + (x**2),
lambda: a + 3)
return control_flow_ops.while_loop(
lambda i, *_: i < 10,
body, (constant_op.constant(0), constant_op.constant(3.)),
maximum_iterations=10)[1]
@def_function.function(experimental_compile=True)
def g(x):
x = ops.convert_to_tensor(x)
with backprop.GradientTape() as tape:
tape.watch(x)
y = f(x)
return y, tape.gradient(y, x)
# Test that XLA context gets correctly propagated.
g._get_concrete_function_garbage_collected(2.0)(2.0)
self.assertAllClose(40.0, f(2.0))
self.assertAllClose([40.0, 28.0], g(2.0))
self.assertAllClose(40.0, f.get_concrete_function(2.0)(2.0))
self.assertAllClose([40.0, 28.0], g.get_concrete_function(2.0)(2.0))
def testMethodCompilation(self):
with ops.device('device:{}:0'.format(self.device)):
class C(object):
@def_function.function(experimental_compile=True)
def f1(self, x, a):
return x + a
inputs = constant_op.constant([1, 2, 2, 3, 3])
c = C()
self.assertAllClose([2, 3, 3, 4, 4], c.f1(inputs, 1))
@test_util.disable_mlir_bridge('TODO(b/162272821): MLIR bridge returns '
' wrong status type')
def testMethodCompilationUnsupportedFunc(self):
with ops.device('device:{}:0'.format(self.device)):
class C(object):
@def_function.function(experimental_compile=True)
def f1(self, x):
return array_ops.unique(x).y
inputs = constant_op.constant([1, 2, 2, 3, 3])
c = C()
with self.assertRaisesRegex(errors.InvalidArgumentError,
'not compilable'):
c.f1(inputs)
def testMustBeConstantPropagation(self):
if 'tpu' in self.device.lower():
self.skipTest('b/162799319: Cannot resolve constant on TPU')
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f():
return constant_op.constant([0, 2, 1], dtype=dtypes.int32)
@def_function.function(experimental_compile=True)
def g(a, b):
return array_ops.transpose(a, b)
@def_function.function
def z():
return g(array_ops.ones([3, 4, 3], dtype=dtypes.float32), f())
z()
@test_util.disable_mlir_bridge('TODO(b/162271237): argmax gives different'
' results in MLIR-based bridge')
def testArgMinMax(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def argmax(x):
return math_ops.argmax(x)
@def_function.function(experimental_compile=True)
def argmin(x):
return math_ops.argmin(x)
self.assertAllClose(0, argmax(array_ops.ones([10], dtype=dtypes.float32)))
self.assertAllClose(0, argmax(array_ops.ones([10])))
self.assertAllClose(0, argmin(array_ops.ones([10], dtype=dtypes.float32)))
self.assertAllClose(0, argmin(array_ops.ones([10])))
@test_util.disable_mlir_bridge('TensorArray support not implemented')
def testErrorMessagePassingTensorArray(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f(x):
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=1, element_shape=[])
ta = ta.write(0, 2 * x)
y = ta.read(0)
return y
x = constant_op.constant(3.14)
with backprop.GradientTape() as tape:
tape.watch(x)
with self.assertRaisesRegex(errors.UnimplementedError,
'TensorList crossing the XLA/TF boundary'):
y = f(x)
tape.gradient(y, x)
@test_util.disable_mlir_bridge('TODO(b/162281863): MLIR bridge errors out'
' lowering TensorListConcatV2')
def testTensorListConcatV2(self):
with ops.device('device:{}:0'.format(self.device)):
def f(x):
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=2, element_shape=[3])
ta = ta.write(0, 2 * x)
ta = ta.write(1, 3 * x)
return ta.concat()
compiled_f = def_function.function(experimental_compile=True)(f)
inputs = constant_op.constant([3.14, 2.68, 7.69])
self.assertAllClose([6.28, 5.36, 15.38, 9.42, 8.04, 23.07], f(inputs))
self.assertAllClose(compiled_f(inputs), f(inputs))
@test_util.disable_mlir_bridge('TODO(b/162281863): MLIR bridge errors out'
' lowering TensorListConcatV2')
def testTensorListConcatV2Multidim(self):
with ops.device('device:{}:0'.format(self.device)):
def f(x):
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=2, element_shape=[3, 2])
ta = ta.write(0, 2 * x)
ta = ta.write(1, 3 * x)
return ta.concat()
compiled_f = def_function.function(experimental_compile=True)(f)
inputs = constant_op.constant([[3.14, 21.1], [2.68, 22.2], [7.69, 23.3]])
self.assertAllClose(f(inputs), compiled_f(inputs))
@test_util.disable_mlir_bridge('TODO(b/162281863): MLIR bridge errors out'
' lowering TensorListConcatV2')
def testTensorListConcatV2Scalars(self):
with ops.device('device:{}:0'.format(self.device)):
def f(x):
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=2, element_shape=[1])
ta = ta.write(0, 2 * x)
ta = ta.write(1, 3 * x)
return ta.concat()
compiled_f = def_function.function(experimental_compile=True)(f)
inputs = constant_op.constant([3.14])
self.assertAllClose(f(inputs), compiled_f(inputs))
@test_util.disable_mlir_bridge('TODO(b/162281863): MLIR bridge errors out'
' lowering TensorListConcatV2')
def testTensorListConcatGrad(self):
with ops.device('device:{}:0'.format(self.device)):
def f(x):
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=2, element_shape=[3])
ta = ta.write(0, 2 * x)
ta = ta.write(1, 3 * x)
return ta.concat()
def g():
x = constant_op.constant([3.14, 2.68, 7.69])
with backprop.GradientTape() as tape:
tape.watch(x)
y = f(x)
return tape.gradient(y, x)
compiled_g = def_function.function(experimental_compile=True)(g)
self.assertAllClose([5.0, 5.0, 5.0], g())
self.assertAllClose(compiled_g(), g())
@test_util.disable_mlir_bridge('TODO(b/162281863): MLIR bridge errors out'
' lowering TensorListConcatV2')
def testTensorListConcatGradNestedCompile(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f(x):
ta = tensor_array_ops.TensorArray(
dtype=dtypes.float32, size=2, element_shape=[3])
ta = ta.write(0, 2 * x)
ta = ta.write(1, 3 * x)
return ta.concat()
@def_function.function(experimental_compile=True)
def g():
x = constant_op.constant([3.14, 2.68, 7.69])
with backprop.GradientTape() as tape:
tape.watch(x)
y = f(x)
out = tape.gradient(y, x)
return out
self.assertAllClose([5.0, 5.0, 5.0], g())
def testCumsum(self):
if 'tpu' in self.device.lower():
self.skipTest('b/162771302: 64bit rewrite of cumsum not supported')
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f(x):
return math_ops.cumsum(x)
f64_input = constant_op.constant([1.1, 2.2, 3.3], dtype=dtypes.float64)
self.assertAllClose([1.1, 3.3, 6.6], f(f64_input))
def testNoExcessiveRetracing(self):
with ops.device('device:{}:0'.format(self.device)):
inner_retracings = 0
@def_function.function(experimental_compile=True)
def inner(a, b):
nonlocal inner_retracings
inner_retracings += 1
return a * b + a
def outer(a, b):
return inner(a, b)
func_input = random_ops.random_normal([10, 10])
for _ in range(2):
def_function.function(outer)(func_input, func_input)
self.assertEqual(inner_retracings, 1)
def testUpdateVariable(self):
with ops.device('device:{}:0'.format(self.device)):
on_gpu = 'gpu' in self.device.lower()
v = variables.Variable([3.1, 3.2])
@def_function.function(experimental_compile=True)
def update_var(a, b):
v.assign_add(a * b)
arg1 = random_ops.random_normal([2])
arg2 = random_ops.random_normal([2])
initial_usage = context.context().get_total_memory_usage(
v.device) if on_gpu else 0
update_var(arg1, arg2)
final_usage = context.context().get_total_memory_usage(
v.device) if on_gpu else 0
self.assertEqual(initial_usage, final_usage)
@test_util.disable_mlir_bridge('TODO(b/162381930): MLIR bridge renames '
' functions')
def testUpdateVariableInClass(self):
with ops.device('device:{}:0'.format(self.device)):
class C(object):
@def_function.function(experimental_compile=True)
def update_var(self, a, b):
if not hasattr(self, 'v'):
self.v = variables.Variable(3.1)
self.v.assign_add(a * b)
c = C()
@def_function.function
def outer():
c.update_var(constant_op.constant(0.7), constant_op.constant(0.6))
outer()
self.assertAllClose(c.v, 3.52)
@test_util.disable_mlir_bridge('TODO(b/162801728): MLIR bridge causes '
' invalid free on TPUs')
def testUpdateVariableMultipleOutputs(self):
with ops.device('device:{}:0'.format(self.device)):
v = variables.Variable(3.1)
@def_function.function(experimental_compile=True)
def update_var(a, b):
v.assign_add(a * b)
return a * b + v
out = update_var(constant_op.constant(0.7), constant_op.constant(0.6))
self.assertAllClose(v, 3.52)
self.assertAllClose(out, 3.94)
def testReturnIdentity(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f(a, b):
return (a, b)
a = random_ops.random_normal([10, 10])
b = random_ops.random_normal([10, 10])
on_gpu = 'gpu' in self.device.lower()
initial_usage = context.context().get_total_memory_usage(
b.backing_device) if on_gpu else 0
f(a, b)
final_usage = context.context().get_total_memory_usage(
b.backing_device) if on_gpu else 0
self.assertEqual(initial_usage, final_usage)
def testGetCompilerIrConstants(self):
if 'tpu' in self.device.lower():
self.skipTest('TPU generates different HLO')
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f(a, b):
return array_ops.transpose(a, b)
a = array_ops.ones([3, 4, 3], dtype=dtypes.float32)
b = constant_op.constant([0, 2, 1], dtype=dtypes.int32)
self.assertIn('{1,2,0}',
f.experimental_get_compiler_ir(a, b)(stage='optimized_hlo'))
@test_util.disable_mlir_bridge('TODO(b/168732524): MLIR bridge does not '
' optimize single-element tuples to scalars')
def testGetCompilerIrResourceVars(self):
with ops.device('device:{}:0'.format(self.device)):
v = variables.Variable([3.1, 3.2])
@def_function.function(experimental_compile=True)
def f(a, b):
v.assign_add(a * b)
a = random_ops.random_normal([2])
b = random_ops.random_normal([2])
self.assertIn('input_output_alias={ {}: (2, {}, may-alias) }',
f.experimental_get_compiler_ir(a, b)('optimized_hlo'))
def testGetCompilerIrNotCompiled(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function
def f(x):
return x + 1
a = random_ops.random_normal([10, 10])
with self.assertRaisesRegex(ValueError,
'marked with experimental_compile'):
f.experimental_get_compiler_ir(a)()
def testGetCompilerIrNested(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def fn(x, a):
return x + a
@def_function.function(experimental_compile=False)
def fn2(x, a):
fn.experimental_get_compiler_ir(x, a)()
return fn(x, a)
inputs = constant_op.constant([1, 2, 2, 3, 3])
with self.assertRaisesRegex(TypeError, '"Graph" tensor'):
fn2(inputs, 1)
def testGetCompilerIrKwargs(self):
with ops.device('device:{}:0'.format(self.device)):
v = variables.Variable([0.1, 0.1])
@def_function.function(experimental_compile=True)
def f(a, b):
return (a + b) * v
a = constant_op.constant([1.1, 1.1])
b = constant_op.constant([2.2, 2.2])
self.assertIn('multiply',
f.experimental_get_compiler_ir(b=a, a=b)(stage='hlo'))
def testGetCompilerIrDot(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f(a, b):
return a + b
a = constant_op.constant([1.1, 1.1])
b = constant_op.constant([2.2, 2.2])
self.assertIn(
'label',
f.experimental_get_compiler_ir(a, b)(stage='optimized_hlo_dot'))
def testGetCompilerIrNoDevicePlacement(self):
if 'gpu' not in self.device.lower():
self.skipTest('Testing get_compiler_ir on GPUs without placement')
@def_function.function(experimental_compile=True)
def f(a, b):
return a + b
a = constant_op.constant([1.1, 1.1])
b = constant_op.constant([2.2, 2.2])
self.assertIn(
'label',
f.experimental_get_compiler_ir(a, b)(stage='optimized_hlo_dot'))
def testGetCompilerIrNonTensors(self):
with ops.device('device:{}:0'.format(self.device)):
@def_function.function(experimental_compile=True)
def f(l):
return l[0] + l[1]
l = [constant_op.constant(1.1), constant_op.constant(2.2)]
self.assertIn('tuple',
f.experimental_get_compiler_ir(l)())
def testConstantOnWrongDevice(self):
with ops.device('device:{}:0'.format(self.device)):
s = random_ops.random_uniform([2], 1, 10, dtypes.int32)
l = random_ops.random_normal([s[0] * s[1]])
@def_function.function(experimental_compile=True)
def f(l):
return array_ops.reshape(l, s)
self.assertIn('tuple',
f.experimental_get_compiler_ir(l)())
if __name__ == '__main__':
ops.enable_eager_execution()
test.main()
| apache-2.0 |
RAtechntukan/Sick-Beard | sickbeard/history.py | 35 | 2768 | # Author: Nic Wolfe <nic@wolfeden.ca>
# URL: http://code.google.com/p/sickbeard/
#
# This file is part of Sick Beard.
#
# Sick Beard 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.
#
# Sick Beard 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 Sick Beard. If not, see <http://www.gnu.org/licenses/>.
import db
import datetime
from sickbeard.common import SNATCHED, SUBTITLED, Quality
dateFormat = "%Y%m%d%H%M%S"
def _logHistoryItem(action, showid, season, episode, quality, resource, provider):
logDate = datetime.datetime.today().strftime(dateFormat)
myDB = db.DBConnection()
myDB.action("INSERT INTO history (action, date, showid, season, episode, quality, resource, provider) VALUES (?,?,?,?,?,?,?,?)",
[action, logDate, showid, season, episode, quality, resource, provider])
def logSnatch(searchResult):
for curEpObj in searchResult.episodes:
showid = int(curEpObj.show.tvdbid)
season = int(curEpObj.season)
episode = int(curEpObj.episode)
quality = searchResult.quality
providerClass = searchResult.provider
if providerClass != None:
provider = providerClass.name
else:
provider = "unknown"
action = Quality.compositeStatus(SNATCHED, searchResult.quality)
resource = searchResult.name
_logHistoryItem(action, showid, season, episode, quality, resource, provider)
def logDownload(episode, filename, new_ep_quality, release_group=None):
showid = int(episode.show.tvdbid)
season = int(episode.season)
epNum = int(episode.episode)
quality = new_ep_quality
# store the release group as the provider if possible
if release_group:
provider = release_group
else:
provider = -1
action = episode.status
_logHistoryItem(action, showid, season, epNum, quality, filename, provider)
def logSubtitle(showid, season, episode, status, subtitleResult):
resource = subtitleResult.path
provider = subtitleResult.service
status, quality = Quality.splitCompositeStatus(status)
action = Quality.compositeStatus(SUBTITLED, quality)
_logHistoryItem(action, showid, season, episode, quality, resource, provider) | gpl-3.0 |
noscripter/edgessh | paramiko/message.py | 21 | 8547 | # Copyright (C) 2003-2007 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# Paramiko is distrubuted in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Paramiko; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
"""
Implementation of an SSH2 "message".
"""
import struct
import cStringIO
from paramiko import util
class Message (object):
"""
An SSH2 I{Message} is a stream of bytes that encodes some combination of
strings, integers, bools, and infinite-precision integers (known in python
as I{long}s). This class builds or breaks down such a byte stream.
Normally you don't need to deal with anything this low-level, but it's
exposed for people implementing custom extensions, or features that
paramiko doesn't support yet.
"""
def __init__(self, content=None):
"""
Create a new SSH2 Message.
@param content: the byte stream to use as the Message content (passed
in only when decomposing a Message).
@type content: string
"""
if content != None:
self.packet = cStringIO.StringIO(content)
else:
self.packet = cStringIO.StringIO()
def __str__(self):
"""
Return the byte stream content of this Message, as a string.
@return: the contents of this Message.
@rtype: string
"""
return self.packet.getvalue()
def __repr__(self):
"""
Returns a string representation of this object, for debugging.
@rtype: string
"""
return 'paramiko.Message(' + repr(self.packet.getvalue()) + ')'
def rewind(self):
"""
Rewind the message to the beginning as if no items had been parsed
out of it yet.
"""
self.packet.seek(0)
def get_remainder(self):
"""
Return the bytes of this Message that haven't already been parsed and
returned.
@return: a string of the bytes not parsed yet.
@rtype: string
"""
position = self.packet.tell()
remainder = self.packet.read()
self.packet.seek(position)
return remainder
def get_so_far(self):
"""
Returns the bytes of this Message that have been parsed and returned.
The string passed into a Message's constructor can be regenerated by
concatenating C{get_so_far} and L{get_remainder}.
@return: a string of the bytes parsed so far.
@rtype: string
"""
position = self.packet.tell()
self.rewind()
return self.packet.read(position)
def get_bytes(self, n):
"""
Return the next C{n} bytes of the Message, without decomposing into
an int, string, etc. Just the raw bytes are returned.
@return: a string of the next C{n} bytes of the Message, or a string
of C{n} zero bytes, if there aren't C{n} bytes remaining.
@rtype: string
"""
b = self.packet.read(n)
if len(b) < n:
return b + '\x00' * (n - len(b))
return b
def get_byte(self):
"""
Return the next byte of the Message, without decomposing it. This
is equivalent to L{get_bytes(1)<get_bytes>}.
@return: the next byte of the Message, or C{'\000'} if there aren't
any bytes remaining.
@rtype: string
"""
return self.get_bytes(1)
def get_boolean(self):
"""
Fetch a boolean from the stream.
@return: C{True} or C{False} (from the Message).
@rtype: bool
"""
b = self.get_bytes(1)
return b != '\x00'
def get_int(self):
"""
Fetch an int from the stream.
@return: a 32-bit unsigned integer.
@rtype: int
"""
return struct.unpack('>I', self.get_bytes(4))[0]
def get_int64(self):
"""
Fetch a 64-bit int from the stream.
@return: a 64-bit unsigned integer.
@rtype: long
"""
return struct.unpack('>Q', self.get_bytes(8))[0]
def get_mpint(self):
"""
Fetch a long int (mpint) from the stream.
@return: an arbitrary-length integer.
@rtype: long
"""
return util.inflate_long(self.get_string())
def get_string(self):
"""
Fetch a string from the stream. This could be a byte string and may
contain unprintable characters. (It's not unheard of for a string to
contain another byte-stream Message.)
@return: a string.
@rtype: string
"""
return self.get_bytes(self.get_int())
def get_list(self):
"""
Fetch a list of strings from the stream. These are trivially encoded
as comma-separated values in a string.
@return: a list of strings.
@rtype: list of strings
"""
return self.get_string().split(',')
def add_bytes(self, b):
"""
Write bytes to the stream, without any formatting.
@param b: bytes to add
@type b: str
"""
self.packet.write(b)
return self
def add_byte(self, b):
"""
Write a single byte to the stream, without any formatting.
@param b: byte to add
@type b: str
"""
self.packet.write(b)
return self
def add_boolean(self, b):
"""
Add a boolean value to the stream.
@param b: boolean value to add
@type b: bool
"""
if b:
self.add_byte('\x01')
else:
self.add_byte('\x00')
return self
def add_int(self, n):
"""
Add an integer to the stream.
@param n: integer to add
@type n: int
"""
self.packet.write(struct.pack('>I', n))
return self
def add_int64(self, n):
"""
Add a 64-bit int to the stream.
@param n: long int to add
@type n: long
"""
self.packet.write(struct.pack('>Q', n))
return self
def add_mpint(self, z):
"""
Add a long int to the stream, encoded as an infinite-precision
integer. This method only works on positive numbers.
@param z: long int to add
@type z: long
"""
self.add_string(util.deflate_long(z))
return self
def add_string(self, s):
"""
Add a string to the stream.
@param s: string to add
@type s: str
"""
self.add_int(len(s))
self.packet.write(s)
return self
def add_list(self, l):
"""
Add a list of strings to the stream. They are encoded identically to
a single string of values separated by commas. (Yes, really, that's
how SSH2 does it.)
@param l: list of strings to add
@type l: list(str)
"""
self.add_string(','.join(l))
return self
def _add(self, i):
if type(i) is str:
return self.add_string(i)
elif type(i) is int:
return self.add_int(i)
elif type(i) is long:
if i > 0xffffffffL:
return self.add_mpint(i)
else:
return self.add_int(i)
elif type(i) is bool:
return self.add_boolean(i)
elif type(i) is list:
return self.add_list(i)
else:
raise Exception('Unknown type')
def add(self, *seq):
"""
Add a sequence of items to the stream. The values are encoded based
on their type: str, int, bool, list, or long.
@param seq: the sequence of items
@type seq: sequence
@bug: longs are encoded non-deterministically. Don't use this method.
"""
for item in seq:
self._add(item)
| gpl-2.0 |
flit/pyOCD | pyocd/target/builtin/target_CC3220SF.py | 2 | 6891 | # pyOCD debugger
# Copyright (c) 2018-2019 Arm Limited
# Copyright (c) 2021 Chris Reed
# SPDX-License-Identifier: Apache-2.0
#
# 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
import time
from ...flash.flash import Flash
from ...coresight.coresight_target import CoreSightTarget
from ...core.memory_map import (RomRegion, FlashRegion, RamRegion, MemoryMap)
LOG = logging.getLogger(__name__)
FLASH_ALGO = { 'load_address' : 0x20000000,
'instructions' : [
0xE00ABE00, 0x062D780D, 0x24084068, 0xD3000040, 0x1E644058, 0x1C49D1FA, 0x2A001E52, 0x4770D1F2,
0xd1fd3801, 0x49964770, 0x6e48b418, 0x0000f440, 0x4b946648, 0xf241681a, 0x380140d5, 0xf042d1fd,
0x60180010, 0x40d5f241, 0xd1fd3801, 0xf8d24a8e, 0xf040016c, 0xf8c2003c, 0x4b8c016c, 0xf0406c98,
0x64980001, 0x6480f44f, 0x6cd86820, 0x0001f040, 0xf04f64d8, 0xf8cd0c00, 0x9800c000, 0x90001c40,
0xd3fa2810, 0xf0206cd8, 0x64d80001, 0xf0206c98, 0x64980001, 0x68c0487e, 0x0ffff010, 0x487dd106,
0xc000f8c0, 0x40d5f241, 0xd1fd3801, 0x00c8f8d1, 0x2802b2c0, 0xf8d2d113, 0xf0200110, 0xf420000f,
0xf0406040, 0xf8c20002, 0xf8d20110, 0xf0200114, 0xf420000f, 0xf0406040, 0xf8c20002, 0xf8d20114,
0xf0400184, 0xf8c20002, 0x486b0184, 0xf3c06800, 0x280e5083, 0x00b0f8d1, 0x007cf420, 0xf440bf0c,
0xf4400048, 0xf8c10024, 0x486400b0, 0xf0236803, 0x60035380, 0xb2806820, 0xd2062802, 0x00a8f8d1,
0x0004f040, 0x00a8f8c1, 0x6820e022, 0xd01f0c00, 0x0188f8d2, 0x00e1f040, 0x0188f8c2, 0x68034858,
0x0f01f013, 0x6803d014, 0x0301f023, 0xf8d26003, 0xf4400188, 0xf8c27000, 0x48520188, 0xf0226802,
0x60020201, 0xf8c01d00, 0x1d00c000, 0xc000f8c0, 0x6800484d, 0xf3c00f02, 0x2a036003, 0xd22cd00f,
0x6800484a, 0x1080f3c0, 0x6a88b158, 0x0080f020, 0x69086288, 0x4070f020, 0x5080f040, 0xb9e0e01c,
0x6a48e7ee, 0x000ff020, 0x6070f420, 0x30c0f420, 0x0001f040, 0x60a0f440, 0x3080f440, 0x6a886248,
0x0080f020, 0x4070f020, 0x007ff420, 0x104cf440, 0x69086288, 0x4070f020, 0xbc186108, 0x0000f04f,
0x20004770, 0x48324770, 0x2201f640, 0x49316142, 0x68816081, 0x0f04f011, 0x68c0d1fb, 0xbf184010,
0x47702001, 0x2201f640, 0x614a4929, 0x482a6008, 0x68886088, 0x0f02f010, 0x68c8d1fb, 0xbf184010,
0x47702001, 0xf242b430, 0x4b216c01, 0xc014f8c3, 0xbf182900, 0xc084f8df, 0xf020d01e, 0x601c047f,
0xf000e00b, 0xf105057c, 0xf5054580, 0xf852257d, 0xf8c54b04, 0x1d004100, 0xf0101f09, 0xd1010f7c,
0xb90c6b1c, 0xd1ec2900, 0xc020f8c3, 0xf0146a1c, 0xd1fb0f01, 0xd1e02900, 0x2000bc30, 0x00004770,
0x4402f000, 0x4402fc18, 0x4402e000, 0x44025000, 0x4402d000, 0x4402f804, 0x4402dc78, 0x4402fc74,
0x4402fc20, 0x4402f818, 0x4402dc80, 0x4402f840, 0x400fd000, 0xa4420004, 0xa4420002, 0xa4420001,
0x00000004, 0x00000008, 0x00000014, 0x00000018, 0x00000024, 0x00000028, 0x00000030, 0x00000034,
0x00000040, 0x00000044, 0x00000048, 0x0000004c, 0x00000050, 0x00000054, 0x00000058, 0x0000005c,
0x00000060, 0x00000064, 0x00000068, 0x0000006c, 0x00000070, 0x00000074, 0x00000078, 0x0000007c,
0x00000080, 0x00000084, 0x00000088, 0x0000008c, 0x00000090, 0x00000094, 0x00000098, 0x0000009c,
0x000000a0, 0x000000a4, 0x000000a8, 0x000000ac, 0x000000b8, 0x000000bc, 0x000000c8, 0x000000cc,
0x000000d8, 0x000000dc, 0x00000000, ],
'pc_init' : 0x20000027,
'pc_eraseAll' : 0x200001e7,
'pc_erase_sector' : 0x20000205,
'pc_program_page' : 0x20000225,
'begin_data' : 0x20002000, # Analyzer uses a max of 1 KB data (256 pages * 4 bytes / page)
'page_buffers' : [0x20002000, 0x20004000], # Enable double buffering
'begin_stack' : 0x20000800,
'static_base' : 0x20000368,
'min_program_length' : 4,
'analyzer_supported' : False,
'analyzer_address' : 0x20003000 # Analyzer 0x20003000..0x20003600
}
class Flash_cc3220sf(Flash):
def __init__(self, target):
super(Flash_cc3220sf, self).__init__(target, FLASH_ALGO)
def init(self):
"""
Download the flash algorithm in RAM
"""
self.target.halt()
self.target.reset_and_halt()
# update core register to execute the init subroutine
result = self._call_function_and_wait(self.flash_algo['pc_init'], init=True)
# check the return code
if result != 0:
LOG.error('init error: %i', result)
# erase the cookie which take up one page
self.erase_sector(0x01000000)
time.sleep(.5)
#do a hardware reset which will put the pc looping in rom
self.target.dp.reset()
time.sleep(1.3)
# reconnect to the board
self.target.dp.connect()
self.target.halt()
self.target.reset_and_halt()
# update core register to execute the init subroutine
result = self._call_function_and_wait(self.flash_algo['pc_init'], init=True)
# check the return code
if result != 0:
LOG.error('init error: %i', result)
class CC3220SF(CoreSightTarget):
VENDOR = "Texas Instruments"
MEMORY_MAP = MemoryMap(
RomRegion(start=0x00000000, length=0x00080000),
FlashRegion(start=0x01000000, length=0x00100000, blocksize=0x800, is_boot_memory=True, flash_class=Flash_cc3220sf),
RamRegion(start=0x20000000, length=0x40000)
)
def __init__(self, session):
super(CC3220SF, self).__init__(session, self.MEMORY_MAP)
def post_connect_hook(self):
self.cores[0].default_reset_type = self.ResetType.SW_VECTRESET
| apache-2.0 |
martynovp/edx-platform | common/lib/xmodule/xmodule/tests/test_lti20_unit.py | 174 | 17021 | # -*- coding: utf-8 -*-
"""Tests for LTI Xmodule LTIv2.0 functional logic."""
import datetime
import textwrap
from django.utils.timezone import UTC
from mock import Mock
from xmodule.lti_module import LTIDescriptor
from xmodule.lti_2_util import LTIError
from . import LogicTest
class LTI20RESTResultServiceTest(LogicTest):
"""Logic tests for LTI module. LTI2.0 REST ResultService"""
descriptor_class = LTIDescriptor
def setUp(self):
super(LTI20RESTResultServiceTest, self).setUp()
self.environ = {'wsgi.url_scheme': 'http', 'REQUEST_METHOD': 'POST'}
self.system.get_real_user = Mock()
self.system.publish = Mock()
self.system.rebind_noauth_module_to_user = Mock()
self.user_id = self.xmodule.runtime.anonymous_student_id
self.lti_id = self.xmodule.lti_id
self.xmodule.due = None
self.xmodule.graceperiod = None
def test_sanitize_get_context(self):
"""Tests that the get_context function does basic sanitization"""
# get_context, unfortunately, requires a lot of mocking machinery
mocked_course = Mock(name='mocked_course', lti_passports=['lti_id:test_client:test_secret'])
modulestore = Mock(name='modulestore')
modulestore.get_course.return_value = mocked_course
runtime = Mock(name='runtime', modulestore=modulestore)
self.xmodule.descriptor.runtime = runtime
self.xmodule.lti_id = "lti_id"
test_cases = ( # (before sanitize, after sanitize)
(u"plaintext", u"plaintext"),
(u"a <script>alert(3)</script>", u"a <script>alert(3)</script>"), # encodes scripts
(u"<b>bold 包</b>", u"<b>bold 包</b>"), # unicode, and <b> tags pass through
)
for case in test_cases:
self.xmodule.score_comment = case[0]
self.assertEqual(
case[1],
self.xmodule.get_context()['comment']
)
def test_lti20_rest_bad_contenttype(self):
"""
Input with bad content type
"""
with self.assertRaisesRegexp(LTIError, "Content-Type must be"):
request = Mock(headers={u'Content-Type': u'Non-existent'})
self.xmodule.verify_lti_2_0_result_rest_headers(request)
def test_lti20_rest_failed_oauth_body_verify(self):
"""
Input with bad oauth body hash verification
"""
err_msg = "OAuth body verification failed"
self.xmodule.verify_oauth_body_sign = Mock(side_effect=LTIError(err_msg))
with self.assertRaisesRegexp(LTIError, err_msg):
request = Mock(headers={u'Content-Type': u'application/vnd.ims.lis.v2.result+json'})
self.xmodule.verify_lti_2_0_result_rest_headers(request)
def test_lti20_rest_good_headers(self):
"""
Input with good oauth body hash verification
"""
self.xmodule.verify_oauth_body_sign = Mock(return_value=True)
request = Mock(headers={u'Content-Type': u'application/vnd.ims.lis.v2.result+json'})
self.xmodule.verify_lti_2_0_result_rest_headers(request)
# We just want the above call to complete without exceptions, and to have called verify_oauth_body_sign
self.assertTrue(self.xmodule.verify_oauth_body_sign.called)
BAD_DISPATCH_INPUTS = [
None,
u"",
u"abcd"
u"notuser/abcd"
u"user/"
u"user//"
u"user/gbere/"
u"user/gbere/xsdf"
u"user/ಠ益ಠ" # not alphanumeric
]
def test_lti20_rest_bad_dispatch(self):
"""
Test the error cases for the "dispatch" argument to the LTI 2.0 handler. Anything that doesn't
fit the form user/<anon_id>
"""
for einput in self.BAD_DISPATCH_INPUTS:
with self.assertRaisesRegexp(LTIError, "No valid user id found in endpoint URL"):
self.xmodule.parse_lti_2_0_handler_suffix(einput)
GOOD_DISPATCH_INPUTS = [
(u"user/abcd3", u"abcd3"),
(u"user/Äbcdè2", u"Äbcdè2"), # unicode, just to make sure
]
def test_lti20_rest_good_dispatch(self):
"""
Test the good cases for the "dispatch" argument to the LTI 2.0 handler. Anything that does
fit the form user/<anon_id>
"""
for ginput, expected in self.GOOD_DISPATCH_INPUTS:
self.assertEquals(self.xmodule.parse_lti_2_0_handler_suffix(ginput), expected)
BAD_JSON_INPUTS = [
# (bad inputs, error message expected)
([
u"kk", # ValueError
u"{{}", # ValueError
u"{}}", # ValueError
3, # TypeError
{}, # TypeError
], u"Supplied JSON string in request body could not be decoded"),
([
u"3", # valid json, not array or object
u"[]", # valid json, array too small
u"[3, {}]", # valid json, 1st element not an object
], u"Supplied JSON string is a list that does not contain an object as the first element"),
([
u'{"@type": "NOTResult"}', # @type key must have value 'Result'
], u"JSON object does not contain correct @type attribute"),
([
# @context missing
u'{"@type": "Result", "resultScore": 0.1}',
], u"JSON object does not contain required key"),
([
u'''
{"@type": "Result",
"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"resultScore": 100}''' # score out of range
], u"score value outside the permitted range of 0-1."),
([
u'''
{"@type": "Result",
"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"resultScore": "1b"}''', # score ValueError
u'''
{"@type": "Result",
"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"resultScore": {}}''', # score TypeError
], u"Could not convert resultScore to float"),
]
def test_lti20_bad_json(self):
"""
Test that bad json_str to parse_lti_2_0_result_json inputs raise appropriate LTI Error
"""
for error_inputs, error_message in self.BAD_JSON_INPUTS:
for einput in error_inputs:
with self.assertRaisesRegexp(LTIError, error_message):
self.xmodule.parse_lti_2_0_result_json(einput)
GOOD_JSON_INPUTS = [
(u'''
{"@type": "Result",
"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"resultScore": 0.1}''', u""), # no comment means we expect ""
(u'''
[{"@type": "Result",
"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"@id": "anon_id:abcdef0123456789",
"resultScore": 0.1}]''', u""), # OK to have array of objects -- just take the first. @id is okay too
(u'''
{"@type": "Result",
"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"resultScore": 0.1,
"comment": "ಠ益ಠ"}''', u"ಠ益ಠ"), # unicode comment
]
def test_lti20_good_json(self):
"""
Test the parsing of good comments
"""
for json_str, expected_comment in self.GOOD_JSON_INPUTS:
score, comment = self.xmodule.parse_lti_2_0_result_json(json_str)
self.assertEqual(score, 0.1)
self.assertEqual(comment, expected_comment)
GOOD_JSON_PUT = textwrap.dedent(u"""
{"@type": "Result",
"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"@id": "anon_id:abcdef0123456789",
"resultScore": 0.1,
"comment": "ಠ益ಠ"}
""").encode('utf-8')
GOOD_JSON_PUT_LIKE_DELETE = textwrap.dedent(u"""
{"@type": "Result",
"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"@id": "anon_id:abcdef0123456789",
"comment": "ಠ益ಠ"}
""").encode('utf-8')
def get_signed_lti20_mock_request(self, body, method=u'PUT'):
"""
Example of signed from LTI 2.0 Provider. Signatures and hashes are example only and won't verify
"""
mock_request = Mock()
mock_request.headers = {
'Content-Type': 'application/vnd.ims.lis.v2.result+json',
'Authorization': (
u'OAuth oauth_nonce="135685044251684026041377608307", '
u'oauth_timestamp="1234567890", oauth_version="1.0", '
u'oauth_signature_method="HMAC-SHA1", '
u'oauth_consumer_key="test_client_key", '
u'oauth_signature="my_signature%3D", '
u'oauth_body_hash="gz+PeJZuF2//n9hNUnDj2v5kN70="'
)
}
mock_request.url = u'http://testurl'
mock_request.http_method = method
mock_request.method = method
mock_request.body = body
return mock_request
USER_STANDIN = Mock()
USER_STANDIN.id = 999
def setup_system_xmodule_mocks_for_lti20_request_test(self):
"""
Helper fn to set up mocking for lti 2.0 request test
"""
self.system.get_real_user = Mock(return_value=self.USER_STANDIN)
self.xmodule.max_score = Mock(return_value=1.0)
self.xmodule.get_client_key_secret = Mock(return_value=('test_client_key', u'test_client_secret'))
self.xmodule.verify_oauth_body_sign = Mock()
def test_lti20_put_like_delete_success(self):
"""
The happy path for LTI 2.0 PUT that acts like a delete
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
SCORE = 0.55 # pylint: disable=invalid-name
COMMENT = u"ಠ益ಠ" # pylint: disable=invalid-name
self.xmodule.module_score = SCORE
self.xmodule.score_comment = COMMENT
mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT_LIKE_DELETE)
# Now call the handler
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
# Now assert there's no score
self.assertEqual(response.status_code, 200)
self.assertIsNone(self.xmodule.module_score)
self.assertEqual(self.xmodule.score_comment, u"")
(_, evt_type, called_grade_obj), _ = self.system.publish.call_args
self.assertEqual(called_grade_obj, {'user_id': self.USER_STANDIN.id, 'value': None, 'max_value': None})
self.assertEqual(evt_type, 'grade')
def test_lti20_delete_success(self):
"""
The happy path for LTI 2.0 DELETE
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
SCORE = 0.55 # pylint: disable=invalid-name
COMMENT = u"ಠ益ಠ" # pylint: disable=invalid-name
self.xmodule.module_score = SCORE
self.xmodule.score_comment = COMMENT
mock_request = self.get_signed_lti20_mock_request("", method=u'DELETE')
# Now call the handler
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
# Now assert there's no score
self.assertEqual(response.status_code, 200)
self.assertIsNone(self.xmodule.module_score)
self.assertEqual(self.xmodule.score_comment, u"")
(_, evt_type, called_grade_obj), _ = self.system.publish.call_args
self.assertEqual(called_grade_obj, {'user_id': self.USER_STANDIN.id, 'value': None, 'max_value': None})
self.assertEqual(evt_type, 'grade')
def test_lti20_put_set_score_success(self):
"""
The happy path for LTI 2.0 PUT that sets a score
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT)
# Now call the handler
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
# Now assert
self.assertEqual(response.status_code, 200)
self.assertEqual(self.xmodule.module_score, 0.1)
self.assertEqual(self.xmodule.score_comment, u"ಠ益ಠ")
(_, evt_type, called_grade_obj), _ = self.system.publish.call_args
self.assertEqual(evt_type, 'grade')
self.assertEqual(called_grade_obj, {'user_id': self.USER_STANDIN.id, 'value': 0.1, 'max_value': 1.0})
def test_lti20_get_no_score_success(self):
"""
The happy path for LTI 2.0 GET when there's no score
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
mock_request = self.get_signed_lti20_mock_request("", method=u'GET')
# Now call the handler
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
# Now assert
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json, {"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"@type": "Result"})
def test_lti20_get_with_score_success(self):
"""
The happy path for LTI 2.0 GET when there is a score
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
SCORE = 0.55 # pylint: disable=invalid-name
COMMENT = u"ಠ益ಠ" # pylint: disable=invalid-name
self.xmodule.module_score = SCORE
self.xmodule.score_comment = COMMENT
mock_request = self.get_signed_lti20_mock_request("", method=u'GET')
# Now call the handler
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
# Now assert
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json, {"@context": "http://purl.imsglobal.org/ctx/lis/v2/Result",
"@type": "Result",
"resultScore": SCORE,
"comment": COMMENT})
UNSUPPORTED_HTTP_METHODS = ["OPTIONS", "HEAD", "POST", "TRACE", "CONNECT"]
def test_lti20_unsupported_method_error(self):
"""
Test we get a 404 when we don't GET or PUT
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT)
for bad_method in self.UNSUPPORTED_HTTP_METHODS:
mock_request.method = bad_method
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
self.assertEqual(response.status_code, 404)
def test_lti20_request_handler_bad_headers(self):
"""
Test that we get a 401 when header verification fails
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
self.xmodule.verify_lti_2_0_result_rest_headers = Mock(side_effect=LTIError())
mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT)
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
self.assertEqual(response.status_code, 401)
def test_lti20_request_handler_bad_dispatch_user(self):
"""
Test that we get a 404 when there's no (or badly formatted) user specified in the url
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT)
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, None)
self.assertEqual(response.status_code, 404)
def test_lti20_request_handler_bad_json(self):
"""
Test that we get a 404 when json verification fails
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
self.xmodule.parse_lti_2_0_result_json = Mock(side_effect=LTIError())
mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT)
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
self.assertEqual(response.status_code, 404)
def test_lti20_request_handler_bad_user(self):
"""
Test that we get a 404 when the supplied user does not exist
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
self.system.get_real_user = Mock(return_value=None)
mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT)
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
self.assertEqual(response.status_code, 404)
def test_lti20_request_handler_grade_past_due(self):
"""
Test that we get a 404 when accept_grades_past_due is False and it is past due
"""
self.setup_system_xmodule_mocks_for_lti20_request_test()
self.xmodule.due = datetime.datetime.now(UTC())
self.xmodule.accept_grades_past_due = False
mock_request = self.get_signed_lti20_mock_request(self.GOOD_JSON_PUT)
response = self.xmodule.lti_2_0_result_rest_handler(mock_request, "user/abcd")
self.assertEqual(response.status_code, 404)
| agpl-3.0 |
dpad/sumatra | sumatra/publishing/sphinxext/sumatra_rst.py | 5 | 7340 | """
idea for an "smtimage" directive (and "smtfigure" similarly) which would be used
like
.. smtimage:: 20120907-153528 demo_cx05_N=500b_LTS_d274f9660531.png
:project: Destexhe_JCNS_2009
:record_store: /path/to/recordstore/file or http://smt.andrewdavison.info/records
:digest: DIGEST_GOES_HERE_FOR_CHECKING (optional)
This would query the recordstore, make a copy of the image file in a temporary
directory, and preferably clean up the temporary directory later (use "pending" node?).
If using a MirroredFileSystemDataStore could just use URL
The project name and recordstore directive are optional if rst2xxxx is used in a Sumatra project directory
:copyright: Copyright 2006-2015 by the Sumatra team, see doc/authors.txt
:license: BSD 2-clause, see LICENSE for details.
"""
from __future__ import unicode_literals
from docutils.parsers.rst import directives, states
from docutils.parsers.rst.directives.images import Image
from docutils.parsers.rst.roles import set_classes
from docutils.parsers.rst import roles
from docutils import nodes, utils
from sumatra.publishing.utils import determine_project, determine_record_store, \
determine_project_name, record_link_url, \
get_image, get_record_label_and_image_path
import os.path
LOCAL_IMAGE_CACHE = "smt_images" # should use tempfile?
def smt_link_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
label = text
settings = inliner.document.settings
ref = "%s/%s/%s/" % (settings.sumatra_record_store,
settings.sumatra_project,
label)
set_classes(options)
node = nodes.reference(rawtext, '', refuri=ref,
**options)
node += nodes.image(uri=settings.sumatra_link_icon, alt='smt:' + utils.unescape(text))
return [node], []
roles.register_local_role('smtlink', smt_link_role)
def build_options(global_settings, local_options):
if hasattr(global_settings, 'env'): # using sphinx
config = global_settings.env.config
else:
config = global_settings # using plain docutils
# convert config into dict, and strip "sumatra_" prefix
combined_options = {}
for name in ("record_store", "project", "link_icon"):
full_name = "sumatra_" + name
if hasattr(config, full_name):
combined_options[name] = getattr(config, full_name)
combined_options.update(local_options)
return combined_options
class SumatraImage(Image):
required_arguments = 1 # Sumatra label
optional_arguments = 1 # path to image file. Not required if record has only a single image file as output
final_argument_whitespace = False
option_spec = {'alt': directives.unchanged,
'height': directives.length_or_unitless,
'width': directives.length_or_percentage_or_unitless,
'scale': directives.percentage,
'align': lambda argument: directives.choice(argument, Image.align_values),
'name': directives.unchanged,
'target': directives.unchanged_required,
'class': directives.class_option,
'project': directives.unchanged,
'record_store': directives.unchanged,
'digest': directives.unchanged,
}
def run(self):
if 'align' in self.options:
if isinstance(self.state, states.SubstitutionDef):
# Check for align_v_values.
if self.options['align'] not in self.align_v_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value '
'for the "align" option within a substitution '
'definition. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_v_values)))
elif self.options['align'] not in self.align_h_values:
raise self.error(
'Error in "%s" directive: "%s" is not a valid value for '
'the "align" option. Valid values for "align" are: "%s".'
% (self.name, self.options['align'],
'", "'.join(self.align_h_values)))
messages = []
# previous code from Image.run()
# --------------------------------------------------------------------
sumatra_options = build_options(self.state.document.settings, self.options)
# determine which record store to use
prj = determine_project(sumatra_options)
record_store = determine_record_store(prj, sumatra_options, self.error)
# determine the project (short) name
project_name = determine_project_name(prj, sumatra_options, self.error)
record_label, image_path = get_record_label_and_image_path(self.arguments[0])
record = record_store.get(project_name, record_label)
image = get_image(record, image_path, self.options, self.error) # automatically checks digest
if hasattr(image, "url"):
reference = image.url
else:
if not os.path.exists(LOCAL_IMAGE_CACHE):
os.makedirs(LOCAL_IMAGE_CACHE)
reference = image.save_copy(LOCAL_IMAGE_CACHE)
# set values for alt and target, if they have not been specified
if not 'target' in self.options and hasattr(record_store, 'server_url'):
self.options['target'] = record_link_url(record_store.server_url, project_name, record_label)
if not 'alt' in self.options:
self.options['alt'] = "Data file generated by computation %s" % record_label
# --------------------------------------------------------------------
# following code from Image.run()
self.options['uri'] = reference
reference_node = None
if 'target' in self.options:
block = states.escape2null(
self.options['target']).splitlines()
block = [line for line in block]
target_type, data = self.state.parse_target(
block, self.block_text, self.lineno)
if target_type == 'refuri':
reference_node = nodes.reference(refuri=data)
elif target_type == 'refname':
reference_node = nodes.reference(
refname=fully_normalize_name(data),
name=whitespace_normalize_name(data))
reference_node.indirect_reference_name = data
self.state.document.note_refname(reference_node)
else: # malformed target
messages.append(data) # data is a system message
del self.options['target']
set_classes(self.options)
image_node = nodes.image(self.block_text, **self.options)
self.add_name(image_node)
if reference_node:
reference_node += image_node
return messages + [reference_node]
else:
return messages + [image_node]
directives.register_directive("smtimage", SumatraImage)
# possible glyphicons for links to record store
# icon-search
# icon-file
# icon-bookmark
# icon-info-sign
# icon-comment
# icon-book
| bsd-2-clause |
jelugbo/ddi | cms/djangoapps/contentstore/tests/test_core_caching.py | 31 | 1702 | from cache_toolbox.core import get_cached_content, set_cached_content, del_cached_content
from opaque_keys.edx.locations import Location
from django.test import TestCase
class Content:
def __init__(self, location, content):
self.location = location
self.content = content
def get_id(self):
return self.location.to_deprecated_son()
class CachingTestCase(TestCase):
# Tests for https://edx.lighthouseapp.com/projects/102637/tickets/112-updating-asset-does-not-refresh-the-cached-copy
unicodeLocation = Location(u'c4x', u'mitX', u'800', u'run', u'thumbnail', u'monsters.jpg')
# Note that some of the parts are strings instead of unicode strings
nonUnicodeLocation = Location('c4x', u'mitX', u'800', u'run', 'thumbnail', 'monsters.jpg')
mockAsset = Content(unicodeLocation, 'my content')
def test_put_and_get(self):
set_cached_content(self.mockAsset)
self.assertEqual(self.mockAsset.content, get_cached_content(self.unicodeLocation).content,
'should be stored in cache with unicodeLocation')
self.assertEqual(self.mockAsset.content, get_cached_content(self.nonUnicodeLocation).content,
'should be stored in cache with nonUnicodeLocation')
def test_delete(self):
set_cached_content(self.mockAsset)
del_cached_content(self.nonUnicodeLocation)
self.assertEqual(None, get_cached_content(self.unicodeLocation),
'should not be stored in cache with unicodeLocation')
self.assertEqual(None, get_cached_content(self.nonUnicodeLocation),
'should not be stored in cache with nonUnicodeLocation')
| agpl-3.0 |
yatinkumbhare/openstack-nova | nova/api/openstack/compute/plugins/v3/migrations.py | 29 | 2283 | # 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 nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova import compute
from nova.objects import base as obj_base
ALIAS = "os-migrations"
def authorize(context, action_name):
extensions.os_compute_authorizer(ALIAS)(context, action=action_name)
def output(migrations_obj):
"""Returns the desired output of the API from an object.
From a MigrationsList's object this method returns a list of
primitive objects with the only necessary fields.
"""
objects = obj_base.obj_to_primitive(migrations_obj)
objects = [x for x in objects if not x['hidden']]
for obj in objects:
del obj['deleted']
del obj['deleted_at']
del obj['migration_type']
del obj['hidden']
return objects
class MigrationsController(wsgi.Controller):
"""Controller for accessing migrations in OpenStack API."""
def __init__(self):
self.compute_api = compute.API()
@extensions.expected_errors(())
def index(self, req):
"""Return all migrations in progress."""
context = req.environ['nova.context']
authorize(context, "index")
migrations = self.compute_api.get_migrations(context, req.GET)
return {'migrations': output(migrations)}
class Migrations(extensions.V3APIExtensionBase):
"""Provide data on migrations."""
name = "Migrations"
alias = ALIAS
version = 1
def get_resources(self):
resources = []
resource = extensions.ResourceExtension(ALIAS,
MigrationsController())
resources.append(resource)
return resources
def get_controller_extensions(self):
return []
| apache-2.0 |
tynn/numpy | numpy/distutils/line_endings.py | 256 | 2053 | """ Functions for converting from DOS to UNIX line endings
"""
from __future__ import division, absolute_import, print_function
import sys, re, os
def dos2unix(file):
"Replace CRLF with LF in argument files. Print names of changed files."
if os.path.isdir(file):
print(file, "Directory!")
return
data = open(file, "rb").read()
if '\0' in data:
print(file, "Binary!")
return
newdata = re.sub("\r\n", "\n", data)
if newdata != data:
print('dos2unix:', file)
f = open(file, "wb")
f.write(newdata)
f.close()
return file
else:
print(file, 'ok')
def dos2unix_one_dir(modified_files, dir_name, file_names):
for file in file_names:
full_path = os.path.join(dir_name, file)
file = dos2unix(full_path)
if file is not None:
modified_files.append(file)
def dos2unix_dir(dir_name):
modified_files = []
os.path.walk(dir_name, dos2unix_one_dir, modified_files)
return modified_files
#----------------------------------
def unix2dos(file):
"Replace LF with CRLF in argument files. Print names of changed files."
if os.path.isdir(file):
print(file, "Directory!")
return
data = open(file, "rb").read()
if '\0' in data:
print(file, "Binary!")
return
newdata = re.sub("\r\n", "\n", data)
newdata = re.sub("\n", "\r\n", newdata)
if newdata != data:
print('unix2dos:', file)
f = open(file, "wb")
f.write(newdata)
f.close()
return file
else:
print(file, 'ok')
def unix2dos_one_dir(modified_files, dir_name, file_names):
for file in file_names:
full_path = os.path.join(dir_name, file)
unix2dos(full_path)
if file is not None:
modified_files.append(file)
def unix2dos_dir(dir_name):
modified_files = []
os.path.walk(dir_name, unix2dos_one_dir, modified_files)
return modified_files
if __name__ == "__main__":
dos2unix_dir(sys.argv[1])
| bsd-3-clause |
PyMamba/mamba-storm | storm/django/middleware.py | 4 | 3107 | #
# Copyright (c) 2008 Canonical
#
# Written by James Henstridge <jamesh@canonical.com>
#
# This file is part of Storm Object Relational Mapper.
#
# Storm is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# Storm is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
"""Django middleware support for the Zope transaction manager.
Adding storm.django.middleware.ZopeTransactionMiddleware to
L{MIDDLEWARE_CLASSES} in the application's settings module will cause a
Zope transaction to be run for each request.
"""
__all__ = ['ZopeTransactionMiddleware']
from django.conf import settings
import transaction
class ZopeTransactionMiddleware(object):
"""Zope Transaction middleware for Django.
If this is enabled, a Zope transaction will be run to cover each
request.
"""
def __init__(self):
self.commit_safe_methods = getattr(
settings, 'STORM_COMMIT_SAFE_METHODS', True)
def process_request(self, request):
"""Begin a transaction on request start.."""
from django.db import transaction as django_transaction
django_transaction.enter_transaction_management()
django_transaction.managed(True)
transaction.begin()
def process_exception(self, request, exception):
"""Abort the transaction on errors."""
from django.db import transaction as django_transaction
transaction.abort()
django_transaction.set_clean()
django_transaction.leave_transaction_management()
def process_response(self, request, response):
"""Commit or abort the transaction after processing the response.
On successful completion of the request, the transaction will
be committed.
As an exception to this, if the L{STORM_COMMIT_SAFE_METHODS}
setting is False, and the request used either of the GET and
HEAD methods, the transaction will be aborted.
"""
from django.db import transaction as django_transaction
# If process_exception() has been called, then we'll no longer
# be in managed transaction mode.
if django_transaction.is_managed():
if self.commit_safe_methods or (
request.method not in ['HEAD', 'GET']):
try:
transaction.commit()
except Exception:
transaction.abort()
raise
else:
transaction.abort()
django_transaction.set_clean()
django_transaction.leave_transaction_management()
return response
| lgpl-2.1 |
xavierwu/scikit-learn | sklearn/cluster/setup.py | 263 | 1449 | # Author: Alexandre Gramfort <alexandre.gramfort@inria.fr>
# License: BSD 3 clause
import os
from os.path import join
import numpy
from sklearn._build_utils import get_blas_info
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
cblas_libs, blas_info = get_blas_info()
libraries = []
if os.name == 'posix':
cblas_libs.append('m')
libraries.append('m')
config = Configuration('cluster', parent_package, top_path)
config.add_extension('_dbscan_inner',
sources=['_dbscan_inner.cpp'],
include_dirs=[numpy.get_include()],
language="c++")
config.add_extension('_hierarchical',
sources=['_hierarchical.cpp'],
language="c++",
include_dirs=[numpy.get_include()],
libraries=libraries)
config.add_extension(
'_k_means',
libraries=cblas_libs,
sources=['_k_means.c'],
include_dirs=[join('..', 'src', 'cblas'),
numpy.get_include(),
blas_info.pop('include_dirs', [])],
extra_compile_args=blas_info.pop('extra_compile_args', []),
**blas_info
)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(**configuration(top_path='').todict())
| bsd-3-clause |
dan-cristian/haiot | cloud/graph_plotly/__init__.py | 1 | 12450 | __author__ = 'dcristian'
import os
from main.logger_helper import L
from common import Constant, utils
from storage.sqalc import model_helper, models
from main import thread_pool
#fixme: make it work without plotly
try:
import plotly.plotly as py
from plotly import graph_objs
from plotly.exceptions import PlotlyAccountError
import graph_plotly_run
except Exception, ex:
pass
initialised = False
# updated plotly cache on all hosts to allow grid update in case mastership changes
def record_update(obj):
source_host_name = utils.get_object_field_value(obj, Constant.JSON_PUBLISH_SOURCE_HOST)
if source_host_name != Constant.HOST_NAME:
# Log.logger.info("Received plotly cache update from {}".format(source_host_name))
models.PlotlyCache().save_changed_fields_from_json_object(json_object=obj, notify_transport_enabled=False,
save_to_graph=False)
# uploads data directly to a graph object in plotly
# not very reliable since plotly changed the API
def upload_data(obj):
try:
L.l.debug('Trying to upload plotly obj {}'.format(obj))
if Constant.JSON_PUBLISH_GRAPH_X in obj:
axis_x_field = obj[Constant.JSON_PUBLISH_GRAPH_X]
graph_id_field = obj[Constant.JSON_PUBLISH_GRAPH_ID]
graph_legend_field = obj[Constant.JSON_PUBLISH_GRAPH_LEGEND]
graph_shape_fields = obj[Constant.JSON_PUBLISH_GRAPH_SHAPE]
graph_y_fields = obj[Constant.JSON_PUBLISH_GRAPH_Y]
changed_fields = obj[Constant.JSON_PUBLISH_FIELDS_CHANGED]
# intersect lists and get only graphable fields that had values changed
list_axis_y = list(set(graph_y_fields) & set(changed_fields))
if len(list_axis_y) == 0:
L.l.debug('Ignoring graph upload graph={} changed={} obj={}'.format(graph_y_fields,
changed_fields, obj))
L.l.debug('Trying to upload y axis {}'.format(list_axis_y))
if axis_x_field in obj and graph_id_field in obj:
table = obj[Constant.JSON_PUBLISH_TABLE]
trace_unique_id = obj[graph_id_field] # unique record/trace identifier
x_val = obj[axis_x_field]
graph_legend_item_name = obj[graph_legend_field] # unique key for legend
x_val = utils.parse_to_date(x_val)
x = [x_val]
index = 0
for axis_y in list_axis_y:
if axis_y in obj:
trace_list = []
y = [obj[axis_y]]
# shape visual type for this trace
shape = graph_shape_fields[index]
# unique name used for graph on upload
graph_base_name = str(table + ' ' + axis_y)
# full name and path to enable archiving
graph_unique_name = graph_plotly_run.get_graph_full_name_path(graph_base_name)
if not graph_plotly_run.graph_url_exists_in_memory(graph_unique_name):
# download series order list to ensure graph consistency, usually done at app start
# or when trace is created
graph_plotly_run.download_trace_id_list(graph_unique_name=graph_unique_name,
shape_type=shape)
if graph_unique_name in graph_plotly_run.g_trace_id_list_per_graph:
trace_unique_id_pattern = graph_plotly_run.g_trace_id_list_per_graph[graph_unique_name]
else:
L.l.warning('Unable to get a reference pattern, graph {}'.format(graph_unique_name))
known_graph_url = graph_plotly_run.get_graph_url_from_memory(graph_unique_name)
if trace_unique_id in trace_unique_id_pattern:
trace_list = graph_plotly_run.populate_trace_for_extend(x=x, y=y,
graph_legend_item_name=graph_legend_item_name,
trace_unique_id=trace_unique_id,
trace_unique_id_pattern=trace_unique_id_pattern,
shape_type=shape)
L.l.debug('Extending graph {}'.format(graph_unique_name, shape))
fileopt = 'extend'
else:
trace_list = graph_plotly_run.populate_trace_for_append(x=x, y=y,
graph_legend_item_name=graph_legend_item_name,
trace_unique_id=trace_unique_id,
shape_type=shape)
L.l.debug('Appending graph {}'.format(graph_unique_name))
fileopt = 'append'
data = graph_objs.Data(trace_list)
try:
if known_graph_url is None:
L.l.warning('Graph {} is setting up, dropping data'.format(graph_unique_name))
else:
graph_plotly_run.add_graph_data(data=data, graph_unique_name=graph_unique_name,
trace_unique_id=trace_unique_id, file_opt=fileopt)
except PlotlyAccountError, ex:
L.l.warning('Unable to plot graph, err {}'.format(ex))
index += 1
else:
L.l.critical(
'Graphable object missing axis_x [{}], graph_id [{}], in obj {}'.format(axis_x_field,
graph_id_field, obj))
else:
L.l.critical('Graphable object missing axis X field {}'.format(Constant.JSON_PUBLISH_GRAPH_X))
except Exception, ex:
L.l.exception('General error saving graph, err {} obj={}'.format(ex, obj))
'''
#upload data to a grid object in plotly. grid will be used as main source to generate graphs
def upload_data_to_grid(obj):
try:
Log.logger.debug('Trying to upload plotly grid record {}'.format(obj))
if Constant.JSON_PUBLISH_GRAPH_X in obj:
#name of x field
axis_x_field = obj[Constant.JSON_PUBLISH_GRAPH_X]
graph_id_field = obj[Constant.JSON_PUBLISH_GRAPH_ID]
graph_legend_field = obj[Constant.JSON_PUBLISH_GRAPH_LEGEND]
graph_shape_fields = obj[Constant.JSON_PUBLISH_GRAPH_SHAPE]
graph_y_fields = obj[Constant.JSON_PUBLISH_GRAPH_Y]
#names of fields that have value changed to record smallest amount of data
changed_fields = obj[Constant.JSON_PUBLISH_FIELDS_CHANGED]
#intersect lists and get only graphable fields that had values changed
list_axis_y = list(set(graph_y_fields) & set(changed_fields))
if len(list_axis_y)==0:
Log.logger.debug('Ignoring graph upload graph={} changed fields={} obj={}'.format(graph_y_fields,
changed_fields, obj))
else:
Log.logger.debug('Trying to upload y axis {}'.format(list_axis_y))
if axis_x_field in obj and graph_id_field in obj:
table = obj[Constant.JSON_PUBLISH_TABLE]
trace_unique_id = obj[graph_id_field] #unique record/trace identifier
x_val = obj[axis_x_field]
graph_legend_item_name = obj[graph_legend_field] #unique key for legend
x_val = utils.parse_to_date(x_val)
x = x_val
index = 0
for axis_y in list_axis_y:
if axis_y in obj:
trace_list = []
y=obj[axis_y]
#shape visual type for this trace
shape = graph_shape_fields[index]
#unique name used for grid on upload
grid_base_name = str(table)
graph_plotly_run.add_grid_data(grid_unique_name=grid_base_name, x=x, y=y,
axis_x_name=axis_x_field, axis_y_name=axis_y,
record_unique_id_name=graph_legend_field,
record_unique_id_value=graph_legend_item_name)
index += 1
else:
Log.logger.critical('Graphable object missing axis_x [{}], graph_id [{}], in obj {}'.format(axis_x_field,
graph_id_field, obj))
else:
Log.logger.critical('Graphable object missing axis X field {}'.format(Constant.JSON_PUBLISH_GRAPH_X))
except Exception, ex:
Log.logger.exception('General error saving graph, err {} obj={}'.format(ex, obj))
'''
def unload():
global initialised
thread_pool.remove_callable(graph_plotly_run.thread_run)
initialised = False
def init():
# use auto setup as described here: https://plot.ly/python/getting-started/ to avoid passwords in code
# or less secure sign_in code below
# py.sign_in(model_helper.get_param(constant.P_PLOTLY_USERNAME),model_helper.get_param(constant.P_PLOTLY_APIKEY))
username = ""
if py.get_credentials()['username'] == '' or py.get_credentials()['api_key'] == '':
env_var = 'PLOTLY_CREDENTIALS_PATH'
alt_path = os.environ.get(env_var)
if not alt_path:
L.l.info('Plotly config not in environment var: {}'.format(env_var))
env_var = 'OPENSHIFT_REPO_DIR'
alt_path = os.environ.get(env_var)
if alt_path is None:
L.l.info('Plotly config not in environment var: {}'.format(env_var))
credential_file = model_helper.get_param(Constant.P_PLOTLY_ALTERNATE_CONFIG)
alt_path = os.getcwd() + '/' + credential_file
else:
L.l.info('Plotly config found in environment var: {}, path={}'.format(env_var, alt_path))
alt_path = str(alt_path) + '/../data/.plotly.credentials'
L.l.info("Plotly standard config empty, trying alt_path={}".format(alt_path))
try:
with open(alt_path, 'r') as cred_file:
data = cred_file.read().replace('\n', '')
if len(data) > 0:
cred_obj = utils.json2obj(data)
username = cred_obj['username']
api_key = cred_obj['api_key']
if username and api_key:
py.sign_in(username, api_key)
global initialised
initialised = True
# else:
# Log.logger.info("Plotly init from db folder config {}{} not ok, trying with db data".format(os.getcwd(),
# credential_file))
# #alternate way if reading data from DB
# py.sign_in(model_helper.get_param(constant.P_PLOTLY_USERNAME),
# model_helper.get_param(constant.P_PLOTLY_APIKEY))
except Exception, ex:
L.l.warning("error reading plotly credentials {}".format(ex))
else:
L.l.info("Plotly standard config found with username {}".format(py.get_credentials()['username']))
initialised = True
if initialised:
L.l.info('Plotly is connected with username={}'.format(username))
thread_pool.add_interval_callable(graph_plotly_run.thread_run, run_interval_second=60)
| gpl-2.0 |
aggiedefenders/aggiedefenders.github.io | node_modules/node-forge/tests/policyserver.py | 171 | 3551 | #!/usr/bin/env python
"""
Flash Socket Policy Server.
- Starts Flash socket policy file server.
- Defaults to port 843.
- NOTE: Most operating systems require administrative privileges to use
ports under 1024.
$ ./policyserver.py [options]
"""
"""
Also consider Adobe's solutions:
http://www.adobe.com/devnet/flashplayer/articles/socket_policy_files.html
"""
from multiprocessing import Process
from optparse import OptionParser
import SocketServer
import logging
# Set address reuse for all TCPServers
SocketServer.TCPServer.allow_reuse_address = True
# Static socket policy file string.
# NOTE: This format is very strict. Edit with care.
socket_policy_file = """\
<?xml version="1.0"?>\
<!DOCTYPE cross-domain-policy\
SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">\
<cross-domain-policy>\
<allow-access-from domain="*" to-ports="*"/>\
</cross-domain-policy>\0"""
class PolicyHandler(SocketServer.BaseRequestHandler):
"""
The RequestHandler class for our server.
Returns a policy file when requested.
"""
def handle(self):
"""Send policy string if proper request string is received."""
# get some data
# TODO: make this more robust (while loop, etc)
self.data = self.request.recv(1024).rstrip('\0')
logging.debug("%s wrote:%s" % (self.client_address[0], repr(self.data)))
# if policy file request, send the file.
if self.data == "<policy-file-request/>":
logging.info("Policy server request from %s." % (self.client_address[0]))
self.request.send(socket_policy_file)
else:
logging.info("Policy server received junk from %s: \"%s\"" % \
(self.client_address[0], repr(self.data)))
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
def serve_forever(self):
"""Handle one request at a time until shutdown or keyboard interrupt."""
try:
SocketServer.BaseServer.serve_forever(self)
except KeyboardInterrupt:
return
def main():
"""Run socket policy file servers."""
usage = "Usage: %prog [options]"
parser = OptionParser(usage=usage)
parser.add_option("", "--host", dest="host", metavar="HOST",
default="localhost", help="bind to HOST")
parser.add_option("-p", "--port", dest="port", metavar="PORT",
default=843, type="int", help="serve on PORT")
parser.add_option("-d", "--debug", dest="debug", action="store_true",
default=False, help="debugging output")
parser.add_option("-v", "--verbose", dest="verbose", action="store_true",
default=False, help="verbose output")
(options, args) = parser.parse_args()
# setup logging
if options.debug:
lvl = logging.DEBUG
elif options.verbose:
lvl = logging.INFO
else:
lvl = logging.WARNING
logging.basicConfig(level=lvl, format="%(levelname)-8s %(message)s")
# log basic info
logging.info("Flash Socket Policy Server. Use ctrl-c to exit.")
# create policy server
logging.info("Socket policy serving on %s:%d." % (options.host, options.port))
policyd = ThreadedTCPServer((options.host, options.port), PolicyHandler)
# start server
policy_p = Process(target=policyd.serve_forever)
policy_p.start()
while policy_p.is_alive():
try:
policy_p.join(1)
except KeyboardInterrupt:
logging.info("Stopping test server...")
if __name__ == "__main__":
main()
| mit |
pabulumm/neighbors | lib/python3.4/site-packages/django/contrib/postgres/operations.py | 374 | 1377 | from django.contrib.postgres.signals import register_hstore_handler
from django.db.migrations.operations.base import Operation
class CreateExtension(Operation):
reversible = True
def __init__(self, name):
self.name = name
def state_forwards(self, app_label, state):
pass
def database_forwards(self, app_label, schema_editor, from_state, to_state):
if schema_editor.connection.vendor != 'postgresql':
return
schema_editor.execute("CREATE EXTENSION IF NOT EXISTS %s" % self.name)
def database_backwards(self, app_label, schema_editor, from_state, to_state):
schema_editor.execute("DROP EXTENSION %s" % self.name)
def describe(self):
return "Creates extension %s" % self.name
class HStoreExtension(CreateExtension):
def __init__(self):
self.name = 'hstore'
def database_forwards(self, app_label, schema_editor, from_state, to_state):
super(HStoreExtension, self).database_forwards(app_label, schema_editor, from_state, to_state)
# Register hstore straight away as it cannot be done before the
# extension is installed, a subsequent data migration would use the
# same connection
register_hstore_handler(schema_editor.connection)
class UnaccentExtension(CreateExtension):
def __init__(self):
self.name = 'unaccent'
| bsd-3-clause |
greggian/TapdIn | django/contrib/gis/gdal/error.py | 13 | 1559 | """
This module houses the OGR & SRS Exception objects, and the
check_err() routine which checks the status code returned by
OGR methods.
"""
#### OGR & SRS Exceptions ####
class GDALException(Exception): pass
class OGRException(Exception): pass
class SRSException(Exception): pass
class OGRIndexError(OGRException, KeyError):
"""
This exception is raised when an invalid index is encountered, and has
the 'silent_variable_feature' attribute set to true. This ensures that
django's templates proceed to use the next lookup type gracefully when
an Exception is raised. Fixes ticket #4740.
"""
silent_variable_failure = True
#### OGR error checking codes and routine ####
# OGR Error Codes
OGRERR_DICT = { 1 : (OGRException, 'Not enough data.'),
2 : (OGRException, 'Not enough memory.'),
3 : (OGRException, 'Unsupported geometry type.'),
4 : (OGRException, 'Unsupported operation.'),
5 : (OGRException, 'Corrupt data.'),
6 : (OGRException, 'OGR failure.'),
7 : (SRSException, 'Unsupported SRS.'),
8 : (OGRException, 'Invalid handle.'),
}
OGRERR_NONE = 0
def check_err(code):
"Checks the given OGRERR, and raises an exception where appropriate."
if code == OGRERR_NONE:
return
elif code in OGRERR_DICT:
e, msg = OGRERR_DICT[code]
raise e, msg
else:
raise OGRException('Unknown error code: "%s"' % code)
| apache-2.0 |
WebArchivCZ/WA-KAT | src/wa_kat/templates/static/js/Lib/site-packages/components/author_picker.py | 1 | 7164 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: brython (http://brython.info) (like python3)
#
"""
Module with interface for picking authors from authority base in NK's Aleph.
"""
#
# Imports =====================================================================
import json
from os.path import join
from browser import html
from browser import alert
from browser import document
from .shared import make_request
from .shared import func_on_enter
from .log_view2 import LogView
from .progressbar import AuthorBar
from .author_switcher import SWITCHER_EL
from .overlay_controller import BlackOverlay
# virtual filesystem / modules provided by REST API
from virtual_fs import settings
# Functions & classes =========================================================
class AuthorPicker(object):
"""
This component is responsible for generating the interface for picking
authors from Aleph.
"""
original_author_el = document["author"]
div_el = document["author_picker"] # whole <div>
input_el = document["author_input"] # <input> for author's name
search_btn_el = document["search_author"] # trigger the search of author
select_el = document["author_select"] # <select> element with authors
storno_btn_el = document["storno_author"] # used to storno the picking
pick_btn_el = document["pick_author"] # used to accept the selected author
overlay = BlackOverlay()
code_to_data = {} # this is used to translate select back to data
selected_code = None
@classmethod
def show(cls):
"""
Show the author picker.
"""
cls.div_el.style.display = "block"
cls.hide_errors()
cls.overlay.show()
cls.overlay.el.bind("click", lambda x: cls.hide())
@classmethod
def hide(cls):
"""
Hide the author picker.
"""
cls.overlay.hide()
cls.div_el.style.display = "none"
@classmethod
def hide_errors(cls):
"""
Hide errors shown by validators.
"""
cls.select_el.style.border = "0"
cls.input_el.style.border = "0"
@classmethod
def _pick_selected_option(cls):
"""
Select handler for authors.
"""
for option in cls.select_el:
# if the select is empty
if not hasattr(option, "selected"):
return None
if option.selected:
return option.value
return None
@classmethod
def on_pick_button_pressed(cls, ev):
"""
Callback called when the user press the button for accepting the picked
author.
This element calls validations, before accepting the choice.
"""
cls.hide_errors()
selected_code = cls._pick_selected_option()
if not selected_code:
cls.select_el.style.border = "2px solid red"
return
cls.selected_code = selected_code
cls.code = str(selected_code)
cls.original_author_el.value = cls.code_to_data[selected_code].get(
"alt_name",
str(cls.code_to_data[selected_code])
)
cls.hide()
@classmethod
def set_select(cls, authors):
"""
Put data into ``<select>`` element.
Args:
authors (dict): Dictionary with author informations returned from
aleph REST API. Format:
``{"name": .., "code": .., "linked_forms": ["..",]}``.
"""
cls.select_el.html = ""
if not authors:
cls.select_el.disabled = True
cls.select_el <= html.OPTION("Nic nenalezeno!")
return
cls.select_el.disabled = False
for author_dict in authors:
name = author_dict.get("name")
code = author_dict.get("code")
alt_name = author_dict.get("alt_name", name)
if not (name and code):
continue
cls.code_to_data[code] = author_dict
cls.select_el <= html.OPTION(alt_name, value=code)
@classmethod
def bind(cls):
"""
Bind the callbacks to the buttons.
"""
document["show_author_picker"].bind("click", lambda x: cls.show())
cls.storno_btn_el.bind("click", lambda x: cls.hide())
cls.pick_btn_el.bind("click", cls.on_pick_button_pressed)
@classmethod
def __get__(cls, obj, objtype):
if not SWITCHER_EL.checked:
return None
return cls.code_to_data[cls.selected_code]
@classmethod
def __set__(cls, obj, value):
# called by reset()
if not value:
cls.selected_code = None
cls.original_author_el.value = ""
return
if type(value) in [list, tuple]:
value = value[0]
code = value["code"]
cls.code_to_data[code] = value
cls.selected_code = code
cls.original_author_el.value = cls.code_to_data[code].get(
"alt_name",
str(cls.code_to_data[code])
)
@classmethod
def validate(cls):
"""
Validate required elements.
"""
if not SWITCHER_EL.checked:
return True
if not cls.selected_code:
cls.original_author_el.style.border = "2px solid red"
return False
cls.original_author_el.style.border = "0"
return True
class AuthorPickerAdapter(AuthorPicker):
"""
Adapter of the :class:`AuthorPicker` to aleph REST API.
This adapter is mapped to the key / button press. It then launches querying
of the REST API in periodic interval, updating the progress bar and so on.
"""
@classmethod
def on_complete(cls, req):
"""
Callback called when the request was received.
"""
# handle http errors
if not (req.status == 200 or req.status == 0):
alert("Couldn't connect to authority base.")
LogView.add(
"Error when calling Aleph authority base: %s" % req.text
)
AuthorBar.hide()
return
AuthorBar.hide()
cls.set_select(json.loads(req.text))
@classmethod
def start(cls, ev):
"""
Event handler which starts the request to REST API.
"""
# somehow the first call doesn't stop the propagation
ev.stopPropagation()
ev.preventDefault()
# make sure, that `author` was filled
author = cls.input_el.value.strip()
if not author:
cls.input_el.style.border = "2px solid red"
return
cls.hide_errors()
AuthorBar.show(50)
make_request(
url=join(settings.API_PATH, "aleph/authors_by_name"),
data={"name": author},
on_complete=cls.on_complete
)
@classmethod
def bind(cls):
"""
Bind the buttons to adapter's event handler.
"""
super(cls, cls).bind()
cls.search_btn_el.bind("click", cls.start)
cls.input_el.bind("keypress", func_on_enter(cls.start))
AuthorPickerAdapter.bind()
| mit |
CivicKnowledge/metaeditor | editor/migrations/0006_auto_20150309_0945.py | 1 | 6631 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import mptt.fields
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('editor', '0005_auto_20150222_0508'),
]
operations = [
migrations.RemoveField(
model_name='dataset',
name='coverage_name',
),
migrations.RemoveField(
model_name='dataset',
name='coverage_type',
),
migrations.AddField(
model_name='dataset',
name='coverage',
field=models.CharField(default='?', max_length=50, choices=[(b'national', b'National'), (b'state', b'State'), (b'county', b'County'), (b'sub-county', b'Sub county')]),
preserve_default=False,
),
migrations.AddField(
model_name='dataset',
name='region',
field=models.CharField(default='?', max_length=100, choices=[(b'state', b'State'), (b'state_and_county', b'State and county')]),
preserve_default=False,
),
migrations.AlterField(
model_name='category',
name='name',
field=models.CharField(help_text=b'The name of the category', max_length=100),
preserve_default=True,
),
migrations.AlterField(
model_name='category',
name='parent',
field=mptt.fields.TreeForeignKey(blank=True, to='editor.Category', help_text=b'A link to another category', null=True),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='categories',
field=models.ManyToManyField(help_text=b'Multiple links to names of categories.', to='editor.Category'),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='contacts',
field=models.TextField(help_text=b'Freeform text of people to email or call about the dataset. '),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='download_page',
field=models.URLField(help_text=b'URL of a web page where dataset files can be downloaded.'),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='end_year',
field=models.IntegerField(help_text=b'The last year for which the dataset has data.'),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='entry_time_minutes',
field=models.IntegerField(help_text=b'A record of how long the user spent creating the record.'),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='formats',
field=models.ManyToManyField(help_text=b'Collection of Formats associated with this dataset.', to='editor.Format'),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='page',
field=models.URLField(help_text=b'URL of a web page about the dataset.'),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='start_year',
field=models.IntegerField(help_text=b'The first year for which the dataset has data.'),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='title',
field=models.CharField(help_text=b'The title of the dataset.', max_length=200),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='user',
field=models.ForeignKey(help_text=b'Link to the user that edited this dataset. ', to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
migrations.AlterField(
model_name='dataset',
name='variant',
field=models.CharField(help_text=b'Distinguished this dataset from similar datasets.', max_length=100),
preserve_default=True,
),
migrations.AlterField(
model_name='format',
name='name',
field=models.CharField(help_text=b'The name of the format.', max_length=100),
preserve_default=True,
),
migrations.AlterField(
model_name='format',
name='parent',
field=mptt.fields.TreeForeignKey(blank=True, to='editor.Format', help_text=b'A link to another format.', null=True),
preserve_default=True,
),
migrations.AlterField(
model_name='source',
name='abbreviation',
field=models.CharField(help_text=b'A common abbreviation for the name of the source, such as "HHS".', max_length=50),
preserve_default=True,
),
migrations.AlterField(
model_name='source',
name='about',
field=models.TextField(help_text=b'Freeform text, paragraph length.'),
preserve_default=True,
),
migrations.AlterField(
model_name='source',
name='categories',
field=models.ManyToManyField(help_text=b'Multiple links to names of categories.', to='editor.Category'),
preserve_default=True,
),
migrations.AlterField(
model_name='source',
name='domain',
field=models.CharField(help_text=b'A short string, by default derived from the Home page url.', max_length=50),
preserve_default=True,
),
migrations.AlterField(
model_name='source',
name='homepage',
field=models.URLField(help_text=b'URL of the home page for the organization.'),
preserve_default=True,
),
migrations.AlterField(
model_name='source',
name='name',
field=models.CharField(help_text=b'Formal name of the source. such as "Department of Health and Human Services".', max_length=200),
preserve_default=True,
),
migrations.AlterField(
model_name='source',
name='parent',
field=mptt.fields.TreeForeignKey(blank=True, to='editor.Source', help_text=b'A link to another source.', null=True),
preserve_default=True,
),
]
| mit |
xiangke/pycopia | mibs/pycopia/mibs/HPR_MIB.py | 1 | 21285 | # python
# This file is generated by a program (mib2py). Any edits will be lost.
from pycopia.aid import Enum
import pycopia.SMI.Basetypes
Range = pycopia.SMI.Basetypes.Range
Ranges = pycopia.SMI.Basetypes.Ranges
from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, NodeObject, ModuleObject, GroupObject
# imports
from SNMPv2_SMI import Counter32, Gauge32, Unsigned32, TimeTicks, OBJECT_TYPE, MODULE_IDENTITY
from SNMPv2_CONF import MODULE_COMPLIANCE, OBJECT_GROUP
from SNA_NAU_MIB import snanauMIB
from SNMPv2_TC import DisplayString, DateAndTime, TimeStamp, TEXTUAL_CONVENTION
from APPN_MIB import SnaControlPointName
class HPR_MIB(ModuleObject):
path = '/usr/share/snmp/mibs/ietf/HPR-MIB'
conformance = 3
name = 'HPR-MIB'
language = 2
description = 'This is the MIB module for objects used to\nmanage network devices with HPR capabilities.'
# nodes
class hprMIB(NodeObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6])
name = 'hprMIB'
class hprObjects(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1])
name = 'hprObjects'
class hprGlobal(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 1])
name = 'hprGlobal'
class hprAnrRouting(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2])
name = 'hprAnrRouting'
class hprTransportUser(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 3])
name = 'hprTransportUser'
class hprRtp(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4])
name = 'hprRtp'
class hprRtpGlobe(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 1])
name = 'hprRtpGlobe'
class hprConformance(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 2])
name = 'hprConformance'
class hprCompliances(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 2, 1])
name = 'hprCompliances'
class hprGroups(NodeObject):
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 2, 2])
name = 'hprGroups'
# macros
# types
class HprNceTypes(pycopia.SMI.Basetypes.BITS):
status = 1
enumerations = [Enum(0, 'controlPoint'), Enum(1, 'logicalUnit'), Enum(2, 'boundaryFunction'), Enum(3, 'routeSetup')]
class HprRtpCounter(pycopia.SMI.Basetypes.Counter32):
status = 1
# scalars
class hprNodeCpName(ScalarObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 1, 1])
syntaxobject = SnaControlPointName
class hprOperatorPathSwitchSupport(ScalarObject):
status = 1
access = 4
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 1, 2])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'notSupported'), Enum(2, 'switchTriggerSupported'), Enum(3, 'switchToPathSupported')]
class hprAnrsAssigned(ScalarObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 1])
syntaxobject = pycopia.SMI.Basetypes.Counter32
access = 4
units = 'ANR labels'
class hprAnrCounterState(ScalarObject):
status = 1
access = 5
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 2])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'notActive'), Enum(2, 'active')]
class hprAnrCounterStateTime(ScalarObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 3])
syntaxobject = pycopia.SMI.Basetypes.DateAndTime
class hprRtpGlobeConnSetups(ScalarObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 1, 1])
syntaxobject = pycopia.SMI.Basetypes.Counter32
access = 4
units = 'RTP connection setups'
class hprRtpGlobeCtrState(ScalarObject):
status = 1
access = 5
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 1, 2])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'notActive'), Enum(2, 'active')]
class hprRtpGlobeCtrStateTime(ScalarObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 1, 3])
syntaxobject = pycopia.SMI.Basetypes.DateAndTime
# columns
class hprAnrLabel(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 4, 1, 1])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprAnrType(ColumnObject):
status = 1
access = 4
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 4, 1, 2])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'nce'), Enum(2, 'tg')]
class hprAnrOutTgDest(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 4, 1, 3])
syntaxobject = pycopia.SMI.Basetypes.DisplayString
class hprAnrOutTgNum(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 4, 1, 4])
syntaxobject = pycopia.SMI.Basetypes.Integer32
class hprAnrPacketsReceived(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 4, 1, 5])
syntaxobject = pycopia.SMI.Basetypes.Counter32
access = 4
units = 'ANR packets'
class hprAnrCounterDisconTime(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 4, 1, 6])
syntaxobject = pycopia.SMI.Basetypes.TimeStamp
class hprNceId(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 3, 1, 1, 1])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprNceType(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 3, 1, 1, 2])
syntaxobject = HprNceTypes
class hprNceDefault(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 3, 1, 1, 3])
syntaxobject = HprNceTypes
class hprNceInstanceId(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 3, 1, 1, 4])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpLocNceId(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 1])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpLocTcid(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 2])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpRemCpName(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 3])
syntaxobject = SnaControlPointName
class hprRtpRemNceId(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 4])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpRemTcid(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 5])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpPathSwitchTrigger(ColumnObject):
status = 1
access = 5
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 6])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'ready'), Enum(2, 'switchPathNow')]
class hprRtpRscv(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 7])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpTopic(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 8])
syntaxobject = pycopia.SMI.Basetypes.DisplayString
class hprRtpState(ColumnObject):
status = 1
access = 4
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 9])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'rtpListening'), Enum(2, 'rtpCalling'), Enum(3, 'rtpConnected'), Enum(4, 'rtpPathSwitching'), Enum(5, 'rtpDisconnecting'), Enum(99, 'other')]
class hprRtpUpTime(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 10])
syntaxobject = pycopia.SMI.Basetypes.TimeTicks
access = 4
units = '1/100ths of a second'
class hprRtpLivenessTimer(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 11])
syntaxobject = pycopia.SMI.Basetypes.Unsigned32
access = 4
units = '1/100ths of a second'
class hprRtpShortReqTimer(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 12])
syntaxobject = pycopia.SMI.Basetypes.Unsigned32
access = 4
units = '1/100ths of a second'
class hprRtpPathSwTimer(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 13])
syntaxobject = pycopia.SMI.Basetypes.Unsigned32
access = 4
units = '1/100ths of a second'
class hprRtpLivenessTimeouts(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 14])
syntaxobject = HprRtpCounter
access = 4
units = 'liveness timeouts'
class hprRtpShortReqTimeouts(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 15])
syntaxobject = HprRtpCounter
access = 4
units = 'short request timeouts'
class hprRtpMaxSendRate(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 16])
syntaxobject = pycopia.SMI.Basetypes.Gauge32
access = 4
units = 'bytes per second'
class hprRtpMinSendRate(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 17])
syntaxobject = pycopia.SMI.Basetypes.Gauge32
access = 4
units = 'bytes per second'
class hprRtpCurSendRate(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 18])
syntaxobject = pycopia.SMI.Basetypes.Gauge32
access = 4
units = 'bytes per second'
class hprRtpSmRdTripDelay(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 19])
syntaxobject = pycopia.SMI.Basetypes.Gauge32
access = 4
units = '1/1000ths of a second'
class hprRtpSendPackets(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 20])
syntaxobject = HprRtpCounter
access = 4
units = 'RTP packets'
class hprRtpRecvPackets(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 21])
syntaxobject = HprRtpCounter
access = 4
units = 'RTP packets'
class hprRtpSendBytes(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 22])
syntaxobject = HprRtpCounter
access = 4
units = 'bytes'
class hprRtpRecvBytes(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 23])
syntaxobject = HprRtpCounter
access = 4
units = 'bytes'
class hprRtpRetrPackets(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 24])
syntaxobject = HprRtpCounter
access = 4
units = 'RTP packets'
class hprRtpPacketsDiscarded(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 25])
syntaxobject = HprRtpCounter
access = 4
units = 'RTP packets'
class hprRtpDetectGaps(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 26])
syntaxobject = HprRtpCounter
access = 4
units = 'gaps'
class hprRtpRateReqSends(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 27])
syntaxobject = HprRtpCounter
access = 4
units = 'rate requests'
class hprRtpOkErrPathSws(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 28])
syntaxobject = HprRtpCounter
access = 4
units = 'path switch attempts'
class hprRtpBadErrPathSws(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 29])
syntaxobject = HprRtpCounter
access = 4
units = 'path switch attempts'
class hprRtpOkOpPathSws(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 30])
syntaxobject = HprRtpCounter
access = 4
units = 'path switches'
class hprRtpBadOpPathSws(ColumnObject):
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 31])
syntaxobject = HprRtpCounter
access = 4
units = 'path switches'
class hprRtpCounterDisconTime(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1, 32])
syntaxobject = pycopia.SMI.Basetypes.TimeStamp
class hprRtpStatusLocNceId(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 1])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpStatusLocTcid(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 2])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpStatusIndex(ColumnObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 3])
syntaxobject = pycopia.SMI.Basetypes.Unsigned32
class hprRtpStatusStartTime(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 4])
syntaxobject = pycopia.SMI.Basetypes.DateAndTime
class hprRtpStatusEndTime(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 5])
syntaxobject = pycopia.SMI.Basetypes.DateAndTime
class hprRtpStatusRemCpName(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 6])
syntaxobject = SnaControlPointName
class hprRtpStatusRemNceId(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 7])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpStatusRemTcid(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 8])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpStatusNewRscv(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 9])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpStatusOldRscv(ColumnObject):
access = 4
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 10])
syntaxobject = pycopia.SMI.Basetypes.OctetString
class hprRtpStatusCause(ColumnObject):
status = 1
access = 4
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 11])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'other'), Enum(2, 'rtpConnFail'), Enum(3, 'locLinkFail'), Enum(4, 'remLinkFail'), Enum(5, 'operRequest')]
class hprRtpStatusLastAttemptResult(ColumnObject):
status = 1
access = 4
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1, 12])
syntaxobject = pycopia.SMI.Basetypes.Enumeration
enumerations = [Enum(1, 'successful'), Enum(2, 'initiatorMoving'), Enum(3, 'directorySearchFailed'), Enum(4, 'rscvCalculationFailed'), Enum(5, 'negativeRouteSetupReply'), Enum(6, 'backoutRouteSetupReply'), Enum(7, 'timeoutDuringFirstAttempt'), Enum(8, 'otherUnsuccessful')]
# rows
class hprAnrRoutingEntry(RowObject):
status = 1
index = pycopia.SMI.Objects.IndexObjects([hprAnrLabel], False)
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 2, 4, 1])
access = 2
columns = {'hprAnrLabel': hprAnrLabel, 'hprAnrType': hprAnrType, 'hprAnrOutTgDest': hprAnrOutTgDest, 'hprAnrOutTgNum': hprAnrOutTgNum, 'hprAnrPacketsReceived': hprAnrPacketsReceived, 'hprAnrCounterDisconTime': hprAnrCounterDisconTime}
class hprNceEntry(RowObject):
status = 1
index = pycopia.SMI.Objects.IndexObjects([hprNceId], False)
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 3, 1, 1])
access = 2
columns = {'hprNceId': hprNceId, 'hprNceType': hprNceType, 'hprNceDefault': hprNceDefault, 'hprNceInstanceId': hprNceInstanceId}
class hprRtpEntry(RowObject):
status = 1
index = pycopia.SMI.Objects.IndexObjects([hprRtpLocNceId, hprRtpLocTcid], False)
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 2, 1])
access = 2
columns = {'hprRtpLocNceId': hprRtpLocNceId, 'hprRtpLocTcid': hprRtpLocTcid, 'hprRtpRemCpName': hprRtpRemCpName, 'hprRtpRemNceId': hprRtpRemNceId, 'hprRtpRemTcid': hprRtpRemTcid, 'hprRtpPathSwitchTrigger': hprRtpPathSwitchTrigger, 'hprRtpRscv': hprRtpRscv, 'hprRtpTopic': hprRtpTopic, 'hprRtpState': hprRtpState, 'hprRtpUpTime': hprRtpUpTime, 'hprRtpLivenessTimer': hprRtpLivenessTimer, 'hprRtpShortReqTimer': hprRtpShortReqTimer, 'hprRtpPathSwTimer': hprRtpPathSwTimer, 'hprRtpLivenessTimeouts': hprRtpLivenessTimeouts, 'hprRtpShortReqTimeouts': hprRtpShortReqTimeouts, 'hprRtpMaxSendRate': hprRtpMaxSendRate, 'hprRtpMinSendRate': hprRtpMinSendRate, 'hprRtpCurSendRate': hprRtpCurSendRate, 'hprRtpSmRdTripDelay': hprRtpSmRdTripDelay, 'hprRtpSendPackets': hprRtpSendPackets, 'hprRtpRecvPackets': hprRtpRecvPackets, 'hprRtpSendBytes': hprRtpSendBytes, 'hprRtpRecvBytes': hprRtpRecvBytes, 'hprRtpRetrPackets': hprRtpRetrPackets, 'hprRtpPacketsDiscarded': hprRtpPacketsDiscarded, 'hprRtpDetectGaps': hprRtpDetectGaps, 'hprRtpRateReqSends': hprRtpRateReqSends, 'hprRtpOkErrPathSws': hprRtpOkErrPathSws, 'hprRtpBadErrPathSws': hprRtpBadErrPathSws, 'hprRtpOkOpPathSws': hprRtpOkOpPathSws, 'hprRtpBadOpPathSws': hprRtpBadOpPathSws, 'hprRtpCounterDisconTime': hprRtpCounterDisconTime}
class hprRtpStatusEntry(RowObject):
status = 1
index = pycopia.SMI.Objects.IndexObjects([hprRtpStatusLocNceId, hprRtpStatusLocTcid, hprRtpStatusIndex], False)
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 1, 4, 3, 1])
access = 2
columns = {'hprRtpStatusLocNceId': hprRtpStatusLocNceId, 'hprRtpStatusLocTcid': hprRtpStatusLocTcid, 'hprRtpStatusIndex': hprRtpStatusIndex, 'hprRtpStatusStartTime': hprRtpStatusStartTime, 'hprRtpStatusEndTime': hprRtpStatusEndTime, 'hprRtpStatusRemCpName': hprRtpStatusRemCpName, 'hprRtpStatusRemNceId': hprRtpStatusRemNceId, 'hprRtpStatusRemTcid': hprRtpStatusRemTcid, 'hprRtpStatusNewRscv': hprRtpStatusNewRscv, 'hprRtpStatusOldRscv': hprRtpStatusOldRscv, 'hprRtpStatusCause': hprRtpStatusCause, 'hprRtpStatusLastAttemptResult': hprRtpStatusLastAttemptResult}
# notifications (traps)
# groups
class hprGlobalConfGroup(GroupObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 2, 2, 1])
group = [hprNodeCpName, hprOperatorPathSwitchSupport]
class hprAnrRoutingConfGroup(GroupObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 2, 2, 2])
group = [hprAnrsAssigned, hprAnrCounterState, hprAnrCounterStateTime, hprAnrType, hprAnrOutTgDest, hprAnrOutTgNum, hprAnrPacketsReceived, hprAnrCounterDisconTime]
class hprTransportUserConfGroup(GroupObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 2, 2, 3])
group = [hprNceType, hprNceDefault, hprNceInstanceId]
class hprRtpConfGroup(GroupObject):
access = 2
status = 1
OID = pycopia.SMI.Basetypes.ObjectIdentifier([1, 3, 6, 1, 2, 1, 34, 6, 2, 2, 4])
group = [hprRtpGlobeConnSetups, hprRtpGlobeCtrState, hprRtpGlobeCtrStateTime, hprRtpRemCpName, hprRtpRemNceId, hprRtpRemTcid, hprRtpPathSwitchTrigger, hprRtpRscv, hprRtpTopic, hprRtpState, hprRtpUpTime, hprRtpLivenessTimer, hprRtpShortReqTimer, hprRtpPathSwTimer, hprRtpLivenessTimeouts, hprRtpShortReqTimeouts, hprRtpMaxSendRate, hprRtpMinSendRate, hprRtpCurSendRate, hprRtpSmRdTripDelay, hprRtpSendPackets, hprRtpRecvPackets, hprRtpSendBytes, hprRtpRecvBytes, hprRtpRetrPackets, hprRtpPacketsDiscarded, hprRtpDetectGaps, hprRtpRateReqSends, hprRtpOkErrPathSws, hprRtpBadErrPathSws, hprRtpOkOpPathSws, hprRtpBadOpPathSws, hprRtpCounterDisconTime, hprRtpStatusStartTime, hprRtpStatusEndTime, hprRtpStatusRemNceId, hprRtpStatusRemTcid, hprRtpStatusRemCpName, hprRtpStatusNewRscv, hprRtpStatusOldRscv, hprRtpStatusCause, hprRtpStatusLastAttemptResult]
# capabilities
# special additions
# Add to master OIDMAP.
from pycopia import SMI
SMI.update_oidmap(__name__)
| lgpl-2.1 |
xiaolvmu/flounder-kernel | tools/perf/scripts/python/syscall-counts-by-pid.py | 11180 | 1927 | # system call counts, by pid
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Displays system-wide system call totals, broken down by syscall.
# If a [comm] arg is specified, only syscalls called by [comm] are displayed.
import os, sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import syscall_name
usage = "perf script -s syscall-counts-by-pid.py [comm]\n";
for_comm = None
for_pid = None
if len(sys.argv) > 2:
sys.exit(usage)
if len(sys.argv) > 1:
try:
for_pid = int(sys.argv[1])
except:
for_comm = sys.argv[1]
syscalls = autodict()
def trace_begin():
print "Press control+C to stop and show the summary"
def trace_end():
print_syscall_totals()
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
if (for_comm and common_comm != for_comm) or \
(for_pid and common_pid != for_pid ):
return
try:
syscalls[common_comm][common_pid][id] += 1
except TypeError:
syscalls[common_comm][common_pid][id] = 1
def print_syscall_totals():
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events by comm/pid:\n\n",
print "%-40s %10s\n" % ("comm [pid]/syscalls", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"----------"),
comm_keys = syscalls.keys()
for comm in comm_keys:
pid_keys = syscalls[comm].keys()
for pid in pid_keys:
print "\n%s [%d]\n" % (comm, pid),
id_keys = syscalls[comm][pid].keys()
for id, val in sorted(syscalls[comm][pid].iteritems(), \
key = lambda(k, v): (v, k), reverse = True):
print " %-38s %10d\n" % (syscall_name(id), val),
| gpl-2.0 |
lfrdm/medpy | bin/others/registration/register_via_basepoints.py | 2 | 10705 | #!/usr/bin/python
"Register two binary 3D RV volumes via there base-points."
# build-in modules
import argparse
import logging
# third-party modules
import scipy
from scipy.ndimage.morphology import binary_erosion
from scipy.spatial.distance import pdist, squareform
# path changes
# own modules
from medpy.core import Logger
from medpy.io import load, header
from medpy.core.exceptions import ArgumentError
from geometry import line_from_points,\
split_line_to_sections, perpendicular_line, find_nearest, distance,\
shiftp, angle_between_vectors
import math
# information
__author__ = "Oskar Maier"
__version__ = "r0.1.0, 2012-07-27"
__email__ = "oskar.maier@googlemail.com"
__status__ = "Release"
__description__ = """
Register two binary 3D RV volumes via there base-points.
Prints a 'elastix'/'transformix'-ready transformation to the stdout.
Returned transformation is from moving to fixed image.
"""
# SOME NOTES ON 'ELASTIX'
# 1. 'elastix' performs shifting before rotation!
# 2. 'elastix' works on the real world coordinates (i.e. with voxel spacing of 0)
# 3. for the angle calculation, the voxel spacing is not relevant
# code
def main():
args = getArguments(getParser())
# prepare logger
logger = Logger.getInstance()
if args.debug: logger.setLevel(logging.DEBUG)
elif args.verbose: logger.setLevel(logging.INFO)
# load input images
data_fixed, header_fixed = load(args.fixed)
data_moving, header_moving = load(args.moving)
# convert to binary arrays
data_fixed = data_fixed.astype(scipy.bool_)
data_moving = data_moving.astype(scipy.bool_)
# check that they are 3D volumes and contain an object
if not 3 == data_fixed.ndim: raise ArgumentError('The fixed image has {} instead of the expected 3 dimensions.'.format(data_fixed.ndim))
if not 3 == data_moving.ndim: raise ArgumentError('The moving image has {} instead of the expected 3 dimensions.'.format(data_moving.ndim))
if not scipy.any(data_fixed): raise ArgumentError('The fixed image contains no binary object.')
if not scipy.any(data_moving): raise ArgumentError('The moving image contains no binary object.')
# get voxel spacing of fixed image
fixed_spacing = header.get_pixel_spacing(header_fixed)
# extract the first basal slices form both RV objects
basal_fixed, basal_fixed_spacing = extract_basal_slice(data_fixed, header_fixed)
basal_moving, basal_moving_spacing = extract_basal_slice(data_moving, header_moving)
logger.debug('Extracted basal slices fixed: {} and moving: {} with voxel spacing {} resp. {}.'.format(basal_fixed.shape, basal_moving.shape, basal_fixed_spacing, basal_moving_spacing))
# get points of interest
fixed_basep, fixed_otherp = get_points_of_interest(basal_fixed)
moving_basep, moving_otherp = get_points_of_interest(basal_moving)
logger.debug('Points of interest found are fixed: {} / {} and moving: {} / {}.'.format(fixed_basep, fixed_otherp, moving_basep, moving_otherp))
# translate all points of interest to physical coordinate system
fixed_basep = [x * y for x, y in zip(fixed_basep, basal_fixed_spacing)]
fixed_otherp = [x * y for x, y in zip(fixed_otherp, basal_fixed_spacing)]
moving_basep = [x * y for x, y in zip(moving_basep, basal_moving_spacing)]
moving_otherp = [x * y for x, y in zip(moving_otherp, basal_moving_spacing)]
logger.debug('Points of interest translated to real-world coordinates are fixed: {} / {} and moving: {} / {}.'.format(fixed_basep, fixed_otherp, moving_basep, moving_otherp))
# determine shift to unite the two base-points
shift = (fixed_basep[0] - moving_basep[0], fixed_basep[1] - moving_basep[1])
logger.debug('Shift to unite base-point is {}.'.format(shift))
# shift the vector end-point of the moving object's vector so that it shares the
# same base as the fixed vector
moving_otherp = shiftp(moving_otherp, shift)
logger.debug('Shifted vector end-point of moving image is {}.'.format(moving_otherp))
# assure correctness of shift
if not scipy.all([x == y for x, y in zip(fixed_basep, shiftp(moving_basep, shift))]):
raise ArgumentError('Aligning base-point through shifting failed due to unknown reason: {} does not equal {}.'.format(shiftp(moving_basep, shift), fixed_basep))
# shift both vector end-points to origin base
fixed_otherp = shiftp(fixed_otherp, map(lambda x: -1. * x, fixed_basep))
moving_otherp = shiftp(moving_otherp, map(lambda x: -1. * x, fixed_basep))
# determine angle
angle = angle_between_vectors(fixed_otherp, moving_otherp)
logger.debug('Angle set to {} degree in radians.'.format(math.degrees(angle)))
# determine angle turn point
turn_point = fixed_basep
logger.debug('Turn point set to {} in real-world coordinates.'.format(turn_point))
# reverse shift to fit into the 'elastix' view
shift = [-1. * x for x in shift]
# print results
print '// {}'.format(math.degrees(angle))
print """
//# SOME NOTES ON 'ELASTIX'
//# 1. 'elastix' performs shifting before rotation!
//# 2. 'elastix' works on the real world coordinates (i.e. with voxel spacing of 0)
"""
print transform_string(data_fixed.shape,
fixed_spacing,
[0] + list(shift),
[angle, 0, 0],
[0] + list(turn_point))
logger.info("Successfully terminated.")
def get_points_of_interest(arr):
"""
Expects a binary object in the array.
FInds the two contour points that are the farthest apart, then determines which of
them is the base point of the RV and returns this first and the other as second
return value.
"""
#########
# 1: Find points in objects contour with the largest distance between them.
#########
# extract only outer contour
arr = arr - binary_erosion(arr)
# extract all positions of the objects contour
points = scipy.asarray(arr.nonzero()).T
# compute pairwise distances
distances = squareform(pdist(points, 'euclidean'))
# get positon of largest distance
position = scipy.unravel_index(scipy.argmax(distances), (len(points), len(points)))
# recompute between which points the largest distance was found
first = points[position[0]]
second = points[position[1]]
#logger.debug('Longest distance found between {} and {}.'.format(first, second))
#########
# 2: Determine which of these is the base point
#########
# go along perpendicular lines, find intersections with contours and keep longest only
intersection = False
longest_length = 0
longest_line = line_from_points(first, second)
segment_points = split_line_to_sections(5, first, second)
for sp in segment_points:
sline = perpendicular_line(longest_line, sp)
nearest = find_nearest(sline, points, 10)
if distance(nearest[0], nearest[1]) > longest_length:
longest_length = distance(nearest[0], nearest[1])
intersection = sp
# determine which of the first two points are nearest to the longest line and return them
if distance(intersection, first) < distance(intersection, second):
return (first, second)
else:
return (second, first)
def extract_basal_slice(arr, head):
"""
Takes a 3D array, iterates over the first dimension and returns the first 2D plane
which contains any non-zero values as we as its voxel spacing.
"""
for plane in arr:
if scipy.any(plane):
# get voxel spacing
spacing = list(header.get_pixel_spacing(head))
spacing = spacing[1:3]
# return plane and spacing
return (plane, spacing)
raise ArgumentError('The supplied array does not contain any object.')
def getArguments(parser):
"Provides additional validation of the arguments collected by argparse."
return parser.parse_args()
def getParser():
"Creates and returns the argparse parser object."
parser = argparse.ArgumentParser(description=__description__)
parser.add_argument('fixed', help='The fixed image.')
parser.add_argument('moving', help='The moving image.')
parser.add_argument('-v', dest='verbose', action='store_true', help='Display more information.')
parser.add_argument('-d', dest='debug', action='store_true', help='Display debug information.')
return parser
def transform_string(shape, spacing, shift, angles, turn_point):
"""Returns a finished transformation file string."""
# NOTE:
# - the transformation file requires real-world coordinates, the points and shifts have therefore to be multiplied with the voxel spacing
base = """
(Transform "EulerTransform")
(NumberOfParameters 6)
(TransformParameters {xangle:.10f} {yangle:.10f} {zangle:.10f} {xshift:.10f} {yshift:.10f} {zshift:.10f})
(InitialTransformParametersFileName "NoInitialTransform")
(HowToCombineTransforms "Compose")
// Image specific
(FixedImageDimension 3)
(MovingImageDimension 3)
(FixedInternalImagePixelType "float")
(MovingInternalImagePixelType "float")
(Size {xsize:d} {ysize:d} {zsize:d})
(Index 0 0 0)
(Spacing {xspacing:.10f} {yspacing:.10f} {zspacing:.10f})
(Origin 0.0000000000 0.0000000000 0.0000000000)
//(Direction 1.0000000000 0.0000000000 0.0000000000 0.0000000000 1.0000000000 0.0000000000 0.0000000000 0.0000000000 1.0000000000) // !TODO: Compute/read this!
(UseDirectionCosines "true")
// EulerTransform specific
(CenterOfRotationPoint {xturn_point} {yturn_point} {zturn_point})
(ComputeZYX "false")
// ResampleInterpolator specific
(ResampleInterpolator "FinalBSplineInterpolator")
(FinalBSplineInterpolationOrder 0)
// Resampler specific
(Resampler "DefaultResampler")
(DefaultPixelValue 0.000000)
(ResultImageFormat "nii")
(ResultImagePixelType "short")
(CompressResultImage "false")
"""
shape = map(int, shape)
spacing = map(float, spacing)
angles = map(float, angles)
turn_point = map(float, turn_point)
return base.format(xsize=shape[0], ysize=shape[1], zsize=shape[2],
xspacing=spacing[0], yspacing=spacing[1], zspacing=spacing[2],
xangle=angles[0], yangle=angles[1], zangle=angles[2],
xshift=shift[0], yshift=shift[1], zshift=shift[2],
xturn_point=turn_point[0], yturn_point=turn_point[1], zturn_point=turn_point[2])
if __name__ == "__main__":
main()
| gpl-3.0 |
pfmooney/dd-agent | checks.d/cacti.py | 34 | 8177 | # stdlib
from collections import namedtuple
from fnmatch import fnmatch
import os
import time
# 3rd party
try:
import rrdtool
except ImportError:
rrdtool = None
import pymysql
# project
from checks import AgentCheck
CFUNC_TO_AGGR = {
'AVERAGE': 'avg',
'MAXIMUM': 'max',
'MINIMUM': 'min'
}
CACTI_TO_DD = {
'hdd_free': 'system.disk.free',
'hdd_used': 'system.disk.used',
'swap_free': 'system.swap.free',
'load_1min': 'system.load.1',
'load_5min': 'system.load.5',
'load_15min': 'system.load.15',
'mem_buffers': 'system.mem.buffered',
'proc': 'system.proc.running',
'users': 'system.users.current',
'mem_swap': 'system.swap.free',
'ping': 'system.ping.latency'
}
class Cacti(AgentCheck):
def __init__(self, name, init_config, agentConfig):
AgentCheck.__init__(self, name, init_config, agentConfig)
self.last_ts = {}
def get_library_versions(self):
if rrdtool is not None:
return {"rrdtool": rrdtool.__version__}
return {"rrdtool": "Not Found"}
def check(self, instance):
if rrdtool is None:
raise Exception("Unable to import python rrdtool module")
# Load the instance config
config = self._get_config(instance)
connection = pymysql.connect(config.host, config.user, config.password, config.db)
self.log.debug("Connected to MySQL to fetch Cacti metadata")
# Get whitelist patterns, if available
patterns = self._get_whitelist_patterns(config.whitelist)
# Fetch the RRD metadata from MySQL
rrd_meta = self._fetch_rrd_meta(connection, config.rrd_path, patterns, config.field_names)
# Load the metrics from each RRD, tracking the count as we go
metric_count = 0
for hostname, device_name, rrd_path in rrd_meta:
m_count = self._read_rrd(rrd_path, hostname, device_name)
metric_count += m_count
self.gauge('cacti.metrics.count', metric_count)
def _get_whitelist_patterns(self, whitelist):
patterns = []
if whitelist:
if not os.path.isfile(whitelist) or not os.access(whitelist, os.R_OK):
# Don't run the check if the whitelist is unavailable
self.log.exception("Unable to read whitelist file at %s" % (whitelist))
wl = open(whitelist)
for line in wl:
patterns.append(line.strip())
wl.close()
return patterns
def _get_config(self, instance):
required = ['mysql_host', 'mysql_user', 'rrd_path']
for param in required:
if not instance.get(param):
raise Exception("Cacti instance missing %s. Skipping." % (param))
host = instance.get('mysql_host')
user = instance.get('mysql_user')
password = instance.get('mysql_password', '') or ''
db = instance.get('mysql_db', 'cacti')
rrd_path = instance.get('rrd_path')
whitelist = instance.get('rrd_whitelist')
field_names = instance.get('field_names', ['ifName', 'dskDevice'])
Config = namedtuple('Config', [
'host',
'user',
'password',
'db',
'rrd_path',
'whitelist',
'field_names']
)
return Config(host, user, password, db, rrd_path, whitelist, field_names)
def _read_rrd(self, rrd_path, hostname, device_name):
''' Main metric fetching method '''
metric_count = 0
try:
info = rrdtool.info(rrd_path)
except Exception:
# Unable to read RRD file, ignore it
self.log.exception("Unable to read RRD file at %s" % rrd_path)
return metric_count
# Find the consolidation functions for the RRD metrics
c_funcs = set([v for k,v in info.items() if k.endswith('.cf')])
for c in list(c_funcs):
last_ts_key = '%s.%s' % (rrd_path, c)
if last_ts_key not in self.last_ts:
self.last_ts[last_ts_key] = int(time.time())
continue
start = self.last_ts[last_ts_key]
last_ts = start
try:
fetched = rrdtool.fetch(rrd_path, c, '--start', str(start))
except rrdtool.error:
# Start time was out of range, skip this RRD
self.log.warn("Time %s out of range for %s" % (rrd_path, start))
return metric_count
# Extract the data
(start_ts, end_ts, interval) = fetched[0]
metric_names = fetched[1]
points = fetched[2]
for k, m_name in enumerate(metric_names):
m_name = self._format_metric_name(m_name, c)
for i, p in enumerate(points):
ts = start_ts + (i * interval)
if p[k] is None:
continue
# Save this metric as a gauge
val = self._transform_metric(m_name, p[k])
self.gauge(m_name, val, hostname=hostname,
device_name=device_name, timestamp=ts)
metric_count += 1
last_ts = (ts + interval)
# Update the last timestamp based on the last valid metric
self.last_ts[last_ts_key] = last_ts
return metric_count
def _fetch_rrd_meta(self, connection, rrd_path_root, whitelist, field_names):
''' Fetch metadata about each RRD in this Cacti DB, returning a list of
tuples of (hostname, device_name, rrd_path)
'''
def _in_whitelist(rrd):
path = rrd.replace('<path_rra>/','')
for p in whitelist:
if fnmatch(path, p):
return True
return False
c = connection.cursor()
and_parameters = " OR ".join(["hsc.field_name = '%s'" % field_name for field_name in field_names])
# Check for the existence of the `host_snmp_cache` table
rrd_query = """
SELECT
h.hostname as hostname,
hsc.field_value as device_name,
dt.data_source_path as rrd_path
FROM data_local dl
JOIN host h on dl.host_id = h.id
JOIN data_template_data dt on dt.local_data_id = dl.id
LEFT JOIN host_snmp_cache hsc on h.id = hsc.host_id
AND dl.snmp_index = hsc.snmp_index
WHERE dt.data_source_path IS NOT NULL
AND dt.data_source_path != ''
AND (%s OR hsc.field_name is NULL) """ % and_parameters
c.execute(rrd_query)
res = []
for hostname, device_name, rrd_path in c.fetchall():
if not whitelist or _in_whitelist(rrd_path):
if hostname in ('localhost', '127.0.0.1'):
hostname = self.hostname
rrd_path = rrd_path.replace('<path_rra>', rrd_path_root)
device_name = device_name or None
res.append((hostname, device_name, rrd_path))
# Collect stats
num_hosts = len(set([r[0] for r in res]))
self.gauge('cacti.rrd.count', len(res))
self.gauge('cacti.hosts.count', num_hosts)
return res
def _format_metric_name(self, m_name, cfunc):
''' Format a cacti metric name into a Datadog-friendly name '''
try:
aggr = CFUNC_TO_AGGR[cfunc]
except KeyError:
aggr = cfunc.lower()
try:
m_name = CACTI_TO_DD[m_name]
if aggr != 'avg':
m_name += '.%s' % (aggr)
return m_name
except KeyError:
return "cacti.%s.%s" % (m_name.lower(), aggr)
def _transform_metric(self, m_name, val):
''' Add any special case transformations here '''
# Report memory in MB
if m_name[0:11] in ('system.mem.', 'system.disk'):
return val / 1024
return val
'''
For backwards compatability with pre-checks.d configuration.
Convert old-style config to new-style config.
'''
| bsd-3-clause |
Alwnikrotikz/l5rcm | models/katamodel.py | 3 | 4173 | # Copyright (C) 2011 Daniele Simonetti
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
from PySide import QtGui, QtCore
import dal.query
class KataItemModel(object):
def __init__(self):
self.name = ''
self.mastery = ''
self.element = ''
self.id = False
self.adv = None
self.text = []
def __str__(self):
return self.name
class KataTableViewModel(QtCore.QAbstractTableModel):
def __init__(self, dstore, parent = None):
super(KataTableViewModel, self).__init__(parent)
self.items = []
self.headers = ['Name', 'Mastery', 'Element']
self.text_color = QtGui.QBrush(QtGui.QColor(0x15, 0x15, 0x15))
self.bg_color = [ QtGui.QBrush(QtGui.QColor(0xFF, 0xEB, 0x82)),
QtGui.QBrush(QtGui.QColor(0xEB, 0xFF, 0x82)) ]
self.item_size = QtCore.QSize(28, 28)
self.dstore = dstore
def rowCount(self, parent = QtCore.QModelIndex()):
return len(self.items)
def columnCount(self, parent = QtCore.QModelIndex()):
return len(self.headers)
def headerData(self, section, orientation, role = QtCore.Qt.ItemDataRole.DisplayRole):
if orientation != QtCore.Qt.Orientation.Horizontal:
return None
if role == QtCore.Qt.DisplayRole:
return self.headers[section]
return None
def data(self, index, role = QtCore.Qt.UserRole):
if not index.isValid() or index.row() >= len(self.items):
return None
item = self.items[index.row()]
if role == QtCore.Qt.DisplayRole:
if index.column() == 0:
return item.name
if index.column() == 1:
return item.mastery
if index.column() == 2:
return item.element
elif role == QtCore.Qt.ForegroundRole:
return self.text_color
elif role == QtCore.Qt.BackgroundRole:
return self.bg_color[ index.row() % 2 ]
elif role == QtCore.Qt.SizeHintRole:
return self.item_size
elif role == QtCore.Qt.UserRole:
return item
return None
def flags(self, index):
if not index.isValid():
return QtCore.Qt.ItemIsDropEnabled
flags = QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled
return flags
def add_item(self, item):
row = self.rowCount()
self.beginInsertRows(QtCore.QModelIndex(), row, row)
self.items.append(item)
self.endInsertRows()
def clean(self):
self.beginResetModel()
self.items = []
self.endResetModel()
def build_item_model(self, ka_id):
itm = KataItemModel()
ka = dal.query.get_kata(self.dstore, ka_id)
if ka:
itm.id = ka.id
itm.adv = ka_id
itm.name = ka.name
itm.mastery = ka.mastery
#itm.element = ka.element
itm.element = dal.query.get_ring(self.dstore, ka.element).text
itm.text = ka.desc
else:
print('cannot find kata: {0}'.format(ka_id))
# TODO: translate element
return itm
def update_from_model(self, model):
kata = model.get_kata()
self.clean()
for s in kata:
itm = self.build_item_model(s)
self.add_item(itm)
| gpl-3.0 |
SynBioDex/pySBOL | Linux_64_2/sbol/CRISPR_example.py | 9 | 21557 | from __future__ import print_function
from sbol import *
setHomespace('http://sbols.org/CRISPR_Example')
Config.setOption('sbol_typed_uris', False)
version = '1.0.0'
doc = Document()
cas9_generic = ComponentDefinition('cas9_generic', BIOPAX_PROTEIN, version)
doc.addComponentDefinition(cas9_generic)
gRNA_generic = ComponentDefinition('gRNA_generic', BIOPAX_RNA, version)
gRNA_generic.roles = [SO_SGRNA]
doc.addComponentDefinition(gRNA_generic)
cas9_gRNA_complex = ComponentDefinition('cas9_gRNA_complex', BIOPAX_COMPLEX, version)
doc.addComponentDefinition(cas9_gRNA_complex)
target_gene = ComponentDefinition('target_gene', BIOPAX_DNA, version)
target_gene.roles = [SO_PROMOTER]
doc.addComponentDefinition(target_gene)
target = ComponentDefinition('target', BIOPAX_PROTEIN, version)
doc.addComponentDefinition(target)
CRISPR_Template = ModuleDefinition('CRISPR_Template', version)
doc.addModuleDefinition(CRISPR_Template)
Cas9Complex_Formation = CRISPR_Template.interactions.create('cas9_complex_formation')
Cas9Complex_Formation.types = [SBO_NONCOVALENT_BINDING]
cas9_generic_fc = CRISPR_Template.functionalComponents.create('cas9_generic')
cas9_generic_fc.definition = cas9_generic.persistentIdentity
cas9_generic_fc.access = SBOL_ACCESS_PUBLIC
cas9_generic_fc.direction = SBOL_DIRECTION_IN_OUT
cas9_generic_fc.version = version
cas9_generic_participation = Cas9Complex_Formation.participations.create('cas9_generic')
cas9_generic_participation.roles = [SBO_REACTANT]
cas9_generic_participation.participant = cas9_generic_fc.identity
gRNA_generic_fc = CRISPR_Template.functionalComponents.create('gRNA_generic')
gRNA_generic_fc.definition = gRNA_generic.persistentIdentity
gRNA_generic_fc.access = SBOL_ACCESS_PUBLIC
gRNA_generic_fc.direction = SBOL_DIRECTION_IN_OUT
gRNA_generic_fc.version = version
gRNA_generic_participation = Cas9Complex_Formation.participations.create('gRNA_generic')
gRNA_generic_participation.roles = [SBO_REACTANT]
gRNA_generic_participation.participant = gRNA_generic_fc.identity
cas9_gRNA_complex_fc = CRISPR_Template.functionalComponents.create('cas9_gRNA_complex')
cas9_gRNA_complex_fc.definition = cas9_gRNA_complex.persistentIdentity
cas9_gRNA_complex_fc.access = SBOL_ACCESS_PUBLIC
cas9_gRNA_complex_fc.direction = SBOL_DIRECTION_IN_OUT
cas9_gRNA_complex_fc.version = version
cas9_gRNA_complex_participation = Cas9Complex_Formation.participations.create('cas9_gRNA_complex')
cas9_gRNA_complex_participation.roles = [SBO_PRODUCT]
cas9_gRNA_complex_participation.participant = cas9_gRNA_complex_fc.identity
EYFP_production = CRISPR_Template.interactions.create('target_production')
EYFP_production.types = [SBO_GENETIC_PRODUCTION]
target_gene_fc = CRISPR_Template.functionalComponents.create('target_gene')
target_gene_fc.definition = target_gene.persistentIdentity
target_gene_fc.access = SBOL_ACCESS_PUBLIC
target_gene_fc.direction = SBOL_DIRECTION_IN_OUT
target_gene_fc.version = version
target_gene_participation = EYFP_production.participations.create('target_gene')
target_gene_participation.roles = [SBO_PROMOTER]
target_gene_participation.participant = target_gene_fc.identity
target_fc = CRISPR_Template.functionalComponents.create('target')
target_fc.definition = target.persistentIdentity
target_fc.access = SBOL_ACCESS_PUBLIC
target_fc.direction = SBOL_DIRECTION_IN_OUT
target_fc.version = version
target_participation = EYFP_production.participations.create('target')
target_participation.roles = [SBO_PRODUCT]
target_participation.participant = target_fc.identity
target_generic_gene_inhibition = CRISPR_Template.interactions.create('target_gene_inhibition')
target_generic_gene_inhibition.types = [SBO_INHIBITION]
cas9_gRNA_complex_participation1 = target_generic_gene_inhibition.participations.create('cas9_gRNA_complex')
cas9_gRNA_complex_participation1.roles = [SBO_INHIBITOR]
cas9_gRNA_complex_participation1.participant = cas9_gRNA_complex_fc.identity
target_gene_participation2 = target_generic_gene_inhibition.participations.create('target_gene')
target_gene_participation2.roles = [SBO_PROMOTER]
target_gene_participation2.participant = target_gene_fc.identity
CRa_U6_seq_elements = ('GGTTTACCGAGCTCTTATTGGTTTTCAAACTTCATTGACTGTGCC'
'AAGGTCGGGCAGGAAGAGGGCCTATTTCCCATGATTCCTTCATAT'
'TTGCATATACGATACAAGGCTGTTAGAGAGATAATTAGAATTAAT'
'TTGACTGTAAACACAAAGATATTAGTACAAAATACGTGACGTAGA'
'AAGTAATAATTTCTTGGGTAGTTTGCAGTTTTAAAATTATGTTTT'
'AAAATGGACTATCATATGCTTACCGTAACTTGAAATATAGAACCG'
'ATCCTCCCATTGGTATATATTATAGAACCGATCCTCCCATTGGCT'
'TGTGGAAAGGACGAAACACCGTACCTCATCAGGAACATGTGTTTA'
'AGAGCTATGCTGGAAACAGCAGAAATAGCAAGTTTAAATAAGGCT'
'AGTCCGTTATCAACTTGAAAAAGTGGCACCGAGTCGGTGCTTTTT'
'TTGGTGCGTTTTTATGCTTGTAGTATTGTATAATGTTTTT')
CRa_U6_seq = Sequence('CRa_U6_seq', CRa_U6_seq_elements, SBOL_ENCODING_IUPAC, version)
doc.addSequence(CRa_U6_seq)
gRNA_b_elements = ('AAGGTCGGGCAGGAAGAGGGCCTATTTCCCATGATTCCTTCATAT'
'TTGCATATACGATACAAGGCTGTTAGAGAGATAATTAGAATTAAT'
'TTGACTGTAAACACAAAGATATTAGTACAAAATACGTGACGTAGA'
'AAGTAATAATTTCTTGGGTAGTTTGCAGTTTTAAAATTATGTTTT'
'AAAATGGACTATCATATGCTTACCGTAACTTGAAAGTATTTCGAT'
'TTCTTGGCTTTATATATCTTGTGGAAAGGACGAAACACCGTACCT'
'CATCAGGAACATGTGTTTAAGAGCTATGCTGGAAACAGCAGAAAT'
'AGCAAGTTTAAATAAGGCTAGTCCGTTATCAACTTGAAAAAGTGG'
'CACCGAGTCGGTGCTTTTTTT')
gRNA_b_seq = Sequence('gRNA_b_seq', gRNA_b_elements, SBOL_ENCODING_IUPAC, version)
doc.addSequence(gRNA_b_seq)
mKate_seq_elements = ('TCTAAGGGCGAAGAGCTGATTAAGGAGAACATGCACATGAAGCTG'
'TACATGGAGGGCACCGTGAACAACCACCACTTCAAGTGCACATCC'
'GAGGGCGAAGGCAAGCCCTACGAGGGCACCCAGACCATGAGAATC'
'AAGGTGGTCGAGGGCGGCCCTCTCCCCTTCGCCTTCGACATCCTG'
'GCTACCAGCTTCATGTACGGCAGCAAAACCTTCATCAACCACACC'
'CAGGGCATCCCCGACTTCTTTAAGCAGTCCTTCCCTGAGGTAAGT'
'GGTCCTACCTCATCAGGAACATGTGTTTTAGAGCTAGAAATAGCA'
'AGTTAAAATAAGGCTAGTCCGTTATCAACTTGAAAAAGTGGCACC'
'GAGTCGGTGCTACTAACTCTCGAGTCTTCTTTTTTTTTTTCACAG'
'GGCTTCACATGGGAGAGAGTCACCACATACGAAGACGGGGGCGTG'
'CTGACCGCTACCCAGGACACCAGCCTCCAGGACGGCTGCCTCATC'
'TACAACGTCAAGATCAGAGGGGTGAACTTCCCATCCAACGGCCCT'
'GTGATGCAGAAGAAAACACTCGGCTGGGAGGCCTCCACCGAGATG'
'CTGTACCCCGCTGACGGCGGCCTGGAAGGCAGAAGCGACATGGCC'
'CTGAAGCTCGTGGGCGGGGGCCACCTGATCTGCAACTTGAAGACC'
'ACATACAGATCCAAGAAACCCGCTAAGAACCTCAAGATGCCCGGC'
'GTCTACTATGTGGACAGAAGACTGGAAAGAATCAAGGAGGCCGAC'
'AAAGAGACCTACGTCGAGCAGCACGAGGTGGCTGTGGCCAGATAC'
'TGCG')
mKate_seq = Sequence('mKate_seq', mKate_seq_elements, SBOL_ENCODING_IUPAC, version)
doc.addSequence(mKate_seq)
CRP_b_seq_elements = ('GCTCCGAATTTCTCGACAGATCTCATGTGATTACGCCAAGCTACG'
'GGCGGAGTACTGTCCTCCGAGCGGAGTACTGTCCTCCGAGCGGAG'
'TACTGTCCTCCGAGCGGAGTACTGTCCTCCGAGCGGAGTTCTGTC'
'CTCCGAGCGGAGACTCTAGATACCTCATCAGGAACATGTTGGAAT'
'TCTAGGCGTGTACGGTGGGAGGCCTATATAAGCAGAGCTCGTTTA'
'GTGAACCGTCAGATCGCCTCGAGTACCTCATCAGGAACATGTTGG'
'ATCCAATTCGACC')
CRP_b_seq = Sequence('CRP_b_seq', CRP_b_seq_elements, SBOL_ENCODING_IUPAC, version)
doc.addSequence(CRP_b_seq)
pConst = ComponentDefinition('pConst', BIOPAX_DNA, version)
pConst.roles = [SO_PROMOTER]
doc.addComponentDefinition(pConst)
cas9m_BFP_cds = ComponentDefinition('cas9m_BFP_cds', BIOPAX_DNA, version)
cas9m_BFP_cds.roles = [SO_CDS]
doc.addComponentDefinition(cas9m_BFP_cds)
cas9m_BFP_gene = ComponentDefinition('cas9m_BFP_gene', BIOPAX_DNA, version)
cas9m_BFP_gene.roles = [SO_PROMOTER]
doc.addComponentDefinition(cas9m_BFP_gene)
pConst_c2 = cas9m_BFP_gene.components.create('pConst')
pConst_c2.definition = pConst.persistentIdentity
pConst_c2.access = SBOL_ACCESS_PUBLIC
pConst_c2.version = version
cas9m_BFP_cds_c = cas9m_BFP_gene.components.create('cas9m_BFP_cds')
cas9m_BFP_cds_c.definition = cas9m_BFP_cds.persistentIdentity
cas9m_BFP_cds_c.access = SBOL_ACCESS_PUBLIC
cas9m_BFP_cds_c.version = version
cas9m_BFP_gene_constraint = cas9m_BFP_gene.sequenceConstraints.create('cas9m_BFP_gene_constraint')
cas9m_BFP_gene_constraint.subject = pConst_c2.identity
cas9m_BFP_gene_constraint.object = cas9m_BFP_cds_c.identity
cas9m_BFP_gene_constraint.restriction = SBOL_RESTRICTION_PRECEDES
cas9m_BFP = ComponentDefinition('cas9m_BFP', BIOPAX_PROTEIN, version)
doc.addComponentDefinition(cas9m_BFP)
CRa_U6 = ComponentDefinition('CRa_U6', BIOPAX_DNA, version)
CRa_U6.sequences.append(CRa_U6_seq.persistentIdentity)
CRa_U6.roles = [SO_PROMOTER]
doc.addComponentDefinition(CRa_U6)
gRNA_b_nc = ComponentDefinition('gRNA_b_nc', BIOPAX_DNA, version)
gRNA_b_nc.roles = [SO_CDS]
gRNA_b_nc.sequences.append(gRNA_b_seq.persistentIdentity)
doc.addComponentDefinition(gRNA_b_nc)
gRNA_b_terminator = ComponentDefinition('gRNA_b_terminator', BIOPAX_DNA, version)
gRNA_b_terminator.roles = [SO_TERMINATOR]
doc.addComponentDefinition(gRNA_b_terminator)
gRNA_b_gene = ComponentDefinition('gRNA_b_gene', BIOPAX_DNA, version)
gRNA_b_gene.roles = [SO_PROMOTER]
doc.addComponentDefinition(gRNA_b_gene)
CRa_U6_c = gRNA_b_gene.components.create('CRa_U6')
CRa_U6_c.definition = CRa_U6.persistentIdentity
CRa_U6_c.access = SBOL_ACCESS_PUBLIC
CRa_U6_c.version = version
gRNA_b_nc_c = gRNA_b_gene.components.create('gRNA_b_nc')
gRNA_b_nc_c.definition = gRNA_b_nc.persistentIdentity
gRNA_b_nc_c.access = SBOL_ACCESS_PUBLIC
gRNA_b_nc_c.version = version
gRNA_b_terminator_c = gRNA_b_gene.components.create('gRNA_b_terminator')
gRNA_b_terminator_c.definition = gRNA_b_terminator.persistentIdentity
gRNA_b_terminator_c.access = SBOL_ACCESS_PUBLIC
gRNA_b_terminator_c.version = version
gRNA_gene_constraint1 = gRNA_b_gene.sequenceConstraints.create('gRNA_b_gene_constraint1')
gRNA_gene_constraint1.subject = CRa_U6_c.identity
gRNA_gene_constraint1.object = gRNA_b_nc_c.identity
gRNA_gene_constraint1.restriction = SBOL_RESTRICTION_PRECEDES
gRNA_gene_constraint2 = gRNA_b_gene.sequenceConstraints.create('gRNA_b_gene_constraint2')
gRNA_gene_constraint2.subject = gRNA_b_nc_c.identity
gRNA_gene_constraint2.object = gRNA_b_terminator_c.identity
gRNA_gene_constraint2.restriction = SBOL_RESTRICTION_PRECEDES
gRNA_b = ComponentDefinition('gRNA_b', BIOPAX_RNA, version)
gRNA_b.roles = [SO_SGRNA]
doc.addComponentDefinition(gRNA_b)
cas9m_BFP_gRNA_b = ComponentDefinition('cas9m_BFP_gRNA_b', BIOPAX_COMPLEX, version)
doc.addComponentDefinition(cas9m_BFP_gRNA_b)
mKate_cds = ComponentDefinition('mKate_cds', BIOPAX_DNA, version)
mKate_cds.roles = [SO_CDS]
mKate_cds.sequences.append(mKate_seq.persistentIdentity)
doc.addComponentDefinition(mKate_cds)
mKate_gene = ComponentDefinition('mKate_gene', BIOPAX_DNA, version)
mKate_gene.roles = [SO_PROMOTER]
doc.addComponentDefinition(mKate_gene)
pConst_c = mKate_gene.components.create('pConst')
pConst_c.definition = pConst.persistentIdentity
pConst_c.access = SBOL_ACCESS_PUBLIC
pConst_c.version = version
mKate_cds_c = mKate_gene.components.create('mKate_cds')
mKate_cds_c.definition = mKate_cds.persistentIdentity
mKate_cds_c.access = SBOL_ACCESS_PUBLIC
mKate_cds_c.version = version
mKate_gene_constraint = mKate_gene.sequenceConstraints.create('mKate_gene_constraint')
mKate_gene_constraint.subject = pConst_c.identity
mKate_gene_constraint.object = mKate_cds_c.identity
mKate_gene_constraint.restriction = SBOL_RESTRICTION_PRECEDES
mKate = ComponentDefinition('mKate', BIOPAX_PROTEIN, version)
doc.addComponentDefinition(mKate)
Gal4VP16_cds = ComponentDefinition('Gal4VP16_cds', BIOPAX_DNA, version)
Gal4VP16_cds.roles = [SO_CDS]
doc.addComponentDefinition(Gal4VP16_cds)
Gal4VP16_gene = ComponentDefinition('Gal4VP16_gene', BIOPAX_DNA, version)
Gal4VP16_gene.roles = [SO_PROMOTER]
doc.addComponentDefinition(Gal4VP16_gene)
pConst_c3 = Gal4VP16_gene.components.create('pConst')
pConst_c3.definition = pConst.persistentIdentity
pConst_c3.access = SBOL_ACCESS_PUBLIC
pConst_c3.version = version
Gal4VP16_cds_c = Gal4VP16_gene.components.create('Gal4VP16_cds')
Gal4VP16_cds_c.definition = Gal4VP16_cds.persistentIdentity
Gal4VP16_cds_c.access = SBOL_ACCESS_PUBLIC
Gal4VP16_cds_c.version = version
GAL4VP16_gene_constraint = Gal4VP16_gene.sequenceConstraints.create('GAL4VP16_gene_constraint')
GAL4VP16_gene_constraint.subject = pConst_c3.identity
GAL4VP16_gene_constraint.object = Gal4VP16_cds_c.identity
GAL4VP16_gene_constraint.restriction = SBOL_RESTRICTION_PRECEDES
Gal4VP16 = ComponentDefinition('Gal4VP16', BIOPAX_PROTEIN, version)
doc.addComponentDefinition(Gal4VP16)
CRP_b = ComponentDefinition('CRP_b', BIOPAX_DNA, version)
CRP_b.roles = [SO_PROMOTER]
CRP_b.sequences.append(CRP_b_seq.persistentIdentity)
doc.addComponentDefinition(CRP_b)
EYFP_cds = ComponentDefinition('EYFP_cds', BIOPAX_DNA, version)
EYFP_cds.roles = [SO_CDS]
doc.addComponentDefinition(EYFP_cds)
EYFP_gene = ComponentDefinition('EYFP_gene', BIOPAX_DNA, version)
EYFP_gene.roles = [SO_PROMOTER]
doc.addComponentDefinition(EYFP_gene)
CRP_b_c = EYFP_gene.components.create('CRP_b')
CRP_b_c.definition = CRP_b.persistentIdentity
CRP_b_c.access = SBOL_ACCESS_PUBLIC
CRP_b_c.version = version
EYFP_cds_c = EYFP_gene.components.create('EYFP_cds')
EYFP_cds_c.definition = EYFP_cds.persistentIdentity
EYFP_cds_c.access = SBOL_ACCESS_PUBLIC
EYFP_cds_c.version = version
EYFP_gene_constraint = EYFP_gene.sequenceConstraints.create('EYFP_gene_constraint')
EYFP_gene_constraint.subject = CRP_b_c.identity
EYFP_gene_constraint.object = EYFP_cds_c.identity
EYFP_gene_constraint.restriction = SBOL_RESTRICTION_PRECEDES
EYFP = ComponentDefinition('EYFP', BIOPAX_PROTEIN, version)
doc.addComponentDefinition(EYFP)
CRPb_circuit = ModuleDefinition('CRPb_characterization_Circuit', version)
doc.addModuleDefinition(CRPb_circuit)
cas9m_BFP_fc = CRPb_circuit.functionalComponents.create('cas9m_BFP')
cas9m_BFP_fc.definition = cas9m_BFP.identity
cas9m_BFP_fc.access = SBOL_ACCESS_PRIVATE
cas9m_BFP_fc.direction = SBOL_DIRECTION_NONE
cas9m_BFP_fc.version = version
cas9m_BFP_gene_fc = CRPb_circuit.functionalComponents.create('cas9m_BFP_gene')
cas9m_BFP_gene_fc.definition = cas9m_BFP_gene.identity
cas9m_BFP_gene_fc.access = SBOL_ACCESS_PRIVATE
cas9m_BFP_gene_fc.direction = SBOL_DIRECTION_NONE
cas9m_BFP_gene_fc.version = version
gRNA_b_fc = CRPb_circuit.functionalComponents.create('gRNA_b')
gRNA_b_fc.definition = gRNA_b.identity
gRNA_b_fc.access = SBOL_ACCESS_PRIVATE
gRNA_b_fc.direction = SBOL_DIRECTION_NONE
gRNA_b_fc.version = version
gRNA_b_gene_fc = CRPb_circuit.functionalComponents.create('gRNA_b_gene')
gRNA_b_gene_fc.definition = gRNA_b_gene.identity
gRNA_b_gene_fc.access = SBOL_ACCESS_PRIVATE
gRNA_b_gene_fc.direction = SBOL_DIRECTION_NONE
gRNA_b_gene_fc.version = version
mKate_fc = CRPb_circuit.functionalComponents.create('mKate')
mKate_fc.definition = mKate.identity
mKate_fc.access = SBOL_ACCESS_PRIVATE
mKate_fc.direction = SBOL_DIRECTION_NONE
mKate_fc.version = version
mKate_gene_fc = CRPb_circuit.functionalComponents.create('mKate_gene')
mKate_gene_fc.definition = mKate_gene.identity
mKate_gene_fc.access = SBOL_ACCESS_PRIVATE
mKate_gene_fc.direction = SBOL_DIRECTION_NONE
mKate_gene_fc.version = version
Gal4VP16_fc = CRPb_circuit.functionalComponents.create('Gal4VP16')
Gal4VP16_fc.definition = Gal4VP16.identity
Gal4VP16_fc.access = SBOL_ACCESS_PRIVATE
Gal4VP16_fc.direction = SBOL_DIRECTION_NONE
Gal4VP16_fc.version = version
Gal4VP16_gene_fc = CRPb_circuit.functionalComponents.create('Gal4VP16_gene')
Gal4VP16_gene_fc.definition = Gal4VP16_gene.identity
Gal4VP16_gene_fc.access = SBOL_ACCESS_PRIVATE
Gal4VP16_gene_fc.direction = SBOL_DIRECTION_NONE
Gal4VP16_gene_fc.version = version
EYFP_fc = CRPb_circuit.functionalComponents.create('EYFP')
EYFP_fc.definition = EYFP.identity
EYFP_fc.access = SBOL_ACCESS_PRIVATE
EYFP_fc.direction = SBOL_DIRECTION_NONE
EYFP_fc.version = version
EYFP_gene_fc = CRPb_circuit.functionalComponents.create('EYFP_gene')
EYFP_gene_fc.definition = EYFP_gene.identity
EYFP_gene_fc.access = SBOL_ACCESS_PRIVATE
EYFP_gene_fc.direction = SBOL_DIRECTION_NONE
EYFP_gene_fc.version = version
cas9m_BFP_gRNA_b_fc = CRPb_circuit.functionalComponents.create('cas9m_BFP_gRNA_b')
cas9m_BFP_gRNA_b_fc.definition = cas9m_BFP_gRNA_b.identity
cas9m_BFP_gRNA_b_fc.access = SBOL_ACCESS_PRIVATE
cas9m_BFP_gRNA_b_fc.direction = SBOL_DIRECTION_NONE
cas9m_BFP_gRNA_b_fc.version = version
mKate_production = CRPb_circuit.interactions.create('mKate_production')
mKate_production.types = [SBO_GENETIC_PRODUCTION]
mKate_participation = mKate_production.participations.create('mKate')
mKate_participation.roles = [SBO_PRODUCT]
mKate_participation.participant = mKate_fc.identity
mKate_gene_participation = mKate_production.participations.create('mKate_gene')
mKate_gene_participation.roles = [SBO_PROMOTER]
mKate_gene_participation.participant = mKate_gene_fc.identity
GAL4VP16_production = CRPb_circuit.interactions.create('Gal4VP16_production')
GAL4VP16_production.types = [SBO_GENETIC_PRODUCTION]
Gal4VP16_gene_participation = GAL4VP16_production.participations.create('Gal4VP16_gene')
Gal4VP16_gene_participation.roles = [SBO_PROMOTER]
Gal4VP16_gene_participation.participant = Gal4VP16_gene_fc.identity
Gal4VP16_participation1 = GAL4VP16_production.participations.create('Gal4VP16')
Gal4VP16_participation1.roles = [SBO_PRODUCT]
Gal4VP16_participation1.participant = Gal4VP16_fc.identity
cas9m_BFP_production = CRPb_circuit.interactions.create('cas9m_BFP_production')
cas9m_BFP_production.types = [SBO_GENETIC_PRODUCTION]
cas9m_BFP_gene_participation = cas9m_BFP_production.participations.create('cas9m_BFP_gene')
cas9m_BFP_gene_participation.roles = [SBO_PROMOTER]
cas9m_BFP_gene_participation.participant = cas9m_BFP_gene_fc.identity
cas9m_BFP_participation = cas9m_BFP_production.participations.create('cas9m_BFP')
cas9m_BFP_participation.roles = [SBO_PRODUCT]
cas9m_BFP_participation.participant = cas9m_BFP_fc.identity
gRNA_b_production = CRPb_circuit.interactions.create('gRNA_b_production')
gRNA_b_production.types = [SBO_GENETIC_PRODUCTION]
gRNA_b_gene_participation = gRNA_b_production.participations.create('gRNA_b_gene')
gRNA_b_gene_participation.roles = [SBO_PROMOTER]
gRNA_b_gene_participation.participant = gRNA_b_gene_fc.identity
gRNA_b_participation = gRNA_b_production.participations.create('gRNA_b')
gRNA_b_participation.roles = [SBO_PRODUCT]
gRNA_b_participation.participant = gRNA_b_fc.identity
EYFP_Activation = CRPb_circuit.interactions.create('EYFP_Activation')
EYFP_Activation.types = [SBO_STIMULATION]
#%%
Gal4VP16_participation = EYFP_Activation.participations.create('Gal4VP16')
Gal4VP16_participation.roles = [SBO_STIMULATOR]
Gal4VP16_participation.participant = Gal4VP16_fc.identity
EYFP_gene_participation = EYFP_Activation.participations.create('EYFP_gene')
EYFP_gene_participation.roles = [SBO_PROMOTER]
EYFP_gene_participation.participant = EYFP_gene_fc.identity
mKate_deg = CRPb_circuit.interactions.create('mKate_deg')
mKate_deg.types = [SBO_DEGRADATION]
mKate_participation1 = mKate_deg.participations.create('mKate')
mKate_participation1.roles = [SBO_REACTANT]
mKate_participation1.participant = mKate_fc.identity
GAL4VP16_deg = CRPb_circuit.interactions.create('Gal4VP16_deg')
GAL4VP16_deg.types = [SBO_DEGRADATION]
Gal4VP16_participation2 = GAL4VP16_deg.participations.create('Gal4VP16')
Gal4VP16_participation2.roles = [SBO_REACTANT]
Gal4VP16_participation2.participant = Gal4VP16_fc.identity
cas9m_BFP_deg = CRPb_circuit.interactions.create('cas9m_BFP_deg')
cas9m_BFP_deg.types = [SBO_DEGRADATION]
cas9m_BFP_participation1 = cas9m_BFP_deg.participations.create('cas9m_BFP')
cas9m_BFP_participation1.roles = [SBO_REACTANT]
cas9m_BFP_participation1.participant = cas9m_BFP_fc.identity
gRNA_b_deg = CRPb_circuit.interactions.create('gRNA_b_deg')
gRNA_b_deg.types = [SBO_DEGRADATION]
gRNA_b_participation1 = gRNA_b_deg.participations.create('gRNA_b')
gRNA_b_participation1.roles = [SBO_REACTANT]
gRNA_b_participation1.participant = gRNA_b_fc.identity
EYFP_deg = CRPb_circuit.interactions.create('EYFP_deg')
EYFP_deg.types = [SBO_DEGRADATION]
EYFP_participation = EYFP_deg.participations.create('EYFP')
EYFP_participation.roles = [SBO_REACTANT]
EYFP_participation.participant = EYFP_fc.identity
cas9m_BFP_gRNA_b_deg = CRPb_circuit.interactions.create('cas9m_BFP_gRNA_b_deg')
cas9m_BFP_gRNA_b_deg.types = [SBO_DEGRADATION]
cas9m_BFP_gRNA_b_participation = cas9m_BFP_gRNA_b_deg.participations.create('cas9m_BFP_gRNA_b')
cas9m_BFP_gRNA_b_participation.roles = [SBO_REACTANT]
cas9m_BFP_gRNA_b_participation.participant = cas9m_BFP_gRNA_b_fc.identity
Template_Module = CRPb_circuit.modules.create('CRISPR_Template')
Template_Module.definition = CRISPR_Template.identity
cas9m_BFP_map = Template_Module.mapsTos.create('cas9m_BFP_map')
cas9m_BFP_map.refinement = SBOL_REFINEMENT_USE_LOCAL
cas9m_BFP_map.local = cas9m_BFP_fc.identity
cas9m_BFP_map.remote = cas9_generic_fc.identity
gRNA_b_map = Template_Module.mapsTos.create('gRNA_b_map')
gRNA_b_map.refinement = SBOL_REFINEMENT_USE_LOCAL
gRNA_b_map.local = gRNA_b_fc.identity
gRNA_b_map.remote = gRNA_generic_fc.identity
cas9m_BFP_gRNA_map = Template_Module.mapsTos.create('cas9m_BFP_gRNA_map')
cas9m_BFP_gRNA_map.refinement = SBOL_REFINEMENT_USE_LOCAL
cas9m_BFP_gRNA_map.local = cas9m_BFP_gRNA_b_fc.identity
cas9m_BFP_gRNA_map.remote = cas9_gRNA_complex_fc.identity
EYFP_map = Template_Module.mapsTos.create('EYFP_map')
EYFP_map.refinement = SBOL_REFINEMENT_USE_LOCAL
EYFP_map.local = EYFP_fc.identity
EYFP_map.remote = target_fc.identity
EYFP_gene_map = Template_Module.mapsTos.create('EYFP_gene_map')
EYFP_gene_map.refinement = SBOL_REFINEMENT_USE_LOCAL
EYFP_gene_map.local = EYFP_gene_fc.identity
EYFP_gene_map.remote = target_gene_fc.identity
doc.write('crispr_example.xml')
| apache-2.0 |
BizShuk/env_setup | pkg/sublime/MarkdownEditing/switch_list_bullet_type.py | 1 | 1312 | import sublime_plugin
import re
class SwitchListBulletTypeCommand(sublime_plugin.TextCommand):
def run(self, edit):
todo = []
for region in self.view.sel():
lines = self.view.line(region)
lines = self.view.split_by_newlines(lines)
for line in lines:
line_content = self.view.substr(line)
print(line_content)
m = re.match(r"^(\s*(?:>\s*)?)[*+\-](\s+.*)$", line_content)
if m:
# Transform the bullet to numbered bullet type
new_line = m.group(1) + "1." + m.group(2)
# Insert the new item
todo.append([line, new_line])
else:
m = re.match(r"^(\s*(?:>\s*)?)[0-9]+\.(\s+.*)$", line_content)
if m:
# Transform the bullet to unnumbered bullet type
new_line = m.group(1) + "-" + m.group(2)
# Insert the new item
todo.append([line, new_line])
while len(todo) > 0:
j = todo.pop()
self.view.replace(edit, j[0], j[1])
def is_enabled(self):
return bool(self.view.score_selector(self.view.sel()[0].a, "text.html.markdown"))
| gpl-3.0 |
clulab/twitter4food | src/main/python/org/clulab/twitter4food/format.py | 2 | 1458 | # input file
full = open("/data/nlp/corpora/twitter4food/overweightData/overweightDataFull.txt", 'r')
# UNCOMMENT THESE AND THE LINES AT THE END TO WRITE TO THE FILES
trainFile = open("overweightTrain.txt", 'w')
# devFile = open("overweightDev.txt", 'w')
testFile = open("overweightTest.txt", 'w')
overweight = []
notOverweight = []
isFirst = True
toAdd = ""
for line in full:
if line == "Overweight\n" or line == "Not overweight\n":
if not isFirst:
if line == "Overweight\n":
overweight.append(toAdd)
elif line == "Not overweight\n":
notOverweight.append(toAdd)
else:
isFirst = False
toAdd = line
else:
toAdd += line
first = int(len(overweight) * 0.6)
second = (len(overweight) - first) / 2
firstN = int(len(notOverweight) * 0.6)
secondN = (len(notOverweight) - firstN) / 2
print str(len(overweight))
print str(len(notOverweight))
train = overweight[0:first]
dev = overweight[first:first+second]
test = overweight[first+second:]
print str(len(train))
print str(len(dev))
print str(len(test))
print
train += notOverweight[0:firstN]
dev += notOverweight[firstN:firstN+secondN]
test += notOverweight[firstN+secondN:]
print str(len(train))
print str(len(dev))
print str(len(test))
# for account in train:
# trainFile.write(account)
# for account in dev:
# devFile.write(account)
# for account in test:
# testFile.write(account) | apache-2.0 |
pasqualguerrero/django | tests/select_related/models.py | 99 | 3320 | """
Tests for select_related()
``select_related()`` follows all relationships and pre-caches any foreign key
values so that complex trees can be fetched in a single query. However, this
isn't always a good idea, so the ``depth`` argument control how many "levels"
the select-related behavior will traverse.
"""
from django.contrib.contenttypes.fields import (
GenericForeignKey, GenericRelation,
)
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
# Who remembers high school biology?
@python_2_unicode_compatible
class Domain(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Kingdom(models.Model):
name = models.CharField(max_length=50)
domain = models.ForeignKey(Domain)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Phylum(models.Model):
name = models.CharField(max_length=50)
kingdom = models.ForeignKey(Kingdom)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Klass(models.Model):
name = models.CharField(max_length=50)
phylum = models.ForeignKey(Phylum)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Order(models.Model):
name = models.CharField(max_length=50)
klass = models.ForeignKey(Klass)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Family(models.Model):
name = models.CharField(max_length=50)
order = models.ForeignKey(Order)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Genus(models.Model):
name = models.CharField(max_length=50)
family = models.ForeignKey(Family)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Species(models.Model):
name = models.CharField(max_length=50)
genus = models.ForeignKey(Genus)
def __str__(self):
return self.name
# and we'll invent a new thing so we have a model with two foreign keys
@python_2_unicode_compatible
class HybridSpecies(models.Model):
name = models.CharField(max_length=50)
parent_1 = models.ForeignKey(Species, related_name='child_1')
parent_2 = models.ForeignKey(Species, related_name='child_2')
def __str__(self):
return self.name
@python_2_unicode_compatible
class Topping(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Pizza(models.Model):
name = models.CharField(max_length=100)
toppings = models.ManyToManyField(Topping)
def __str__(self):
return self.name
@python_2_unicode_compatible
class TaggedItem(models.Model):
tag = models.CharField(max_length=30)
content_type = models.ForeignKey(ContentType, related_name='select_related_tagged_items')
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
def __str__(self):
return self.tag
@python_2_unicode_compatible
class Bookmark(models.Model):
url = models.URLField()
tags = GenericRelation(TaggedItem)
def __str__(self):
return self.url
| bsd-3-clause |
leorochael/odoo | odoo.py | 257 | 5618 | #!/usr/bin/env python
#----------------------------------------------------------
# odoo cli
#
# To install your odoo development environement type:
#
# wget -O- https://raw.githubusercontent.com/odoo/odoo/8.0/odoo.py | python
#
# The setup_* subcommands used to boostrap odoo are defined here inline and may
# only depends on the python 2.7 stdlib
#
# The rest of subcommands are defined in odoo/cli or in <module>/cli by
# subclassing the Command object
#
#----------------------------------------------------------
import os
import re
import sys
import subprocess
GIT_HOOKS_PRE_PUSH = """
#!/usr/bin/env python2
import re
import sys
if re.search('github.com[:/]odoo/odoo.git$', sys.argv[2]):
print "Pushing to /odoo/odoo.git is forbidden, please push to odoo-dev, use --no-verify to override"
sys.exit(1)
"""
def printf(f,*l):
print "odoo:" + f % l
def run(*l):
if isinstance(l[0], list):
l = l[0]
printf("running %s", " ".join(l))
subprocess.check_call(l)
def git_locate():
# Locate git dir
# TODO add support for os.environ.get('GIT_DIR')
# check for an odoo child
if os.path.isfile('odoo/.git/config'):
os.chdir('odoo')
path = os.getcwd()
while path != os.path.abspath(os.sep):
gitconfig_path = os.path.join(path, '.git/config')
if os.path.isfile(gitconfig_path):
release_py = os.path.join(path, 'openerp/release.py')
if os.path.isfile(release_py):
break
path = os.path.dirname(path)
if path == os.path.abspath(os.sep):
path = None
return path
def cmd_setup_git():
git_dir = git_locate()
if git_dir:
printf('git repo found at %s',git_dir)
else:
run("git", "init", "odoo")
os.chdir('odoo')
git_dir = os.getcwd()
if git_dir:
# push sane config for git < 2.0, and hooks
#run('git','config','push.default','simple')
# alias
run('git','config','alias.st','status')
# merge bzr style
run('git','config','merge.commit','no')
# pull let me choose between merge or rebase only works in git > 2.0, use an alias for 1
run('git','config','pull.ff','only')
run('git','config','alias.pl','pull --ff-only')
pre_push_path = os.path.join(git_dir, '.git/hooks/pre-push')
open(pre_push_path,'w').write(GIT_HOOKS_PRE_PUSH.strip())
os.chmod(pre_push_path, 0755)
# setup odoo remote
run('git','config','remote.odoo.url','https://github.com/odoo/odoo.git')
run('git','config','remote.odoo.pushurl','git@github.com:odoo/odoo.git')
run('git','config','--add','remote.odoo.fetch','dummy')
run('git','config','--unset-all','remote.odoo.fetch')
run('git','config','--add','remote.odoo.fetch','+refs/heads/*:refs/remotes/odoo/*')
# setup odoo-dev remote
run('git','config','remote.odoo-dev.url','https://github.com/odoo-dev/odoo.git')
run('git','config','remote.odoo-dev.pushurl','git@github.com:odoo-dev/odoo.git')
run('git','remote','update')
# setup 8.0 branch
run('git','config','branch.8.0.remote','odoo')
run('git','config','branch.8.0.merge','refs/heads/8.0')
run('git','checkout','8.0')
else:
printf('no git repo found')
def cmd_setup_git_dev():
git_dir = git_locate()
if git_dir:
# setup odoo-dev remote
run('git','config','--add','remote.odoo-dev.fetch','dummy')
run('git','config','--unset-all','remote.odoo-dev.fetch')
run('git','config','--add','remote.odoo-dev.fetch','+refs/heads/*:refs/remotes/odoo-dev/*')
run('git','config','--add','remote.odoo-dev.fetch','+refs/pull/*:refs/remotes/odoo-dev/pull/*')
run('git','remote','update')
def cmd_setup_git_review():
git_dir = git_locate()
if git_dir:
# setup odoo-dev remote
run('git','config','--add','remote.odoo.fetch','dummy')
run('git','config','--unset-all','remote.odoo.fetch')
run('git','config','--add','remote.odoo.fetch','+refs/heads/*:refs/remotes/odoo/*')
run('git','config','--add','remote.odoo.fetch','+refs/tags/*:refs/remotes/odoo/tags/*')
run('git','config','--add','remote.odoo.fetch','+refs/pull/*:refs/remotes/odoo/pull/*')
def setup_deps_debian(git_dir):
debian_control_path = os.path.join(git_dir, 'debian/control')
debian_control = open(debian_control_path).read()
debs = re.findall('python-[0-9a-z]+',debian_control)
debs += ["postgresql"]
proc = subprocess.Popen(['sudo','apt-get','install'] + debs, stdin=open('/dev/tty'))
proc.communicate()
def cmd_setup_deps():
git_dir = git_locate()
if git_dir:
if os.path.isfile('/etc/debian_version'):
setup_deps_debian(git_dir)
def setup_pg_debian(git_dir):
cmd = ['sudo','su','-','postgres','-c','createuser -s %s' % os.environ['USER']]
subprocess.call(cmd)
def cmd_setup_pg():
git_dir = git_locate()
if git_dir:
if os.path.isfile('/etc/debian_version'):
setup_pg_debian(git_dir)
def cmd_setup():
cmd_setup_git()
cmd_setup_deps()
cmd_setup_pg()
def main():
# regsitry of commands
g = globals()
cmds = dict([(i[4:],g[i]) for i in g if i.startswith('cmd_')])
# if curl URL | python2 then use command setup
if len(sys.argv) == 1 and __file__ == '<stdin>':
cmd_setup()
elif len(sys.argv) == 2 and sys.argv[1] in cmds:
cmds[sys.argv[1]]()
else:
import openerp
openerp.cli.main()
if __name__ == "__main__":
main()
| agpl-3.0 |
Azure/azure-sdk-for-python | sdk/applicationinsights/azure-mgmt-applicationinsights/azure/mgmt/applicationinsights/v2020_02_02_preview/_configuration.py | 1 | 3315 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any
from azure.core.credentials import TokenCredential
VERSION = "unknown"
class ApplicationInsightsManagementClientConfiguration(Configuration):
"""Configuration for ApplicationInsightsManagementClient.
Note that all parameters used to create this instance are saved as instance
attributes.
:param credential: Credential needed for the client to connect to Azure.
:type credential: ~azure.core.credentials.TokenCredential
:param subscription_id: The ID of the target subscription.
:type subscription_id: str
"""
def __init__(
self,
credential, # type: "TokenCredential"
subscription_id, # type: str
**kwargs # type: Any
):
# type: (...) -> None
if credential is None:
raise ValueError("Parameter 'credential' must not be None.")
if subscription_id is None:
raise ValueError("Parameter 'subscription_id' must not be None.")
super(ApplicationInsightsManagementClientConfiguration, self).__init__(**kwargs)
self.credential = credential
self.subscription_id = subscription_id
self.api_version = "2020-02-02-preview"
self.credential_scopes = kwargs.pop('credential_scopes', ['https://management.azure.com/.default'])
kwargs.setdefault('sdk_moniker', 'mgmt-applicationinsights/{}'.format(VERSION))
self._configure(**kwargs)
def _configure(
self,
**kwargs # type: Any
):
# type: (...) -> None
self.user_agent_policy = kwargs.get('user_agent_policy') or policies.UserAgentPolicy(**kwargs)
self.headers_policy = kwargs.get('headers_policy') or policies.HeadersPolicy(**kwargs)
self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs)
self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs)
self.http_logging_policy = kwargs.get('http_logging_policy') or ARMHttpLoggingPolicy(**kwargs)
self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs)
self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs)
self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs)
self.authentication_policy = kwargs.get('authentication_policy')
if self.credential and not self.authentication_policy:
self.authentication_policy = policies.BearerTokenCredentialPolicy(self.credential, *self.credential_scopes, **kwargs)
| mit |
Cito/sqlalchemy | lib/sqlalchemy/testing/assertsql.py | 78 | 10607 | # testing/assertsql.py
# Copyright (C) 2005-2014 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
from ..engine.default import DefaultDialect
from .. import util
import re
class AssertRule(object):
def process_execute(self, clauseelement, *multiparams, **params):
pass
def process_cursor_execute(self, statement, parameters, context,
executemany):
pass
def is_consumed(self):
"""Return True if this rule has been consumed, False if not.
Should raise an AssertionError if this rule's condition has
definitely failed.
"""
raise NotImplementedError()
def rule_passed(self):
"""Return True if the last test of this rule passed, False if
failed, None if no test was applied."""
raise NotImplementedError()
def consume_final(self):
"""Return True if this rule has been consumed.
Should raise an AssertionError if this rule's condition has not
been consumed or has failed.
"""
if self._result is None:
assert False, 'Rule has not been consumed'
return self.is_consumed()
class SQLMatchRule(AssertRule):
def __init__(self):
self._result = None
self._errmsg = ""
def rule_passed(self):
return self._result
def is_consumed(self):
if self._result is None:
return False
assert self._result, self._errmsg
return True
class ExactSQL(SQLMatchRule):
def __init__(self, sql, params=None):
SQLMatchRule.__init__(self)
self.sql = sql
self.params = params
def process_cursor_execute(self, statement, parameters, context,
executemany):
if not context:
return
_received_statement = \
_process_engine_statement(context.unicode_statement,
context)
_received_parameters = context.compiled_parameters
# TODO: remove this step once all unit tests are migrated, as
# ExactSQL should really be *exact* SQL
sql = _process_assertion_statement(self.sql, context)
equivalent = _received_statement == sql
if self.params:
if util.callable(self.params):
params = self.params(context)
else:
params = self.params
if not isinstance(params, list):
params = [params]
equivalent = equivalent and params \
== context.compiled_parameters
else:
params = {}
self._result = equivalent
if not self._result:
self._errmsg = \
'Testing for exact statement %r exact params %r, '\
'received %r with params %r' % (sql, params,
_received_statement, _received_parameters)
class RegexSQL(SQLMatchRule):
def __init__(self, regex, params=None):
SQLMatchRule.__init__(self)
self.regex = re.compile(regex)
self.orig_regex = regex
self.params = params
def process_cursor_execute(self, statement, parameters, context,
executemany):
if not context:
return
_received_statement = \
_process_engine_statement(context.unicode_statement,
context)
_received_parameters = context.compiled_parameters
equivalent = bool(self.regex.match(_received_statement))
if self.params:
if util.callable(self.params):
params = self.params(context)
else:
params = self.params
if not isinstance(params, list):
params = [params]
# do a positive compare only
for param, received in zip(params, _received_parameters):
for k, v in param.items():
if k not in received or received[k] != v:
equivalent = False
break
else:
params = {}
self._result = equivalent
if not self._result:
self._errmsg = \
'Testing for regex %r partial params %r, received %r '\
'with params %r' % (self.orig_regex, params,
_received_statement,
_received_parameters)
class CompiledSQL(SQLMatchRule):
def __init__(self, statement, params=None):
SQLMatchRule.__init__(self)
self.statement = statement
self.params = params
def process_cursor_execute(self, statement, parameters, context,
executemany):
if not context:
return
from sqlalchemy.schema import _DDLCompiles
_received_parameters = list(context.compiled_parameters)
# recompile from the context, using the default dialect
if isinstance(context.compiled.statement, _DDLCompiles):
compiled = \
context.compiled.statement.compile(dialect=DefaultDialect())
else:
compiled = \
context.compiled.statement.compile(dialect=DefaultDialect(),
column_keys=context.compiled.column_keys)
_received_statement = re.sub(r'[\n\t]', '', str(compiled))
equivalent = self.statement == _received_statement
if self.params:
if util.callable(self.params):
params = self.params(context)
else:
params = self.params
if not isinstance(params, list):
params = [params]
else:
params = list(params)
all_params = list(params)
all_received = list(_received_parameters)
while params:
param = dict(params.pop(0))
for k, v in context.compiled.params.items():
param.setdefault(k, v)
if param not in _received_parameters:
equivalent = False
break
else:
_received_parameters.remove(param)
if _received_parameters:
equivalent = False
else:
params = {}
all_params = {}
all_received = []
self._result = equivalent
if not self._result:
print('Testing for compiled statement %r partial params '\
'%r, received %r with params %r' % (self.statement,
all_params, _received_statement, all_received))
self._errmsg = \
'Testing for compiled statement %r partial params %r, '\
'received %r with params %r' % (self.statement,
all_params, _received_statement, all_received)
# print self._errmsg
class CountStatements(AssertRule):
def __init__(self, count):
self.count = count
self._statement_count = 0
def process_execute(self, clauseelement, *multiparams, **params):
self._statement_count += 1
def process_cursor_execute(self, statement, parameters, context,
executemany):
pass
def is_consumed(self):
return False
def consume_final(self):
assert self.count == self._statement_count, \
'desired statement count %d does not match %d' \
% (self.count, self._statement_count)
return True
class AllOf(AssertRule):
def __init__(self, *rules):
self.rules = set(rules)
def process_execute(self, clauseelement, *multiparams, **params):
for rule in self.rules:
rule.process_execute(clauseelement, *multiparams, **params)
def process_cursor_execute(self, statement, parameters, context,
executemany):
for rule in self.rules:
rule.process_cursor_execute(statement, parameters, context,
executemany)
def is_consumed(self):
if not self.rules:
return True
for rule in list(self.rules):
if rule.rule_passed(): # a rule passed, move on
self.rules.remove(rule)
return len(self.rules) == 0
assert False, 'No assertion rules were satisfied for statement'
def consume_final(self):
return len(self.rules) == 0
def _process_engine_statement(query, context):
if util.jython:
# oracle+zxjdbc passes a PyStatement when returning into
query = str(query)
if context.engine.name == 'mssql' \
and query.endswith('; select scope_identity()'):
query = query[:-25]
query = re.sub(r'\n', '', query)
return query
def _process_assertion_statement(query, context):
paramstyle = context.dialect.paramstyle
if paramstyle == 'named':
pass
elif paramstyle == 'pyformat':
query = re.sub(r':([\w_]+)', r"%(\1)s", query)
else:
# positional params
repl = None
if paramstyle == 'qmark':
repl = "?"
elif paramstyle == 'format':
repl = r"%s"
elif paramstyle == 'numeric':
repl = None
query = re.sub(r':([\w_]+)', repl, query)
return query
class SQLAssert(object):
rules = None
def add_rules(self, rules):
self.rules = list(rules)
def statement_complete(self):
for rule in self.rules:
if not rule.consume_final():
assert False, \
'All statements are complete, but pending '\
'assertion rules remain'
def clear_rules(self):
del self.rules
def execute(self, conn, clauseelement, multiparams, params, result):
if self.rules is not None:
if not self.rules:
assert False, \
'All rules have been exhausted, but further '\
'statements remain'
rule = self.rules[0]
rule.process_execute(clauseelement, *multiparams, **params)
if rule.is_consumed():
self.rules.pop(0)
def cursor_execute(self, conn, cursor, statement, parameters,
context, executemany):
if self.rules:
rule = self.rules[0]
rule.process_cursor_execute(statement, parameters, context,
executemany)
asserter = SQLAssert()
| mit |
pkilambi/python-gnocchiclient | gnocchiclient/common/http.py | 1 | 9455 | # Copyright 2012 OpenStack LLC.
# 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 copy
import httplib
import logging
import os
import socket
import StringIO
import urlparse
try:
import ssl
except ImportError:
#TODO(bcwaldon): Handle this failure more gracefully
pass
try:
import json
except ImportError:
import simplejson as json
# Python 2.5 compat fix
if not hasattr(urlparse, 'parse_qsl'):
import cgi
urlparse.parse_qsl = cgi.parse_qsl
from gnocchiclient import exc
LOG = logging.getLogger(__name__)
USER_AGENT = 'python-gnocchiclient'
CHUNKSIZE = 1024 * 64 # 64kB
class HTTPClient(object):
def __init__(self, endpoint, **kwargs):
self.endpoint = endpoint
self.auth_token = kwargs.get('token')
self.connection_params = self.get_connection_params(endpoint, **kwargs)
@staticmethod
def get_connection_params(endpoint, **kwargs):
parts = urlparse.urlparse(endpoint)
_args = (parts.hostname, parts.port, parts.path)
_kwargs = {'timeout': float(kwargs.get('timeout', 600))}
if parts.scheme == 'https':
_class = VerifiedHTTPSConnection
_kwargs['ca_file'] = kwargs.get('ca_file', None)
_kwargs['cert_file'] = kwargs.get('cert_file', None)
_kwargs['key_file'] = kwargs.get('key_file', None)
_kwargs['insecure'] = kwargs.get('insecure', False)
elif parts.scheme == 'http':
_class = httplib.HTTPConnection
else:
msg = 'Unsupported scheme: %s' % parts.scheme
raise exc.InvalidEndpoint(msg)
return (_class, _args, _kwargs)
def get_connection(self):
_class = self.connection_params[0]
try:
return _class(*self.connection_params[1],
**self.connection_params[2])
except httplib.InvalidURL:
raise exc.InvalidEndpoint()
def log_curl_request(self, method, url, kwargs):
curl = ['curl -i -X %s' % method]
for (key, value) in kwargs['headers'].items():
header = '-H \'%s: %s\'' % (key, value)
curl.append(header)
conn_params_fmt = [
('key_file', '--key %s'),
('cert_file', '--cert %s'),
('ca_file', '--cacert %s'),
]
for (key, fmt) in conn_params_fmt:
value = self.connection_params[2].get(key)
if value:
curl.append(fmt % value)
if self.connection_params[2].get('insecure'):
curl.append('-k')
if 'body' in kwargs:
curl.append('-d \'%s\'' % kwargs['body'])
curl.append('%s%s' % (self.endpoint, url))
LOG.debug(' '.join(curl))
@staticmethod
def log_http_response(resp, body=None):
status = (resp.version / 10.0, resp.status, resp.reason)
dump = ['\nHTTP/%.1f %s %s' % status]
dump.extend(['%s: %s' % (k, v) for k, v in resp.getheaders()])
dump.append('')
if body:
dump.extend([body, ''])
LOG.debug('\n'.join(dump))
def _http_request(self, url, method, **kwargs):
""" Send an http request with the specified characteristics.
Wrapper around httplib.HTTP(S)Connection.request to handle tasks such
as setting headers and error handling.
"""
# Copy the kwargs so we can reuse the original in case of redirects
kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {}))
kwargs['headers'].setdefault('User-Agent', USER_AGENT)
if self.auth_token:
kwargs['headers'].setdefault('X-Auth-Token', self.auth_token)
self.log_curl_request(method, url, kwargs)
conn = self.get_connection()
try:
conn_params = self.connection_params[1][2]
conn_url = os.path.normpath('%s/%s' % (conn_params, url))
conn.request(method, conn_url, **kwargs)
resp = conn.getresponse()
except socket.gaierror as e:
message = "Error finding address for %(url)s: %(e)s" % locals()
raise exc.InvalidEndpoint(message=message)
except (socket.error, socket.timeout) as e:
endpoint = self.endpoint
message = "Error communicating with %(endpoint)s %(e)s" % locals()
raise exc.CommunicationError(message=message)
body_iter = ResponseBodyIterator(resp)
# Read body into string if it isn't obviously image data
if resp.getheader('content-type', None) != 'application/octet-stream':
body_str = ''.join([chunk for chunk in body_iter])
self.log_http_response(resp, body_str)
body_iter = StringIO.StringIO(body_str)
else:
self.log_http_response(resp)
if 400 <= resp.status < 600:
LOG.warn("Request returned failure status.")
raise exc.from_response(resp)
elif resp.status in (301, 302, 305):
# Redirected. Reissue the request to the new location.
return self._http_request(resp['location'], method, **kwargs)
elif resp.status == 300:
raise exc.from_response(resp)
return resp, body_iter
def json_request(self, method, url, **kwargs):
kwargs.setdefault('headers', {})
kwargs['headers'].setdefault('Content-Type', 'application/json')
kwargs['headers'].setdefault('Accept', 'application/json')
if 'body' in kwargs:
kwargs['body'] = json.dumps(kwargs['body'])
resp, body_iter = self._http_request(url, method, **kwargs)
if 'application/json' in resp.getheader('content-type', None):
body = ''.join([chunk for chunk in body_iter])
try:
body = json.loads(body)
except ValueError:
LOG.error('Could not decode response body as JSON')
else:
body = None
return resp, body
def raw_request(self, method, url, **kwargs):
kwargs.setdefault('headers', {})
kwargs['headers'].setdefault('Content-Type',
'application/octet-stream')
return self._http_request(url, method, **kwargs)
class VerifiedHTTPSConnection(httplib.HTTPSConnection):
"""httplib-compatibile connection using client-side SSL authentication
:see http://code.activestate.com/recipes/
577548-https-httplib-client-connection-with-certificate-v/
"""
def __init__(self, host, port, key_file=None, cert_file=None,
ca_file=None, timeout=None, insecure=False):
httplib.HTTPSConnection.__init__(self, host, port, key_file=key_file,
cert_file=cert_file)
self.key_file = key_file
self.cert_file = cert_file
if ca_file is not None:
self.ca_file = ca_file
else:
self.ca_file = self.get_system_ca_file()
self.timeout = timeout
self.insecure = insecure
def connect(self):
"""
Connect to a host on a given (SSL) port.
If ca_file is pointing somewhere, use it to check Server Certificate.
Redefined/copied and extended from httplib.py:1105 (Python 2.6.x).
This is needed to pass cert_reqs=ssl.CERT_REQUIRED as parameter to
ssl.wrap_socket(), which forces SSL to check server certificate against
our client certificate.
"""
sock = socket.create_connection((self.host, self.port), self.timeout)
if self._tunnel_host:
self.sock = sock
self._tunnel()
if self.insecure is True:
kwargs = {'cert_reqs': ssl.CERT_NONE}
else:
kwargs = {'cert_reqs': ssl.CERT_REQUIRED, 'ca_certs': self.ca_file}
if self.cert_file:
kwargs['certfile'] = self.cert_file
if self.key_file:
kwargs['keyfile'] = self.key_file
self.sock = ssl.wrap_socket(sock, **kwargs)
@staticmethod
def get_system_ca_file():
""""Return path to system default CA file"""
# Standard CA file locations for Debian/Ubuntu, RedHat/Fedora,
# Suse, FreeBSD/OpenBSD
ca_path = ['/etc/ssl/certs/ca-certificates.crt',
'/etc/pki/tls/certs/ca-bundle.crt',
'/etc/ssl/ca-bundle.pem',
'/etc/ssl/cert.pem']
for ca in ca_path:
if os.path.exists(ca):
return ca
return None
class ResponseBodyIterator(object):
"""A class that acts as an iterator over an HTTP response."""
def __init__(self, resp):
self.resp = resp
def __iter__(self):
while True:
yield self.next()
def next(self):
chunk = self.resp.read(CHUNKSIZE)
if chunk:
return chunk
else:
raise StopIteration()
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.