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 |
|---|---|---|---|---|---|
tony/kivy | kivy/tools/report.py | 9 | 6190 | '''
Report tool
===========
This tool is a helper for users. It can be used to dump information
for help during the debugging process.
'''
import os
import sys
import platform as plf
from time import ctime
try:
# PY3
from configparser import ConfigParser
except ImportError:
# PY2
from ConfigParser import ConfigParser
try:
from StringIO import StringIO
input = raw_input
except ImportError:
from io import StringIO
import kivy
report = []
report_dict = {} # One key value pair for each title.
def title(t):
report.append('')
report.append('=' * 80)
report.append(t)
report.append('=' * 80)
report.append('')
# This method sends report to gist(Different file in a single gist) and
# returns the URL
def send_report(dict_report):
import requests
import json
gist_report = {
"description": "Report",
"public": "true",
"files": {
"Global.txt": {
"content": "\n".join(dict_report['Global']),
"type": 'text'
},
"OpenGL.txt": {
"content": "\n".join(dict_report['OpenGL']),
"type": 'text'
},
"Core selection.txt": {
"content": "\n".join(dict_report['Core']),
"type": 'text'
},
"Libraries.txt": {
"content": "\n".join(dict_report['Libraries']),
"type": 'text'
},
"Configuration.txt": {
"content": "\n".join(dict_report['Configuration']),
"type": 'text'
},
"Input Availablity.txt": {
"content": "\n".join(dict_report['InputAvailablity']),
"type": 'text'
},
"Environ.txt": {
"content": "\n".join(dict_report['Environ']),
"type": 'text'
},
"Options.txt": {
"content": "\n".join(dict_report['Options']),
"type": 'text'
},
}
}
report_json = json.dumps(gist_report)
response = requests.post("https://api.github.com/gists", report_json)
return json.loads(response.text)['html_url']
# ----------------------------------------------------------
# Start output debugging
# ----------------------------------------------------------
title('Global')
report.append('OS platform : %s | %s' % (plf.platform(), plf.machine()))
report.append('Python EXE : %s' % sys.executable)
report.append('Python Version : %s' % sys.version)
report.append('Python API : %s' % sys.api_version)
report.append('Kivy Version : %s' % kivy.__version__)
report.append('Install path : %s' % os.path.dirname(kivy.__file__))
report.append('Install date : %s' % ctime(os.path.getctime(kivy.__file__)))
report_dict['Global'] = report
report = []
title('OpenGL')
from kivy.core import gl
from kivy.core.window import Window
report.append('GL Vendor: %s' % gl.glGetString(gl.GL_VENDOR))
report.append('GL Renderer: %s' % gl.glGetString(gl.GL_RENDERER))
report.append('GL Version: %s' % gl.glGetString(gl.GL_VERSION))
ext = None
try:
gl.glGetString(gl.GL_EXTENSIONS)
except AttributeError:
pass
if ext is None:
report.append('GL Extensions: %s' % ext)
else:
report.append('GL Extensions:')
for x in ext.split():
report.append('\t%s' % x)
Window.close()
report_dict['OpenGL'] = report
report = []
title('Core selection')
from kivy.core.audio import SoundLoader
report.append('Audio = %s' % SoundLoader._classes)
from kivy.core.camera import Camera
report.append('Camera = %s' % Camera)
from kivy.core.image import ImageLoader
report.append('Image = %s' % ImageLoader.loaders)
from kivy.core.text import Label
report.append('Text = %s' % Label)
from kivy.core.video import Video
report.append('Video = %s' % Video)
report.append('Window = %s' % Window)
report_dict['Core'] = report
report = []
title('Libraries')
def testimport(libname):
try:
lib = __import__(libname)
report.append('%-20s exist at %s' % (libname, lib.__file__))
except ImportError:
report.append('%-20s is missing' % libname)
for x in ('gst',
'pygame',
'pygame.midi',
'squirtle',
'PIL',
'sdl2',
'glew',
'opencv',
'opencv.cv',
'opencv.highgui',
'cython'):
testimport(x)
report_dict['Libraries'] = report
report = []
title('Configuration')
s = StringIO()
from kivy.config import Config
ConfigParser.write(Config, s)
report.extend(s.getvalue().split('\n'))
report_dict['Configuration'] = report
report = []
title('Input availability')
from kivy.input.factory import MotionEventFactory
for x in MotionEventFactory.list():
report.append(x)
report_dict['InputAvailablity'] = report
report = []
'''
title('Log')
for x in pymt_logger_history.history:
report.append(x.message)
'''
title('Environ')
for k, v in os.environ.items():
report.append('%s = %s' % (k, v))
report_dict['Environ'] = report
report = []
title('Options')
for k, v in kivy.kivy_options.items():
report.append('%s = %s' % (k, v))
report_dict['Options'] = report
report = []
# Prints the entire Output
print('\n'.join(report_dict['Global'] + report_dict['OpenGL'] +
report_dict['Core'] + report_dict['Libraries'] +
report_dict['Configuration'] +
report_dict['InputAvailablity'] +
report_dict['Environ'] + report_dict['Options']))
print()
print()
try:
print('The report will be sent as an anonymous gist.')
reply = input(
'Do you accept to send report to https://gist.github.com/ (Y/n) : ')
except EOFError:
sys.exit(0)
if reply.lower().strip() in ('', 'y'):
print('Please wait while sending the report...')
paste_url = send_report(report_dict)
print()
print()
print('REPORT posted at %s' % paste_url)
print()
print()
else:
print('No report posted.')
# On windows system, the console leave directly after the end
# of the dump. That's not cool if we want get report url
input('Enter any key to leave.')
| mit |
ubiar/odoo | addons/crm/res_config.py | 361 | 4156 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (C) 2004-TODAY OpenERP S.A. (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
class crm_configuration(osv.TransientModel):
_name = 'sale.config.settings'
_inherit = ['sale.config.settings', 'fetchmail.config.settings']
_columns = {
'group_fund_raising': fields.boolean("Manage Fund Raising",
implied_group='crm.group_fund_raising',
help="""Allows you to trace and manage your activities for fund raising."""),
'module_crm_claim': fields.boolean("Manage Customer Claims",
help='Allows you to track your customers/suppliers claims and grievances.\n'
'-This installs the module crm_claim.'),
'module_crm_helpdesk': fields.boolean("Manage Helpdesk and Support",
help='Allows you to communicate with Customer, process Customer query, and provide better help and support.\n'
'-This installs the module crm_helpdesk.'),
'alias_prefix': fields.char('Default Alias Name for Leads'),
'alias_domain' : fields.char('Alias Domain'),
'group_scheduled_calls': fields.boolean("Schedule calls to manage call center",
implied_group='crm.group_scheduled_calls',
help="""This adds the menu 'Scheduled Calls' under 'Sales / Phone Calls'""")
}
_defaults = {
'alias_domain': lambda self, cr, uid, context: self.pool['mail.alias']._get_alias_domain(cr, SUPERUSER_ID, [1], None, None)[1],
}
def _find_default_lead_alias_id(self, cr, uid, context=None):
alias_id = self.pool['ir.model.data'].xmlid_to_res_id(cr, uid, 'crm.mail_alias_lead_info')
if not alias_id:
alias_ids = self.pool['mail.alias'].search(
cr, uid, [
('alias_model_id.model', '=', 'crm.lead'),
('alias_force_thread_id', '=', False),
('alias_parent_model_id.model', '=', 'crm.case.section'),
('alias_parent_thread_id', '=', False),
('alias_defaults', '=', '{}')
], context=context)
alias_id = alias_ids and alias_ids[0] or False
return alias_id
def get_default_alias_prefix(self, cr, uid, ids, context=None):
alias_name = False
alias_id = self._find_default_lead_alias_id(cr, uid, context=context)
if alias_id:
alias_name = self.pool['mail.alias'].browse(cr, uid, alias_id, context=context).alias_name
return {'alias_prefix': alias_name}
def set_default_alias_prefix(self, cr, uid, ids, context=None):
mail_alias = self.pool['mail.alias']
for record in self.browse(cr, uid, ids, context=context):
alias_id = self._find_default_lead_alias_id(cr, uid, context=context)
if not alias_id:
create_ctx = dict(context, alias_model_name='crm.lead', alias_parent_model_name='crm.case.section')
alias_id = self.pool['mail.alias'].create(cr, uid, {'alias_name': record.alias_prefix}, context=create_ctx)
else:
mail_alias.write(cr, uid, alias_id, {'alias_name': record.alias_prefix}, context=context)
return True
| agpl-3.0 |
chen0031/nupic | nupic/regions/ImageSensorFilters/Resize.py | 17 | 7903 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
from PIL import Image
from nupic.regions.ImageSensorFilters.BaseFilter import BaseFilter
class Resize(BaseFilter):
"""
Create resized versions of the original image, using various methods of
padding and stretching.
"""
def __init__(self,
size=None,
sizes=None,
method='fit',
simultaneous=False,
highQuality=False):
"""
size -- Target size. Either a tuple (width, height), specifying an
absolute size in pixels, or a single value, specifying a scale factor
to apply to the current size.
sizes -- List of target sizes, for creating multiple output images
for each input image. Each entry in the list must satisfy the
requirements for the 'size' parameter, above. 'size' and 'sizes'
may not be used together.
method -- Method to use for generating new images, one of:
'fit' : scale and pad to match new size, preserving aspect ratio
'crop' : scale and crop the image to fill the new size
'stretch' : stretch the image to fill new size, ignoring aspect ratio
'center' : center the original image in the new size without scaling
simultaneous -- Whether the images should be sent out of the sensor
simultaneously.
highQuality -- Whether to use high-quality sampling for resizing
instead of nearest neighbor. If highQuality is True, antialiasing is
used for downsampling and bicubic interpolation is used for
upsampling.
Example usage:
Resize the incoming image to fit within (320, 240) by scaling so that
the image fits exactly within (320, 240) but the aspect ratio is
maintained, and padding with the sensor's background color:
Resize(size=(320, 240))
Scale the image to three different sizes: 100% of the original size,
50% of the original size, and 25% of the original size, and send the
three images out of the sensor simultaneously as multiple scales:
Resize(sizes=(1.0, 0.5, 0.25), simultaneous=True)
Pad the image to fit in a larger image of size (640, 480), centering it
in the new image:
Resize(size=(640, 480), method='center')
"""
BaseFilter.__init__(self)
if (not size and not sizes) or (size and sizes):
raise RuntimeError("Must specify either 'size' or 'sizes'")
if size:
sizes = [size]
if type(sizes) not in (list, tuple):
raise ValueError("Sizes must be a list or tuple")
if type(sizes) is tuple:
sizes = list(sizes)
for i, size in enumerate(sizes):
if type(size) in (list, tuple):
if len(size) > 2:
raise ValueError("Size is too long (must be a scalar or 2-tuple)")
elif type(size) in (int, float):
if size <= 0:
raise ValueError("Sizes must be positive numbers")
sizes[i] = [size]
else:
raise TypeError("Sizes must be positive numbers")
if method not in ('fit', 'crop', 'stretch', 'center'):
raise ValueError("Unknown method "
"(options are 'fit', 'crop', 'stretch', and 'center')")
self.sizes = sizes
self.method = method
self.simultaneous = simultaneous
self.highQuality = highQuality
def process(self, image):
"""
@param image -- The image to process.
Returns a single image, or a list containing one or more images.
"""
BaseFilter.process(self, image)
sizes = []
for i, size in enumerate(self.sizes):
if len(size) == 1:
# Convert scalar sizes to absolute sizes in pixels
sizes.append((int(round(image.size[0]*float(size[0]))),
int(round(image.size[1]*float(size[0])))))
else:
sizes.append((int(size[0]), int(size[1])))
newImages = []
for size in sizes:
if image.size == size:
newImage = image
elif self.method == 'fit':
# Resize the image to fit in the target size, preserving aspect ratio
targetRatio = size[0] / float(size[1])
imageRatio = image.size[0] / float(image.size[1])
if imageRatio > targetRatio:
xSize = size[0]
scale = size[0] / float(image.size[0])
ySize = int(scale * image.size[1])
else:
ySize = size[1]
scale = size[1] / float(image.size[1])
xSize = int(scale * image.size[0])
newImage = self._resize(image, (xSize, ySize))
# Pad with the background color if necessary
if newImage.size != size:
paddedImage = Image.new('LA', size, self.background)
paddedImage.paste(newImage,
((size[0] - newImage.size[0])/2,
(size[1] - newImage.size[1])/2))
newImage = paddedImage
elif self.method == 'crop':
# Resize the image to fill the new size
targetRatio = size[0] / float(size[1])
imageRatio = image.size[0] / float(image.size[1])
if imageRatio > targetRatio:
# Original image is too wide
scale = size[1] / float(image.size[1])
newSize = (int(scale * image.size[0]), size[1])
cropStart = ((newSize[0] - size[0]) / 2, 0)
else:
# Original image is too tall
scale = size[0] / float(image.size[0])
newSize = (size[0], int(scale * image.size[1]))
cropStart = (0, (newSize[1] - size[1]) / 2)
newImage = self._resize(image, newSize)
# Crop if necessary
if newSize != size:
newImage = newImage.crop((cropStart[0], cropStart[1],
cropStart[0] + size[0], cropStart[1] + size[1]))
elif self.method == 'stretch':
# Resize the image to each target size, ignoring aspect ratio
newImage = self._resize(image, size)
elif self.method == 'center':
# Center the original image in the new image without rescaling it
newImage = Image.new('LA', size, self.background)
x = (size[0] - image.size[0]) / 2
y = (size[1] - image.size[1]) / 2
newImage.paste(image, (x, y))
newImages.append(newImage)
if not self.simultaneous:
if len(newImages) == 1:
return newImages[0]
else:
return newImages
else:
return [newImages]
def getOutputCount(self):
"""
Return the number of images returned by each call to process().
If the filter creates multiple simultaneous outputs, return a tuple:
(outputCount, simultaneousOutputCount).
"""
if not self.simultaneous:
return len(self.sizes)
else:
return 1, len(self.sizes)
def _resize(self, image, size):
"""
Resize the image with the appropriate sampling method.
"""
if self.highQuality:
if size < image.size:
return image.resize(size, Image.ANTIALIAS)
else:
return image.resize(size, Image.BICUBIC)
else:
return image.resize(size)
| agpl-3.0 |
xzYue/odoo | addons/subscription/__openerp__.py | 261 | 1885 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Recurring Documents',
'version': '1.0',
'category': 'Tools',
'description': """
Create recurring documents.
===========================
This module allows to create new documents and add subscriptions on that document.
e.g. To have an invoice generated automatically periodically:
-------------------------------------------------------------
* Define a document type based on Invoice object
* Define a subscription whose source document is the document defined as
above. Specify the interval information and partner to be invoice.
""",
'author': 'OpenERP SA',
'depends': ['base'],
'data': ['security/subcription_security.xml', 'security/ir.model.access.csv', 'subscription_view.xml'],
'demo': ['subscription_demo.xml',],
'installable': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
abelkhan/websearch | websearch/pymongo/command_cursor.py | 14 | 6153 | # Copyright 2014 MongoDB, 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.
"""CommandCursor class to iterate over command results."""
from collections import deque
from pymongo import helpers, message
from pymongo.errors import AutoReconnect, CursorNotFound
class CommandCursor(object):
"""A cursor / iterator over command cursors.
"""
def __init__(self, collection, cursor_info,
conn_id, compile_re=True, retrieved=0):
"""Create a new command cursor.
"""
self.__collection = collection
self.__id = cursor_info['id']
self.__conn_id = conn_id
self.__data = deque(cursor_info['firstBatch'])
self.__decode_opts = (
collection.database.connection.document_class,
collection.database.connection.tz_aware,
collection.uuid_subtype,
compile_re
)
self.__retrieved = retrieved
self.__batch_size = 0
self.__killed = False
def __del__(self):
if self.__id and not self.__killed:
self.__die()
def __die(self):
"""Closes this cursor.
"""
if self.__id and not self.__killed:
client = self.__collection.database.connection
if self.__conn_id is not None:
client.close_cursor(self.__id, self.__conn_id)
else:
client.close_cursor(self.__id)
self.__killed = True
def close(self):
"""Explicitly close / kill this cursor. Required for PyPy, Jython and
other Python implementations that don't use reference counting
garbage collection.
"""
self.__die()
def batch_size(self, batch_size):
"""Limits the number of documents returned in one batch. Each batch
requires a round trip to the server. It can be adjusted to optimize
performance and limit data transfer.
.. note:: batch_size can not override MongoDB's internal limits on the
amount of data it will return to the client in a single batch (i.e
if you set batch size to 1,000,000,000, MongoDB will currently only
return 4-16MB of results per batch).
Raises :exc:`TypeError` if `batch_size` is not an integer.
Raises :exc:`ValueError` if `batch_size` is less than ``0``.
:Parameters:
- `batch_size`: The size of each batch of results requested.
"""
if not isinstance(batch_size, (int, long)):
raise TypeError("batch_size must be an integer")
if batch_size < 0:
raise ValueError("batch_size must be >= 0")
self.__batch_size = batch_size == 1 and 2 or batch_size
return self
def __send_message(self, msg):
"""Send a getmore message and handle the response.
"""
client = self.__collection.database.connection
try:
res = client._send_message_with_response(
msg, _connection_to_use=self.__conn_id)
self.__conn_id, (response, dummy0, dummy1) = res
except AutoReconnect:
# Don't try to send kill cursors on another socket
# or to another server. It can cause a _pinValue
# assertion on some server releases if we get here
# due to a socket timeout.
self.__killed = True
raise
try:
response = helpers._unpack_response(response,
self.__id,
*self.__decode_opts)
except CursorNotFound:
self.__killed = True
raise
except AutoReconnect:
# Don't send kill cursors to another server after a "not master"
# error. It's completely pointless.
self.__killed = True
client.disconnect()
raise
self.__id = response["cursor_id"]
assert response["starting_from"] == self.__retrieved, (
"Result batch started from %s, expected %s" % (
response['starting_from'], self.__retrieved))
self.__retrieved += response["number_returned"]
self.__data = deque(response["data"])
def _refresh(self):
"""Refreshes the cursor with more data from the server.
Returns the length of self.__data after refresh. Will exit early if
self.__data is already non-empty. Raises OperationFailure when the
cursor cannot be refreshed due to an error on the query.
"""
if len(self.__data) or self.__killed:
return len(self.__data)
if self.__id: # Get More
self.__send_message(
message.get_more(self.__collection.full_name,
self.__batch_size, self.__id))
else: # Cursor id is zero nothing else to return
self.__killed = True
return len(self.__data)
@property
def alive(self):
"""Does this cursor have the potential to return more data?"""
return bool(len(self.__data) or (not self.__killed))
@property
def cursor_id(self):
"""Returns the id of the cursor."""
return self.__id
def __iter__(self):
return self
def next(self):
"""Advance the cursor.
"""
if len(self.__data) or self._refresh():
coll = self.__collection
return coll.database._fix_incoming(self.__data.popleft(), coll)
else:
raise StopIteration
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.__die()
| gpl-3.0 |
carlgao/lenga | images/lenny64-peon/usr/share/python-support/python-django/django/contrib/comments/models.py | 313 | 7636 | import datetime
from django.contrib.auth.models import User
from django.contrib.comments.managers import CommentManager
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.db import models
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
COMMENT_MAX_LENGTH = getattr(settings,'COMMENT_MAX_LENGTH',3000)
class BaseCommentAbstractModel(models.Model):
"""
An abstract base class that any custom comment models probably should
subclass.
"""
# Content-object field
content_type = models.ForeignKey(ContentType,
verbose_name=_('content type'),
related_name="content_type_set_for_%(class)s")
object_pk = models.TextField(_('object ID'))
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
# Metadata about the comment
site = models.ForeignKey(Site)
class Meta:
abstract = True
def get_content_object_url(self):
"""
Get a URL suitable for redirecting to the content object.
"""
return urlresolvers.reverse(
"comments-url-redirect",
args=(self.content_type_id, self.object_pk)
)
class Comment(BaseCommentAbstractModel):
"""
A user comment about some object.
"""
# Who posted this comment? If ``user`` is set then it was an authenticated
# user; otherwise at least user_name should have been set and the comment
# was posted by a non-authenticated user.
user = models.ForeignKey(User, verbose_name=_('user'),
blank=True, null=True, related_name="%(class)s_comments")
user_name = models.CharField(_("user's name"), max_length=50, blank=True)
user_email = models.EmailField(_("user's email address"), blank=True)
user_url = models.URLField(_("user's URL"), blank=True)
comment = models.TextField(_('comment'), max_length=COMMENT_MAX_LENGTH)
# Metadata about the comment
submit_date = models.DateTimeField(_('date/time submitted'), default=None)
ip_address = models.IPAddressField(_('IP address'), blank=True, null=True)
is_public = models.BooleanField(_('is public'), default=True,
help_text=_('Uncheck this box to make the comment effectively ' \
'disappear from the site.'))
is_removed = models.BooleanField(_('is removed'), default=False,
help_text=_('Check this box if the comment is inappropriate. ' \
'A "This comment has been removed" message will ' \
'be displayed instead.'))
# Manager
objects = CommentManager()
class Meta:
db_table = "django_comments"
ordering = ('submit_date',)
permissions = [("can_moderate", "Can moderate comments")]
verbose_name = _('comment')
verbose_name_plural = _('comments')
def __unicode__(self):
return "%s: %s..." % (self.name, self.comment[:50])
def save(self, *args, **kwargs):
if self.submit_date is None:
self.submit_date = datetime.datetime.now()
super(Comment, self).save(*args, **kwargs)
def _get_userinfo(self):
"""
Get a dictionary that pulls together information about the poster
safely for both authenticated and non-authenticated comments.
This dict will have ``name``, ``email``, and ``url`` fields.
"""
if not hasattr(self, "_userinfo"):
self._userinfo = {
"name" : self.user_name,
"email" : self.user_email,
"url" : self.user_url
}
if self.user_id:
u = self.user
if u.email:
self._userinfo["email"] = u.email
# If the user has a full name, use that for the user name.
# However, a given user_name overrides the raw user.username,
# so only use that if this comment has no associated name.
if u.get_full_name():
self._userinfo["name"] = self.user.get_full_name()
elif not self.user_name:
self._userinfo["name"] = u.username
return self._userinfo
userinfo = property(_get_userinfo, doc=_get_userinfo.__doc__)
def _get_name(self):
return self.userinfo["name"]
def _set_name(self, val):
if self.user_id:
raise AttributeError(_("This comment was posted by an authenticated "\
"user and thus the name is read-only."))
self.user_name = val
name = property(_get_name, _set_name, doc="The name of the user who posted this comment")
def _get_email(self):
return self.userinfo["email"]
def _set_email(self, val):
if self.user_id:
raise AttributeError(_("This comment was posted by an authenticated "\
"user and thus the email is read-only."))
self.user_email = val
email = property(_get_email, _set_email, doc="The email of the user who posted this comment")
def _get_url(self):
return self.userinfo["url"]
def _set_url(self, val):
self.user_url = val
url = property(_get_url, _set_url, doc="The URL given by the user who posted this comment")
def get_absolute_url(self, anchor_pattern="#c%(id)s"):
return self.get_content_object_url() + (anchor_pattern % self.__dict__)
def get_as_text(self):
"""
Return this comment as plain text. Useful for emails.
"""
d = {
'user': self.user or self.name,
'date': self.submit_date,
'comment': self.comment,
'domain': self.site.domain,
'url': self.get_absolute_url()
}
return _('Posted by %(user)s at %(date)s\n\n%(comment)s\n\nhttp://%(domain)s%(url)s') % d
class CommentFlag(models.Model):
"""
Records a flag on a comment. This is intentionally flexible; right now, a
flag could be:
* A "removal suggestion" -- where a user suggests a comment for (potential) removal.
* A "moderator deletion" -- used when a moderator deletes a comment.
You can (ab)use this model to add other flags, if needed. However, by
design users are only allowed to flag a comment with a given flag once;
if you want rating look elsewhere.
"""
user = models.ForeignKey(User, verbose_name=_('user'), related_name="comment_flags")
comment = models.ForeignKey(Comment, verbose_name=_('comment'), related_name="flags")
flag = models.CharField(_('flag'), max_length=30, db_index=True)
flag_date = models.DateTimeField(_('date'), default=None)
# Constants for flag types
SUGGEST_REMOVAL = "removal suggestion"
MODERATOR_DELETION = "moderator deletion"
MODERATOR_APPROVAL = "moderator approval"
class Meta:
db_table = 'django_comment_flags'
unique_together = [('user', 'comment', 'flag')]
verbose_name = _('comment flag')
verbose_name_plural = _('comment flags')
def __unicode__(self):
return "%s flag of comment ID %s by %s" % \
(self.flag, self.comment_id, self.user.username)
def save(self, *args, **kwargs):
if self.flag_date is None:
self.flag_date = datetime.datetime.now()
super(CommentFlag, self).save(*args, **kwargs)
| mit |
lsinfo/odoo | addons/web_linkedin/web_linkedin.py | 333 | 4485 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import base64
import urllib2
from urlparse import urlparse, urlunparse
import openerp
import openerp.addons.web
from openerp.osv import fields, osv
class Binary(openerp.http.Controller):
@openerp.http.route('/web_linkedin/binary/url2binary', type='json', auth='user')
def url2binary(self, url):
"""Used exclusively to load images from LinkedIn profiles, must not be used for anything else."""
_scheme, _netloc, path, params, query, fragment = urlparse(url)
# media.linkedin.com is the master domain for LinkedIn media (replicated to CDNs),
# so forcing it should always work and prevents abusing this method to load arbitrary URLs
url = urlunparse(('http', 'media.licdn.com', path, params, query, fragment))
bfile = urllib2.urlopen(url)
return base64.b64encode(bfile.read())
class web_linkedin_settings(osv.osv_memory):
_inherit = 'sale.config.settings'
_columns = {
'api_key': fields.char(string="API Key", size=50),
'server_domain': fields.char(),
}
def get_default_linkedin(self, cr, uid, fields, context=None):
key = self.pool.get("ir.config_parameter").get_param(cr, uid, "web.linkedin.apikey") or ""
dom = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url')
return {'api_key': key, 'server_domain': dom,}
def set_linkedin(self, cr, uid, ids, context=None):
key = self.browse(cr, uid, ids[0], context)["api_key"] or ""
self.pool.get("ir.config_parameter").set_param(cr, uid, "web.linkedin.apikey", key, groups=['base.group_user'])
class web_linkedin_fields(osv.Model):
_inherit = 'res.partner'
def _get_url(self, cr, uid, ids, name, arg, context=None):
res = dict((id, False) for id in ids)
for partner in self.browse(cr, uid, ids, context=context):
res[partner.id] = partner.linkedin_url
return res
def linkedin_check_similar_partner(self, cr, uid, linkedin_datas, context=None):
res = []
res_partner = self.pool.get('res.partner')
for linkedin_data in linkedin_datas:
partner_ids = res_partner.search(cr, uid, ["|", ("linkedin_id", "=", linkedin_data['id']),
"&", ("linkedin_id", "=", False),
"|", ("name", "ilike", linkedin_data['firstName'] + "%" + linkedin_data['lastName']), ("name", "ilike", linkedin_data['lastName'] + "%" + linkedin_data['firstName'])], context=context)
if partner_ids:
partner = res_partner.read(cr, uid, partner_ids[0], ["image", "mobile", "phone", "parent_id", "name", "email", "function", "linkedin_id"], context=context)
if partner['linkedin_id'] and partner['linkedin_id'] != linkedin_data['id']:
partner.pop('id')
if partner['parent_id']:
partner['parent_id'] = partner['parent_id'][0]
for key, val in partner.items():
if not val:
partner.pop(key)
res.append(partner)
else:
res.append({})
return res
_columns = {
'linkedin_id': fields.char(string="LinkedIn ID"),
'linkedin_url': fields.char(string="LinkedIn url", store=True),
'linkedin_public_url': fields.function(_get_url, type='text', string="LinkedIn url",
help="This url is set automatically when you join the partner with a LinkedIn account."),
}
| agpl-3.0 |
russellb/powerline | powerline/lint/markedjson/parser.py | 37 | 8124 | # vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
from powerline.lint.markedjson.error import MarkedError
from powerline.lint.markedjson import tokens
from powerline.lint.markedjson import events
class ParserError(MarkedError):
pass
class Parser:
def __init__(self):
self.current_event = None
self.yaml_version = None
self.states = []
self.marks = []
self.state = self.parse_stream_start
def dispose(self):
# Reset the state attributes (to clear self-references)
self.states = []
self.state = None
def check_event(self, *choices):
# Check the type of the next event.
if self.current_event is None:
if self.state:
self.current_event = self.state()
if self.current_event is not None:
if not choices:
return True
for choice in choices:
if isinstance(self.current_event, choice):
return True
return False
def peek_event(self):
# Get the next event.
if self.current_event is None:
if self.state:
self.current_event = self.state()
return self.current_event
def get_event(self):
# Get the next event and proceed further.
if self.current_event is None:
if self.state:
self.current_event = self.state()
value = self.current_event
self.current_event = None
return value
# stream ::= STREAM-START implicit_document? explicit_document* STREAM-END
# implicit_document ::= block_node DOCUMENT-END*
# explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END*
def parse_stream_start(self):
# Parse the stream start.
token = self.get_token()
event = events.StreamStartEvent(token.start_mark, token.end_mark, encoding=token.encoding)
# Prepare the next state.
self.state = self.parse_implicit_document_start
return event
def parse_implicit_document_start(self):
# Parse an implicit document.
if not self.check_token(tokens.StreamEndToken):
token = self.peek_token()
start_mark = end_mark = token.start_mark
event = events.DocumentStartEvent(start_mark, end_mark, explicit=False)
# Prepare the next state.
self.states.append(self.parse_document_end)
self.state = self.parse_node
return event
else:
return self.parse_document_start()
def parse_document_start(self):
# Parse an explicit document.
if not self.check_token(tokens.StreamEndToken):
token = self.peek_token()
self.echoerr(
None, None,
('expected \'<stream end>\', but found %r' % token.id), token.start_mark
)
return events.StreamEndEvent(token.start_mark, token.end_mark)
else:
# Parse the end of the stream.
token = self.get_token()
event = events.StreamEndEvent(token.start_mark, token.end_mark)
assert not self.states
assert not self.marks
self.state = None
return event
def parse_document_end(self):
# Parse the document end.
token = self.peek_token()
start_mark = end_mark = token.start_mark
explicit = False
event = events.DocumentEndEvent(start_mark, end_mark, explicit=explicit)
# Prepare the next state.
self.state = self.parse_document_start
return event
def parse_document_content(self):
return self.parse_node()
def parse_node(self, indentless_sequence=False):
start_mark = end_mark = None
if start_mark is None:
start_mark = end_mark = self.peek_token().start_mark
event = None
implicit = True
if self.check_token(tokens.ScalarToken):
token = self.get_token()
end_mark = token.end_mark
if token.plain:
implicit = (True, False)
else:
implicit = (False, True)
event = events.ScalarEvent(implicit, token.value, start_mark, end_mark, style=token.style)
self.state = self.states.pop()
elif self.check_token(tokens.FlowSequenceStartToken):
end_mark = self.peek_token().end_mark
event = events.SequenceStartEvent(implicit, start_mark, end_mark, flow_style=True)
self.state = self.parse_flow_sequence_first_entry
elif self.check_token(tokens.FlowMappingStartToken):
end_mark = self.peek_token().end_mark
event = events.MappingStartEvent(implicit, start_mark, end_mark, flow_style=True)
self.state = self.parse_flow_mapping_first_key
else:
token = self.peek_token()
raise ParserError(
'while parsing a flow node', start_mark,
'expected the node content, but found %r' % token.id,
token.start_mark
)
return event
def parse_flow_sequence_first_entry(self):
token = self.get_token()
self.marks.append(token.start_mark)
return self.parse_flow_sequence_entry(first=True)
def parse_flow_sequence_entry(self, first=False):
if not self.check_token(tokens.FlowSequenceEndToken):
if not first:
if self.check_token(tokens.FlowEntryToken):
self.get_token()
if self.check_token(tokens.FlowSequenceEndToken):
token = self.peek_token()
self.echoerr(
'While parsing a flow sequence', self.marks[-1],
('expected sequence value, but got %r' % token.id), token.start_mark
)
else:
token = self.peek_token()
raise ParserError(
'while parsing a flow sequence', self.marks[-1],
('expected \',\' or \']\', but got %r' % token.id), token.start_mark
)
if not self.check_token(tokens.FlowSequenceEndToken):
self.states.append(self.parse_flow_sequence_entry)
return self.parse_node()
token = self.get_token()
event = events.SequenceEndEvent(token.start_mark, token.end_mark)
self.state = self.states.pop()
self.marks.pop()
return event
def parse_flow_sequence_entry_mapping_end(self):
self.state = self.parse_flow_sequence_entry
token = self.peek_token()
return events.MappingEndEvent(token.start_mark, token.start_mark)
def parse_flow_mapping_first_key(self):
token = self.get_token()
self.marks.append(token.start_mark)
return self.parse_flow_mapping_key(first=True)
def parse_flow_mapping_key(self, first=False):
if not self.check_token(tokens.FlowMappingEndToken):
if not first:
if self.check_token(tokens.FlowEntryToken):
self.get_token()
if self.check_token(tokens.FlowMappingEndToken):
token = self.peek_token()
self.echoerr(
'While parsing a flow mapping', self.marks[-1],
('expected mapping key, but got %r' % token.id), token.start_mark
)
else:
token = self.peek_token()
raise ParserError(
'while parsing a flow mapping', self.marks[-1],
('expected \',\' or \'}\', but got %r' % token.id), token.start_mark
)
if self.check_token(tokens.KeyToken):
token = self.get_token()
if not self.check_token(tokens.ValueToken, tokens.FlowEntryToken, tokens.FlowMappingEndToken):
self.states.append(self.parse_flow_mapping_value)
return self.parse_node()
else:
token = self.peek_token()
raise ParserError(
'while parsing a flow mapping', self.marks[-1],
('expected value, but got %r' % token.id), token.start_mark
)
elif not self.check_token(tokens.FlowMappingEndToken):
token = self.peek_token()
expect_key = self.check_token(tokens.ValueToken, tokens.FlowEntryToken)
if not expect_key:
self.get_token()
expect_key = self.check_token(tokens.ValueToken)
if expect_key:
raise ParserError(
'while parsing a flow mapping', self.marks[-1],
('expected string key, but got %r' % token.id), token.start_mark
)
else:
token = self.peek_token()
raise ParserError(
'while parsing a flow mapping', self.marks[-1],
('expected \':\', but got %r' % token.id), token.start_mark
)
token = self.get_token()
event = events.MappingEndEvent(token.start_mark, token.end_mark)
self.state = self.states.pop()
self.marks.pop()
return event
def parse_flow_mapping_value(self):
if self.check_token(tokens.ValueToken):
token = self.get_token()
if not self.check_token(tokens.FlowEntryToken, tokens.FlowMappingEndToken):
self.states.append(self.parse_flow_mapping_key)
return self.parse_node()
token = self.peek_token()
raise ParserError(
'while parsing a flow mapping', self.marks[-1],
('expected mapping value, but got %r' % token.id), token.start_mark
)
| mit |
kawamuray/ganeti | lib/tools/prepare_node_join.py | 7 | 7039 | #
#
# Copyright (C) 2012 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
"""Script to prepare a node for joining a cluster.
"""
import os
import os.path
import optparse
import sys
import logging
import OpenSSL
from ganeti import cli
from ganeti import constants
from ganeti import errors
from ganeti import pathutils
from ganeti import utils
from ganeti import serializer
from ganeti import ht
from ganeti import ssh
from ganeti import ssconf
_SSH_KEY_LIST_ITEM = \
ht.TAnd(ht.TIsLength(3),
ht.TItems([
ht.TElemOf(constants.SSHK_ALL),
ht.Comment("public")(ht.TNonEmptyString),
ht.Comment("private")(ht.TNonEmptyString),
]))
_SSH_KEY_LIST = ht.TListOf(_SSH_KEY_LIST_ITEM)
_DATA_CHECK = ht.TStrictDict(False, True, {
constants.SSHS_CLUSTER_NAME: ht.TNonEmptyString,
constants.SSHS_NODE_DAEMON_CERTIFICATE: ht.TNonEmptyString,
constants.SSHS_SSH_HOST_KEY: _SSH_KEY_LIST,
constants.SSHS_SSH_ROOT_KEY: _SSH_KEY_LIST,
})
class JoinError(errors.GenericError):
"""Local class for reporting errors.
"""
def ParseOptions():
"""Parses the options passed to the program.
@return: Options and arguments
"""
program = os.path.basename(sys.argv[0])
parser = optparse.OptionParser(usage="%prog [--dry-run]",
prog=program)
parser.add_option(cli.DEBUG_OPT)
parser.add_option(cli.VERBOSE_OPT)
parser.add_option(cli.DRY_RUN_OPT)
(opts, args) = parser.parse_args()
return VerifyOptions(parser, opts, args)
def VerifyOptions(parser, opts, args):
"""Verifies options and arguments for correctness.
"""
if args:
parser.error("No arguments are expected")
return opts
def _VerifyCertificate(cert_pem, _check_fn=utils.CheckNodeCertificate):
"""Verifies a certificate against the local node daemon certificate.
@type cert_pem: string
@param cert_pem: Certificate in PEM format (no key)
"""
try:
OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, cert_pem)
except OpenSSL.crypto.Error, err:
pass
else:
raise JoinError("No private key may be given")
try:
cert = \
OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert_pem)
except Exception, err:
raise errors.X509CertError("(stdin)",
"Unable to load certificate: %s" % err)
_check_fn(cert)
def VerifyCertificate(data, _verify_fn=_VerifyCertificate):
"""Verifies cluster certificate.
@type data: dict
"""
cert = data.get(constants.SSHS_NODE_DAEMON_CERTIFICATE)
if cert:
_verify_fn(cert)
def VerifyClusterName(data, _verify_fn=ssconf.VerifyClusterName):
"""Verifies cluster name.
@type data: dict
"""
name = data.get(constants.SSHS_CLUSTER_NAME)
if name:
_verify_fn(name)
else:
raise JoinError("Cluster name must be specified")
def _UpdateKeyFiles(keys, dry_run, keyfiles):
"""Updates SSH key files.
@type keys: sequence of tuple; (string, string, string)
@param keys: Keys to write, tuples consist of key type
(L{constants.SSHK_ALL}), public and private key
@type dry_run: boolean
@param dry_run: Whether to perform a dry run
@type keyfiles: dict; (string as key, tuple with (string, string) as values)
@param keyfiles: Mapping from key types (L{constants.SSHK_ALL}) to file
names; value tuples consist of public key filename and private key filename
"""
assert set(keyfiles) == constants.SSHK_ALL
for (kind, private_key, public_key) in keys:
(private_file, public_file) = keyfiles[kind]
logging.debug("Writing %s ...", private_file)
utils.WriteFile(private_file, data=private_key, mode=0600,
backup=True, dry_run=dry_run)
logging.debug("Writing %s ...", public_file)
utils.WriteFile(public_file, data=public_key, mode=0644,
backup=True, dry_run=dry_run)
def UpdateSshDaemon(data, dry_run, _runcmd_fn=utils.RunCmd,
_keyfiles=None):
"""Updates SSH daemon's keys.
Unless C{dry_run} is set, the daemon is restarted at the end.
@type data: dict
@param data: Input data
@type dry_run: boolean
@param dry_run: Whether to perform a dry run
"""
keys = data.get(constants.SSHS_SSH_HOST_KEY)
if not keys:
return
if _keyfiles is None:
_keyfiles = constants.SSH_DAEMON_KEYFILES
logging.info("Updating SSH daemon key files")
_UpdateKeyFiles(keys, dry_run, _keyfiles)
if dry_run:
logging.info("This is a dry run, not restarting SSH daemon")
else:
result = _runcmd_fn([pathutils.DAEMON_UTIL, "reload-ssh-keys"],
interactive=True)
if result.failed:
raise JoinError("Could not reload SSH keys, command '%s'"
" had exitcode %s and error %s" %
(result.cmd, result.exit_code, result.output))
def UpdateSshRoot(data, dry_run, _homedir_fn=None):
"""Updates root's SSH keys.
Root's C{authorized_keys} file is also updated with new public keys.
@type data: dict
@param data: Input data
@type dry_run: boolean
@param dry_run: Whether to perform a dry run
"""
keys = data.get(constants.SSHS_SSH_ROOT_KEY)
if not keys:
return
(auth_keys_file, keyfiles) = \
ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=True,
_homedir_fn=_homedir_fn)
_UpdateKeyFiles(keys, dry_run, keyfiles)
if dry_run:
logging.info("This is a dry run, not modifying %s", auth_keys_file)
else:
for (_, _, public_key) in keys:
utils.AddAuthorizedKey(auth_keys_file, public_key)
def LoadData(raw):
"""Parses and verifies input data.
@rtype: dict
"""
return serializer.LoadAndVerifyJson(raw, _DATA_CHECK)
def Main():
"""Main routine.
"""
opts = ParseOptions()
utils.SetupToolLogging(opts.debug, opts.verbose)
try:
data = LoadData(sys.stdin.read())
# Check if input data is correct
VerifyClusterName(data)
VerifyCertificate(data)
# Update SSH files
UpdateSshDaemon(data, opts.dry_run)
UpdateSshRoot(data, opts.dry_run)
logging.info("Setup finished successfully")
except Exception, err: # pylint: disable=W0703
logging.debug("Caught unhandled exception", exc_info=True)
(retcode, message) = cli.FormatError(err)
logging.error(message)
return retcode
else:
return constants.EXIT_SUCCESS
| gpl-2.0 |
JBonsink/GSOC-2013 | core/fs/Node.py | 2 | 2111 | from sadit_configure.Node import NNode
from core.BaseNode import BaseNode
from util import abstract_method
class Node(NNode, BaseNode):
def __init__(self, ipdests, node_seq):
self.sock_num = 0
self.socks = []
def start(self): abstract_method()
#################################
### Some Utility Function ###
#################################
@property
def now(self): return self.network.now()
def sleep(self, t, call_back=None):
pass
def create_timer(self, t, call_back): abstract_method()
#################################
### Network Related ###
#################################
def set_master_sock(self, sock): abstract_method()
@property
def client_socks(self): abstract_method()
#### Socket API ####
def create_sock(self, desc):
sid = self.sock_num
self.socks.append(desc)
self.sock_num += 1
return sid
def bind(self, sock, port):
self.socks[sock]['ipdests'] = self.ipdests
self.socks[sock]['port'] = self.ipdests
def listen(self, sock, backlog): pass
def accept(self, sock): pass
def recv(self, sock, bufsize, dispatcher, threaded=False): abstract_method()
def send(self, sock, data): abstract_method()
def connect(self, sock, addr_port): abstract_method()
def sendto(self, sock, data, addr, port): abstract_method()
def close_sock(self, sock): abstract_method()
#################################
### Application Layer #######
#################################
def ping(self, sock, data, threaded=False): abstract_method()
def ftp(self, sock, data, threaded=False): abstract_method()
def icmp(self, sock, data, threaded=False): abstract_method()
def http(self, sock, data, threaded=False): abstract_method()
def stop_app(self, sock, app_name): abstract_method()
#################################
## New Func ##
#################################
# def install(self, network):
# self.network = network
# network.add_node(self)
| gpl-3.0 |
philrosenfield/TPAGB-calib | parse_tracks/parse_agb_tracks.py | 1 | 14568 | import os
import sys
import glob
try:
import numpy as np
except ImportError:
print 'You need numpy to run this script'
print 'sudo apt-get install python-numpy'
sys.exit()
if np.__version__ < '1.6':
print 'Warning -- you should update numpy, you might get errors. E.g:'
print 'sudo apt-get install python-numpy=1:1.7.1-1ubuntu1'
class AGBTracks(object):
'''
A fast way of loading files.
examples:
track = some agb track file name (string)
AGB = get_numeric_data(track)
all the data:
AGB.data_array
the file name:
AGB.name
a dictionary with 'key': column_number
AGB.key_dict
get the row of the AGB track by calling the number in the first column
(ex: 7):
AGB.get_row_bynum(7)
get a specified column (use AGB.key_dict to know which one, or do head -1)
(ex: logL)
AGB.get_col('L_*')
'''
def __init__(self, data_array, col_keys, name):
self.data_array = data_array
self.key_dict = dict(zip(col_keys, range(len(col_keys))))
self.name = name
self.firstname = os.path.split(name)[1]
self.mass = float(self.firstname.split('_')[1])
self.metallicity = float(self.firstname.split('_')[2].replace('Z', ''))
# initialize: it's a well formatted track with more than one pulse
self.bad_track = False
# if only one thermal pulse, stop the press.
self.check_ntp()
self.get_TP_inds()
if not self.bad_track:
# force the beginning phase to not look like it's quiescent
self.fix_phi()
# load quiescent tracks
self.get_quiescent_inds()
# load indices of m and c stars
self.m_cstars()
# calculate the lifetimes of m and c stars
self.tauc_m()
# add points to low mass quiescent track for better interpolation
self.addpt = []
if len(self.Qs) <= 9 and self.mass < 3.:
self.add_points_to_q_track()
# find dl/dt of track
self.find_dldt()
else:
print 'bad track:', name
def find_dldt(self, order=1):
'''
Finds dL/dt of track object by a poly fit of order = 1 (default)
'''
TPs = self.TPs
status = self.get_col('status')
logl = self.get_col('L_star')
logt = self.get_col('T_star')
phi = self.get_col('PHI_TP')
# if a low mass interpolation point was added it will get
# the same slope as the rest of the thermal pulse.
#dl/dT seems somewhat linear for 0.2 < phi < 0.4 ...
lin_rise, = np.nonzero((status == 7) & (phi < 0.4) & (phi > 0.2))
rising = [list(set(TP) & set(lin_rise)) for TP in TPs]
fits = [np.polyfit(logt[r], logl[r], order) for r in rising if len(r) > 0]
slopes = np.array([])
# first line slope
slopes = np.append(slopes, (logl[2] - logl[0]) / (logt[2] - logt[0]))
# poly fitted slopes
slopes = np.append(slopes, [fits[i][0] for i in range(len(fits))])
# pop in an additional copy of the slope if an interpolation point
# was added.
if len(self.addpt) > 0:
tps_of_addpt = np.array([i for i in range(len(TPs))
if list(set(self.addpt) & set(TPs[i])) > 0])
slopes = np.insert(slopes, tps_of_addpt, slopes[tps_of_addpt])
self.Qs = np.insert(self.Qs, 0, 0)
self.rising = rising
self.slopes = slopes
self.fits = fits
def add_points_to_q_track(self):
'''
when to add an extra point for low masses
if logt[qs+1] is hotter than logt[qs]
and there is a point inbetween logt[qs] and logt[qs+1] that is cooler
than logt[qs] add the coolest point.
'''
addpt = self.addpt
qs = list(self.Qs)
logt = self.get_col('T_star')
tstep = self.get_col('step')
status = self.get_col('status')
Tqs = logt[qs]
# need to use some unique array, not logt, since logt could repeat,
# index would find the first one, not necessarily the correct one.
Sqs = tstep[qs] - 1. # steps start at 1, not zero
# takes the sign of the difference in logt(qs)
# if the sign of the difference is more than 0, we're going from cold to ho
# finds where the logt goes from getting colder to hotter...
ht, = np.nonzero(np.sign(np.diff(Tqs)) > 0)
ht = np.append(ht, ht + 1) # between the first and second
Sqs_ht = Sqs[ht]
# the indices between each hot point.
t_mids = [map(int, tstep[int(Sqs_ht[i]): int(Sqs_ht[i + 1])])
for i in range(len(Sqs_ht) - 1)]
Sqs_ht = Sqs_ht[: -1]
for i in range(len(Sqs_ht) - 1):
hot_inds = np.nonzero(logt[int(Sqs_ht[i])] > logt[t_mids[i]])[0]
if len(hot_inds) > 0:
# index of the min T of the hot index from above.
addpt.append(list(logt).index(np.min(logt[[t_mids[i][hi]
for hi in hot_inds]])))
if len(addpt) > 0:
addpt = np.unique([a for a in addpt if status[a] == 7.])
# hack: if there is more than one point, take the most evolved.
if len(addpt) > 1:
addpt = [np.max(addpt)]
# update Qs with added pts.
self.Qs = np.sort(np.concatenate((addpt, qs)))
self.addpt = addpt
def check_ntp(self):
'''
sets self.bad_track = True if only one thermal pulse.
'''
ntp = self.get_col('NTP')
if ntp.size == 1:
print 'no tracks!', self.name
self.bad_track = True
def fix_phi(self):
'''
The first line in the agb track is 1. This isn't a quiescent stage.
'''
self.data_array['PHI_TP'][0] = -1.
def get_row(self, i):
return self.data_array[i, :]
def get_row_bynum(self, i):
row = np.nonzero(self.data_array[:, self.key_dict['step']] == i)[0]
return self.data_array[row, :]
def get_col(self, key):
return self.data_array[key]
def m_cstars(self, mdot_cond=-5, logl_cond=3.3):
'''
adds mstar and cstar attribute of indices that are true for:
mstar: co <=1 logl >= 3.3 mdot <= -5
cstar: co >=1 mdot <= -5
(by default) adjust mdot with mdot_cond and logl with logl_cond.
'''
data = self.data_array
self.mstar, = np.nonzero((data['CO'] <= 1) &
(data['L_star'] >= logl_cond) &
(data['dMdt'] <= mdot_cond))
self.cstar, = np.nonzero((data['CO'] >= 1) &
(data['dMdt'] <= mdot_cond))
def tauc_m(self):
'''
lifetimes of c and m stars
'''
try:
tauc = np.sum(self.data_array['dt'][self.cstar]) / 1e6
except IndexError:
tauc = 0.
print 'no tauc'
try:
taum = np.sum(self.data_array['dt'][self.mstar]) / 1e6
except IndexError:
taum = 0.
print 'no taum'
self.taum = taum
self.tauc = tauc
def get_TP_inds(self):
'''
find the thermal pulsations of each file
'''
if not self.bad_track:
ntp = self.get_col('NTP')
un = np.unique(ntp)
if un.size == 1:
print 'only one themal pulse.'
self.TPs = un
else:
# this is the first step in each TP.
iTPs = [list(ntp).index(u) for u in un]
# The indices of each TP.
TPs = [np.arange(iTPs[i], iTPs[i + 1]) for i in range(len(iTPs) - 1)]
# don't forget the last one.
TPs.append(np.arange(iTPs[i + 1], len(ntp)))
self.TPs = TPs
else:
self.TPs = []
if len(self.TPs) == 1:
self.bad_track = True
def get_quiescent_inds(self):
'''
The quiescent phase, Qs, is the the max phase in each TP,
i.e., closest to 1.
'''
phi = self.get_col('PHI_TP')
self.Qs = np.unique([TP[np.argmax(phi[TP])] for TP in self.TPs])
def get_numeric_data(filename):
'''
made to read all of Paola's tracks. It takes away her "lg" meaning log.
Returns an AGBTracks object. If there is a problem reading the data, all
data are passed as zeros.
'''
f = open(filename, 'r')
lines = f.readlines()
f.close()
line = lines[0]
if len(lines) == 1:
print 'only one line in %s' % filename
return -1
col_keys = line.replace('#', '').replace('lg', '').replace('*', 'star')
col_keys = col_keys.strip().split()
try:
data = np.genfromtxt(filename, missing_values='************',
names=col_keys)
except ValueError:
print 'problem with', filename
data = np.zeros(len(col_keys))
return AGBTracks(data, col_keys, filename)
def make_iso_file(track, isofile):
'''
this only writes the quiescent lines and the first line.
format of this file is:
t_min, age in yr
logl_min, logL
logte_min, logTe
mass_min, actual mass along track
mcore_min, core mass
co_min, C/O ratio
per_min, period in days
ip_min, 1=first overtone, 0=fundamental mode
mlr_min, - mass loss rate in Msun/yr
logtem_min, keep equal to logTe
x_min, X
y_min, Y
xcno_min X_C+X_O+X_N
slope dTe/dL
'''
fmt = '%.4e %.4f %.4f %.5f %.5f %.4f %.4e %i %.4e %.4f %.6e %.6e %.6e %.4f \n'
# cull agb track to quiescent, write out.
rows = [q for q in track.Qs] # cutting the final point for the file.
# I don't know why this is here.
#rows[0] += 1
keys = track.key_dict.keys()
vals = track.key_dict.values()
col_keys = np.array(keys)[np.argsort(vals)]
cno = [key for key in col_keys if (key.startswith('C1') or
key.startswith('N1') or
key.startswith('O1'))]
isofile.write(' %.4f %i # %s \n' % (track.mass, len(rows), track.firstname))
# hack, is the line length killing trilegal?
# isofile.write(' %.4f %i # test \n' % (track.mass, len(rows)))
for r in rows:
row = track.data_array[r]
CNO = np.sum([row[c] for c in cno])
mdot = 10 ** (row['dMdt'])
if row['Pmod'] == 0:
period = row['P0']
else:
period = row['P1']
if r == rows[-1]:
# adding nonsense slope for the final row.
slope = 999
else:
try:
slope = 1. / track.slopes[list(rows).index(r)]
except:
print 'SLOPE ERROR', track.firstname
try:
isofile.write(fmt % (row['ageyr'], row['L_star'], row['T_star'],
row['M_star'], row['M_c'], row['CO'], period,
row['Pmod'], mdot, row['T_star'], row['H'],
row['Y'], CNO, slope))
except IndexError:
print list(rows).index(r)
print len(rows), len(track.slopes)
print 1. / slope[list(rows).index(r)]
return
def get_files(src, search_string):
'''
returns a list of files, similar to ls src/search_string
'''
if not src.endswith('/'):
src += '/'
try:
files = glob.glob1(src, search_string)
except IndexError:
print 'Can''t find %s in %s' % (search_string, src)
sys.exit(2)
files = [os.path.join(src, f) for f in files]
return files
def metallicity_from_dir(met):
''' take Z and Y values from string'''
if met.endswith('/'):
met = met[:-1]
if len(os.path.split(met)) > 0:
met = os.path.split(met)[1]
z = float(met.split('_')[1].replace('Z', ''))
y = float(met.split('_')[-1].replace('Y', ''))
return z, y
def parse_tracks(metal_dir, track_identifier='agb_*Z*.dat',
agb_mix='CAF09', set_name='AGBSET'):
'''
parse colibri agb tracks.
parameters:
metal_dir string
the prefix of the directory with agb tracks, e.g., S12_Z0.0001_Y0.249
track_identifier string
a unix like search string for the agb track, do not set to agbq.
agb_mix string
the agb mix for the file name e.g, CAF09
set_name string
this agb model for the file name e.g., S_NOV13
returns:
writes parsed files to directory ./isotrack_agb
usage:
e.g. parse the tracks of CAF09/S_NOV13/S12_Z0.001_Y0.250:
navigate to CAF09/S_NOV13/
$ python parse_agb_tracks.py CAF09 S_NOV13 S12_Z0.001_Y0.250
'''
# the current directory
working_dir = os.getcwd()
# find the metallicity
metallicity, Y = metallicity_from_dir(metal_dir)
print 'Z = %.4f' % metallicity
# load the list of agb tracks and sort
agb_tracks = get_files(os.path.join(working_dir, metal_dir),
track_identifier)
agb_tracks.sort()
print 'found %i tracks' % len(agb_tracks)
# set up and begin writting the parsed file
name_conv = '%s.dat' % '_'.join(('Z%.4f' % metallicity, agb_mix, set_name))
# make sure we can write to the isotrack_agb directory
ensure_dir(os.path.join(working_dir, 'isotrack_agb/'))
isofile = os.path.join(working_dir, 'isotrack_agb', name_conv)
isofile_header = '# age(yr) logL logTe m_act mcore c/o period ip'
isofile_header += ' Mdot(Msun/yr) logTe X Y CNO dlogTe/dlogL \n'
out = open(isofile, 'w')
out.write(isofile_header)
for agb_track in agb_tracks:
# load track
track = get_numeric_data(agb_track)
# skip bad tracks
if track == -1:
continue
if track.bad_track is True:
continue
# parse the track
make_iso_file(track, out)
out.close()
print 'wrote %s' % isofile
return
def ensure_dir(f):
d = os.path.dirname(f)
if not os.path.isdir(d):
os.makedirs(d)
print 'made dirs: ', d
if __name__ == "__main__":
try:
agb_mix, set_name, metal_dir = sys.argv[1:]
except:
print parse_tracks.__doc__
parse_tracks(metal_dir, agb_mix=agb_mix, set_name=set_name)
| bsd-3-clause |
Fafou/Sick-Beard | lib/guessit/transfo/guess_weak_episodes_rexps.py | 56 | 2126 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# GuessIt - A library for guessing information from filenames
# Copyright (c) 2012 Nicolas Wack <wackou@gmail.com>
#
# GuessIt is free software; you can redistribute it and/or modify it under
# the terms of the Lesser GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# GuessIt 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
# Lesser GNU General Public License for more details.
#
# You should have received a copy of the Lesser GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import unicode_literals
from guessit import Guess
from guessit.transfo import SingleNodeGuesser
from guessit.patterns import weak_episode_rexps
import re
import logging
log = logging.getLogger(__name__)
def guess_weak_episodes_rexps(string, node):
if 'episodeNumber' in node.root.info:
return None, None
for rexp, span_adjust in weak_episode_rexps:
match = re.search(rexp, string, re.IGNORECASE)
if match:
metadata = match.groupdict()
span = (match.start() + span_adjust[0],
match.end() + span_adjust[1])
epnum = int(metadata['episodeNumber'])
if epnum > 100:
season, epnum = epnum // 100, epnum % 100
# episodes which have a season > 25 are most likely errors
# (Simpsons is at 23!)
if season > 25:
continue
return Guess({ 'season': season,
'episodeNumber': epnum },
confidence=0.6), span
else:
return Guess(metadata, confidence=0.3), span
return None, None
guess_weak_episodes_rexps.use_node = True
def process(mtree):
SingleNodeGuesser(guess_weak_episodes_rexps, 0.6, log).process(mtree)
| gpl-3.0 |
jcchin/MagnePlane | src/hyperloop/Python/pod/magnetic_levitation/breakpoint_levitation.py | 4 | 16346 | """
Current Levitation Code
Outputs minimum mass and area of magnets needed for levitation at desired breakpoint velocity.
Outputs Halbach array wavelength, track resistance, and inductance can be used to find
drag force at any velocity using given pod weight.
"""
from math import pi, sin
from openmdao.api import Group, Component, IndepVarComp, Problem, ExecComp, ScipyOptimizer
import numpy as np
class BreakPointDrag(Component):
"""
Current Break Point Drag Calculation very rough. Needs refinement.
Default parameters taken from Inductrack I.
Calculates minimum drag given at set breakpoint velocity desired with given track parameters.
Params
------
m_pod : float
Mass of the hyperloop pod. Default value is 3000.
b_res : float
Residual strength of the Neodynium Magnets. Default value is 1.48.
num_mag_hal : float
Number of Magnets per Halbach Array. Default value is 4
mag_thk : float
Thickness of Magnet. Default value is 0.15.
g : float
Gravitational Acceleration. Default value is 9.81.
l_pod : float
Length of the Hyperloop pod. Default value is 22.
gamma : float
Percent factor used in Area. Default value is 1.
w_mag : float
Width of magnet array. Default value is 3.
spacing : float
Halbach Spacing Factor. Default value is 0.0.
w_strip : float
Width of conductive strip. Default value is .005.
num_sheets : float
Number of laminated sheets. Default value is 1.0.
delta_c : float
Single layer thickness. Default value is .005.
strip_c : float
Center strip spacing. Default value is .0105.
rc : float
Electric resistance. Default value is 1.713*10**-8.
MU0 : float
Permeability of Free Space. Default value is 4*pi*10^-7.
vel_b : float
Breakpoint velocity of the pod. Default value is 23.
h_lev : float
Levitation height. Default value is .01.
d_pod : float
Diameter of the pod. Default value is 1.
track_factor : float
Factor to adjust track width. Default value is .75.
Returns
-------
lam : float
Wavelength of the Halbach Array. Default value is 0.0.
track_res : float
Resistance of the track. Default value is 0.0
track_ind : float
Inductance of the track. Default value is 0.0.
pod_weight : float
Weight of the Pod. Default value is 0.0.
References
-------------
[1] Friend, Paul. Magnetic Levitation Train Technology 1. Thesis.
Bradley University, 2004. N.p.: n.p., n.d. Print.
"""
def __init__(self):
super(BreakPointDrag, self).__init__()
# Pod Inputs
self.add_param('m_pod', val=3000.0, units='kg', desc='Pod Mass')
self.add_param('b_res',
val=1.48,
units='T',
desc='Residual Magnetic Flux')
self.add_param('num_mag_hal',
val=4.0,
desc='Number of Magnets per Halbach Array')
self.add_param('mag_thk', val=0.031416, units='m', desc='Thickness of magnet')
self.add_param('l_pod', val=22.0, units='m', desc='Length of Pod')
self.add_param('gamma', val=0.005502, desc='Percent Factor')
self.add_param('w_mag', val=3.0, units='m', desc='Width of magnet array')
self.add_param('spacing',
val=0.0,
units='m',
desc='Halbach Spacing Factor')
# Track Inputs (laminated track)
self.add_param('d_pod', val=1.0, units='m', desc='Diameter of the Pod')
self.add_param('w_strip',
val=0.005,
units='m',
desc='Width of Conductive Strip')
self.add_param('num_sheets', val=1.0, desc='Number of Laminated Sheets')
self.add_param('delta_c',
val=0.0321,
units='m',
desc='Single Layer Thickness')
self.add_param('strip_c',
val=0.0105,
units='m',
desc='Center Strip Spacing')
self.add_param('rc',
val=1.713 * 10 ** -8,
units='ohm-m',
desc='Electric Resistivity')
self.add_param('MU0',
val=4.0 * pi * 10 ** -7,
units='ohm*s/m',
desc='Permeability of Free Space')
self.add_param('track_factor', val=0.75, desc='Track Width Factor')
# Pod/Track Relation Inputs
self.add_param('vel_b',
val=23.0,
units='m/s',
desc='Desired Breakpoint Velocity')
self.add_param('h_lev', val=0.01, units='m', desc='Levitation Height')
self.add_param('g', val=9.81, units='m/s**2', desc='Gravity')
# Outputs
self.add_output('lam', val=0.0, units='m', desc='Halbach wavelength')
self.add_output('track_ind', val=0.0, units='ohm*s', desc='Inductance')
self.add_output('b0', val=0.0, units='T', desc='Halbach peak strength')
self.add_output('mag_area',
val=0.0,
units='m**2',
desc='Total Area of Magnets')
self.add_output('omegab',
val=0.0,
units='rad/s',
desc='Breakpoint Frequency')
self.add_output('w_track', val=0.0, units='m', desc='Width of the Track')
self.add_output('fyu', val=0.0, units='N', desc='Levitation Force')
self.add_output('fxu', val=0.0, units='N', desc='Break Point Drag Force')
self.add_output('ld_ratio', val=0.0, desc='Lift to Drag Ratio')
self.add_output('track_res', val=0.0, units='ohm', desc='Resistance')
self.add_output('pod_weight', val=0.0, units='N', desc='Weight of Pod')
def solve_nonlinear(self, params, unknowns, resids):
# Pod Parameters
vel_b = params['vel_b'] # Breakpoint Velocity
b_res = params['b_res'] # Magnet Strength
num_mag_hal = params['num_mag_hal'] # Number of Magnets per Wavelength
h_lev = params['h_lev'] # Desired Levitation Height
mag_thk = params['mag_thk'] # Magnet Thickness
gamma = params['gamma'] # Area Scalar
l_pod = params['l_pod'] # Length of the Pod
m_pod = params['m_pod'] # Mass of Pod
d_pod = params['d_pod'] # Diameter of the Pod
w_mag = params['w_mag'] # Width of Magnetic Array
spacing = params['spacing'] # Spacing between each magnet
track_factor = params['track_factor'] # Factor for track width
# Track Parameters
w_strip = params['w_strip'] # Width of Conductive Strip
num_sheets = params['num_sheets'] # Number of Laminated Layers
delta_c = params['delta_c'] # Single Layer Thickness
strip_c = params['strip_c'] # Center Strip Spacing
rc = params['rc'] # Electrical Resistivity of Material
#Constants
MU0 = params['MU0'] # Permeability of Free Space
g = params['g'] # gravity
# Compute Intermediate Variables
w_track = d_pod * track_factor
track_res = rc * w_track / (delta_c * w_strip * num_sheets) # Track Resistance
w_mag = w_track # Set equal for simple model
lam = num_mag_hal * mag_thk + spacing # Compute Wavelength
b0 = b_res * (1. - np.exp(-2. * pi * mag_thk / lam)) * (
(sin(pi / num_mag_hal)) / (pi / num_mag_hal)) # Compute Peak Field Strength
track_ind = MU0 * w_track / (4 * pi * strip_c / lam) # Compute Track Inductance
mag_area = w_mag * l_pod * gamma # Compute Magnet Area
pod_weight = m_pod * g
if vel_b == 0:
omegab = 0
fyu = 0
fxu = 0
ld_ratio = 0
else:
omegab = 2 * pi * vel_b / lam # Compute Induced Frequency
fyu = (b0**2. * w_mag / (4. * pi * track_ind * strip_c / lam)) * (1. / (
1. + (track_res / (omegab * track_ind))**2)) * np.exp(
-4. * pi * h_lev / lam) * mag_area # Compute Lift Force
fxu = (b0**2. * w_mag / (4. * pi * track_ind * strip_c / lam)) * (
(track_res / (omegab * track_ind)) / (1. + (track_res / (omegab * track_ind))**2.)) * np.exp(
-4 * pi * h_lev / lam) * mag_area # Compute Break Point Drag Force
ld_ratio = fyu / fxu # Compute Lift to Drag Ratio
unknowns['lam'] = lam
unknowns['b0'] = b0
unknowns['w_track'] = w_track
unknowns['track_ind'] = track_ind
unknowns['mag_area'] = mag_area
unknowns['omegab'] = omegab
unknowns['fyu'] = fyu
unknowns['fxu'] = fxu
unknowns['ld_ratio'] = ld_ratio
unknowns['track_res'] = track_res
unknowns['pod_weight'] = pod_weight
class MagMass(Component):
"""
Current Magnet Mass Calculation very rough. Needs refinement.
Default parameters taken from Inductrack I.
Calculates minimum magnet mass needed at set breakpoint velocity desired with given track parameters.
Params
------
m_pod : float
Mass of the pod with no magnets. Default value is 3000.0 kg
mag_thk : float
Thickness of Magnet. Default value is 0.15.
rho_mag : float
Density of Magnet. Default value is 7500.
l_pod : float
Length of the Hyperloop pod. Default value is 22.
gamma : float
Percent factor used in Area. Default value is 1.
d_pod : float
Diameter of the pod. Default value is 1.
track_factor : float
Factor to calculate track width. Default value is .75.
w_mag : float
Width of magnet array. Default value is 3.
cost_per_kg : flost
Cost of the magnets per kilogram. Default value is 44.
track_factor : float
Factor to adjust track width. Default value is .75.
Returns
-------
mag_area : float
Total area of the magnetic array. Default value is 0.0
cost : float
Total cost of the magnets. Default value is 0.0.
total_pod_mass : float
Final mass of the pod with magnets. Default value is 0.0.
Notes
-----
[1] Friend, Paul. Magnetic Levitation Train Technology 1. Thesis.
Bradley University, 2004. N.p.: n.p., n.d. Print.
"""
def __init__(self):
super(MagMass, self).__init__()
# Pod Inputs
self.add_param('m_pod', val=30000.0, units='kg', desc='Pod Mass')
self.add_param('mag_thk', val=0.031416, units='m', desc='Thickness of Magnet')
self.add_param('rho_mag',
val=7500.0,
units='kg/m**3',
desc='Density of Magnet')
self.add_param('l_pod', val=22.0, units='m', desc='Length of Pod')
self.add_param('gamma', val=0.027510, desc='Percent Factor')
self.add_param('cost_per_kg',
val=44.0,
units='USD/kg',
desc='Cost of Magnet per Kilogram')
self.add_param('w_mag', val=3.0, units='m', desc='Width of Magnet Array')
self.add_param('d_pod', val=3.0, units='m', desc='Diameter of Pod')
self.add_param('track_factor', val=0.75, desc='Track Factor Width')
# Outputs
self.add_output('mag_area', val=0.0, units='m', desc='Total Area of Magnets')
self.add_output('m_mag', val=0.0, units='kg', desc='Mass of Magnets')
self.add_output('cost', val=0.0, units='USD', desc='Cost of Magnets')
self.add_output('total_pod_mass', val=100.0, units = 'kg', desc = 'Total pod mass')
def solve_nonlinear(self, params, unknowns,
resids): # params, unknowns, residuals
# Parameters
m_pod = params['m_pod']
mag_thk = params['mag_thk'] # Thickness of Magnet
w_mag = params['w_mag'] # Width of Magnet Array
gamma = params['gamma'] # Area Scalar
l_pod = params['l_pod'] # Length of Pod
rho_mag = params['rho_mag'] # Density of Magnets
cost_per_kg = params['cost_per_kg'] # Cost per kg of Magnet
d_pod = params['d_pod'] # Diameter of the pod
track_factor = params['track_factor'] # Track Width Factor
# Compute Intermediate Variables
w_track = d_pod * track_factor # Calculate width of the track
w_mag = w_track # Set equal for simple model
mag_area = w_mag * l_pod * gamma # Compute Magnet Area
m_mag = rho_mag * mag_area * mag_thk # Compute Magnet Mass
cost = m_mag * cost_per_kg # Compute Total Magnet Cost
unknowns['mag_area'] = mag_area
unknowns['m_mag'] = m_mag
unknowns['cost'] = cost
unknowns['total_pod_mass'] = m_mag + m_pod
if __name__ == "__main__":
top = Problem()
root = top.root = Group()
root.add('p', BreakPointDrag())
root.add('q', MagMass())
#Define Parameters
params = (('m_pod', 30000.0, {'units': 'kg'}),
('l_pod', 22.0, {'units': 'm'}),
('d_pod', 2.0, {'units': 'm'}),
('vel_b', 23.0, {'units': 'm/s'}),
('h_lev', 0.01, {'unit': 'm'}),
('mag_thk', .15, {'units': 'm'}),
('gamma', 0.5),
('g', 9.81, {'units': 'm/s**2'}))
top.root.add('input_vars', IndepVarComp(params))
#Constraint Equation
root.add('con1', ExecComp('c1 = (fyu - m_pod * g)/1e5'))
# Connect
root.connect('input_vars.m_pod', ['p.m_pod','q.m_pod'])
root.connect('input_vars.vel_b', 'p.vel_b')
root.connect('input_vars.h_lev', 'p.h_lev')
root.connect('input_vars.g','p.g')
root.connect('input_vars.mag_thk',['q.mag_thk', 'p.mag_thk'])
root.connect('input_vars.gamma',['p.gamma','q.gamma'])
root.connect('input_vars.d_pod', ['p.d_pod','q.d_pod'])
root.connect('p.m_pod', 'con1.m_pod')
root.connect('p.fyu', 'con1.fyu')
root.connect('p.g', 'con1.g')
#Finite Difference
root.deriv_options['type'] = 'fd'
root.fd_options['form'] = 'forward'
root.fd_options['step_size'] = 1.0e-6
#Optimizer Driver
top.driver = ScipyOptimizer()
top.driver.options['optimizer'] = 'COBYLA'
#Design Variables
top.driver.add_desvar('input_vars.mag_thk', lower=.01, upper=.15, scaler=100)
top.driver.add_desvar('input_vars.gamma', lower=0.1, upper=1.0)
#Add Constraint
top.driver.add_constraint('con1.c1', lower=0.0)
#Problem Objective
alpha = .5
root.add('obj_cmp', ExecComp('obj = (alpha*fxu)/1000 + ((1-alpha)*m_mag)'))
root.connect('p.fxu', 'obj_cmp.fxu')
root.connect('q.m_mag', 'obj_cmp.m_mag')
top.driver.add_objective('obj_cmp.obj')
top.setup()
top.run()
# Print Outputs for Debugging
# print('\n')
# print('Lift to BreakPointDrag Ratio is %f' % prob['p.ld_ratio'])
# print('fyu is %f' % prob['p.fyu'])
# print('fxu is %f' % prob['p.fxu'])
# print('c1 is %f' % prob['con1.c1'])
# print('Total Magnet Area is %f m^2' % prob['p.mag_area'])
# print('Total Magnet Weight is %f kg' % prob['q.m_mag'])
# print('Total Magnet Cost is $%f' % prob['q.cost'])
print('mag_thk is %f m' % top['p.mag_thk'])
print('Gamma is %f' % top['p.gamma'])
print('track_res is %f' % top['p.track_res'])
print('track_ind is %.15f' % top['p.track_ind'])
print('lam is %f' % top['p.lam'])
print('pod_weight is %f kg' % top['p.pod_weight'])
print('lift is %f' % top['p.fyu'])
print('\n')
print('m_mag is %f kg' % top['q.m_mag'])
print('mag_area is %f m' % top['q.mag_area'])
print('total_pod_mass is %f kg' % top['q.total_pod_mass'])
print(top['p.m_pod'])
| apache-2.0 |
DalikarFT/CFVOP | venv/Lib/site-packages/pkg_resources/_vendor/pyparsing.py | 417 | 224171 | # module pyparsing.py
#
# Copyright (c) 2003-2016 Paul T. McGuire
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
__doc__ = \
"""
pyparsing module - Classes and methods to define and execute parsing grammars
The pyparsing module is an alternative approach to creating and executing simple grammars,
vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you
don't need to learn a new syntax for defining grammars or matching expressions - the parsing module
provides a library of classes that you use to construct the grammar directly in Python.
Here is a program to parse "Hello, World!" (or any greeting of the form
C{"<salutation>, <addressee>!"}), built up using L{Word}, L{Literal}, and L{And} elements
(L{'+'<ParserElement.__add__>} operator gives L{And} expressions, strings are auto-converted to
L{Literal} expressions)::
from pyparsing import Word, alphas
# define grammar of a greeting
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hello))
The program outputs the following::
Hello, World! -> ['Hello', ',', 'World', '!']
The Python representation of the grammar is quite readable, owing to the self-explanatory
class names, and the use of '+', '|' and '^' operators.
The L{ParseResults} object returned from L{ParserElement.parseString<ParserElement.parseString>} can be accessed as a nested list, a dictionary, or an
object with named attributes.
The pyparsing module handles some of the problems that are typically vexing when writing text parsers:
- extra or missing whitespace (the above program will also handle "Hello,World!", "Hello , World !", etc.)
- quoted strings
- embedded comments
"""
__version__ = "2.1.10"
__versionTime__ = "07 Oct 2016 01:31 UTC"
__author__ = "Paul McGuire <ptmcg@users.sourceforge.net>"
import string
from weakref import ref as wkref
import copy
import sys
import warnings
import re
import sre_constants
import collections
import pprint
import traceback
import types
from datetime import datetime
try:
from _thread import RLock
except ImportError:
from threading import RLock
try:
from collections import OrderedDict as _OrderedDict
except ImportError:
try:
from ordereddict import OrderedDict as _OrderedDict
except ImportError:
_OrderedDict = None
#~ sys.stderr.write( "testing pyparsing module, version %s, %s\n" % (__version__,__versionTime__ ) )
__all__ = [
'And', 'CaselessKeyword', 'CaselessLiteral', 'CharsNotIn', 'Combine', 'Dict', 'Each', 'Empty',
'FollowedBy', 'Forward', 'GoToColumn', 'Group', 'Keyword', 'LineEnd', 'LineStart', 'Literal',
'MatchFirst', 'NoMatch', 'NotAny', 'OneOrMore', 'OnlyOnce', 'Optional', 'Or',
'ParseBaseException', 'ParseElementEnhance', 'ParseException', 'ParseExpression', 'ParseFatalException',
'ParseResults', 'ParseSyntaxException', 'ParserElement', 'QuotedString', 'RecursiveGrammarException',
'Regex', 'SkipTo', 'StringEnd', 'StringStart', 'Suppress', 'Token', 'TokenConverter',
'White', 'Word', 'WordEnd', 'WordStart', 'ZeroOrMore',
'alphanums', 'alphas', 'alphas8bit', 'anyCloseTag', 'anyOpenTag', 'cStyleComment', 'col',
'commaSeparatedList', 'commonHTMLEntity', 'countedArray', 'cppStyleComment', 'dblQuotedString',
'dblSlashComment', 'delimitedList', 'dictOf', 'downcaseTokens', 'empty', 'hexnums',
'htmlComment', 'javaStyleComment', 'line', 'lineEnd', 'lineStart', 'lineno',
'makeHTMLTags', 'makeXMLTags', 'matchOnlyAtCol', 'matchPreviousExpr', 'matchPreviousLiteral',
'nestedExpr', 'nullDebugAction', 'nums', 'oneOf', 'opAssoc', 'operatorPrecedence', 'printables',
'punc8bit', 'pythonStyleComment', 'quotedString', 'removeQuotes', 'replaceHTMLEntity',
'replaceWith', 'restOfLine', 'sglQuotedString', 'srange', 'stringEnd',
'stringStart', 'traceParseAction', 'unicodeString', 'upcaseTokens', 'withAttribute',
'indentedBlock', 'originalTextFor', 'ungroup', 'infixNotation','locatedExpr', 'withClass',
'CloseMatch', 'tokenMap', 'pyparsing_common',
]
system_version = tuple(sys.version_info)[:3]
PY_3 = system_version[0] == 3
if PY_3:
_MAX_INT = sys.maxsize
basestring = str
unichr = chr
_ustr = str
# build list of single arg builtins, that can be used as parse actions
singleArgBuiltins = [sum, len, sorted, reversed, list, tuple, set, any, all, min, max]
else:
_MAX_INT = sys.maxint
range = xrange
def _ustr(obj):
"""Drop-in replacement for str(obj) that tries to be Unicode friendly. It first tries
str(obj). If that fails with a UnicodeEncodeError, then it tries unicode(obj). It
then < returns the unicode object | encodes it with the default encoding | ... >.
"""
if isinstance(obj,unicode):
return obj
try:
# If this works, then _ustr(obj) has the same behaviour as str(obj), so
# it won't break any existing code.
return str(obj)
except UnicodeEncodeError:
# Else encode it
ret = unicode(obj).encode(sys.getdefaultencoding(), 'xmlcharrefreplace')
xmlcharref = Regex('&#\d+;')
xmlcharref.setParseAction(lambda t: '\\u' + hex(int(t[0][2:-1]))[2:])
return xmlcharref.transformString(ret)
# build list of single arg builtins, tolerant of Python version, that can be used as parse actions
singleArgBuiltins = []
import __builtin__
for fname in "sum len sorted reversed list tuple set any all min max".split():
try:
singleArgBuiltins.append(getattr(__builtin__,fname))
except AttributeError:
continue
_generatorType = type((y for y in range(1)))
def _xml_escape(data):
"""Escape &, <, >, ", ', etc. in a string of data."""
# ampersand must be replaced first
from_symbols = '&><"\''
to_symbols = ('&'+s+';' for s in "amp gt lt quot apos".split())
for from_,to_ in zip(from_symbols, to_symbols):
data = data.replace(from_, to_)
return data
class _Constants(object):
pass
alphas = string.ascii_uppercase + string.ascii_lowercase
nums = "0123456789"
hexnums = nums + "ABCDEFabcdef"
alphanums = alphas + nums
_bslash = chr(92)
printables = "".join(c for c in string.printable if c not in string.whitespace)
class ParseBaseException(Exception):
"""base exception class for all parsing runtime exceptions"""
# Performance tuning: we construct a *lot* of these, so keep this
# constructor as small and fast as possible
def __init__( self, pstr, loc=0, msg=None, elem=None ):
self.loc = loc
if msg is None:
self.msg = pstr
self.pstr = ""
else:
self.msg = msg
self.pstr = pstr
self.parserElement = elem
self.args = (pstr, loc, msg)
@classmethod
def _from_exception(cls, pe):
"""
internal factory method to simplify creating one type of ParseException
from another - avoids having __init__ signature conflicts among subclasses
"""
return cls(pe.pstr, pe.loc, pe.msg, pe.parserElement)
def __getattr__( self, aname ):
"""supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
"""
if( aname == "lineno" ):
return lineno( self.loc, self.pstr )
elif( aname in ("col", "column") ):
return col( self.loc, self.pstr )
elif( aname == "line" ):
return line( self.loc, self.pstr )
else:
raise AttributeError(aname)
def __str__( self ):
return "%s (at char %d), (line:%d, col:%d)" % \
( self.msg, self.loc, self.lineno, self.column )
def __repr__( self ):
return _ustr(self)
def markInputline( self, markerString = ">!<" ):
"""Extracts the exception line from the input string, and marks
the location of the exception with a special symbol.
"""
line_str = self.line
line_column = self.column - 1
if markerString:
line_str = "".join((line_str[:line_column],
markerString, line_str[line_column:]))
return line_str.strip()
def __dir__(self):
return "lineno col line".split() + dir(type(self))
class ParseException(ParseBaseException):
"""
Exception thrown when parse expressions don't match class;
supported attributes by name are:
- lineno - returns the line number of the exception text
- col - returns the column number of the exception text
- line - returns the line containing the exception text
Example::
try:
Word(nums).setName("integer").parseString("ABC")
except ParseException as pe:
print(pe)
print("column: {}".format(pe.col))
prints::
Expected integer (at char 0), (line:1, col:1)
column: 1
"""
pass
class ParseFatalException(ParseBaseException):
"""user-throwable exception thrown when inconsistent parse content
is found; stops all parsing immediately"""
pass
class ParseSyntaxException(ParseFatalException):
"""just like L{ParseFatalException}, but thrown internally when an
L{ErrorStop<And._ErrorStop>} ('-' operator) indicates that parsing is to stop
immediately because an unbacktrackable syntax error has been found"""
pass
#~ class ReparseException(ParseBaseException):
#~ """Experimental class - parse actions can raise this exception to cause
#~ pyparsing to reparse the input string:
#~ - with a modified input string, and/or
#~ - with a modified start location
#~ Set the values of the ReparseException in the constructor, and raise the
#~ exception in a parse action to cause pyparsing to use the new string/location.
#~ Setting the values as None causes no change to be made.
#~ """
#~ def __init_( self, newstring, restartLoc ):
#~ self.newParseText = newstring
#~ self.reparseLoc = restartLoc
class RecursiveGrammarException(Exception):
"""exception thrown by L{ParserElement.validate} if the grammar could be improperly recursive"""
def __init__( self, parseElementList ):
self.parseElementTrace = parseElementList
def __str__( self ):
return "RecursiveGrammarException: %s" % self.parseElementTrace
class _ParseResultsWithOffset(object):
def __init__(self,p1,p2):
self.tup = (p1,p2)
def __getitem__(self,i):
return self.tup[i]
def __repr__(self):
return repr(self.tup[0])
def setOffset(self,i):
self.tup = (self.tup[0],i)
class ParseResults(object):
"""
Structured parse results, to provide multiple means of access to the parsed data:
- as a list (C{len(results)})
- by list index (C{results[0], results[1]}, etc.)
- by attribute (C{results.<resultsName>} - see L{ParserElement.setResultsName})
Example::
integer = Word(nums)
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
# date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
# parseString returns a ParseResults object
result = date_str.parseString("1999/12/31")
def test(s, fn=repr):
print("%s -> %s" % (s, fn(eval(s))))
test("list(result)")
test("result[0]")
test("result['month']")
test("result.day")
test("'month' in result")
test("'minutes' in result")
test("result.dump()", str)
prints::
list(result) -> ['1999', '/', '12', '/', '31']
result[0] -> '1999'
result['month'] -> '12'
result.day -> '31'
'month' in result -> True
'minutes' in result -> False
result.dump() -> ['1999', '/', '12', '/', '31']
- day: 31
- month: 12
- year: 1999
"""
def __new__(cls, toklist=None, name=None, asList=True, modal=True ):
if isinstance(toklist, cls):
return toklist
retobj = object.__new__(cls)
retobj.__doinit = True
return retobj
# Performance tuning: we construct a *lot* of these, so keep this
# constructor as small and fast as possible
def __init__( self, toklist=None, name=None, asList=True, modal=True, isinstance=isinstance ):
if self.__doinit:
self.__doinit = False
self.__name = None
self.__parent = None
self.__accumNames = {}
self.__asList = asList
self.__modal = modal
if toklist is None:
toklist = []
if isinstance(toklist, list):
self.__toklist = toklist[:]
elif isinstance(toklist, _generatorType):
self.__toklist = list(toklist)
else:
self.__toklist = [toklist]
self.__tokdict = dict()
if name is not None and name:
if not modal:
self.__accumNames[name] = 0
if isinstance(name,int):
name = _ustr(name) # will always return a str, but use _ustr for consistency
self.__name = name
if not (isinstance(toklist, (type(None), basestring, list)) and toklist in (None,'',[])):
if isinstance(toklist,basestring):
toklist = [ toklist ]
if asList:
if isinstance(toklist,ParseResults):
self[name] = _ParseResultsWithOffset(toklist.copy(),0)
else:
self[name] = _ParseResultsWithOffset(ParseResults(toklist[0]),0)
self[name].__name = name
else:
try:
self[name] = toklist[0]
except (KeyError,TypeError,IndexError):
self[name] = toklist
def __getitem__( self, i ):
if isinstance( i, (int,slice) ):
return self.__toklist[i]
else:
if i not in self.__accumNames:
return self.__tokdict[i][-1][0]
else:
return ParseResults([ v[0] for v in self.__tokdict[i] ])
def __setitem__( self, k, v, isinstance=isinstance ):
if isinstance(v,_ParseResultsWithOffset):
self.__tokdict[k] = self.__tokdict.get(k,list()) + [v]
sub = v[0]
elif isinstance(k,(int,slice)):
self.__toklist[k] = v
sub = v
else:
self.__tokdict[k] = self.__tokdict.get(k,list()) + [_ParseResultsWithOffset(v,0)]
sub = v
if isinstance(sub,ParseResults):
sub.__parent = wkref(self)
def __delitem__( self, i ):
if isinstance(i,(int,slice)):
mylen = len( self.__toklist )
del self.__toklist[i]
# convert int to slice
if isinstance(i, int):
if i < 0:
i += mylen
i = slice(i, i+1)
# get removed indices
removed = list(range(*i.indices(mylen)))
removed.reverse()
# fixup indices in token dictionary
for name,occurrences in self.__tokdict.items():
for j in removed:
for k, (value, position) in enumerate(occurrences):
occurrences[k] = _ParseResultsWithOffset(value, position - (position > j))
else:
del self.__tokdict[i]
def __contains__( self, k ):
return k in self.__tokdict
def __len__( self ): return len( self.__toklist )
def __bool__(self): return ( not not self.__toklist )
__nonzero__ = __bool__
def __iter__( self ): return iter( self.__toklist )
def __reversed__( self ): return iter( self.__toklist[::-1] )
def _iterkeys( self ):
if hasattr(self.__tokdict, "iterkeys"):
return self.__tokdict.iterkeys()
else:
return iter(self.__tokdict)
def _itervalues( self ):
return (self[k] for k in self._iterkeys())
def _iteritems( self ):
return ((k, self[k]) for k in self._iterkeys())
if PY_3:
keys = _iterkeys
"""Returns an iterator of all named result keys (Python 3.x only)."""
values = _itervalues
"""Returns an iterator of all named result values (Python 3.x only)."""
items = _iteritems
"""Returns an iterator of all named result key-value tuples (Python 3.x only)."""
else:
iterkeys = _iterkeys
"""Returns an iterator of all named result keys (Python 2.x only)."""
itervalues = _itervalues
"""Returns an iterator of all named result values (Python 2.x only)."""
iteritems = _iteritems
"""Returns an iterator of all named result key-value tuples (Python 2.x only)."""
def keys( self ):
"""Returns all named result keys (as a list in Python 2.x, as an iterator in Python 3.x)."""
return list(self.iterkeys())
def values( self ):
"""Returns all named result values (as a list in Python 2.x, as an iterator in Python 3.x)."""
return list(self.itervalues())
def items( self ):
"""Returns all named result key-values (as a list of tuples in Python 2.x, as an iterator in Python 3.x)."""
return list(self.iteritems())
def haskeys( self ):
"""Since keys() returns an iterator, this method is helpful in bypassing
code that looks for the existence of any defined results names."""
return bool(self.__tokdict)
def pop( self, *args, **kwargs):
"""
Removes and returns item at specified index (default=C{last}).
Supports both C{list} and C{dict} semantics for C{pop()}. If passed no
argument or an integer argument, it will use C{list} semantics
and pop tokens from the list of parsed tokens. If passed a
non-integer argument (most likely a string), it will use C{dict}
semantics and pop the corresponding value from any defined
results names. A second default return value argument is
supported, just as in C{dict.pop()}.
Example::
def remove_first(tokens):
tokens.pop(0)
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
print(OneOrMore(Word(nums)).addParseAction(remove_first).parseString("0 123 321")) # -> ['123', '321']
label = Word(alphas)
patt = label("LABEL") + OneOrMore(Word(nums))
print(patt.parseString("AAB 123 321").dump())
# Use pop() in a parse action to remove named result (note that corresponding value is not
# removed from list form of results)
def remove_LABEL(tokens):
tokens.pop("LABEL")
return tokens
patt.addParseAction(remove_LABEL)
print(patt.parseString("AAB 123 321").dump())
prints::
['AAB', '123', '321']
- LABEL: AAB
['AAB', '123', '321']
"""
if not args:
args = [-1]
for k,v in kwargs.items():
if k == 'default':
args = (args[0], v)
else:
raise TypeError("pop() got an unexpected keyword argument '%s'" % k)
if (isinstance(args[0], int) or
len(args) == 1 or
args[0] in self):
index = args[0]
ret = self[index]
del self[index]
return ret
else:
defaultvalue = args[1]
return defaultvalue
def get(self, key, defaultValue=None):
"""
Returns named result matching the given key, or if there is no
such name, then returns the given C{defaultValue} or C{None} if no
C{defaultValue} is specified.
Similar to C{dict.get()}.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString("1999/12/31")
print(result.get("year")) # -> '1999'
print(result.get("hour", "not specified")) # -> 'not specified'
print(result.get("hour")) # -> None
"""
if key in self:
return self[key]
else:
return defaultValue
def insert( self, index, insStr ):
"""
Inserts new element at location index in the list of parsed tokens.
Similar to C{list.insert()}.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to insert the parse location in the front of the parsed results
def insert_locn(locn, tokens):
tokens.insert(0, locn)
print(OneOrMore(Word(nums)).addParseAction(insert_locn).parseString("0 123 321")) # -> [0, '0', '123', '321']
"""
self.__toklist.insert(index, insStr)
# fixup indices in token dictionary
for name,occurrences in self.__tokdict.items():
for k, (value, position) in enumerate(occurrences):
occurrences[k] = _ParseResultsWithOffset(value, position + (position > index))
def append( self, item ):
"""
Add single element to end of ParseResults list of elements.
Example::
print(OneOrMore(Word(nums)).parseString("0 123 321")) # -> ['0', '123', '321']
# use a parse action to compute the sum of the parsed integers, and add it to the end
def append_sum(tokens):
tokens.append(sum(map(int, tokens)))
print(OneOrMore(Word(nums)).addParseAction(append_sum).parseString("0 123 321")) # -> ['0', '123', '321', 444]
"""
self.__toklist.append(item)
def extend( self, itemseq ):
"""
Add sequence of elements to end of ParseResults list of elements.
Example::
patt = OneOrMore(Word(alphas))
# use a parse action to append the reverse of the matched strings, to make a palindrome
def make_palindrome(tokens):
tokens.extend(reversed([t[::-1] for t in tokens]))
return ''.join(tokens)
print(patt.addParseAction(make_palindrome).parseString("lskdj sdlkjf lksd")) # -> 'lskdjsdlkjflksddsklfjkldsjdksl'
"""
if isinstance(itemseq, ParseResults):
self += itemseq
else:
self.__toklist.extend(itemseq)
def clear( self ):
"""
Clear all elements and results names.
"""
del self.__toklist[:]
self.__tokdict.clear()
def __getattr__( self, name ):
try:
return self[name]
except KeyError:
return ""
if name in self.__tokdict:
if name not in self.__accumNames:
return self.__tokdict[name][-1][0]
else:
return ParseResults([ v[0] for v in self.__tokdict[name] ])
else:
return ""
def __add__( self, other ):
ret = self.copy()
ret += other
return ret
def __iadd__( self, other ):
if other.__tokdict:
offset = len(self.__toklist)
addoffset = lambda a: offset if a<0 else a+offset
otheritems = other.__tokdict.items()
otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) )
for (k,vlist) in otheritems for v in vlist]
for k,v in otherdictitems:
self[k] = v
if isinstance(v[0],ParseResults):
v[0].__parent = wkref(self)
self.__toklist += other.__toklist
self.__accumNames.update( other.__accumNames )
return self
def __radd__(self, other):
if isinstance(other,int) and other == 0:
# useful for merging many ParseResults using sum() builtin
return self.copy()
else:
# this may raise a TypeError - so be it
return other + self
def __repr__( self ):
return "(%s, %s)" % ( repr( self.__toklist ), repr( self.__tokdict ) )
def __str__( self ):
return '[' + ', '.join(_ustr(i) if isinstance(i, ParseResults) else repr(i) for i in self.__toklist) + ']'
def _asStringList( self, sep='' ):
out = []
for item in self.__toklist:
if out and sep:
out.append(sep)
if isinstance( item, ParseResults ):
out += item._asStringList()
else:
out.append( _ustr(item) )
return out
def asList( self ):
"""
Returns the parse results as a nested list of matching tokens, all converted to strings.
Example::
patt = OneOrMore(Word(alphas))
result = patt.parseString("sldkj lsdkj sldkj")
# even though the result prints in string-like form, it is actually a pyparsing ParseResults
print(type(result), result) # -> <class 'pyparsing.ParseResults'> ['sldkj', 'lsdkj', 'sldkj']
# Use asList() to create an actual list
result_list = result.asList()
print(type(result_list), result_list) # -> <class 'list'> ['sldkj', 'lsdkj', 'sldkj']
"""
return [res.asList() if isinstance(res,ParseResults) else res for res in self.__toklist]
def asDict( self ):
"""
Returns the named parse results as a nested dictionary.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(type(result), repr(result)) # -> <class 'pyparsing.ParseResults'> (['12', '/', '31', '/', '1999'], {'day': [('1999', 4)], 'year': [('12', 0)], 'month': [('31', 2)]})
result_dict = result.asDict()
print(type(result_dict), repr(result_dict)) # -> <class 'dict'> {'day': '1999', 'year': '12', 'month': '31'}
# even though a ParseResults supports dict-like access, sometime you just need to have a dict
import json
print(json.dumps(result)) # -> Exception: TypeError: ... is not JSON serializable
print(json.dumps(result.asDict())) # -> {"month": "31", "day": "1999", "year": "12"}
"""
if PY_3:
item_fn = self.items
else:
item_fn = self.iteritems
def toItem(obj):
if isinstance(obj, ParseResults):
if obj.haskeys():
return obj.asDict()
else:
return [toItem(v) for v in obj]
else:
return obj
return dict((k,toItem(v)) for k,v in item_fn())
def copy( self ):
"""
Returns a new copy of a C{ParseResults} object.
"""
ret = ParseResults( self.__toklist )
ret.__tokdict = self.__tokdict.copy()
ret.__parent = self.__parent
ret.__accumNames.update( self.__accumNames )
ret.__name = self.__name
return ret
def asXML( self, doctag=None, namedItemsOnly=False, indent="", formatted=True ):
"""
(Deprecated) Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.
"""
nl = "\n"
out = []
namedItems = dict((v[1],k) for (k,vlist) in self.__tokdict.items()
for v in vlist)
nextLevelIndent = indent + " "
# collapse out indents if formatting is not desired
if not formatted:
indent = ""
nextLevelIndent = ""
nl = ""
selfTag = None
if doctag is not None:
selfTag = doctag
else:
if self.__name:
selfTag = self.__name
if not selfTag:
if namedItemsOnly:
return ""
else:
selfTag = "ITEM"
out += [ nl, indent, "<", selfTag, ">" ]
for i,res in enumerate(self.__toklist):
if isinstance(res,ParseResults):
if i in namedItems:
out += [ res.asXML(namedItems[i],
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
out += [ res.asXML(None,
namedItemsOnly and doctag is None,
nextLevelIndent,
formatted)]
else:
# individual token, see if there is a name for it
resTag = None
if i in namedItems:
resTag = namedItems[i]
if not resTag:
if namedItemsOnly:
continue
else:
resTag = "ITEM"
xmlBodyText = _xml_escape(_ustr(res))
out += [ nl, nextLevelIndent, "<", resTag, ">",
xmlBodyText,
"</", resTag, ">" ]
out += [ nl, indent, "</", selfTag, ">" ]
return "".join(out)
def __lookup(self,sub):
for k,vlist in self.__tokdict.items():
for v,loc in vlist:
if sub is v:
return k
return None
def getName(self):
"""
Returns the results name for this token expression. Useful when several
different expressions might match at a particular location.
Example::
integer = Word(nums)
ssn_expr = Regex(r"\d\d\d-\d\d-\d\d\d\d")
house_number_expr = Suppress('#') + Word(nums, alphanums)
user_data = (Group(house_number_expr)("house_number")
| Group(ssn_expr)("ssn")
| Group(integer)("age"))
user_info = OneOrMore(user_data)
result = user_info.parseString("22 111-22-3333 #221B")
for item in result:
print(item.getName(), ':', item[0])
prints::
age : 22
ssn : 111-22-3333
house_number : 221B
"""
if self.__name:
return self.__name
elif self.__parent:
par = self.__parent()
if par:
return par.__lookup(self)
else:
return None
elif (len(self) == 1 and
len(self.__tokdict) == 1 and
next(iter(self.__tokdict.values()))[0][1] in (0,-1)):
return next(iter(self.__tokdict.keys()))
else:
return None
def dump(self, indent='', depth=0, full=True):
"""
Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data.
Example::
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
result = date_str.parseString('12/31/1999')
print(result.dump())
prints::
['12', '/', '31', '/', '1999']
- day: 1999
- month: 31
- year: 12
"""
out = []
NL = '\n'
out.append( indent+_ustr(self.asList()) )
if full:
if self.haskeys():
items = sorted((str(k), v) for k,v in self.items())
for k,v in items:
if out:
out.append(NL)
out.append( "%s%s- %s: " % (indent,(' '*depth), k) )
if isinstance(v,ParseResults):
if v:
out.append( v.dump(indent,depth+1) )
else:
out.append(_ustr(v))
else:
out.append(repr(v))
elif any(isinstance(vv,ParseResults) for vv in self):
v = self
for i,vv in enumerate(v):
if isinstance(vv,ParseResults):
out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),vv.dump(indent,depth+1) ))
else:
out.append("\n%s%s[%d]:\n%s%s%s" % (indent,(' '*(depth)),i,indent,(' '*(depth+1)),_ustr(vv)))
return "".join(out)
def pprint(self, *args, **kwargs):
"""
Pretty-printer for parsed results as a list, using the C{pprint} module.
Accepts additional positional or keyword args as defined for the
C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})
Example::
ident = Word(alphas, alphanums)
num = Word(nums)
func = Forward()
term = ident | num | Group('(' + func + ')')
func <<= ident + Group(Optional(delimitedList(term)))
result = func.parseString("fna a,b,(fnb c,d,200),100")
result.pprint(width=40)
prints::
['fna',
['a',
'b',
['(', 'fnb', ['c', 'd', '200'], ')'],
'100']]
"""
pprint.pprint(self.asList(), *args, **kwargs)
# add support for pickle protocol
def __getstate__(self):
return ( self.__toklist,
( self.__tokdict.copy(),
self.__parent is not None and self.__parent() or None,
self.__accumNames,
self.__name ) )
def __setstate__(self,state):
self.__toklist = state[0]
(self.__tokdict,
par,
inAccumNames,
self.__name) = state[1]
self.__accumNames = {}
self.__accumNames.update(inAccumNames)
if par is not None:
self.__parent = wkref(par)
else:
self.__parent = None
def __getnewargs__(self):
return self.__toklist, self.__name, self.__asList, self.__modal
def __dir__(self):
return (dir(type(self)) + list(self.keys()))
collections.MutableMapping.register(ParseResults)
def col (loc,strg):
"""Returns current column within a string, counting newlines as line separators.
The first column is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
s = strg
return 1 if 0<loc<len(s) and s[loc-1] == '\n' else loc - s.rfind("\n", 0, loc)
def lineno(loc,strg):
"""Returns current line number within a string, counting newlines as line separators.
The first line is number 1.
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{ParserElement.parseString}<ParserElement.parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
"""
return strg.count("\n",0,loc) + 1
def line( loc, strg ):
"""Returns the line of text containing loc within a string, counting newlines as line separators.
"""
lastCR = strg.rfind("\n", 0, loc)
nextCR = strg.find("\n", loc)
if nextCR >= 0:
return strg[lastCR+1:nextCR]
else:
return strg[lastCR+1:]
def _defaultStartDebugAction( instring, loc, expr ):
print (("Match " + _ustr(expr) + " at loc " + _ustr(loc) + "(%d,%d)" % ( lineno(loc,instring), col(loc,instring) )))
def _defaultSuccessDebugAction( instring, startloc, endloc, expr, toks ):
print ("Matched " + _ustr(expr) + " -> " + str(toks.asList()))
def _defaultExceptionDebugAction( instring, loc, expr, exc ):
print ("Exception raised:" + _ustr(exc))
def nullDebugAction(*args):
"""'Do-nothing' debug action, to suppress debugging output during parsing."""
pass
# Only works on Python 3.x - nonlocal is toxic to Python 2 installs
#~ 'decorator to trim function calls to match the arity of the target'
#~ def _trim_arity(func, maxargs=3):
#~ if func in singleArgBuiltins:
#~ return lambda s,l,t: func(t)
#~ limit = 0
#~ foundArity = False
#~ def wrapper(*args):
#~ nonlocal limit,foundArity
#~ while 1:
#~ try:
#~ ret = func(*args[limit:])
#~ foundArity = True
#~ return ret
#~ except TypeError:
#~ if limit == maxargs or foundArity:
#~ raise
#~ limit += 1
#~ continue
#~ return wrapper
# this version is Python 2.x-3.x cross-compatible
'decorator to trim function calls to match the arity of the target'
def _trim_arity(func, maxargs=2):
if func in singleArgBuiltins:
return lambda s,l,t: func(t)
limit = [0]
foundArity = [False]
# traceback return data structure changed in Py3.5 - normalize back to plain tuples
if system_version[:2] >= (3,5):
def extract_stack(limit=0):
# special handling for Python 3.5.0 - extra deep call stack by 1
offset = -3 if system_version == (3,5,0) else -2
frame_summary = traceback.extract_stack(limit=-offset+limit-1)[offset]
return [(frame_summary.filename, frame_summary.lineno)]
def extract_tb(tb, limit=0):
frames = traceback.extract_tb(tb, limit=limit)
frame_summary = frames[-1]
return [(frame_summary.filename, frame_summary.lineno)]
else:
extract_stack = traceback.extract_stack
extract_tb = traceback.extract_tb
# synthesize what would be returned by traceback.extract_stack at the call to
# user's parse action 'func', so that we don't incur call penalty at parse time
LINE_DIFF = 6
# IF ANY CODE CHANGES, EVEN JUST COMMENTS OR BLANK LINES, BETWEEN THE NEXT LINE AND
# THE CALL TO FUNC INSIDE WRAPPER, LINE_DIFF MUST BE MODIFIED!!!!
this_line = extract_stack(limit=2)[-1]
pa_call_line_synth = (this_line[0], this_line[1]+LINE_DIFF)
def wrapper(*args):
while 1:
try:
ret = func(*args[limit[0]:])
foundArity[0] = True
return ret
except TypeError:
# re-raise TypeErrors if they did not come from our arity testing
if foundArity[0]:
raise
else:
try:
tb = sys.exc_info()[-1]
if not extract_tb(tb, limit=2)[-1][:2] == pa_call_line_synth:
raise
finally:
del tb
if limit[0] <= maxargs:
limit[0] += 1
continue
raise
# copy func name to wrapper for sensible debug output
func_name = "<parse action>"
try:
func_name = getattr(func, '__name__',
getattr(func, '__class__').__name__)
except Exception:
func_name = str(func)
wrapper.__name__ = func_name
return wrapper
class ParserElement(object):
"""Abstract base level parser element class."""
DEFAULT_WHITE_CHARS = " \n\t\r"
verbose_stacktrace = False
@staticmethod
def setDefaultWhitespaceChars( chars ):
r"""
Overrides the default whitespace chars
Example::
# default whitespace chars are space, <TAB> and newline
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def', 'ghi', 'jkl']
# change to just treat newline as significant
ParserElement.setDefaultWhitespaceChars(" \t")
OneOrMore(Word(alphas)).parseString("abc def\nghi jkl") # -> ['abc', 'def']
"""
ParserElement.DEFAULT_WHITE_CHARS = chars
@staticmethod
def inlineLiteralsUsing(cls):
"""
Set class to be used for inclusion of string literals into a parser.
Example::
# default literal class used is Literal
integer = Word(nums)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# change to Suppress
ParserElement.inlineLiteralsUsing(Suppress)
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
date_str.parseString("1999/12/31") # -> ['1999', '12', '31']
"""
ParserElement._literalStringClass = cls
def __init__( self, savelist=False ):
self.parseAction = list()
self.failAction = None
#~ self.name = "<unknown>" # don't define self.name, let subclasses try/except upcall
self.strRepr = None
self.resultsName = None
self.saveAsList = savelist
self.skipWhitespace = True
self.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
self.copyDefaultWhiteChars = True
self.mayReturnEmpty = False # used when checking for left-recursion
self.keepTabs = False
self.ignoreExprs = list()
self.debug = False
self.streamlined = False
self.mayIndexError = True # used to optimize exception handling for subclasses that don't advance parse index
self.errmsg = ""
self.modalResults = True # used to mark results names as modal (report only last) or cumulative (list all)
self.debugActions = ( None, None, None ) #custom debug actions
self.re = None
self.callPreparse = True # used to avoid redundant calls to preParse
self.callDuringTry = False
def copy( self ):
"""
Make a copy of this C{ParserElement}. Useful for defining different parse actions
for the same parsing pattern, using copies of the original parse element.
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
integerK = integer.copy().addParseAction(lambda toks: toks[0]*1024) + Suppress("K")
integerM = integer.copy().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
print(OneOrMore(integerK | integerM | integer).parseString("5K 100 640K 256M"))
prints::
[5120, 100, 655360, 268435456]
Equivalent form of C{expr.copy()} is just C{expr()}::
integerM = integer().addParseAction(lambda toks: toks[0]*1024*1024) + Suppress("M")
"""
cpy = copy.copy( self )
cpy.parseAction = self.parseAction[:]
cpy.ignoreExprs = self.ignoreExprs[:]
if self.copyDefaultWhiteChars:
cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS
return cpy
def setName( self, name ):
"""
Define name for this expression, makes debugging and exception messages clearer.
Example::
Word(nums).parseString("ABC") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)
Word(nums).setName("integer").parseString("ABC") # -> Exception: Expected integer (at char 0), (line:1, col:1)
"""
self.name = name
self.errmsg = "Expected " + self.name
if hasattr(self,"exception"):
self.exception.msg = self.errmsg
return self
def setResultsName( self, name, listAllMatches=False ):
"""
Define name for referencing matching tokens as a nested attribute
of the returned parse results.
NOTE: this returns a *copy* of the original C{ParserElement} object;
this is so that the client can define a basic element, such as an
integer, and reference it in multiple places with different names.
You can also set results names using the abbreviated syntax,
C{expr("name")} in place of C{expr.setResultsName("name")} -
see L{I{__call__}<__call__>}.
Example::
date_str = (integer.setResultsName("year") + '/'
+ integer.setResultsName("month") + '/'
+ integer.setResultsName("day"))
# equivalent form:
date_str = integer("year") + '/' + integer("month") + '/' + integer("day")
"""
newself = self.copy()
if name.endswith("*"):
name = name[:-1]
listAllMatches=True
newself.resultsName = name
newself.modalResults = not listAllMatches
return newself
def setBreak(self,breakFlag = True):
"""Method to invoke the Python pdb debugger when this element is
about to be parsed. Set C{breakFlag} to True to enable, False to
disable.
"""
if breakFlag:
_parseMethod = self._parse
def breaker(instring, loc, doActions=True, callPreParse=True):
import pdb
pdb.set_trace()
return _parseMethod( instring, loc, doActions, callPreParse )
breaker._originalParseMethod = _parseMethod
self._parse = breaker
else:
if hasattr(self._parse,"_originalParseMethod"):
self._parse = self._parse._originalParseMethod
return self
def setParseAction( self, *fns, **kwargs ):
"""
Define action to perform when successfully matching parse element definition.
Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)},
C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where:
- s = the original string being parsed (see note below)
- loc = the location of the matching substring
- toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object
If the functions in fns modify the tokens, they can return them as the return
value from fn, and the modified list of tokens will replace the original.
Otherwise, fn does not need to return any value.
Optional keyword arguments:
- callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing
Note: the default parsing behavior is to expand tabs in the input string
before starting the parsing process. See L{I{parseString}<parseString>} for more information
on parsing strings containing C{<TAB>}s, and suggested methods to maintain a
consistent view of the parsed string, the parse location, and line and column
positions within the parsed string.
Example::
integer = Word(nums)
date_str = integer + '/' + integer + '/' + integer
date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31']
# use parse action to convert to ints at parse time
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
date_str = integer + '/' + integer + '/' + integer
# note that integer fields are now ints, not strings
date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
"""
self.parseAction = list(map(_trim_arity, list(fns)))
self.callDuringTry = kwargs.get("callDuringTry", False)
return self
def addParseAction( self, *fns, **kwargs ):
"""
Add parse action to expression's list of parse actions. See L{I{setParseAction}<setParseAction>}.
See examples in L{I{copy}<copy>}.
"""
self.parseAction += list(map(_trim_arity, list(fns)))
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
return self
def addCondition(self, *fns, **kwargs):
"""Add a boolean predicate function to expression's list of parse actions. See
L{I{setParseAction}<setParseAction>} for function call signatures. Unlike C{setParseAction},
functions passed to C{addCondition} need to return boolean success/fail of the condition.
Optional keyword arguments:
- message = define a custom message to be used in the raised exception
- fatal = if True, will raise ParseFatalException to stop parsing immediately; otherwise will raise ParseException
Example::
integer = Word(nums).setParseAction(lambda toks: int(toks[0]))
year_int = integer.copy()
year_int.addCondition(lambda toks: toks[0] >= 2000, message="Only support years 2000 and later")
date_str = year_int + '/' + integer + '/' + integer
result = date_str.parseString("1999/12/31") # -> Exception: Only support years 2000 and later (at char 0), (line:1, col:1)
"""
msg = kwargs.get("message", "failed user-defined condition")
exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException
for fn in fns:
def pa(s,l,t):
if not bool(_trim_arity(fn)(s,l,t)):
raise exc_type(s,l,msg)
self.parseAction.append(pa)
self.callDuringTry = self.callDuringTry or kwargs.get("callDuringTry", False)
return self
def setFailAction( self, fn ):
"""Define action to perform if parsing fails at this expression.
Fail acton fn is a callable function that takes the arguments
C{fn(s,loc,expr,err)} where:
- s = string being parsed
- loc = location where expression match was attempted and failed
- expr = the parse expression that failed
- err = the exception thrown
The function returns no value. It may throw C{L{ParseFatalException}}
if it is desired to stop parsing immediately."""
self.failAction = fn
return self
def _skipIgnorables( self, instring, loc ):
exprsFound = True
while exprsFound:
exprsFound = False
for e in self.ignoreExprs:
try:
while 1:
loc,dummy = e._parse( instring, loc )
exprsFound = True
except ParseException:
pass
return loc
def preParse( self, instring, loc ):
if self.ignoreExprs:
loc = self._skipIgnorables( instring, loc )
if self.skipWhitespace:
wt = self.whiteChars
instrlen = len(instring)
while loc < instrlen and instring[loc] in wt:
loc += 1
return loc
def parseImpl( self, instring, loc, doActions=True ):
return loc, []
def postParse( self, instring, loc, tokenlist ):
return tokenlist
#~ @profile
def _parseNoCache( self, instring, loc, doActions=True, callPreParse=True ):
debugging = ( self.debug ) #and doActions )
if debugging or self.failAction:
#~ print ("Match",self,"at loc",loc,"(%d,%d)" % ( lineno(loc,instring), col(loc,instring) ))
if (self.debugActions[0] ):
self.debugActions[0]( instring, loc, self )
if callPreParse and self.callPreparse:
preloc = self.preParse( instring, loc )
else:
preloc = loc
tokensStart = preloc
try:
try:
loc,tokens = self.parseImpl( instring, preloc, doActions )
except IndexError:
raise ParseException( instring, len(instring), self.errmsg, self )
except ParseBaseException as err:
#~ print ("Exception raised:", err)
if self.debugActions[2]:
self.debugActions[2]( instring, tokensStart, self, err )
if self.failAction:
self.failAction( instring, tokensStart, self, err )
raise
else:
if callPreParse and self.callPreparse:
preloc = self.preParse( instring, loc )
else:
preloc = loc
tokensStart = preloc
if self.mayIndexError or loc >= len(instring):
try:
loc,tokens = self.parseImpl( instring, preloc, doActions )
except IndexError:
raise ParseException( instring, len(instring), self.errmsg, self )
else:
loc,tokens = self.parseImpl( instring, preloc, doActions )
tokens = self.postParse( instring, loc, tokens )
retTokens = ParseResults( tokens, self.resultsName, asList=self.saveAsList, modal=self.modalResults )
if self.parseAction and (doActions or self.callDuringTry):
if debugging:
try:
for fn in self.parseAction:
tokens = fn( instring, tokensStart, retTokens )
if tokens is not None:
retTokens = ParseResults( tokens,
self.resultsName,
asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
modal=self.modalResults )
except ParseBaseException as err:
#~ print "Exception raised in user parse action:", err
if (self.debugActions[2] ):
self.debugActions[2]( instring, tokensStart, self, err )
raise
else:
for fn in self.parseAction:
tokens = fn( instring, tokensStart, retTokens )
if tokens is not None:
retTokens = ParseResults( tokens,
self.resultsName,
asList=self.saveAsList and isinstance(tokens,(ParseResults,list)),
modal=self.modalResults )
if debugging:
#~ print ("Matched",self,"->",retTokens.asList())
if (self.debugActions[1] ):
self.debugActions[1]( instring, tokensStart, loc, self, retTokens )
return loc, retTokens
def tryParse( self, instring, loc ):
try:
return self._parse( instring, loc, doActions=False )[0]
except ParseFatalException:
raise ParseException( instring, loc, self.errmsg, self)
def canParseNext(self, instring, loc):
try:
self.tryParse(instring, loc)
except (ParseException, IndexError):
return False
else:
return True
class _UnboundedCache(object):
def __init__(self):
cache = {}
self.not_in_cache = not_in_cache = object()
def get(self, key):
return cache.get(key, not_in_cache)
def set(self, key, value):
cache[key] = value
def clear(self):
cache.clear()
self.get = types.MethodType(get, self)
self.set = types.MethodType(set, self)
self.clear = types.MethodType(clear, self)
if _OrderedDict is not None:
class _FifoCache(object):
def __init__(self, size):
self.not_in_cache = not_in_cache = object()
cache = _OrderedDict()
def get(self, key):
return cache.get(key, not_in_cache)
def set(self, key, value):
cache[key] = value
if len(cache) > size:
cache.popitem(False)
def clear(self):
cache.clear()
self.get = types.MethodType(get, self)
self.set = types.MethodType(set, self)
self.clear = types.MethodType(clear, self)
else:
class _FifoCache(object):
def __init__(self, size):
self.not_in_cache = not_in_cache = object()
cache = {}
key_fifo = collections.deque([], size)
def get(self, key):
return cache.get(key, not_in_cache)
def set(self, key, value):
cache[key] = value
if len(cache) > size:
cache.pop(key_fifo.popleft(), None)
key_fifo.append(key)
def clear(self):
cache.clear()
key_fifo.clear()
self.get = types.MethodType(get, self)
self.set = types.MethodType(set, self)
self.clear = types.MethodType(clear, self)
# argument cache for optimizing repeated calls when backtracking through recursive expressions
packrat_cache = {} # this is set later by enabledPackrat(); this is here so that resetCache() doesn't fail
packrat_cache_lock = RLock()
packrat_cache_stats = [0, 0]
# this method gets repeatedly called during backtracking with the same arguments -
# we can cache these arguments and save ourselves the trouble of re-parsing the contained expression
def _parseCache( self, instring, loc, doActions=True, callPreParse=True ):
HIT, MISS = 0, 1
lookup = (self, instring, loc, callPreParse, doActions)
with ParserElement.packrat_cache_lock:
cache = ParserElement.packrat_cache
value = cache.get(lookup)
if value is cache.not_in_cache:
ParserElement.packrat_cache_stats[MISS] += 1
try:
value = self._parseNoCache(instring, loc, doActions, callPreParse)
except ParseBaseException as pe:
# cache a copy of the exception, without the traceback
cache.set(lookup, pe.__class__(*pe.args))
raise
else:
cache.set(lookup, (value[0], value[1].copy()))
return value
else:
ParserElement.packrat_cache_stats[HIT] += 1
if isinstance(value, Exception):
raise value
return (value[0], value[1].copy())
_parse = _parseNoCache
@staticmethod
def resetCache():
ParserElement.packrat_cache.clear()
ParserElement.packrat_cache_stats[:] = [0] * len(ParserElement.packrat_cache_stats)
_packratEnabled = False
@staticmethod
def enablePackrat(cache_size_limit=128):
"""Enables "packrat" parsing, which adds memoizing to the parsing logic.
Repeated parse attempts at the same string location (which happens
often in many complex grammars) can immediately return a cached value,
instead of re-executing parsing/validating code. Memoizing is done of
both valid results and parsing exceptions.
Parameters:
- cache_size_limit - (default=C{128}) - if an integer value is provided
will limit the size of the packrat cache; if None is passed, then
the cache size will be unbounded; if 0 is passed, the cache will
be effectively disabled.
This speedup may break existing programs that use parse actions that
have side-effects. For this reason, packrat parsing is disabled when
you first import pyparsing. To activate the packrat feature, your
program must call the class method C{ParserElement.enablePackrat()}. If
your program uses C{psyco} to "compile as you go", you must call
C{enablePackrat} before calling C{psyco.full()}. If you do not do this,
Python will crash. For best results, call C{enablePackrat()} immediately
after importing pyparsing.
Example::
import pyparsing
pyparsing.ParserElement.enablePackrat()
"""
if not ParserElement._packratEnabled:
ParserElement._packratEnabled = True
if cache_size_limit is None:
ParserElement.packrat_cache = ParserElement._UnboundedCache()
else:
ParserElement.packrat_cache = ParserElement._FifoCache(cache_size_limit)
ParserElement._parse = ParserElement._parseCache
def parseString( self, instring, parseAll=False ):
"""
Execute the parse expression with the given string.
This is the main interface to the client code, once the complete
expression has been built.
If you want the grammar to require that the entire input string be
successfully parsed, then set C{parseAll} to True (equivalent to ending
the grammar with C{L{StringEnd()}}).
Note: C{parseString} implicitly calls C{expandtabs()} on the input string,
in order to report proper column numbers in parse actions.
If the input string contains tabs and
the grammar uses parse actions that use the C{loc} argument to index into the
string being parsed, you can ensure you have a consistent view of the input
string by:
- calling C{parseWithTabs} on your grammar before calling C{parseString}
(see L{I{parseWithTabs}<parseWithTabs>})
- define your parse action using the full C{(s,loc,toks)} signature, and
reference the input string using the parse action's C{s} argument
- explictly expand the tabs in your input string before calling
C{parseString}
Example::
Word('a').parseString('aaaaabaaa') # -> ['aaaaa']
Word('a').parseString('aaaaabaaa', parseAll=True) # -> Exception: Expected end of text
"""
ParserElement.resetCache()
if not self.streamlined:
self.streamline()
#~ self.saveAsList = True
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = instring.expandtabs()
try:
loc, tokens = self._parse( instring, 0 )
if parseAll:
loc = self.preParse( instring, loc )
se = Empty() + StringEnd()
se._parse( instring, loc )
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc
else:
return tokens
def scanString( self, instring, maxMatches=_MAX_INT, overlap=False ):
"""
Scan the input string for expression matches. Each match will return the
matching tokens, start location, and end location. May be called with optional
C{maxMatches} argument, to clip scanning after 'n' matches are found. If
C{overlap} is specified, then overlapping matches will be reported.
Note that the start and end locations are reported relative to the string
being parsed. See L{I{parseString}<parseString>} for more information on parsing
strings with embedded tabs.
Example::
source = "sldjf123lsdjjkf345sldkjf879lkjsfd987"
print(source)
for tokens,start,end in Word(alphas).scanString(source):
print(' '*start + '^'*(end-start))
print(' '*start + tokens[0])
prints::
sldjf123lsdjjkf345sldkjf879lkjsfd987
^^^^^
sldjf
^^^^^^^
lsdjjkf
^^^^^^
sldkjf
^^^^^^
lkjsfd
"""
if not self.streamlined:
self.streamline()
for e in self.ignoreExprs:
e.streamline()
if not self.keepTabs:
instring = _ustr(instring).expandtabs()
instrlen = len(instring)
loc = 0
preparseFn = self.preParse
parseFn = self._parse
ParserElement.resetCache()
matches = 0
try:
while loc <= instrlen and matches < maxMatches:
try:
preloc = preparseFn( instring, loc )
nextLoc,tokens = parseFn( instring, preloc, callPreParse=False )
except ParseException:
loc = preloc+1
else:
if nextLoc > loc:
matches += 1
yield tokens, preloc, nextLoc
if overlap:
nextloc = preparseFn( instring, loc )
if nextloc > loc:
loc = nextLoc
else:
loc += 1
else:
loc = nextLoc
else:
loc = preloc+1
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc
def transformString( self, instring ):
"""
Extension to C{L{scanString}}, to modify matching text with modified tokens that may
be returned from a parse action. To use C{transformString}, define a grammar and
attach a parse action to it that modifies the returned token list.
Invoking C{transformString()} on a target string will then scan for matches,
and replace the matched text patterns according to the logic in the parse
action. C{transformString()} returns the resulting transformed string.
Example::
wd = Word(alphas)
wd.setParseAction(lambda toks: toks[0].title())
print(wd.transformString("now is the winter of our discontent made glorious summer by this sun of york."))
Prints::
Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York.
"""
out = []
lastE = 0
# force preservation of <TAB>s, to minimize unwanted transformation of string, and to
# keep string locs straight between transformString and scanString
self.keepTabs = True
try:
for t,s,e in self.scanString( instring ):
out.append( instring[lastE:s] )
if t:
if isinstance(t,ParseResults):
out += t.asList()
elif isinstance(t,list):
out += t
else:
out.append(t)
lastE = e
out.append(instring[lastE:])
out = [o for o in out if o]
return "".join(map(_ustr,_flatten(out)))
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc
def searchString( self, instring, maxMatches=_MAX_INT ):
"""
Another extension to C{L{scanString}}, simplifying the access to the tokens found
to match the given parse expression. May be called with optional
C{maxMatches} argument, to clip searching after 'n' matches are found.
Example::
# a capitalized word starts with an uppercase letter, followed by zero or more lowercase letters
cap_word = Word(alphas.upper(), alphas.lower())
print(cap_word.searchString("More than Iron, more than Lead, more than Gold I need Electricity"))
prints::
['More', 'Iron', 'Lead', 'Gold', 'I']
"""
try:
return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ])
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc
def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False):
"""
Generator method to split a string using the given expression as a separator.
May be called with optional C{maxsplit} argument, to limit the number of splits;
and the optional C{includeSeparators} argument (default=C{False}), if the separating
matching text should be included in the split results.
Example::
punc = oneOf(list(".,;:/-!?"))
print(list(punc.split("This, this?, this sentence, is badly punctuated!")))
prints::
['This', ' this', '', ' this sentence', ' is badly punctuated', '']
"""
splits = 0
last = 0
for t,s,e in self.scanString(instring, maxMatches=maxsplit):
yield instring[last:s]
if includeSeparators:
yield t[0]
last = e
yield instring[last:]
def __add__(self, other ):
"""
Implementation of + operator - returns C{L{And}}. Adding strings to a ParserElement
converts them to L{Literal}s by default.
Example::
greet = Word(alphas) + "," + Word(alphas) + "!"
hello = "Hello, World!"
print (hello, "->", greet.parseString(hello))
Prints::
Hello, World! -> ['Hello', ',', 'World', '!']
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return And( [ self, other ] )
def __radd__(self, other ):
"""
Implementation of + operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other + self
def __sub__(self, other):
"""
Implementation of - operator, returns C{L{And}} with error stop
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return And( [ self, And._ErrorStop(), other ] )
def __rsub__(self, other ):
"""
Implementation of - operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other - self
def __mul__(self,other):
"""
Implementation of * operator, allows use of C{expr * 3} in place of
C{expr + expr + expr}. Expressions may also me multiplied by a 2-integer
tuple, similar to C{{min,max}} multipliers in regular expressions. Tuples
may also include C{None} as in:
- C{expr*(n,None)} or C{expr*(n,)} is equivalent
to C{expr*n + L{ZeroOrMore}(expr)}
(read as "at least n instances of C{expr}")
- C{expr*(None,n)} is equivalent to C{expr*(0,n)}
(read as "0 to n instances of C{expr}")
- C{expr*(None,None)} is equivalent to C{L{ZeroOrMore}(expr)}
- C{expr*(1,None)} is equivalent to C{L{OneOrMore}(expr)}
Note that C{expr*(None,n)} does not raise an exception if
more than n exprs exist in the input stream; that is,
C{expr*(None,n)} does not enforce a maximum number of expr
occurrences. If this behavior is desired, then write
C{expr*(None,n) + ~expr}
"""
if isinstance(other,int):
minElements, optElements = other,0
elif isinstance(other,tuple):
other = (other + (None, None))[:2]
if other[0] is None:
other = (0, other[1])
if isinstance(other[0],int) and other[1] is None:
if other[0] == 0:
return ZeroOrMore(self)
if other[0] == 1:
return OneOrMore(self)
else:
return self*other[0] + ZeroOrMore(self)
elif isinstance(other[0],int) and isinstance(other[1],int):
minElements, optElements = other
optElements -= minElements
else:
raise TypeError("cannot multiply 'ParserElement' and ('%s','%s') objects", type(other[0]),type(other[1]))
else:
raise TypeError("cannot multiply 'ParserElement' and '%s' objects", type(other))
if minElements < 0:
raise ValueError("cannot multiply ParserElement by negative value")
if optElements < 0:
raise ValueError("second tuple value must be greater or equal to first tuple value")
if minElements == optElements == 0:
raise ValueError("cannot multiply ParserElement by 0 or (0,0)")
if (optElements):
def makeOptionalList(n):
if n>1:
return Optional(self + makeOptionalList(n-1))
else:
return Optional(self)
if minElements:
if minElements == 1:
ret = self + makeOptionalList(optElements)
else:
ret = And([self]*minElements) + makeOptionalList(optElements)
else:
ret = makeOptionalList(optElements)
else:
if minElements == 1:
ret = self
else:
ret = And([self]*minElements)
return ret
def __rmul__(self, other):
return self.__mul__(other)
def __or__(self, other ):
"""
Implementation of | operator - returns C{L{MatchFirst}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return MatchFirst( [ self, other ] )
def __ror__(self, other ):
"""
Implementation of | operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other | self
def __xor__(self, other ):
"""
Implementation of ^ operator - returns C{L{Or}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Or( [ self, other ] )
def __rxor__(self, other ):
"""
Implementation of ^ operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other ^ self
def __and__(self, other ):
"""
Implementation of & operator - returns C{L{Each}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return Each( [ self, other ] )
def __rand__(self, other ):
"""
Implementation of & operator when left operand is not a C{L{ParserElement}}
"""
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
if not isinstance( other, ParserElement ):
warnings.warn("Cannot combine element of type %s with ParserElement" % type(other),
SyntaxWarning, stacklevel=2)
return None
return other & self
def __invert__( self ):
"""
Implementation of ~ operator - returns C{L{NotAny}}
"""
return NotAny( self )
def __call__(self, name=None):
"""
Shortcut for C{L{setResultsName}}, with C{listAllMatches=False}.
If C{name} is given with a trailing C{'*'} character, then C{listAllMatches} will be
passed as C{True}.
If C{name} is omitted, same as calling C{L{copy}}.
Example::
# these are equivalent
userdata = Word(alphas).setResultsName("name") + Word(nums+"-").setResultsName("socsecno")
userdata = Word(alphas)("name") + Word(nums+"-")("socsecno")
"""
if name is not None:
return self.setResultsName(name)
else:
return self.copy()
def suppress( self ):
"""
Suppresses the output of this C{ParserElement}; useful to keep punctuation from
cluttering up returned output.
"""
return Suppress( self )
def leaveWhitespace( self ):
"""
Disables the skipping of whitespace before matching the characters in the
C{ParserElement}'s defined pattern. This is normally only used internally by
the pyparsing module, but may be needed in some whitespace-sensitive grammars.
"""
self.skipWhitespace = False
return self
def setWhitespaceChars( self, chars ):
"""
Overrides the default whitespace chars
"""
self.skipWhitespace = True
self.whiteChars = chars
self.copyDefaultWhiteChars = False
return self
def parseWithTabs( self ):
"""
Overrides default behavior to expand C{<TAB>}s to spaces before parsing the input string.
Must be called before C{parseString} when the input grammar contains elements that
match C{<TAB>} characters.
"""
self.keepTabs = True
return self
def ignore( self, other ):
"""
Define expression to be ignored (e.g., comments) while doing pattern
matching; may be called repeatedly, to define multiple comment or other
ignorable patterns.
Example::
patt = OneOrMore(Word(alphas))
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj']
patt.ignore(cStyleComment)
patt.parseString('ablaj /* comment */ lskjd') # -> ['ablaj', 'lskjd']
"""
if isinstance(other, basestring):
other = Suppress(other)
if isinstance( other, Suppress ):
if other not in self.ignoreExprs:
self.ignoreExprs.append(other)
else:
self.ignoreExprs.append( Suppress( other.copy() ) )
return self
def setDebugActions( self, startAction, successAction, exceptionAction ):
"""
Enable display of debugging messages while doing pattern matching.
"""
self.debugActions = (startAction or _defaultStartDebugAction,
successAction or _defaultSuccessDebugAction,
exceptionAction or _defaultExceptionDebugAction)
self.debug = True
return self
def setDebug( self, flag=True ):
"""
Enable display of debugging messages while doing pattern matching.
Set C{flag} to True to enable, False to disable.
Example::
wd = Word(alphas).setName("alphaword")
integer = Word(nums).setName("numword")
term = wd | integer
# turn on debugging for wd
wd.setDebug()
OneOrMore(term).parseString("abc 123 xyz 890")
prints::
Match alphaword at loc 0(1,1)
Matched alphaword -> ['abc']
Match alphaword at loc 3(1,4)
Exception raised:Expected alphaword (at char 4), (line:1, col:5)
Match alphaword at loc 7(1,8)
Matched alphaword -> ['xyz']
Match alphaword at loc 11(1,12)
Exception raised:Expected alphaword (at char 12), (line:1, col:13)
Match alphaword at loc 15(1,16)
Exception raised:Expected alphaword (at char 15), (line:1, col:16)
The output shown is that produced by the default debug actions - custom debug actions can be
specified using L{setDebugActions}. Prior to attempting
to match the C{wd} expression, the debugging message C{"Match <exprname> at loc <n>(<line>,<col>)"}
is shown. Then if the parse succeeds, a C{"Matched"} message is shown, or an C{"Exception raised"}
message is shown. Also note the use of L{setName} to assign a human-readable name to the expression,
which makes debugging and exception messages easier to understand - for instance, the default
name created for the C{Word} expression without calling C{setName} is C{"W:(ABCD...)"}.
"""
if flag:
self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction )
else:
self.debug = False
return self
def __str__( self ):
return self.name
def __repr__( self ):
return _ustr(self)
def streamline( self ):
self.streamlined = True
self.strRepr = None
return self
def checkRecursion( self, parseElementList ):
pass
def validate( self, validateTrace=[] ):
"""
Check defined expressions for valid structure, check for infinite recursive definitions.
"""
self.checkRecursion( [] )
def parseFile( self, file_or_filename, parseAll=False ):
"""
Execute the parse expression on the given file or filename.
If a filename is specified (instead of a file object),
the entire file is opened, read, and closed before parsing.
"""
try:
file_contents = file_or_filename.read()
except AttributeError:
with open(file_or_filename, "r") as f:
file_contents = f.read()
try:
return self.parseString(file_contents, parseAll)
except ParseBaseException as exc:
if ParserElement.verbose_stacktrace:
raise
else:
# catch and re-raise exception from here, clears out pyparsing internal stack trace
raise exc
def __eq__(self,other):
if isinstance(other, ParserElement):
return self is other or vars(self) == vars(other)
elif isinstance(other, basestring):
return self.matches(other)
else:
return super(ParserElement,self)==other
def __ne__(self,other):
return not (self == other)
def __hash__(self):
return hash(id(self))
def __req__(self,other):
return self == other
def __rne__(self,other):
return not (self == other)
def matches(self, testString, parseAll=True):
"""
Method for quick testing of a parser against a test string. Good for simple
inline microtests of sub expressions while building up larger parser.
Parameters:
- testString - to test against this expression for a match
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
Example::
expr = Word(nums)
assert expr.matches("100")
"""
try:
self.parseString(_ustr(testString), parseAll=parseAll)
return True
except ParseBaseException:
return False
def runTests(self, tests, parseAll=True, comment='#', fullDump=True, printResults=True, failureTests=False):
"""
Execute the parse expression on a series of test strings, showing each
test, the parsed results or where the parse failed. Quick and easy way to
run a parse expression against a list of sample strings.
Parameters:
- tests - a list of separate test strings, or a multiline string of test strings
- parseAll - (default=C{True}) - flag to pass to C{L{parseString}} when running tests
- comment - (default=C{'#'}) - expression for indicating embedded comments in the test
string; pass None to disable comment filtering
- fullDump - (default=C{True}) - dump results as list followed by results names in nested outline;
if False, only dump nested list
- printResults - (default=C{True}) prints test output to stdout
- failureTests - (default=C{False}) indicates if these tests are expected to fail parsing
Returns: a (success, results) tuple, where success indicates that all tests succeeded
(or failed if C{failureTests} is True), and the results contain a list of lines of each
test's output
Example::
number_expr = pyparsing_common.number.copy()
result = number_expr.runTests('''
# unsigned integer
100
# negative integer
-100
# float with scientific notation
6.02e23
# integer with scientific notation
1e-12
''')
print("Success" if result[0] else "Failed!")
result = number_expr.runTests('''
# stray character
100Z
# missing leading digit before '.'
-.100
# too many '.'
3.14.159
''', failureTests=True)
print("Success" if result[0] else "Failed!")
prints::
# unsigned integer
100
[100]
# negative integer
-100
[-100]
# float with scientific notation
6.02e23
[6.02e+23]
# integer with scientific notation
1e-12
[1e-12]
Success
# stray character
100Z
^
FAIL: Expected end of text (at char 3), (line:1, col:4)
# missing leading digit before '.'
-.100
^
FAIL: Expected {real number with scientific notation | real number | signed integer} (at char 0), (line:1, col:1)
# too many '.'
3.14.159
^
FAIL: Expected end of text (at char 4), (line:1, col:5)
Success
Each test string must be on a single line. If you want to test a string that spans multiple
lines, create a test like this::
expr.runTest(r"this is a test\\n of strings that spans \\n 3 lines")
(Note that this is a raw string literal, you must include the leading 'r'.)
"""
if isinstance(tests, basestring):
tests = list(map(str.strip, tests.rstrip().splitlines()))
if isinstance(comment, basestring):
comment = Literal(comment)
allResults = []
comments = []
success = True
for t in tests:
if comment is not None and comment.matches(t, False) or comments and not t:
comments.append(t)
continue
if not t:
continue
out = ['\n'.join(comments), t]
comments = []
try:
t = t.replace(r'\n','\n')
result = self.parseString(t, parseAll=parseAll)
out.append(result.dump(full=fullDump))
success = success and not failureTests
except ParseBaseException as pe:
fatal = "(FATAL)" if isinstance(pe, ParseFatalException) else ""
if '\n' in t:
out.append(line(pe.loc, t))
out.append(' '*(col(pe.loc,t)-1) + '^' + fatal)
else:
out.append(' '*pe.loc + '^' + fatal)
out.append("FAIL: " + str(pe))
success = success and failureTests
result = pe
except Exception as exc:
out.append("FAIL-EXCEPTION: " + str(exc))
success = success and failureTests
result = exc
if printResults:
if fullDump:
out.append('')
print('\n'.join(out))
allResults.append((t, result))
return success, allResults
class Token(ParserElement):
"""
Abstract C{ParserElement} subclass, for defining atomic matching patterns.
"""
def __init__( self ):
super(Token,self).__init__( savelist=False )
class Empty(Token):
"""
An empty token, will always match.
"""
def __init__( self ):
super(Empty,self).__init__()
self.name = "Empty"
self.mayReturnEmpty = True
self.mayIndexError = False
class NoMatch(Token):
"""
A token that will never match.
"""
def __init__( self ):
super(NoMatch,self).__init__()
self.name = "NoMatch"
self.mayReturnEmpty = True
self.mayIndexError = False
self.errmsg = "Unmatchable token"
def parseImpl( self, instring, loc, doActions=True ):
raise ParseException(instring, loc, self.errmsg, self)
class Literal(Token):
"""
Token to exactly match a specified string.
Example::
Literal('blah').parseString('blah') # -> ['blah']
Literal('blah').parseString('blahfooblah') # -> ['blah']
Literal('blah').parseString('bla') # -> Exception: Expected "blah"
For case-insensitive matching, use L{CaselessLiteral}.
For keyword matching (force word break before and after the matched string),
use L{Keyword} or L{CaselessKeyword}.
"""
def __init__( self, matchString ):
super(Literal,self).__init__()
self.match = matchString
self.matchLen = len(matchString)
try:
self.firstMatchChar = matchString[0]
except IndexError:
warnings.warn("null string passed to Literal; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.__class__ = Empty
self.name = '"%s"' % _ustr(self.match)
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = False
self.mayIndexError = False
# Performance tuning: this routine gets called a *lot*
# if this is a single character match string and the first character matches,
# short-circuit as quickly as possible, and avoid calling startswith
#~ @profile
def parseImpl( self, instring, loc, doActions=True ):
if (instring[loc] == self.firstMatchChar and
(self.matchLen==1 or instring.startswith(self.match,loc)) ):
return loc+self.matchLen, self.match
raise ParseException(instring, loc, self.errmsg, self)
_L = Literal
ParserElement._literalStringClass = Literal
class Keyword(Token):
"""
Token to exactly match a specified string as a keyword, that is, it must be
immediately followed by a non-keyword character. Compare with C{L{Literal}}:
- C{Literal("if")} will match the leading C{'if'} in C{'ifAndOnlyIf'}.
- C{Keyword("if")} will not; it will only match the leading C{'if'} in C{'if x=1'}, or C{'if(y==2)'}
Accepts two optional constructor arguments in addition to the keyword string:
- C{identChars} is a string of characters that would be valid identifier characters,
defaulting to all alphanumerics + "_" and "$"
- C{caseless} allows case-insensitive matching, default is C{False}.
Example::
Keyword("start").parseString("start") # -> ['start']
Keyword("start").parseString("starting") # -> Exception
For case-insensitive matching, use L{CaselessKeyword}.
"""
DEFAULT_KEYWORD_CHARS = alphanums+"_$"
def __init__( self, matchString, identChars=None, caseless=False ):
super(Keyword,self).__init__()
if identChars is None:
identChars = Keyword.DEFAULT_KEYWORD_CHARS
self.match = matchString
self.matchLen = len(matchString)
try:
self.firstMatchChar = matchString[0]
except IndexError:
warnings.warn("null string passed to Keyword; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.name = '"%s"' % self.match
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = False
self.mayIndexError = False
self.caseless = caseless
if caseless:
self.caselessmatch = matchString.upper()
identChars = identChars.upper()
self.identChars = set(identChars)
def parseImpl( self, instring, loc, doActions=True ):
if self.caseless:
if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) and
(loc == 0 or instring[loc-1].upper() not in self.identChars) ):
return loc+self.matchLen, self.match
else:
if (instring[loc] == self.firstMatchChar and
(self.matchLen==1 or instring.startswith(self.match,loc)) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen] not in self.identChars) and
(loc == 0 or instring[loc-1] not in self.identChars) ):
return loc+self.matchLen, self.match
raise ParseException(instring, loc, self.errmsg, self)
def copy(self):
c = super(Keyword,self).copy()
c.identChars = Keyword.DEFAULT_KEYWORD_CHARS
return c
@staticmethod
def setDefaultKeywordChars( chars ):
"""Overrides the default Keyword chars
"""
Keyword.DEFAULT_KEYWORD_CHARS = chars
class CaselessLiteral(Literal):
"""
Token to match a specified string, ignoring case of letters.
Note: the matched results will always be in the case of the given
match string, NOT the case of the input text.
Example::
OneOrMore(CaselessLiteral("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD', 'CMD']
(Contrast with example for L{CaselessKeyword}.)
"""
def __init__( self, matchString ):
super(CaselessLiteral,self).__init__( matchString.upper() )
# Preserve the defining literal.
self.returnString = matchString
self.name = "'%s'" % self.returnString
self.errmsg = "Expected " + self.name
def parseImpl( self, instring, loc, doActions=True ):
if instring[ loc:loc+self.matchLen ].upper() == self.match:
return loc+self.matchLen, self.returnString
raise ParseException(instring, loc, self.errmsg, self)
class CaselessKeyword(Keyword):
"""
Caseless version of L{Keyword}.
Example::
OneOrMore(CaselessKeyword("CMD")).parseString("cmd CMD Cmd10") # -> ['CMD', 'CMD']
(Contrast with example for L{CaselessLiteral}.)
"""
def __init__( self, matchString, identChars=None ):
super(CaselessKeyword,self).__init__( matchString, identChars, caseless=True )
def parseImpl( self, instring, loc, doActions=True ):
if ( (instring[ loc:loc+self.matchLen ].upper() == self.caselessmatch) and
(loc >= len(instring)-self.matchLen or instring[loc+self.matchLen].upper() not in self.identChars) ):
return loc+self.matchLen, self.match
raise ParseException(instring, loc, self.errmsg, self)
class CloseMatch(Token):
"""
A variation on L{Literal} which matches "close" matches, that is,
strings with at most 'n' mismatching characters. C{CloseMatch} takes parameters:
- C{match_string} - string to be matched
- C{maxMismatches} - (C{default=1}) maximum number of mismatches allowed to count as a match
The results from a successful parse will contain the matched text from the input string and the following named results:
- C{mismatches} - a list of the positions within the match_string where mismatches were found
- C{original} - the original match_string used to compare against the input string
If C{mismatches} is an empty list, then the match was an exact match.
Example::
patt = CloseMatch("ATCATCGAATGGA")
patt.parseString("ATCATCGAAXGGA") # -> (['ATCATCGAAXGGA'], {'mismatches': [[9]], 'original': ['ATCATCGAATGGA']})
patt.parseString("ATCAXCGAAXGGA") # -> Exception: Expected 'ATCATCGAATGGA' (with up to 1 mismatches) (at char 0), (line:1, col:1)
# exact match
patt.parseString("ATCATCGAATGGA") # -> (['ATCATCGAATGGA'], {'mismatches': [[]], 'original': ['ATCATCGAATGGA']})
# close match allowing up to 2 mismatches
patt = CloseMatch("ATCATCGAATGGA", maxMismatches=2)
patt.parseString("ATCAXCGAAXGGA") # -> (['ATCAXCGAAXGGA'], {'mismatches': [[4, 9]], 'original': ['ATCATCGAATGGA']})
"""
def __init__(self, match_string, maxMismatches=1):
super(CloseMatch,self).__init__()
self.name = match_string
self.match_string = match_string
self.maxMismatches = maxMismatches
self.errmsg = "Expected %r (with up to %d mismatches)" % (self.match_string, self.maxMismatches)
self.mayIndexError = False
self.mayReturnEmpty = False
def parseImpl( self, instring, loc, doActions=True ):
start = loc
instrlen = len(instring)
maxloc = start + len(self.match_string)
if maxloc <= instrlen:
match_string = self.match_string
match_stringloc = 0
mismatches = []
maxMismatches = self.maxMismatches
for match_stringloc,s_m in enumerate(zip(instring[loc:maxloc], self.match_string)):
src,mat = s_m
if src != mat:
mismatches.append(match_stringloc)
if len(mismatches) > maxMismatches:
break
else:
loc = match_stringloc + 1
results = ParseResults([instring[start:loc]])
results['original'] = self.match_string
results['mismatches'] = mismatches
return loc, results
raise ParseException(instring, loc, self.errmsg, self)
class Word(Token):
"""
Token for matching words composed of allowed character sets.
Defined with string containing all allowed initial characters,
an optional string containing allowed body characters (if omitted,
defaults to the initial character set), and an optional minimum,
maximum, and/or exact length. The default value for C{min} is 1 (a
minimum value < 1 is not valid); the default values for C{max} and C{exact}
are 0, meaning no maximum or exact length restriction. An optional
C{excludeChars} parameter can list characters that might be found in
the input C{bodyChars} string; useful to define a word of all printables
except for one or two characters, for instance.
L{srange} is useful for defining custom character set strings for defining
C{Word} expressions, using range notation from regular expression character sets.
A common mistake is to use C{Word} to match a specific literal string, as in
C{Word("Address")}. Remember that C{Word} uses the string argument to define
I{sets} of matchable characters. This expression would match "Add", "AAA",
"dAred", or any other word made up of the characters 'A', 'd', 'r', 'e', and 's'.
To match an exact literal string, use L{Literal} or L{Keyword}.
pyparsing includes helper strings for building Words:
- L{alphas}
- L{nums}
- L{alphanums}
- L{hexnums}
- L{alphas8bit} (alphabetic characters in ASCII range 128-255 - accented, tilded, umlauted, etc.)
- L{punc8bit} (non-alphabetic characters in ASCII range 128-255 - currency, symbols, superscripts, diacriticals, etc.)
- L{printables} (any non-whitespace character)
Example::
# a word composed of digits
integer = Word(nums) # equivalent to Word("0123456789") or Word(srange("0-9"))
# a word with a leading capital, and zero or more lowercase
capital_word = Word(alphas.upper(), alphas.lower())
# hostnames are alphanumeric, with leading alpha, and '-'
hostname = Word(alphas, alphanums+'-')
# roman numeral (not a strict parser, accepts invalid mix of characters)
roman = Word("IVXLCDM")
# any string of non-whitespace characters, except for ','
csv_value = Word(printables, excludeChars=",")
"""
def __init__( self, initChars, bodyChars=None, min=1, max=0, exact=0, asKeyword=False, excludeChars=None ):
super(Word,self).__init__()
if excludeChars:
initChars = ''.join(c for c in initChars if c not in excludeChars)
if bodyChars:
bodyChars = ''.join(c for c in bodyChars if c not in excludeChars)
self.initCharsOrig = initChars
self.initChars = set(initChars)
if bodyChars :
self.bodyCharsOrig = bodyChars
self.bodyChars = set(bodyChars)
else:
self.bodyCharsOrig = initChars
self.bodyChars = set(initChars)
self.maxSpecified = max > 0
if min < 1:
raise ValueError("cannot specify a minimum length < 1; use Optional(Word()) if zero-length word is permitted")
self.minLen = min
if max > 0:
self.maxLen = max
else:
self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
self.minLen = exact
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
self.mayIndexError = False
self.asKeyword = asKeyword
if ' ' not in self.initCharsOrig+self.bodyCharsOrig and (min==1 and max==0 and exact==0):
if self.bodyCharsOrig == self.initCharsOrig:
self.reString = "[%s]+" % _escapeRegexRangeChars(self.initCharsOrig)
elif len(self.initCharsOrig) == 1:
self.reString = "%s[%s]*" % \
(re.escape(self.initCharsOrig),
_escapeRegexRangeChars(self.bodyCharsOrig),)
else:
self.reString = "[%s][%s]*" % \
(_escapeRegexRangeChars(self.initCharsOrig),
_escapeRegexRangeChars(self.bodyCharsOrig),)
if self.asKeyword:
self.reString = r"\b"+self.reString+r"\b"
try:
self.re = re.compile( self.reString )
except Exception:
self.re = None
def parseImpl( self, instring, loc, doActions=True ):
if self.re:
result = self.re.match(instring,loc)
if not result:
raise ParseException(instring, loc, self.errmsg, self)
loc = result.end()
return loc, result.group()
if not(instring[ loc ] in self.initChars):
raise ParseException(instring, loc, self.errmsg, self)
start = loc
loc += 1
instrlen = len(instring)
bodychars = self.bodyChars
maxloc = start + self.maxLen
maxloc = min( maxloc, instrlen )
while loc < maxloc and instring[loc] in bodychars:
loc += 1
throwException = False
if loc - start < self.minLen:
throwException = True
if self.maxSpecified and loc < instrlen and instring[loc] in bodychars:
throwException = True
if self.asKeyword:
if (start>0 and instring[start-1] in bodychars) or (loc<instrlen and instring[loc] in bodychars):
throwException = True
if throwException:
raise ParseException(instring, loc, self.errmsg, self)
return loc, instring[start:loc]
def __str__( self ):
try:
return super(Word,self).__str__()
except Exception:
pass
if self.strRepr is None:
def charsAsStr(s):
if len(s)>4:
return s[:4]+"..."
else:
return s
if ( self.initCharsOrig != self.bodyCharsOrig ):
self.strRepr = "W:(%s,%s)" % ( charsAsStr(self.initCharsOrig), charsAsStr(self.bodyCharsOrig) )
else:
self.strRepr = "W:(%s)" % charsAsStr(self.initCharsOrig)
return self.strRepr
class Regex(Token):
"""
Token for matching strings that match a given regular expression.
Defined with string specifying the regular expression in a form recognized by the inbuilt Python re module.
If the given regex contains named groups (defined using C{(?P<name>...)}), these will be preserved as
named parse results.
Example::
realnum = Regex(r"[+-]?\d+\.\d*")
date = Regex(r'(?P<year>\d{4})-(?P<month>\d\d?)-(?P<day>\d\d?)')
# ref: http://stackoverflow.com/questions/267399/how-do-you-match-only-valid-roman-numerals-with-a-regular-expression
roman = Regex(r"M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})")
"""
compiledREtype = type(re.compile("[A-Z]"))
def __init__( self, pattern, flags=0):
"""The parameters C{pattern} and C{flags} are passed to the C{re.compile()} function as-is. See the Python C{re} module for an explanation of the acceptable patterns and flags."""
super(Regex,self).__init__()
if isinstance(pattern, basestring):
if not pattern:
warnings.warn("null string passed to Regex; use Empty() instead",
SyntaxWarning, stacklevel=2)
self.pattern = pattern
self.flags = flags
try:
self.re = re.compile(self.pattern, self.flags)
self.reString = self.pattern
except sre_constants.error:
warnings.warn("invalid pattern (%s) passed to Regex" % pattern,
SyntaxWarning, stacklevel=2)
raise
elif isinstance(pattern, Regex.compiledREtype):
self.re = pattern
self.pattern = \
self.reString = str(pattern)
self.flags = flags
else:
raise ValueError("Regex may only be constructed with a string or a compiled RE object")
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
self.mayIndexError = False
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
result = self.re.match(instring,loc)
if not result:
raise ParseException(instring, loc, self.errmsg, self)
loc = result.end()
d = result.groupdict()
ret = ParseResults(result.group())
if d:
for k in d:
ret[k] = d[k]
return loc,ret
def __str__( self ):
try:
return super(Regex,self).__str__()
except Exception:
pass
if self.strRepr is None:
self.strRepr = "Re:(%s)" % repr(self.pattern)
return self.strRepr
class QuotedString(Token):
r"""
Token for matching strings that are delimited by quoting characters.
Defined with the following parameters:
- quoteChar - string of one or more characters defining the quote delimiting string
- escChar - character to escape quotes, typically backslash (default=C{None})
- escQuote - special quote sequence to escape an embedded quote string (such as SQL's "" to escape an embedded ") (default=C{None})
- multiline - boolean indicating whether quotes can span multiple lines (default=C{False})
- unquoteResults - boolean indicating whether the matched text should be unquoted (default=C{True})
- endQuoteChar - string of one or more characters defining the end of the quote delimited string (default=C{None} => same as quoteChar)
- convertWhitespaceEscapes - convert escaped whitespace (C{'\t'}, C{'\n'}, etc.) to actual whitespace (default=C{True})
Example::
qs = QuotedString('"')
print(qs.searchString('lsjdf "This is the quote" sldjf'))
complex_qs = QuotedString('{{', endQuoteChar='}}')
print(complex_qs.searchString('lsjdf {{This is the "quote"}} sldjf'))
sql_qs = QuotedString('"', escQuote='""')
print(sql_qs.searchString('lsjdf "This is the quote with ""embedded"" quotes" sldjf'))
prints::
[['This is the quote']]
[['This is the "quote"']]
[['This is the quote with "embedded" quotes']]
"""
def __init__( self, quoteChar, escChar=None, escQuote=None, multiline=False, unquoteResults=True, endQuoteChar=None, convertWhitespaceEscapes=True):
super(QuotedString,self).__init__()
# remove white space from quote chars - wont work anyway
quoteChar = quoteChar.strip()
if not quoteChar:
warnings.warn("quoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
raise SyntaxError()
if endQuoteChar is None:
endQuoteChar = quoteChar
else:
endQuoteChar = endQuoteChar.strip()
if not endQuoteChar:
warnings.warn("endQuoteChar cannot be the empty string",SyntaxWarning,stacklevel=2)
raise SyntaxError()
self.quoteChar = quoteChar
self.quoteCharLen = len(quoteChar)
self.firstQuoteChar = quoteChar[0]
self.endQuoteChar = endQuoteChar
self.endQuoteCharLen = len(endQuoteChar)
self.escChar = escChar
self.escQuote = escQuote
self.unquoteResults = unquoteResults
self.convertWhitespaceEscapes = convertWhitespaceEscapes
if multiline:
self.flags = re.MULTILINE | re.DOTALL
self.pattern = r'%s(?:[^%s%s]' % \
( re.escape(self.quoteChar),
_escapeRegexRangeChars(self.endQuoteChar[0]),
(escChar is not None and _escapeRegexRangeChars(escChar) or '') )
else:
self.flags = 0
self.pattern = r'%s(?:[^%s\n\r%s]' % \
( re.escape(self.quoteChar),
_escapeRegexRangeChars(self.endQuoteChar[0]),
(escChar is not None and _escapeRegexRangeChars(escChar) or '') )
if len(self.endQuoteChar) > 1:
self.pattern += (
'|(?:' + ')|(?:'.join("%s[^%s]" % (re.escape(self.endQuoteChar[:i]),
_escapeRegexRangeChars(self.endQuoteChar[i]))
for i in range(len(self.endQuoteChar)-1,0,-1)) + ')'
)
if escQuote:
self.pattern += (r'|(?:%s)' % re.escape(escQuote))
if escChar:
self.pattern += (r'|(?:%s.)' % re.escape(escChar))
self.escCharReplacePattern = re.escape(self.escChar)+"(.)"
self.pattern += (r')*%s' % re.escape(self.endQuoteChar))
try:
self.re = re.compile(self.pattern, self.flags)
self.reString = self.pattern
except sre_constants.error:
warnings.warn("invalid pattern (%s) passed to Regex" % self.pattern,
SyntaxWarning, stacklevel=2)
raise
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
self.mayIndexError = False
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
result = instring[loc] == self.firstQuoteChar and self.re.match(instring,loc) or None
if not result:
raise ParseException(instring, loc, self.errmsg, self)
loc = result.end()
ret = result.group()
if self.unquoteResults:
# strip off quotes
ret = ret[self.quoteCharLen:-self.endQuoteCharLen]
if isinstance(ret,basestring):
# replace escaped whitespace
if '\\' in ret and self.convertWhitespaceEscapes:
ws_map = {
r'\t' : '\t',
r'\n' : '\n',
r'\f' : '\f',
r'\r' : '\r',
}
for wslit,wschar in ws_map.items():
ret = ret.replace(wslit, wschar)
# replace escaped characters
if self.escChar:
ret = re.sub(self.escCharReplacePattern,"\g<1>",ret)
# replace escaped quotes
if self.escQuote:
ret = ret.replace(self.escQuote, self.endQuoteChar)
return loc, ret
def __str__( self ):
try:
return super(QuotedString,self).__str__()
except Exception:
pass
if self.strRepr is None:
self.strRepr = "quoted string, starting with %s ending with %s" % (self.quoteChar, self.endQuoteChar)
return self.strRepr
class CharsNotIn(Token):
"""
Token for matching words composed of characters I{not} in a given set (will
include whitespace in matched characters if not listed in the provided exclusion set - see example).
Defined with string containing all disallowed characters, and an optional
minimum, maximum, and/or exact length. The default value for C{min} is 1 (a
minimum value < 1 is not valid); the default values for C{max} and C{exact}
are 0, meaning no maximum or exact length restriction.
Example::
# define a comma-separated-value as anything that is not a ','
csv_value = CharsNotIn(',')
print(delimitedList(csv_value).parseString("dkls,lsdkjf,s12 34,@!#,213"))
prints::
['dkls', 'lsdkjf', 's12 34', '@!#', '213']
"""
def __init__( self, notChars, min=1, max=0, exact=0 ):
super(CharsNotIn,self).__init__()
self.skipWhitespace = False
self.notChars = notChars
if min < 1:
raise ValueError("cannot specify a minimum length < 1; use Optional(CharsNotIn()) if zero-length char group is permitted")
self.minLen = min
if max > 0:
self.maxLen = max
else:
self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
self.minLen = exact
self.name = _ustr(self)
self.errmsg = "Expected " + self.name
self.mayReturnEmpty = ( self.minLen == 0 )
self.mayIndexError = False
def parseImpl( self, instring, loc, doActions=True ):
if instring[loc] in self.notChars:
raise ParseException(instring, loc, self.errmsg, self)
start = loc
loc += 1
notchars = self.notChars
maxlen = min( start+self.maxLen, len(instring) )
while loc < maxlen and \
(instring[loc] not in notchars):
loc += 1
if loc - start < self.minLen:
raise ParseException(instring, loc, self.errmsg, self)
return loc, instring[start:loc]
def __str__( self ):
try:
return super(CharsNotIn, self).__str__()
except Exception:
pass
if self.strRepr is None:
if len(self.notChars) > 4:
self.strRepr = "!W:(%s...)" % self.notChars[:4]
else:
self.strRepr = "!W:(%s)" % self.notChars
return self.strRepr
class White(Token):
"""
Special matching class for matching whitespace. Normally, whitespace is ignored
by pyparsing grammars. This class is included when some whitespace structures
are significant. Define with a string containing the whitespace characters to be
matched; default is C{" \\t\\r\\n"}. Also takes optional C{min}, C{max}, and C{exact} arguments,
as defined for the C{L{Word}} class.
"""
whiteStrs = {
" " : "<SPC>",
"\t": "<TAB>",
"\n": "<LF>",
"\r": "<CR>",
"\f": "<FF>",
}
def __init__(self, ws=" \t\r\n", min=1, max=0, exact=0):
super(White,self).__init__()
self.matchWhite = ws
self.setWhitespaceChars( "".join(c for c in self.whiteChars if c not in self.matchWhite) )
#~ self.leaveWhitespace()
self.name = ("".join(White.whiteStrs[c] for c in self.matchWhite))
self.mayReturnEmpty = True
self.errmsg = "Expected " + self.name
self.minLen = min
if max > 0:
self.maxLen = max
else:
self.maxLen = _MAX_INT
if exact > 0:
self.maxLen = exact
self.minLen = exact
def parseImpl( self, instring, loc, doActions=True ):
if not(instring[ loc ] in self.matchWhite):
raise ParseException(instring, loc, self.errmsg, self)
start = loc
loc += 1
maxloc = start + self.maxLen
maxloc = min( maxloc, len(instring) )
while loc < maxloc and instring[loc] in self.matchWhite:
loc += 1
if loc - start < self.minLen:
raise ParseException(instring, loc, self.errmsg, self)
return loc, instring[start:loc]
class _PositionToken(Token):
def __init__( self ):
super(_PositionToken,self).__init__()
self.name=self.__class__.__name__
self.mayReturnEmpty = True
self.mayIndexError = False
class GoToColumn(_PositionToken):
"""
Token to advance to a specific column of input text; useful for tabular report scraping.
"""
def __init__( self, colno ):
super(GoToColumn,self).__init__()
self.col = colno
def preParse( self, instring, loc ):
if col(loc,instring) != self.col:
instrlen = len(instring)
if self.ignoreExprs:
loc = self._skipIgnorables( instring, loc )
while loc < instrlen and instring[loc].isspace() and col( loc, instring ) != self.col :
loc += 1
return loc
def parseImpl( self, instring, loc, doActions=True ):
thiscol = col( loc, instring )
if thiscol > self.col:
raise ParseException( instring, loc, "Text not in expected column", self )
newloc = loc + self.col - thiscol
ret = instring[ loc: newloc ]
return newloc, ret
class LineStart(_PositionToken):
"""
Matches if current position is at the beginning of a line within the parse string
Example::
test = '''\
AAA this line
AAA and this line
AAA but not this one
B AAA and definitely not this one
'''
for t in (LineStart() + 'AAA' + restOfLine).searchString(test):
print(t)
Prints::
['AAA', ' this line']
['AAA', ' and this line']
"""
def __init__( self ):
super(LineStart,self).__init__()
self.errmsg = "Expected start of line"
def parseImpl( self, instring, loc, doActions=True ):
if col(loc, instring) == 1:
return loc, []
raise ParseException(instring, loc, self.errmsg, self)
class LineEnd(_PositionToken):
"""
Matches if current position is at the end of a line within the parse string
"""
def __init__( self ):
super(LineEnd,self).__init__()
self.setWhitespaceChars( ParserElement.DEFAULT_WHITE_CHARS.replace("\n","") )
self.errmsg = "Expected end of line"
def parseImpl( self, instring, loc, doActions=True ):
if loc<len(instring):
if instring[loc] == "\n":
return loc+1, "\n"
else:
raise ParseException(instring, loc, self.errmsg, self)
elif loc == len(instring):
return loc+1, []
else:
raise ParseException(instring, loc, self.errmsg, self)
class StringStart(_PositionToken):
"""
Matches if current position is at the beginning of the parse string
"""
def __init__( self ):
super(StringStart,self).__init__()
self.errmsg = "Expected start of text"
def parseImpl( self, instring, loc, doActions=True ):
if loc != 0:
# see if entire string up to here is just whitespace and ignoreables
if loc != self.preParse( instring, 0 ):
raise ParseException(instring, loc, self.errmsg, self)
return loc, []
class StringEnd(_PositionToken):
"""
Matches if current position is at the end of the parse string
"""
def __init__( self ):
super(StringEnd,self).__init__()
self.errmsg = "Expected end of text"
def parseImpl( self, instring, loc, doActions=True ):
if loc < len(instring):
raise ParseException(instring, loc, self.errmsg, self)
elif loc == len(instring):
return loc+1, []
elif loc > len(instring):
return loc, []
else:
raise ParseException(instring, loc, self.errmsg, self)
class WordStart(_PositionToken):
"""
Matches if the current position is at the beginning of a Word, and
is not preceded by any character in a given set of C{wordChars}
(default=C{printables}). To emulate the C{\b} behavior of regular expressions,
use C{WordStart(alphanums)}. C{WordStart} will also match at the beginning of
the string being parsed, or at the beginning of a line.
"""
def __init__(self, wordChars = printables):
super(WordStart,self).__init__()
self.wordChars = set(wordChars)
self.errmsg = "Not at the start of a word"
def parseImpl(self, instring, loc, doActions=True ):
if loc != 0:
if (instring[loc-1] in self.wordChars or
instring[loc] not in self.wordChars):
raise ParseException(instring, loc, self.errmsg, self)
return loc, []
class WordEnd(_PositionToken):
"""
Matches if the current position is at the end of a Word, and
is not followed by any character in a given set of C{wordChars}
(default=C{printables}). To emulate the C{\b} behavior of regular expressions,
use C{WordEnd(alphanums)}. C{WordEnd} will also match at the end of
the string being parsed, or at the end of a line.
"""
def __init__(self, wordChars = printables):
super(WordEnd,self).__init__()
self.wordChars = set(wordChars)
self.skipWhitespace = False
self.errmsg = "Not at the end of a word"
def parseImpl(self, instring, loc, doActions=True ):
instrlen = len(instring)
if instrlen>0 and loc<instrlen:
if (instring[loc] in self.wordChars or
instring[loc-1] not in self.wordChars):
raise ParseException(instring, loc, self.errmsg, self)
return loc, []
class ParseExpression(ParserElement):
"""
Abstract subclass of ParserElement, for combining and post-processing parsed tokens.
"""
def __init__( self, exprs, savelist = False ):
super(ParseExpression,self).__init__(savelist)
if isinstance( exprs, _generatorType ):
exprs = list(exprs)
if isinstance( exprs, basestring ):
self.exprs = [ ParserElement._literalStringClass( exprs ) ]
elif isinstance( exprs, collections.Iterable ):
exprs = list(exprs)
# if sequence of strings provided, wrap with Literal
if all(isinstance(expr, basestring) for expr in exprs):
exprs = map(ParserElement._literalStringClass, exprs)
self.exprs = list(exprs)
else:
try:
self.exprs = list( exprs )
except TypeError:
self.exprs = [ exprs ]
self.callPreparse = False
def __getitem__( self, i ):
return self.exprs[i]
def append( self, other ):
self.exprs.append( other )
self.strRepr = None
return self
def leaveWhitespace( self ):
"""Extends C{leaveWhitespace} defined in base class, and also invokes C{leaveWhitespace} on
all contained expressions."""
self.skipWhitespace = False
self.exprs = [ e.copy() for e in self.exprs ]
for e in self.exprs:
e.leaveWhitespace()
return self
def ignore( self, other ):
if isinstance( other, Suppress ):
if other not in self.ignoreExprs:
super( ParseExpression, self).ignore( other )
for e in self.exprs:
e.ignore( self.ignoreExprs[-1] )
else:
super( ParseExpression, self).ignore( other )
for e in self.exprs:
e.ignore( self.ignoreExprs[-1] )
return self
def __str__( self ):
try:
return super(ParseExpression,self).__str__()
except Exception:
pass
if self.strRepr is None:
self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.exprs) )
return self.strRepr
def streamline( self ):
super(ParseExpression,self).streamline()
for e in self.exprs:
e.streamline()
# collapse nested And's of the form And( And( And( a,b), c), d) to And( a,b,c,d )
# but only if there are no parse actions or resultsNames on the nested And's
# (likewise for Or's and MatchFirst's)
if ( len(self.exprs) == 2 ):
other = self.exprs[0]
if ( isinstance( other, self.__class__ ) and
not(other.parseAction) and
other.resultsName is None and
not other.debug ):
self.exprs = other.exprs[:] + [ self.exprs[1] ]
self.strRepr = None
self.mayReturnEmpty |= other.mayReturnEmpty
self.mayIndexError |= other.mayIndexError
other = self.exprs[-1]
if ( isinstance( other, self.__class__ ) and
not(other.parseAction) and
other.resultsName is None and
not other.debug ):
self.exprs = self.exprs[:-1] + other.exprs[:]
self.strRepr = None
self.mayReturnEmpty |= other.mayReturnEmpty
self.mayIndexError |= other.mayIndexError
self.errmsg = "Expected " + _ustr(self)
return self
def setResultsName( self, name, listAllMatches=False ):
ret = super(ParseExpression,self).setResultsName(name,listAllMatches)
return ret
def validate( self, validateTrace=[] ):
tmp = validateTrace[:]+[self]
for e in self.exprs:
e.validate(tmp)
self.checkRecursion( [] )
def copy(self):
ret = super(ParseExpression,self).copy()
ret.exprs = [e.copy() for e in self.exprs]
return ret
class And(ParseExpression):
"""
Requires all given C{ParseExpression}s to be found in the given order.
Expressions may be separated by whitespace.
May be constructed using the C{'+'} operator.
May also be constructed using the C{'-'} operator, which will suppress backtracking.
Example::
integer = Word(nums)
name_expr = OneOrMore(Word(alphas))
expr = And([integer("id"),name_expr("name"),integer("age")])
# more easily written as:
expr = integer("id") + name_expr("name") + integer("age")
"""
class _ErrorStop(Empty):
def __init__(self, *args, **kwargs):
super(And._ErrorStop,self).__init__(*args, **kwargs)
self.name = '-'
self.leaveWhitespace()
def __init__( self, exprs, savelist = True ):
super(And,self).__init__(exprs, savelist)
self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
self.setWhitespaceChars( self.exprs[0].whiteChars )
self.skipWhitespace = self.exprs[0].skipWhitespace
self.callPreparse = True
def parseImpl( self, instring, loc, doActions=True ):
# pass False as last arg to _parse for first element, since we already
# pre-parsed the string as part of our And pre-parsing
loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPreParse=False )
errorStop = False
for e in self.exprs[1:]:
if isinstance(e, And._ErrorStop):
errorStop = True
continue
if errorStop:
try:
loc, exprtokens = e._parse( instring, loc, doActions )
except ParseSyntaxException:
raise
except ParseBaseException as pe:
pe.__traceback__ = None
raise ParseSyntaxException._from_exception(pe)
except IndexError:
raise ParseSyntaxException(instring, len(instring), self.errmsg, self)
else:
loc, exprtokens = e._parse( instring, loc, doActions )
if exprtokens or exprtokens.haskeys():
resultlist += exprtokens
return loc, resultlist
def __iadd__(self, other ):
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
return self.append( other ) #And( [ self, other ] )
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
if not e.mayReturnEmpty:
break
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + " ".join(_ustr(e) for e in self.exprs) + "}"
return self.strRepr
class Or(ParseExpression):
"""
Requires that at least one C{ParseExpression} is found.
If two expressions match, the expression that matches the longest string will be used.
May be constructed using the C{'^'} operator.
Example::
# construct Or using '^' operator
number = Word(nums) ^ Combine(Word(nums) + '.' + Word(nums))
print(number.searchString("123 3.1416 789"))
prints::
[['123'], ['3.1416'], ['789']]
"""
def __init__( self, exprs, savelist = False ):
super(Or,self).__init__(exprs, savelist)
if self.exprs:
self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
else:
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
maxExcLoc = -1
maxException = None
matches = []
for e in self.exprs:
try:
loc2 = e.tryParse( instring, loc )
except ParseException as err:
err.__traceback__ = None
if err.loc > maxExcLoc:
maxException = err
maxExcLoc = err.loc
except IndexError:
if len(instring) > maxExcLoc:
maxException = ParseException(instring,len(instring),e.errmsg,self)
maxExcLoc = len(instring)
else:
# save match among all matches, to retry longest to shortest
matches.append((loc2, e))
if matches:
matches.sort(key=lambda x: -x[0])
for _,e in matches:
try:
return e._parse( instring, loc, doActions )
except ParseException as err:
err.__traceback__ = None
if err.loc > maxExcLoc:
maxException = err
maxExcLoc = err.loc
if maxException is not None:
maxException.msg = self.errmsg
raise maxException
else:
raise ParseException(instring, loc, "no defined alternatives to match", self)
def __ixor__(self, other ):
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
return self.append( other ) #Or( [ self, other ] )
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + " ^ ".join(_ustr(e) for e in self.exprs) + "}"
return self.strRepr
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
class MatchFirst(ParseExpression):
"""
Requires that at least one C{ParseExpression} is found.
If two expressions match, the first one listed is the one that will match.
May be constructed using the C{'|'} operator.
Example::
# construct MatchFirst using '|' operator
# watch the order of expressions to match
number = Word(nums) | Combine(Word(nums) + '.' + Word(nums))
print(number.searchString("123 3.1416 789")) # Fail! -> [['123'], ['3'], ['1416'], ['789']]
# put more selective expression first
number = Combine(Word(nums) + '.' + Word(nums)) | Word(nums)
print(number.searchString("123 3.1416 789")) # Better -> [['123'], ['3.1416'], ['789']]
"""
def __init__( self, exprs, savelist = False ):
super(MatchFirst,self).__init__(exprs, savelist)
if self.exprs:
self.mayReturnEmpty = any(e.mayReturnEmpty for e in self.exprs)
else:
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
maxExcLoc = -1
maxException = None
for e in self.exprs:
try:
ret = e._parse( instring, loc, doActions )
return ret
except ParseException as err:
if err.loc > maxExcLoc:
maxException = err
maxExcLoc = err.loc
except IndexError:
if len(instring) > maxExcLoc:
maxException = ParseException(instring,len(instring),e.errmsg,self)
maxExcLoc = len(instring)
# only got here if no expression matched, raise exception for match that made it the furthest
else:
if maxException is not None:
maxException.msg = self.errmsg
raise maxException
else:
raise ParseException(instring, loc, "no defined alternatives to match", self)
def __ior__(self, other ):
if isinstance( other, basestring ):
other = ParserElement._literalStringClass( other )
return self.append( other ) #MatchFirst( [ self, other ] )
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + " | ".join(_ustr(e) for e in self.exprs) + "}"
return self.strRepr
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
class Each(ParseExpression):
"""
Requires all given C{ParseExpression}s to be found, but in any order.
Expressions may be separated by whitespace.
May be constructed using the C{'&'} operator.
Example::
color = oneOf("RED ORANGE YELLOW GREEN BLUE PURPLE BLACK WHITE BROWN")
shape_type = oneOf("SQUARE CIRCLE TRIANGLE STAR HEXAGON OCTAGON")
integer = Word(nums)
shape_attr = "shape:" + shape_type("shape")
posn_attr = "posn:" + Group(integer("x") + ',' + integer("y"))("posn")
color_attr = "color:" + color("color")
size_attr = "size:" + integer("size")
# use Each (using operator '&') to accept attributes in any order
# (shape and posn are required, color and size are optional)
shape_spec = shape_attr & posn_attr & Optional(color_attr) & Optional(size_attr)
shape_spec.runTests('''
shape: SQUARE color: BLACK posn: 100, 120
shape: CIRCLE size: 50 color: BLUE posn: 50,80
color:GREEN size:20 shape:TRIANGLE posn:20,40
'''
)
prints::
shape: SQUARE color: BLACK posn: 100, 120
['shape:', 'SQUARE', 'color:', 'BLACK', 'posn:', ['100', ',', '120']]
- color: BLACK
- posn: ['100', ',', '120']
- x: 100
- y: 120
- shape: SQUARE
shape: CIRCLE size: 50 color: BLUE posn: 50,80
['shape:', 'CIRCLE', 'size:', '50', 'color:', 'BLUE', 'posn:', ['50', ',', '80']]
- color: BLUE
- posn: ['50', ',', '80']
- x: 50
- y: 80
- shape: CIRCLE
- size: 50
color: GREEN size: 20 shape: TRIANGLE posn: 20,40
['color:', 'GREEN', 'size:', '20', 'shape:', 'TRIANGLE', 'posn:', ['20', ',', '40']]
- color: GREEN
- posn: ['20', ',', '40']
- x: 20
- y: 40
- shape: TRIANGLE
- size: 20
"""
def __init__( self, exprs, savelist = True ):
super(Each,self).__init__(exprs, savelist)
self.mayReturnEmpty = all(e.mayReturnEmpty for e in self.exprs)
self.skipWhitespace = True
self.initExprGroups = True
def parseImpl( self, instring, loc, doActions=True ):
if self.initExprGroups:
self.opt1map = dict((id(e.expr),e) for e in self.exprs if isinstance(e,Optional))
opt1 = [ e.expr for e in self.exprs if isinstance(e,Optional) ]
opt2 = [ e for e in self.exprs if e.mayReturnEmpty and not isinstance(e,Optional)]
self.optionals = opt1 + opt2
self.multioptionals = [ e.expr for e in self.exprs if isinstance(e,ZeroOrMore) ]
self.multirequired = [ e.expr for e in self.exprs if isinstance(e,OneOrMore) ]
self.required = [ e for e in self.exprs if not isinstance(e,(Optional,ZeroOrMore,OneOrMore)) ]
self.required += self.multirequired
self.initExprGroups = False
tmpLoc = loc
tmpReqd = self.required[:]
tmpOpt = self.optionals[:]
matchOrder = []
keepMatching = True
while keepMatching:
tmpExprs = tmpReqd + tmpOpt + self.multioptionals + self.multirequired
failed = []
for e in tmpExprs:
try:
tmpLoc = e.tryParse( instring, tmpLoc )
except ParseException:
failed.append(e)
else:
matchOrder.append(self.opt1map.get(id(e),e))
if e in tmpReqd:
tmpReqd.remove(e)
elif e in tmpOpt:
tmpOpt.remove(e)
if len(failed) == len(tmpExprs):
keepMatching = False
if tmpReqd:
missing = ", ".join(_ustr(e) for e in tmpReqd)
raise ParseException(instring,loc,"Missing one or more required elements (%s)" % missing )
# add any unmatched Optionals, in case they have default values defined
matchOrder += [e for e in self.exprs if isinstance(e,Optional) and e.expr in tmpOpt]
resultlist = []
for e in matchOrder:
loc,results = e._parse(instring,loc,doActions)
resultlist.append(results)
finalResults = sum(resultlist, ParseResults([]))
return loc, finalResults
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + " & ".join(_ustr(e) for e in self.exprs) + "}"
return self.strRepr
def checkRecursion( self, parseElementList ):
subRecCheckList = parseElementList[:] + [ self ]
for e in self.exprs:
e.checkRecursion( subRecCheckList )
class ParseElementEnhance(ParserElement):
"""
Abstract subclass of C{ParserElement}, for combining and post-processing parsed tokens.
"""
def __init__( self, expr, savelist=False ):
super(ParseElementEnhance,self).__init__(savelist)
if isinstance( expr, basestring ):
if issubclass(ParserElement._literalStringClass, Token):
expr = ParserElement._literalStringClass(expr)
else:
expr = ParserElement._literalStringClass(Literal(expr))
self.expr = expr
self.strRepr = None
if expr is not None:
self.mayIndexError = expr.mayIndexError
self.mayReturnEmpty = expr.mayReturnEmpty
self.setWhitespaceChars( expr.whiteChars )
self.skipWhitespace = expr.skipWhitespace
self.saveAsList = expr.saveAsList
self.callPreparse = expr.callPreparse
self.ignoreExprs.extend(expr.ignoreExprs)
def parseImpl( self, instring, loc, doActions=True ):
if self.expr is not None:
return self.expr._parse( instring, loc, doActions, callPreParse=False )
else:
raise ParseException("",loc,self.errmsg,self)
def leaveWhitespace( self ):
self.skipWhitespace = False
self.expr = self.expr.copy()
if self.expr is not None:
self.expr.leaveWhitespace()
return self
def ignore( self, other ):
if isinstance( other, Suppress ):
if other not in self.ignoreExprs:
super( ParseElementEnhance, self).ignore( other )
if self.expr is not None:
self.expr.ignore( self.ignoreExprs[-1] )
else:
super( ParseElementEnhance, self).ignore( other )
if self.expr is not None:
self.expr.ignore( self.ignoreExprs[-1] )
return self
def streamline( self ):
super(ParseElementEnhance,self).streamline()
if self.expr is not None:
self.expr.streamline()
return self
def checkRecursion( self, parseElementList ):
if self in parseElementList:
raise RecursiveGrammarException( parseElementList+[self] )
subRecCheckList = parseElementList[:] + [ self ]
if self.expr is not None:
self.expr.checkRecursion( subRecCheckList )
def validate( self, validateTrace=[] ):
tmp = validateTrace[:]+[self]
if self.expr is not None:
self.expr.validate(tmp)
self.checkRecursion( [] )
def __str__( self ):
try:
return super(ParseElementEnhance,self).__str__()
except Exception:
pass
if self.strRepr is None and self.expr is not None:
self.strRepr = "%s:(%s)" % ( self.__class__.__name__, _ustr(self.expr) )
return self.strRepr
class FollowedBy(ParseElementEnhance):
"""
Lookahead matching of the given parse expression. C{FollowedBy}
does I{not} advance the parsing position within the input string, it only
verifies that the specified parse expression matches at the current
position. C{FollowedBy} always returns a null token list.
Example::
# use FollowedBy to match a label only if it is followed by a ':'
data_word = Word(alphas)
label = data_word + FollowedBy(':')
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
OneOrMore(attr_expr).parseString("shape: SQUARE color: BLACK posn: upper left").pprint()
prints::
[['shape', 'SQUARE'], ['color', 'BLACK'], ['posn', 'upper left']]
"""
def __init__( self, expr ):
super(FollowedBy,self).__init__(expr)
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
self.expr.tryParse( instring, loc )
return loc, []
class NotAny(ParseElementEnhance):
"""
Lookahead to disallow matching with the given parse expression. C{NotAny}
does I{not} advance the parsing position within the input string, it only
verifies that the specified parse expression does I{not} match at the current
position. Also, C{NotAny} does I{not} skip over leading whitespace. C{NotAny}
always returns a null token list. May be constructed using the '~' operator.
Example::
"""
def __init__( self, expr ):
super(NotAny,self).__init__(expr)
#~ self.leaveWhitespace()
self.skipWhitespace = False # do NOT use self.leaveWhitespace(), don't want to propagate to exprs
self.mayReturnEmpty = True
self.errmsg = "Found unwanted token, "+_ustr(self.expr)
def parseImpl( self, instring, loc, doActions=True ):
if self.expr.canParseNext(instring, loc):
raise ParseException(instring, loc, self.errmsg, self)
return loc, []
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "~{" + _ustr(self.expr) + "}"
return self.strRepr
class _MultipleMatch(ParseElementEnhance):
def __init__( self, expr, stopOn=None):
super(_MultipleMatch, self).__init__(expr)
self.saveAsList = True
ender = stopOn
if isinstance(ender, basestring):
ender = ParserElement._literalStringClass(ender)
self.not_ender = ~ender if ender is not None else None
def parseImpl( self, instring, loc, doActions=True ):
self_expr_parse = self.expr._parse
self_skip_ignorables = self._skipIgnorables
check_ender = self.not_ender is not None
if check_ender:
try_not_ender = self.not_ender.tryParse
# must be at least one (but first see if we are the stopOn sentinel;
# if so, fail)
if check_ender:
try_not_ender(instring, loc)
loc, tokens = self_expr_parse( instring, loc, doActions, callPreParse=False )
try:
hasIgnoreExprs = (not not self.ignoreExprs)
while 1:
if check_ender:
try_not_ender(instring, loc)
if hasIgnoreExprs:
preloc = self_skip_ignorables( instring, loc )
else:
preloc = loc
loc, tmptokens = self_expr_parse( instring, preloc, doActions )
if tmptokens or tmptokens.haskeys():
tokens += tmptokens
except (ParseException,IndexError):
pass
return loc, tokens
class OneOrMore(_MultipleMatch):
"""
Repetition of one or more of the given expression.
Parameters:
- expr - expression that must match one or more times
- stopOn - (default=C{None}) - expression for a terminating sentinel
(only required if the sentinel would ordinarily match the repetition
expression)
Example::
data_word = Word(alphas)
label = data_word + FollowedBy(':')
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))
text = "shape: SQUARE posn: upper left color: BLACK"
OneOrMore(attr_expr).parseString(text).pprint() # Fail! read 'color' as data instead of next label -> [['shape', 'SQUARE color']]
# use stopOn attribute for OneOrMore to avoid reading label string as part of the data
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
OneOrMore(attr_expr).parseString(text).pprint() # Better -> [['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'BLACK']]
# could also be written as
(attr_expr * (1,)).parseString(text).pprint()
"""
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "{" + _ustr(self.expr) + "}..."
return self.strRepr
class ZeroOrMore(_MultipleMatch):
"""
Optional repetition of zero or more of the given expression.
Parameters:
- expr - expression that must match zero or more times
- stopOn - (default=C{None}) - expression for a terminating sentinel
(only required if the sentinel would ordinarily match the repetition
expression)
Example: similar to L{OneOrMore}
"""
def __init__( self, expr, stopOn=None):
super(ZeroOrMore,self).__init__(expr, stopOn=stopOn)
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
try:
return super(ZeroOrMore, self).parseImpl(instring, loc, doActions)
except (ParseException,IndexError):
return loc, []
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "[" + _ustr(self.expr) + "]..."
return self.strRepr
class _NullToken(object):
def __bool__(self):
return False
__nonzero__ = __bool__
def __str__(self):
return ""
_optionalNotMatched = _NullToken()
class Optional(ParseElementEnhance):
"""
Optional matching of the given expression.
Parameters:
- expr - expression that must match zero or more times
- default (optional) - value to be returned if the optional expression is not found.
Example::
# US postal code can be a 5-digit zip, plus optional 4-digit qualifier
zip = Combine(Word(nums, exact=5) + Optional('-' + Word(nums, exact=4)))
zip.runTests('''
# traditional ZIP code
12345
# ZIP+4 form
12101-0001
# invalid ZIP
98765-
''')
prints::
# traditional ZIP code
12345
['12345']
# ZIP+4 form
12101-0001
['12101-0001']
# invalid ZIP
98765-
^
FAIL: Expected end of text (at char 5), (line:1, col:6)
"""
def __init__( self, expr, default=_optionalNotMatched ):
super(Optional,self).__init__( expr, savelist=False )
self.saveAsList = self.expr.saveAsList
self.defaultValue = default
self.mayReturnEmpty = True
def parseImpl( self, instring, loc, doActions=True ):
try:
loc, tokens = self.expr._parse( instring, loc, doActions, callPreParse=False )
except (ParseException,IndexError):
if self.defaultValue is not _optionalNotMatched:
if self.expr.resultsName:
tokens = ParseResults([ self.defaultValue ])
tokens[self.expr.resultsName] = self.defaultValue
else:
tokens = [ self.defaultValue ]
else:
tokens = []
return loc, tokens
def __str__( self ):
if hasattr(self,"name"):
return self.name
if self.strRepr is None:
self.strRepr = "[" + _ustr(self.expr) + "]"
return self.strRepr
class SkipTo(ParseElementEnhance):
"""
Token for skipping over all undefined text until the matched expression is found.
Parameters:
- expr - target expression marking the end of the data to be skipped
- include - (default=C{False}) if True, the target expression is also parsed
(the skipped text and target expression are returned as a 2-element list).
- ignore - (default=C{None}) used to define grammars (typically quoted strings and
comments) that might contain false matches to the target expression
- failOn - (default=C{None}) define expressions that are not allowed to be
included in the skipped test; if found before the target expression is found,
the SkipTo is not a match
Example::
report = '''
Outstanding Issues Report - 1 Jan 2000
# | Severity | Description | Days Open
-----+----------+-------------------------------------------+-----------
101 | Critical | Intermittent system crash | 6
94 | Cosmetic | Spelling error on Login ('log|n') | 14
79 | Minor | System slow when running too many reports | 47
'''
integer = Word(nums)
SEP = Suppress('|')
# use SkipTo to simply match everything up until the next SEP
# - ignore quoted strings, so that a '|' character inside a quoted string does not match
# - parse action will call token.strip() for each matched token, i.e., the description body
string_data = SkipTo(SEP, ignore=quotedString)
string_data.setParseAction(tokenMap(str.strip))
ticket_expr = (integer("issue_num") + SEP
+ string_data("sev") + SEP
+ string_data("desc") + SEP
+ integer("days_open"))
for tkt in ticket_expr.searchString(report):
print tkt.dump()
prints::
['101', 'Critical', 'Intermittent system crash', '6']
- days_open: 6
- desc: Intermittent system crash
- issue_num: 101
- sev: Critical
['94', 'Cosmetic', "Spelling error on Login ('log|n')", '14']
- days_open: 14
- desc: Spelling error on Login ('log|n')
- issue_num: 94
- sev: Cosmetic
['79', 'Minor', 'System slow when running too many reports', '47']
- days_open: 47
- desc: System slow when running too many reports
- issue_num: 79
- sev: Minor
"""
def __init__( self, other, include=False, ignore=None, failOn=None ):
super( SkipTo, self ).__init__( other )
self.ignoreExpr = ignore
self.mayReturnEmpty = True
self.mayIndexError = False
self.includeMatch = include
self.asList = False
if isinstance(failOn, basestring):
self.failOn = ParserElement._literalStringClass(failOn)
else:
self.failOn = failOn
self.errmsg = "No match found for "+_ustr(self.expr)
def parseImpl( self, instring, loc, doActions=True ):
startloc = loc
instrlen = len(instring)
expr = self.expr
expr_parse = self.expr._parse
self_failOn_canParseNext = self.failOn.canParseNext if self.failOn is not None else None
self_ignoreExpr_tryParse = self.ignoreExpr.tryParse if self.ignoreExpr is not None else None
tmploc = loc
while tmploc <= instrlen:
if self_failOn_canParseNext is not None:
# break if failOn expression matches
if self_failOn_canParseNext(instring, tmploc):
break
if self_ignoreExpr_tryParse is not None:
# advance past ignore expressions
while 1:
try:
tmploc = self_ignoreExpr_tryParse(instring, tmploc)
except ParseBaseException:
break
try:
expr_parse(instring, tmploc, doActions=False, callPreParse=False)
except (ParseException, IndexError):
# no match, advance loc in string
tmploc += 1
else:
# matched skipto expr, done
break
else:
# ran off the end of the input string without matching skipto expr, fail
raise ParseException(instring, loc, self.errmsg, self)
# build up return values
loc = tmploc
skiptext = instring[startloc:loc]
skipresult = ParseResults(skiptext)
if self.includeMatch:
loc, mat = expr_parse(instring,loc,doActions,callPreParse=False)
skipresult += mat
return loc, skipresult
class Forward(ParseElementEnhance):
"""
Forward declaration of an expression to be defined later -
used for recursive grammars, such as algebraic infix notation.
When the expression is known, it is assigned to the C{Forward} variable using the '<<' operator.
Note: take care when assigning to C{Forward} not to overlook precedence of operators.
Specifically, '|' has a lower precedence than '<<', so that::
fwdExpr << a | b | c
will actually be evaluated as::
(fwdExpr << a) | b | c
thereby leaving b and c out as parseable alternatives. It is recommended that you
explicitly group the values inserted into the C{Forward}::
fwdExpr << (a | b | c)
Converting to use the '<<=' operator instead will avoid this problem.
See L{ParseResults.pprint} for an example of a recursive parser created using
C{Forward}.
"""
def __init__( self, other=None ):
super(Forward,self).__init__( other, savelist=False )
def __lshift__( self, other ):
if isinstance( other, basestring ):
other = ParserElement._literalStringClass(other)
self.expr = other
self.strRepr = None
self.mayIndexError = self.expr.mayIndexError
self.mayReturnEmpty = self.expr.mayReturnEmpty
self.setWhitespaceChars( self.expr.whiteChars )
self.skipWhitespace = self.expr.skipWhitespace
self.saveAsList = self.expr.saveAsList
self.ignoreExprs.extend(self.expr.ignoreExprs)
return self
def __ilshift__(self, other):
return self << other
def leaveWhitespace( self ):
self.skipWhitespace = False
return self
def streamline( self ):
if not self.streamlined:
self.streamlined = True
if self.expr is not None:
self.expr.streamline()
return self
def validate( self, validateTrace=[] ):
if self not in validateTrace:
tmp = validateTrace[:]+[self]
if self.expr is not None:
self.expr.validate(tmp)
self.checkRecursion([])
def __str__( self ):
if hasattr(self,"name"):
return self.name
return self.__class__.__name__ + ": ..."
# stubbed out for now - creates awful memory and perf issues
self._revertClass = self.__class__
self.__class__ = _ForwardNoRecurse
try:
if self.expr is not None:
retString = _ustr(self.expr)
else:
retString = "None"
finally:
self.__class__ = self._revertClass
return self.__class__.__name__ + ": " + retString
def copy(self):
if self.expr is not None:
return super(Forward,self).copy()
else:
ret = Forward()
ret <<= self
return ret
class _ForwardNoRecurse(Forward):
def __str__( self ):
return "..."
class TokenConverter(ParseElementEnhance):
"""
Abstract subclass of C{ParseExpression}, for converting parsed results.
"""
def __init__( self, expr, savelist=False ):
super(TokenConverter,self).__init__( expr )#, savelist )
self.saveAsList = False
class Combine(TokenConverter):
"""
Converter to concatenate all matching tokens to a single string.
By default, the matching patterns must also be contiguous in the input string;
this can be disabled by specifying C{'adjacent=False'} in the constructor.
Example::
real = Word(nums) + '.' + Word(nums)
print(real.parseString('3.1416')) # -> ['3', '.', '1416']
# will also erroneously match the following
print(real.parseString('3. 1416')) # -> ['3', '.', '1416']
real = Combine(Word(nums) + '.' + Word(nums))
print(real.parseString('3.1416')) # -> ['3.1416']
# no match when there are internal spaces
print(real.parseString('3. 1416')) # -> Exception: Expected W:(0123...)
"""
def __init__( self, expr, joinString="", adjacent=True ):
super(Combine,self).__init__( expr )
# suppress whitespace-stripping in contained parse expressions, but re-enable it on the Combine itself
if adjacent:
self.leaveWhitespace()
self.adjacent = adjacent
self.skipWhitespace = True
self.joinString = joinString
self.callPreparse = True
def ignore( self, other ):
if self.adjacent:
ParserElement.ignore(self, other)
else:
super( Combine, self).ignore( other )
return self
def postParse( self, instring, loc, tokenlist ):
retToks = tokenlist.copy()
del retToks[:]
retToks += ParseResults([ "".join(tokenlist._asStringList(self.joinString)) ], modal=self.modalResults)
if self.resultsName and retToks.haskeys():
return [ retToks ]
else:
return retToks
class Group(TokenConverter):
"""
Converter to return the matched tokens as a list - useful for returning tokens of C{L{ZeroOrMore}} and C{L{OneOrMore}} expressions.
Example::
ident = Word(alphas)
num = Word(nums)
term = ident | num
func = ident + Optional(delimitedList(term))
print(func.parseString("fn a,b,100")) # -> ['fn', 'a', 'b', '100']
func = ident + Group(Optional(delimitedList(term)))
print(func.parseString("fn a,b,100")) # -> ['fn', ['a', 'b', '100']]
"""
def __init__( self, expr ):
super(Group,self).__init__( expr )
self.saveAsList = True
def postParse( self, instring, loc, tokenlist ):
return [ tokenlist ]
class Dict(TokenConverter):
"""
Converter to return a repetitive expression as a list, but also as a dictionary.
Each element can also be referenced using the first token in the expression as its key.
Useful for tabular report scraping when the first column can be used as a item key.
Example::
data_word = Word(alphas)
label = data_word + FollowedBy(':')
attr_expr = Group(label + Suppress(':') + OneOrMore(data_word).setParseAction(' '.join))
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
# print attributes as plain groups
print(OneOrMore(attr_expr).parseString(text).dump())
# instead of OneOrMore(expr), parse using Dict(OneOrMore(Group(expr))) - Dict will auto-assign names
result = Dict(OneOrMore(Group(attr_expr))).parseString(text)
print(result.dump())
# access named fields as dict entries, or output as dict
print(result['shape'])
print(result.asDict())
prints::
['shape', 'SQUARE', 'posn', 'upper left', 'color', 'light blue', 'texture', 'burlap']
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
{'color': 'light blue', 'posn': 'upper left', 'texture': 'burlap', 'shape': 'SQUARE'}
See more examples at L{ParseResults} of accessing fields by results name.
"""
def __init__( self, expr ):
super(Dict,self).__init__( expr )
self.saveAsList = True
def postParse( self, instring, loc, tokenlist ):
for i,tok in enumerate(tokenlist):
if len(tok) == 0:
continue
ikey = tok[0]
if isinstance(ikey,int):
ikey = _ustr(tok[0]).strip()
if len(tok)==1:
tokenlist[ikey] = _ParseResultsWithOffset("",i)
elif len(tok)==2 and not isinstance(tok[1],ParseResults):
tokenlist[ikey] = _ParseResultsWithOffset(tok[1],i)
else:
dictvalue = tok.copy() #ParseResults(i)
del dictvalue[0]
if len(dictvalue)!= 1 or (isinstance(dictvalue,ParseResults) and dictvalue.haskeys()):
tokenlist[ikey] = _ParseResultsWithOffset(dictvalue,i)
else:
tokenlist[ikey] = _ParseResultsWithOffset(dictvalue[0],i)
if self.resultsName:
return [ tokenlist ]
else:
return tokenlist
class Suppress(TokenConverter):
"""
Converter for ignoring the results of a parsed expression.
Example::
source = "a, b, c,d"
wd = Word(alphas)
wd_list1 = wd + ZeroOrMore(',' + wd)
print(wd_list1.parseString(source))
# often, delimiters that are useful during parsing are just in the
# way afterward - use Suppress to keep them out of the parsed output
wd_list2 = wd + ZeroOrMore(Suppress(',') + wd)
print(wd_list2.parseString(source))
prints::
['a', ',', 'b', ',', 'c', ',', 'd']
['a', 'b', 'c', 'd']
(See also L{delimitedList}.)
"""
def postParse( self, instring, loc, tokenlist ):
return []
def suppress( self ):
return self
class OnlyOnce(object):
"""
Wrapper for parse actions, to ensure they are only called once.
"""
def __init__(self, methodCall):
self.callable = _trim_arity(methodCall)
self.called = False
def __call__(self,s,l,t):
if not self.called:
results = self.callable(s,l,t)
self.called = True
return results
raise ParseException(s,l,"")
def reset(self):
self.called = False
def traceParseAction(f):
"""
Decorator for debugging parse actions.
When the parse action is called, this decorator will print C{">> entering I{method-name}(line:I{current_source_line}, I{parse_location}, I{matched_tokens})".}
When the parse action completes, the decorator will print C{"<<"} followed by the returned value, or any exception that the parse action raised.
Example::
wd = Word(alphas)
@traceParseAction
def remove_duplicate_chars(tokens):
return ''.join(sorted(set(''.join(tokens)))
wds = OneOrMore(wd).setParseAction(remove_duplicate_chars)
print(wds.parseString("slkdjs sld sldd sdlf sdljf"))
prints::
>>entering remove_duplicate_chars(line: 'slkdjs sld sldd sdlf sdljf', 0, (['slkdjs', 'sld', 'sldd', 'sdlf', 'sdljf'], {}))
<<leaving remove_duplicate_chars (ret: 'dfjkls')
['dfjkls']
"""
f = _trim_arity(f)
def z(*paArgs):
thisFunc = f.__name__
s,l,t = paArgs[-3:]
if len(paArgs)>3:
thisFunc = paArgs[0].__class__.__name__ + '.' + thisFunc
sys.stderr.write( ">>entering %s(line: '%s', %d, %r)\n" % (thisFunc,line(l,s),l,t) )
try:
ret = f(*paArgs)
except Exception as exc:
sys.stderr.write( "<<leaving %s (exception: %s)\n" % (thisFunc,exc) )
raise
sys.stderr.write( "<<leaving %s (ret: %r)\n" % (thisFunc,ret) )
return ret
try:
z.__name__ = f.__name__
except AttributeError:
pass
return z
#
# global helpers
#
def delimitedList( expr, delim=",", combine=False ):
"""
Helper to define a delimited list of expressions - the delimiter defaults to ','.
By default, the list elements and delimiters can have intervening whitespace, and
comments, but this can be overridden by passing C{combine=True} in the constructor.
If C{combine} is set to C{True}, the matching tokens are returned as a single token
string, with the delimiters included; otherwise, the matching tokens are returned
as a list of tokens, with the delimiters suppressed.
Example::
delimitedList(Word(alphas)).parseString("aa,bb,cc") # -> ['aa', 'bb', 'cc']
delimitedList(Word(hexnums), delim=':', combine=True).parseString("AA:BB:CC:DD:EE") # -> ['AA:BB:CC:DD:EE']
"""
dlName = _ustr(expr)+" ["+_ustr(delim)+" "+_ustr(expr)+"]..."
if combine:
return Combine( expr + ZeroOrMore( delim + expr ) ).setName(dlName)
else:
return ( expr + ZeroOrMore( Suppress( delim ) + expr ) ).setName(dlName)
def countedArray( expr, intExpr=None ):
"""
Helper to define a counted list of expressions.
This helper defines a pattern of the form::
integer expr expr expr...
where the leading integer tells how many expr expressions follow.
The matched tokens returns the array of expr tokens as a list - the leading count token is suppressed.
If C{intExpr} is specified, it should be a pyparsing expression that produces an integer value.
Example::
countedArray(Word(alphas)).parseString('2 ab cd ef') # -> ['ab', 'cd']
# in this parser, the leading integer value is given in binary,
# '10' indicating that 2 values are in the array
binaryConstant = Word('01').setParseAction(lambda t: int(t[0], 2))
countedArray(Word(alphas), intExpr=binaryConstant).parseString('10 ab cd ef') # -> ['ab', 'cd']
"""
arrayExpr = Forward()
def countFieldParseAction(s,l,t):
n = t[0]
arrayExpr << (n and Group(And([expr]*n)) or Group(empty))
return []
if intExpr is None:
intExpr = Word(nums).setParseAction(lambda t:int(t[0]))
else:
intExpr = intExpr.copy()
intExpr.setName("arrayLen")
intExpr.addParseAction(countFieldParseAction, callDuringTry=True)
return ( intExpr + arrayExpr ).setName('(len) ' + _ustr(expr) + '...')
def _flatten(L):
ret = []
for i in L:
if isinstance(i,list):
ret.extend(_flatten(i))
else:
ret.append(i)
return ret
def matchPreviousLiteral(expr):
"""
Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousLiteral(first)
matchExpr = first + ":" + second
will match C{"1:1"}, but not C{"1:2"}. Because this matches a
previous literal, will also match the leading C{"1:1"} in C{"1:10"}.
If this is not desired, use C{matchPreviousExpr}.
Do I{not} use with packrat parsing enabled.
"""
rep = Forward()
def copyTokenToRepeater(s,l,t):
if t:
if len(t) == 1:
rep << t[0]
else:
# flatten t tokens
tflat = _flatten(t.asList())
rep << And(Literal(tt) for tt in tflat)
else:
rep << Empty()
expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
rep.setName('(prev) ' + _ustr(expr))
return rep
def matchPreviousExpr(expr):
"""
Helper to define an expression that is indirectly defined from
the tokens matched in a previous expression, that is, it looks
for a 'repeat' of a previous expression. For example::
first = Word(nums)
second = matchPreviousExpr(first)
matchExpr = first + ":" + second
will match C{"1:1"}, but not C{"1:2"}. Because this matches by
expressions, will I{not} match the leading C{"1:1"} in C{"1:10"};
the expressions are evaluated first, and then compared, so
C{"1"} is compared with C{"10"}.
Do I{not} use with packrat parsing enabled.
"""
rep = Forward()
e2 = expr.copy()
rep <<= e2
def copyTokenToRepeater(s,l,t):
matchTokens = _flatten(t.asList())
def mustMatchTheseTokens(s,l,t):
theseTokens = _flatten(t.asList())
if theseTokens != matchTokens:
raise ParseException("",0,"")
rep.setParseAction( mustMatchTheseTokens, callDuringTry=True )
expr.addParseAction(copyTokenToRepeater, callDuringTry=True)
rep.setName('(prev) ' + _ustr(expr))
return rep
def _escapeRegexRangeChars(s):
#~ escape these chars: ^-]
for c in r"\^-]":
s = s.replace(c,_bslash+c)
s = s.replace("\n",r"\n")
s = s.replace("\t",r"\t")
return _ustr(s)
def oneOf( strs, caseless=False, useRegex=True ):
"""
Helper to quickly define a set of alternative Literals, and makes sure to do
longest-first testing when there is a conflict, regardless of the input order,
but returns a C{L{MatchFirst}} for best performance.
Parameters:
- strs - a string of space-delimited literals, or a collection of string literals
- caseless - (default=C{False}) - treat all literals as caseless
- useRegex - (default=C{True}) - as an optimization, will generate a Regex
object; otherwise, will generate a C{MatchFirst} object (if C{caseless=True}, or
if creating a C{Regex} raises an exception)
Example::
comp_oper = oneOf("< = > <= >= !=")
var = Word(alphas)
number = Word(nums)
term = var | number
comparison_expr = term + comp_oper + term
print(comparison_expr.searchString("B = 12 AA=23 B<=AA AA>12"))
prints::
[['B', '=', '12'], ['AA', '=', '23'], ['B', '<=', 'AA'], ['AA', '>', '12']]
"""
if caseless:
isequal = ( lambda a,b: a.upper() == b.upper() )
masks = ( lambda a,b: b.upper().startswith(a.upper()) )
parseElementClass = CaselessLiteral
else:
isequal = ( lambda a,b: a == b )
masks = ( lambda a,b: b.startswith(a) )
parseElementClass = Literal
symbols = []
if isinstance(strs,basestring):
symbols = strs.split()
elif isinstance(strs, collections.Iterable):
symbols = list(strs)
else:
warnings.warn("Invalid argument to oneOf, expected string or iterable",
SyntaxWarning, stacklevel=2)
if not symbols:
return NoMatch()
i = 0
while i < len(symbols)-1:
cur = symbols[i]
for j,other in enumerate(symbols[i+1:]):
if ( isequal(other, cur) ):
del symbols[i+j+1]
break
elif ( masks(cur, other) ):
del symbols[i+j+1]
symbols.insert(i,other)
cur = other
break
else:
i += 1
if not caseless and useRegex:
#~ print (strs,"->", "|".join( [ _escapeRegexChars(sym) for sym in symbols] ))
try:
if len(symbols)==len("".join(symbols)):
return Regex( "[%s]" % "".join(_escapeRegexRangeChars(sym) for sym in symbols) ).setName(' | '.join(symbols))
else:
return Regex( "|".join(re.escape(sym) for sym in symbols) ).setName(' | '.join(symbols))
except Exception:
warnings.warn("Exception creating Regex for oneOf, building MatchFirst",
SyntaxWarning, stacklevel=2)
# last resort, just use MatchFirst
return MatchFirst(parseElementClass(sym) for sym in symbols).setName(' | '.join(symbols))
def dictOf( key, value ):
"""
Helper to easily and clearly define a dictionary by specifying the respective patterns
for the key and value. Takes care of defining the C{L{Dict}}, C{L{ZeroOrMore}}, and C{L{Group}} tokens
in the proper order. The key pattern can include delimiting markers or punctuation,
as long as they are suppressed, thereby leaving the significant key text. The value
pattern can include named results, so that the C{Dict} results can include named token
fields.
Example::
text = "shape: SQUARE posn: upper left color: light blue texture: burlap"
attr_expr = (label + Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join))
print(OneOrMore(attr_expr).parseString(text).dump())
attr_label = label
attr_value = Suppress(':') + OneOrMore(data_word, stopOn=label).setParseAction(' '.join)
# similar to Dict, but simpler call format
result = dictOf(attr_label, attr_value).parseString(text)
print(result.dump())
print(result['shape'])
print(result.shape) # object attribute access works too
print(result.asDict())
prints::
[['shape', 'SQUARE'], ['posn', 'upper left'], ['color', 'light blue'], ['texture', 'burlap']]
- color: light blue
- posn: upper left
- shape: SQUARE
- texture: burlap
SQUARE
SQUARE
{'color': 'light blue', 'shape': 'SQUARE', 'posn': 'upper left', 'texture': 'burlap'}
"""
return Dict( ZeroOrMore( Group ( key + value ) ) )
def originalTextFor(expr, asString=True):
"""
Helper to return the original, untokenized text for a given expression. Useful to
restore the parsed fields of an HTML start tag into the raw tag text itself, or to
revert separate tokens with intervening whitespace back to the original matching
input text. By default, returns astring containing the original parsed text.
If the optional C{asString} argument is passed as C{False}, then the return value is a
C{L{ParseResults}} containing any results names that were originally matched, and a
single token containing the original matched text from the input string. So if
the expression passed to C{L{originalTextFor}} contains expressions with defined
results names, you must set C{asString} to C{False} if you want to preserve those
results name values.
Example::
src = "this is test <b> bold <i>text</i> </b> normal text "
for tag in ("b","i"):
opener,closer = makeHTMLTags(tag)
patt = originalTextFor(opener + SkipTo(closer) + closer)
print(patt.searchString(src)[0])
prints::
['<b> bold <i>text</i> </b>']
['<i>text</i>']
"""
locMarker = Empty().setParseAction(lambda s,loc,t: loc)
endlocMarker = locMarker.copy()
endlocMarker.callPreparse = False
matchExpr = locMarker("_original_start") + expr + endlocMarker("_original_end")
if asString:
extractText = lambda s,l,t: s[t._original_start:t._original_end]
else:
def extractText(s,l,t):
t[:] = [s[t.pop('_original_start'):t.pop('_original_end')]]
matchExpr.setParseAction(extractText)
matchExpr.ignoreExprs = expr.ignoreExprs
return matchExpr
def ungroup(expr):
"""
Helper to undo pyparsing's default grouping of And expressions, even
if all but one are non-empty.
"""
return TokenConverter(expr).setParseAction(lambda t:t[0])
def locatedExpr(expr):
"""
Helper to decorate a returned token with its starting and ending locations in the input string.
This helper adds the following results names:
- locn_start = location where matched expression begins
- locn_end = location where matched expression ends
- value = the actual parsed results
Be careful if the input text contains C{<TAB>} characters, you may want to call
C{L{ParserElement.parseWithTabs}}
Example::
wd = Word(alphas)
for match in locatedExpr(wd).searchString("ljsdf123lksdjjf123lkkjj1222"):
print(match)
prints::
[[0, 'ljsdf', 5]]
[[8, 'lksdjjf', 15]]
[[18, 'lkkjj', 23]]
"""
locator = Empty().setParseAction(lambda s,l,t: l)
return Group(locator("locn_start") + expr("value") + locator.copy().leaveWhitespace()("locn_end"))
# convenience constants for positional expressions
empty = Empty().setName("empty")
lineStart = LineStart().setName("lineStart")
lineEnd = LineEnd().setName("lineEnd")
stringStart = StringStart().setName("stringStart")
stringEnd = StringEnd().setName("stringEnd")
_escapedPunc = Word( _bslash, r"\[]-*.$+^?()~ ", exact=2 ).setParseAction(lambda s,l,t:t[0][1])
_escapedHexChar = Regex(r"\\0?[xX][0-9a-fA-F]+").setParseAction(lambda s,l,t:unichr(int(t[0].lstrip(r'\0x'),16)))
_escapedOctChar = Regex(r"\\0[0-7]+").setParseAction(lambda s,l,t:unichr(int(t[0][1:],8)))
_singleChar = _escapedPunc | _escapedHexChar | _escapedOctChar | Word(printables, excludeChars=r'\]', exact=1) | Regex(r"\w", re.UNICODE)
_charRange = Group(_singleChar + Suppress("-") + _singleChar)
_reBracketExpr = Literal("[") + Optional("^").setResultsName("negate") + Group( OneOrMore( _charRange | _singleChar ) ).setResultsName("body") + "]"
def srange(s):
r"""
Helper to easily define string ranges for use in Word construction. Borrows
syntax from regexp '[]' string range definitions::
srange("[0-9]") -> "0123456789"
srange("[a-z]") -> "abcdefghijklmnopqrstuvwxyz"
srange("[a-z$_]") -> "abcdefghijklmnopqrstuvwxyz$_"
The input string must be enclosed in []'s, and the returned string is the expanded
character set joined into a single string.
The values enclosed in the []'s may be:
- a single character
- an escaped character with a leading backslash (such as C{\-} or C{\]})
- an escaped hex character with a leading C{'\x'} (C{\x21}, which is a C{'!'} character)
(C{\0x##} is also supported for backwards compatibility)
- an escaped octal character with a leading C{'\0'} (C{\041}, which is a C{'!'} character)
- a range of any of the above, separated by a dash (C{'a-z'}, etc.)
- any combination of the above (C{'aeiouy'}, C{'a-zA-Z0-9_$'}, etc.)
"""
_expanded = lambda p: p if not isinstance(p,ParseResults) else ''.join(unichr(c) for c in range(ord(p[0]),ord(p[1])+1))
try:
return "".join(_expanded(part) for part in _reBracketExpr.parseString(s).body)
except Exception:
return ""
def matchOnlyAtCol(n):
"""
Helper method for defining parse actions that require matching at a specific
column in the input text.
"""
def verifyCol(strg,locn,toks):
if col(locn,strg) != n:
raise ParseException(strg,locn,"matched token not at column %d" % n)
return verifyCol
def replaceWith(replStr):
"""
Helper method for common parse actions that simply return a literal value. Especially
useful when used with C{L{transformString<ParserElement.transformString>}()}.
Example::
num = Word(nums).setParseAction(lambda toks: int(toks[0]))
na = oneOf("N/A NA").setParseAction(replaceWith(math.nan))
term = na | num
OneOrMore(term).parseString("324 234 N/A 234") # -> [324, 234, nan, 234]
"""
return lambda s,l,t: [replStr]
def removeQuotes(s,l,t):
"""
Helper parse action for removing quotation marks from parsed quoted strings.
Example::
# by default, quotation marks are included in parsed results
quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"]
# use removeQuotes to strip quotation marks from parsed results
quotedString.setParseAction(removeQuotes)
quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
"""
return t[0][1:-1]
def tokenMap(func, *args):
"""
Helper to define a parse action by mapping a function to all elements of a ParseResults list.If any additional
args are passed, they are forwarded to the given function as additional arguments after
the token, as in C{hex_integer = Word(hexnums).setParseAction(tokenMap(int, 16))}, which will convert the
parsed data to an integer using base 16.
Example (compare the last to example in L{ParserElement.transformString}::
hex_ints = OneOrMore(Word(hexnums)).setParseAction(tokenMap(int, 16))
hex_ints.runTests('''
00 11 22 aa FF 0a 0d 1a
''')
upperword = Word(alphas).setParseAction(tokenMap(str.upper))
OneOrMore(upperword).runTests('''
my kingdom for a horse
''')
wd = Word(alphas).setParseAction(tokenMap(str.title))
OneOrMore(wd).setParseAction(' '.join).runTests('''
now is the winter of our discontent made glorious summer by this sun of york
''')
prints::
00 11 22 aa FF 0a 0d 1a
[0, 17, 34, 170, 255, 10, 13, 26]
my kingdom for a horse
['MY', 'KINGDOM', 'FOR', 'A', 'HORSE']
now is the winter of our discontent made glorious summer by this sun of york
['Now Is The Winter Of Our Discontent Made Glorious Summer By This Sun Of York']
"""
def pa(s,l,t):
return [func(tokn, *args) for tokn in t]
try:
func_name = getattr(func, '__name__',
getattr(func, '__class__').__name__)
except Exception:
func_name = str(func)
pa.__name__ = func_name
return pa
upcaseTokens = tokenMap(lambda t: _ustr(t).upper())
"""(Deprecated) Helper parse action to convert tokens to upper case. Deprecated in favor of L{pyparsing_common.upcaseTokens}"""
downcaseTokens = tokenMap(lambda t: _ustr(t).lower())
"""(Deprecated) Helper parse action to convert tokens to lower case. Deprecated in favor of L{pyparsing_common.downcaseTokens}"""
def _makeTags(tagStr, xml):
"""Internal helper to construct opening and closing tag expressions, given a tag name"""
if isinstance(tagStr,basestring):
resname = tagStr
tagStr = Keyword(tagStr, caseless=not xml)
else:
resname = tagStr.name
tagAttrName = Word(alphas,alphanums+"_-:")
if (xml):
tagAttrValue = dblQuotedString.copy().setParseAction( removeQuotes )
openTag = Suppress("<") + tagStr("tag") + \
Dict(ZeroOrMore(Group( tagAttrName + Suppress("=") + tagAttrValue ))) + \
Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
else:
printablesLessRAbrack = "".join(c for c in printables if c not in ">")
tagAttrValue = quotedString.copy().setParseAction( removeQuotes ) | Word(printablesLessRAbrack)
openTag = Suppress("<") + tagStr("tag") + \
Dict(ZeroOrMore(Group( tagAttrName.setParseAction(downcaseTokens) + \
Optional( Suppress("=") + tagAttrValue ) ))) + \
Optional("/",default=[False]).setResultsName("empty").setParseAction(lambda s,l,t:t[0]=='/') + Suppress(">")
closeTag = Combine(_L("</") + tagStr + ">")
openTag = openTag.setResultsName("start"+"".join(resname.replace(":"," ").title().split())).setName("<%s>" % resname)
closeTag = closeTag.setResultsName("end"+"".join(resname.replace(":"," ").title().split())).setName("</%s>" % resname)
openTag.tag = resname
closeTag.tag = resname
return openTag, closeTag
def makeHTMLTags(tagStr):
"""
Helper to construct opening and closing tag expressions for HTML, given a tag name. Matches
tags in either upper or lower case, attributes with namespaces and with quoted or unquoted values.
Example::
text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
# makeHTMLTags returns pyparsing expressions for the opening and closing tags as a 2-tuple
a,a_end = makeHTMLTags("A")
link_expr = a + SkipTo(a_end)("link_text") + a_end
for link in link_expr.searchString(text):
# attributes in the <A> tag (like "href" shown here) are also accessible as named results
print(link.link_text, '->', link.href)
prints::
pyparsing -> http://pyparsing.wikispaces.com
"""
return _makeTags( tagStr, False )
def makeXMLTags(tagStr):
"""
Helper to construct opening and closing tag expressions for XML, given a tag name. Matches
tags only in the given upper/lower case.
Example: similar to L{makeHTMLTags}
"""
return _makeTags( tagStr, True )
def withAttribute(*args,**attrDict):
"""
Helper to create a validating parse action to be used with start tags created
with C{L{makeXMLTags}} or C{L{makeHTMLTags}}. Use C{withAttribute} to qualify a starting tag
with a required attribute value, to avoid false matches on common tags such as
C{<TD>} or C{<DIV>}.
Call C{withAttribute} with a series of attribute names and values. Specify the list
of filter attributes names and values as:
- keyword arguments, as in C{(align="right")}, or
- as an explicit dict with C{**} operator, when an attribute name is also a Python
reserved word, as in C{**{"class":"Customer", "align":"right"}}
- a list of name-value tuples, as in ( ("ns1:class", "Customer"), ("ns2:align","right") )
For attribute names with a namespace prefix, you must use the second form. Attribute
names are matched insensitive to upper/lower case.
If just testing for C{class} (with or without a namespace), use C{L{withClass}}.
To verify that the attribute exists, but without specifying a value, pass
C{withAttribute.ANY_VALUE} as the value.
Example::
html = '''
<div>
Some text
<div type="grid">1 4 0 1 0</div>
<div type="graph">1,3 2,3 1,1</div>
<div>this has no type</div>
</div>
'''
div,div_end = makeHTMLTags("div")
# only match div tag having a type attribute with value "grid"
div_grid = div().setParseAction(withAttribute(type="grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
# construct a match with any div tag having a type attribute, regardless of the value
div_any_type = div().setParseAction(withAttribute(type=withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
"""
if args:
attrs = args[:]
else:
attrs = attrDict.items()
attrs = [(k,v) for k,v in attrs]
def pa(s,l,tokens):
for attrName,attrValue in attrs:
if attrName not in tokens:
raise ParseException(s,l,"no matching attribute " + attrName)
if attrValue != withAttribute.ANY_VALUE and tokens[attrName] != attrValue:
raise ParseException(s,l,"attribute '%s' has value '%s', must be '%s'" %
(attrName, tokens[attrName], attrValue))
return pa
withAttribute.ANY_VALUE = object()
def withClass(classname, namespace=''):
"""
Simplified version of C{L{withAttribute}} when matching on a div class - made
difficult because C{class} is a reserved word in Python.
Example::
html = '''
<div>
Some text
<div class="grid">1 4 0 1 0</div>
<div class="graph">1,3 2,3 1,1</div>
<div>this <div> has no class</div>
</div>
'''
div,div_end = makeHTMLTags("div")
div_grid = div().setParseAction(withClass("grid"))
grid_expr = div_grid + SkipTo(div | div_end)("body")
for grid_header in grid_expr.searchString(html):
print(grid_header.body)
div_any_type = div().setParseAction(withClass(withAttribute.ANY_VALUE))
div_expr = div_any_type + SkipTo(div | div_end)("body")
for div_header in div_expr.searchString(html):
print(div_header.body)
prints::
1 4 0 1 0
1 4 0 1 0
1,3 2,3 1,1
"""
classattr = "%s:class" % namespace if namespace else "class"
return withAttribute(**{classattr : classname})
opAssoc = _Constants()
opAssoc.LEFT = object()
opAssoc.RIGHT = object()
def infixNotation( baseExpr, opList, lpar=Suppress('('), rpar=Suppress(')') ):
"""
Helper method for constructing grammars of expressions made up of
operators working in a precedence hierarchy. Operators may be unary or
binary, left- or right-associative. Parse actions can also be attached
to operator expressions. The generated parser will also recognize the use
of parentheses to override operator precedences (see example below).
Note: if you define a deep operator list, you may see performance issues
when using infixNotation. See L{ParserElement.enablePackrat} for a
mechanism to potentially improve your parser performance.
Parameters:
- baseExpr - expression representing the most basic element for the nested
- opList - list of tuples, one for each operator precedence level in the
expression grammar; each tuple is of the form
(opExpr, numTerms, rightLeftAssoc, parseAction), where:
- opExpr is the pyparsing expression for the operator;
may also be a string, which will be converted to a Literal;
if numTerms is 3, opExpr is a tuple of two expressions, for the
two operators separating the 3 terms
- numTerms is the number of terms for this operator (must
be 1, 2, or 3)
- rightLeftAssoc is the indicator whether the operator is
right or left associative, using the pyparsing-defined
constants C{opAssoc.RIGHT} and C{opAssoc.LEFT}.
- parseAction is the parse action to be associated with
expressions matching this operator expression (the
parse action tuple member may be omitted)
- lpar - expression for matching left-parentheses (default=C{Suppress('(')})
- rpar - expression for matching right-parentheses (default=C{Suppress(')')})
Example::
# simple example of four-function arithmetic with ints and variable names
integer = pyparsing_common.signed_integer
varname = pyparsing_common.identifier
arith_expr = infixNotation(integer | varname,
[
('-', 1, opAssoc.RIGHT),
(oneOf('* /'), 2, opAssoc.LEFT),
(oneOf('+ -'), 2, opAssoc.LEFT),
])
arith_expr.runTests('''
5+3*6
(5+3)*6
-2--11
''', fullDump=False)
prints::
5+3*6
[[5, '+', [3, '*', 6]]]
(5+3)*6
[[[5, '+', 3], '*', 6]]
-2--11
[[['-', 2], '-', ['-', 11]]]
"""
ret = Forward()
lastExpr = baseExpr | ( lpar + ret + rpar )
for i,operDef in enumerate(opList):
opExpr,arity,rightLeftAssoc,pa = (operDef + (None,))[:4]
termName = "%s term" % opExpr if arity < 3 else "%s%s term" % opExpr
if arity == 3:
if opExpr is None or len(opExpr) != 2:
raise ValueError("if numterms=3, opExpr must be a tuple or list of two expressions")
opExpr1, opExpr2 = opExpr
thisExpr = Forward().setName(termName)
if rightLeftAssoc == opAssoc.LEFT:
if arity == 1:
matchExpr = FollowedBy(lastExpr + opExpr) + Group( lastExpr + OneOrMore( opExpr ) )
elif arity == 2:
if opExpr is not None:
matchExpr = FollowedBy(lastExpr + opExpr + lastExpr) + Group( lastExpr + OneOrMore( opExpr + lastExpr ) )
else:
matchExpr = FollowedBy(lastExpr+lastExpr) + Group( lastExpr + OneOrMore(lastExpr) )
elif arity == 3:
matchExpr = FollowedBy(lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr) + \
Group( lastExpr + opExpr1 + lastExpr + opExpr2 + lastExpr )
else:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
elif rightLeftAssoc == opAssoc.RIGHT:
if arity == 1:
# try to avoid LR with this extra test
if not isinstance(opExpr, Optional):
opExpr = Optional(opExpr)
matchExpr = FollowedBy(opExpr.expr + thisExpr) + Group( opExpr + thisExpr )
elif arity == 2:
if opExpr is not None:
matchExpr = FollowedBy(lastExpr + opExpr + thisExpr) + Group( lastExpr + OneOrMore( opExpr + thisExpr ) )
else:
matchExpr = FollowedBy(lastExpr + thisExpr) + Group( lastExpr + OneOrMore( thisExpr ) )
elif arity == 3:
matchExpr = FollowedBy(lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr) + \
Group( lastExpr + opExpr1 + thisExpr + opExpr2 + thisExpr )
else:
raise ValueError("operator must be unary (1), binary (2), or ternary (3)")
else:
raise ValueError("operator must indicate right or left associativity")
if pa:
matchExpr.setParseAction( pa )
thisExpr <<= ( matchExpr.setName(termName) | lastExpr )
lastExpr = thisExpr
ret <<= lastExpr
return ret
operatorPrecedence = infixNotation
"""(Deprecated) Former name of C{L{infixNotation}}, will be dropped in a future release."""
dblQuotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*')+'"').setName("string enclosed in double quotes")
sglQuotedString = Combine(Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*")+"'").setName("string enclosed in single quotes")
quotedString = Combine(Regex(r'"(?:[^"\n\r\\]|(?:"")|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*')+'"'|
Regex(r"'(?:[^'\n\r\\]|(?:'')|(?:\\(?:[^x]|x[0-9a-fA-F]+)))*")+"'").setName("quotedString using single or double quotes")
unicodeString = Combine(_L('u') + quotedString.copy()).setName("unicode string literal")
def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()):
"""
Helper method for defining nested lists enclosed in opening and closing
delimiters ("(" and ")" are the default).
Parameters:
- opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression
- closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression
- content - expression for items within the nested lists (default=C{None})
- ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString})
If an expression is not provided for the content argument, the nested
expression will capture all whitespace-delimited content between delimiters
as a list of separate values.
Use the C{ignoreExpr} argument to define expressions that may contain
opening or closing characters that should not be treated as opening
or closing characters for nesting, such as quotedString or a comment
expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}.
The default is L{quotedString}, but if no expressions are to be ignored,
then pass C{None} for this argument.
Example::
data_type = oneOf("void int short long char float double")
decl_data_type = Combine(data_type + Optional(Word('*')))
ident = Word(alphas+'_', alphanums+'_')
number = pyparsing_common.number
arg = Group(decl_data_type + ident)
LPAR,RPAR = map(Suppress, "()")
code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment))
c_function = (decl_data_type("type")
+ ident("name")
+ LPAR + Optional(delimitedList(arg), [])("args") + RPAR
+ code_body("body"))
c_function.ignore(cStyleComment)
source_code = '''
int is_odd(int x) {
return (x%2);
}
int dec_to_hex(char hchar) {
if (hchar >= '0' && hchar <= '9') {
return (ord(hchar)-ord('0'));
} else {
return (10+ord(hchar)-ord('A'));
}
}
'''
for func in c_function.searchString(source_code):
print("%(name)s (%(type)s) args: %(args)s" % func)
prints::
is_odd (int) args: [['int', 'x']]
dec_to_hex (int) args: [['char', 'hchar']]
"""
if opener == closer:
raise ValueError("opening and closing strings cannot be the same")
if content is None:
if isinstance(opener,basestring) and isinstance(closer,basestring):
if len(opener) == 1 and len(closer)==1:
if ignoreExpr is not None:
content = (Combine(OneOrMore(~ignoreExpr +
CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1))
).setParseAction(lambda t:t[0].strip()))
else:
content = (empty.copy()+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS
).setParseAction(lambda t:t[0].strip()))
else:
if ignoreExpr is not None:
content = (Combine(OneOrMore(~ignoreExpr +
~Literal(opener) + ~Literal(closer) +
CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
).setParseAction(lambda t:t[0].strip()))
else:
content = (Combine(OneOrMore(~Literal(opener) + ~Literal(closer) +
CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1))
).setParseAction(lambda t:t[0].strip()))
else:
raise ValueError("opening and closing arguments must be strings if no content expression is given")
ret = Forward()
if ignoreExpr is not None:
ret <<= Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) )
else:
ret <<= Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) )
ret.setName('nested %s%s expression' % (opener,closer))
return ret
def indentedBlock(blockStatementExpr, indentStack, indent=True):
"""
Helper method for defining space-delimited indentation blocks, such as
those used to define block statements in Python source code.
Parameters:
- blockStatementExpr - expression defining syntax of statement that
is repeated within the indented block
- indentStack - list created by caller to manage indentation stack
(multiple statementWithIndentedBlock expressions within a single grammar
should share a common indentStack)
- indent - boolean indicating whether block must be indented beyond the
the current level; set to False for block of left-most statements
(default=C{True})
A valid block must contain at least one C{blockStatement}.
Example::
data = '''
def A(z):
A1
B = 100
G = A2
A2
A3
B
def BB(a,b,c):
BB1
def BBA():
bba1
bba2
bba3
C
D
def spam(x,y):
def eggs(z):
pass
'''
indentStack = [1]
stmt = Forward()
identifier = Word(alphas, alphanums)
funcDecl = ("def" + identifier + Group( "(" + Optional( delimitedList(identifier) ) + ")" ) + ":")
func_body = indentedBlock(stmt, indentStack)
funcDef = Group( funcDecl + func_body )
rvalue = Forward()
funcCall = Group(identifier + "(" + Optional(delimitedList(rvalue)) + ")")
rvalue << (funcCall | identifier | Word(nums))
assignment = Group(identifier + "=" + rvalue)
stmt << ( funcDef | assignment | identifier )
module_body = OneOrMore(stmt)
parseTree = module_body.parseString(data)
parseTree.pprint()
prints::
[['def',
'A',
['(', 'z', ')'],
':',
[['A1'], [['B', '=', '100']], [['G', '=', 'A2']], ['A2'], ['A3']]],
'B',
['def',
'BB',
['(', 'a', 'b', 'c', ')'],
':',
[['BB1'], [['def', 'BBA', ['(', ')'], ':', [['bba1'], ['bba2'], ['bba3']]]]]],
'C',
'D',
['def',
'spam',
['(', 'x', 'y', ')'],
':',
[[['def', 'eggs', ['(', 'z', ')'], ':', [['pass']]]]]]]
"""
def checkPeerIndent(s,l,t):
if l >= len(s): return
curCol = col(l,s)
if curCol != indentStack[-1]:
if curCol > indentStack[-1]:
raise ParseFatalException(s,l,"illegal nesting")
raise ParseException(s,l,"not a peer entry")
def checkSubIndent(s,l,t):
curCol = col(l,s)
if curCol > indentStack[-1]:
indentStack.append( curCol )
else:
raise ParseException(s,l,"not a subentry")
def checkUnindent(s,l,t):
if l >= len(s): return
curCol = col(l,s)
if not(indentStack and curCol < indentStack[-1] and curCol <= indentStack[-2]):
raise ParseException(s,l,"not an unindent")
indentStack.pop()
NL = OneOrMore(LineEnd().setWhitespaceChars("\t ").suppress())
INDENT = (Empty() + Empty().setParseAction(checkSubIndent)).setName('INDENT')
PEER = Empty().setParseAction(checkPeerIndent).setName('')
UNDENT = Empty().setParseAction(checkUnindent).setName('UNINDENT')
if indent:
smExpr = Group( Optional(NL) +
#~ FollowedBy(blockStatementExpr) +
INDENT + (OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) + UNDENT)
else:
smExpr = Group( Optional(NL) +
(OneOrMore( PEER + Group(blockStatementExpr) + Optional(NL) )) )
blockStatementExpr.ignore(_bslash + LineEnd())
return smExpr.setName('indented block')
alphas8bit = srange(r"[\0xc0-\0xd6\0xd8-\0xf6\0xf8-\0xff]")
punc8bit = srange(r"[\0xa1-\0xbf\0xd7\0xf7]")
anyOpenTag,anyCloseTag = makeHTMLTags(Word(alphas,alphanums+"_:").setName('any tag'))
_htmlEntityMap = dict(zip("gt lt amp nbsp quot apos".split(),'><& "\''))
commonHTMLEntity = Regex('&(?P<entity>' + '|'.join(_htmlEntityMap.keys()) +");").setName("common HTML entity")
def replaceHTMLEntity(t):
"""Helper parser action to replace common HTML entities with their special characters"""
return _htmlEntityMap.get(t.entity)
# it's easy to get these comment structures wrong - they're very common, so may as well make them available
cStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/').setName("C style comment")
"Comment of the form C{/* ... */}"
htmlComment = Regex(r"<!--[\s\S]*?-->").setName("HTML comment")
"Comment of the form C{<!-- ... -->}"
restOfLine = Regex(r".*").leaveWhitespace().setName("rest of line")
dblSlashComment = Regex(r"//(?:\\\n|[^\n])*").setName("// comment")
"Comment of the form C{// ... (to end of line)}"
cppStyleComment = Combine(Regex(r"/\*(?:[^*]|\*(?!/))*") + '*/'| dblSlashComment).setName("C++ style comment")
"Comment of either form C{L{cStyleComment}} or C{L{dblSlashComment}}"
javaStyleComment = cppStyleComment
"Same as C{L{cppStyleComment}}"
pythonStyleComment = Regex(r"#.*").setName("Python style comment")
"Comment of the form C{# ... (to end of line)}"
_commasepitem = Combine(OneOrMore(Word(printables, excludeChars=',') +
Optional( Word(" \t") +
~Literal(",") + ~LineEnd() ) ) ).streamline().setName("commaItem")
commaSeparatedList = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("commaSeparatedList")
"""(Deprecated) Predefined expression of 1 or more printable words or quoted strings, separated by commas.
This expression is deprecated in favor of L{pyparsing_common.comma_separated_list}."""
# some other useful expressions - using lower-case class name since we are really using this as a namespace
class pyparsing_common:
"""
Here are some common low-level expressions that may be useful in jump-starting parser development:
- numeric forms (L{integers<integer>}, L{reals<real>}, L{scientific notation<sci_real>})
- common L{programming identifiers<identifier>}
- network addresses (L{MAC<mac_address>}, L{IPv4<ipv4_address>}, L{IPv6<ipv6_address>})
- ISO8601 L{dates<iso8601_date>} and L{datetime<iso8601_datetime>}
- L{UUID<uuid>}
- L{comma-separated list<comma_separated_list>}
Parse actions:
- C{L{convertToInteger}}
- C{L{convertToFloat}}
- C{L{convertToDate}}
- C{L{convertToDatetime}}
- C{L{stripHTMLTags}}
- C{L{upcaseTokens}}
- C{L{downcaseTokens}}
Example::
pyparsing_common.number.runTests('''
# any int or real number, returned as the appropriate type
100
-100
+100
3.14159
6.02e23
1e-12
''')
pyparsing_common.fnumber.runTests('''
# any int or real number, returned as float
100
-100
+100
3.14159
6.02e23
1e-12
''')
pyparsing_common.hex_integer.runTests('''
# hex numbers
100
FF
''')
pyparsing_common.fraction.runTests('''
# fractions
1/2
-3/4
''')
pyparsing_common.mixed_integer.runTests('''
# mixed fractions
1
1/2
-3/4
1-3/4
''')
import uuid
pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
pyparsing_common.uuid.runTests('''
# uuid
12345678-1234-5678-1234-567812345678
''')
prints::
# any int or real number, returned as the appropriate type
100
[100]
-100
[-100]
+100
[100]
3.14159
[3.14159]
6.02e23
[6.02e+23]
1e-12
[1e-12]
# any int or real number, returned as float
100
[100.0]
-100
[-100.0]
+100
[100.0]
3.14159
[3.14159]
6.02e23
[6.02e+23]
1e-12
[1e-12]
# hex numbers
100
[256]
FF
[255]
# fractions
1/2
[0.5]
-3/4
[-0.75]
# mixed fractions
1
[1]
1/2
[0.5]
-3/4
[-0.75]
1-3/4
[1.75]
# uuid
12345678-1234-5678-1234-567812345678
[UUID('12345678-1234-5678-1234-567812345678')]
"""
convertToInteger = tokenMap(int)
"""
Parse action for converting parsed integers to Python int
"""
convertToFloat = tokenMap(float)
"""
Parse action for converting parsed numbers to Python float
"""
integer = Word(nums).setName("integer").setParseAction(convertToInteger)
"""expression that parses an unsigned integer, returns an int"""
hex_integer = Word(hexnums).setName("hex integer").setParseAction(tokenMap(int,16))
"""expression that parses a hexadecimal integer, returns an int"""
signed_integer = Regex(r'[+-]?\d+').setName("signed integer").setParseAction(convertToInteger)
"""expression that parses an integer with optional leading sign, returns an int"""
fraction = (signed_integer().setParseAction(convertToFloat) + '/' + signed_integer().setParseAction(convertToFloat)).setName("fraction")
"""fractional expression of an integer divided by an integer, returns a float"""
fraction.addParseAction(lambda t: t[0]/t[-1])
mixed_integer = (fraction | signed_integer + Optional(Optional('-').suppress() + fraction)).setName("fraction or mixed integer-fraction")
"""mixed integer of the form 'integer - fraction', with optional leading integer, returns float"""
mixed_integer.addParseAction(sum)
real = Regex(r'[+-]?\d+\.\d*').setName("real number").setParseAction(convertToFloat)
"""expression that parses a floating point number and returns a float"""
sci_real = Regex(r'[+-]?\d+([eE][+-]?\d+|\.\d*([eE][+-]?\d+)?)').setName("real number with scientific notation").setParseAction(convertToFloat)
"""expression that parses a floating point number with optional scientific notation and returns a float"""
# streamlining this expression makes the docs nicer-looking
number = (sci_real | real | signed_integer).streamline()
"""any numeric expression, returns the corresponding Python type"""
fnumber = Regex(r'[+-]?\d+\.?\d*([eE][+-]?\d+)?').setName("fnumber").setParseAction(convertToFloat)
"""any int or real number, returned as float"""
identifier = Word(alphas+'_', alphanums+'_').setName("identifier")
"""typical code identifier (leading alpha or '_', followed by 0 or more alphas, nums, or '_')"""
ipv4_address = Regex(r'(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|1?[0-9]{1,2})){3}').setName("IPv4 address")
"IPv4 address (C{0.0.0.0 - 255.255.255.255})"
_ipv6_part = Regex(r'[0-9a-fA-F]{1,4}').setName("hex_integer")
_full_ipv6_address = (_ipv6_part + (':' + _ipv6_part)*7).setName("full IPv6 address")
_short_ipv6_address = (Optional(_ipv6_part + (':' + _ipv6_part)*(0,6)) + "::" + Optional(_ipv6_part + (':' + _ipv6_part)*(0,6))).setName("short IPv6 address")
_short_ipv6_address.addCondition(lambda t: sum(1 for tt in t if pyparsing_common._ipv6_part.matches(tt)) < 8)
_mixed_ipv6_address = ("::ffff:" + ipv4_address).setName("mixed IPv6 address")
ipv6_address = Combine((_full_ipv6_address | _mixed_ipv6_address | _short_ipv6_address).setName("IPv6 address")).setName("IPv6 address")
"IPv6 address (long, short, or mixed form)"
mac_address = Regex(r'[0-9a-fA-F]{2}([:.-])[0-9a-fA-F]{2}(?:\1[0-9a-fA-F]{2}){4}').setName("MAC address")
"MAC address xx:xx:xx:xx:xx (may also have '-' or '.' delimiters)"
@staticmethod
def convertToDate(fmt="%Y-%m-%d"):
"""
Helper to create a parse action for converting parsed date string to Python datetime.date
Params -
- fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%d"})
Example::
date_expr = pyparsing_common.iso8601_date.copy()
date_expr.setParseAction(pyparsing_common.convertToDate())
print(date_expr.parseString("1999-12-31"))
prints::
[datetime.date(1999, 12, 31)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt).date()
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn
@staticmethod
def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"):
"""
Helper to create a parse action for converting parsed datetime string to Python datetime.datetime
Params -
- fmt - format to be passed to datetime.strptime (default=C{"%Y-%m-%dT%H:%M:%S.%f"})
Example::
dt_expr = pyparsing_common.iso8601_datetime.copy()
dt_expr.setParseAction(pyparsing_common.convertToDatetime())
print(dt_expr.parseString("1999-12-31T23:59:59.999"))
prints::
[datetime.datetime(1999, 12, 31, 23, 59, 59, 999000)]
"""
def cvt_fn(s,l,t):
try:
return datetime.strptime(t[0], fmt)
except ValueError as ve:
raise ParseException(s, l, str(ve))
return cvt_fn
iso8601_date = Regex(r'(?P<year>\d{4})(?:-(?P<month>\d\d)(?:-(?P<day>\d\d))?)?').setName("ISO8601 date")
"ISO8601 date (C{yyyy-mm-dd})"
iso8601_datetime = Regex(r'(?P<year>\d{4})-(?P<month>\d\d)-(?P<day>\d\d)[T ](?P<hour>\d\d):(?P<minute>\d\d)(:(?P<second>\d\d(\.\d*)?)?)?(?P<tz>Z|[+-]\d\d:?\d\d)?').setName("ISO8601 datetime")
"ISO8601 datetime (C{yyyy-mm-ddThh:mm:ss.s(Z|+-00:00)}) - trailing seconds, milliseconds, and timezone optional; accepts separating C{'T'} or C{' '}"
uuid = Regex(r'[0-9a-fA-F]{8}(-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}').setName("UUID")
"UUID (C{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx})"
_html_stripper = anyOpenTag.suppress() | anyCloseTag.suppress()
@staticmethod
def stripHTMLTags(s, l, tokens):
"""
Parse action to remove HTML tags from web page HTML source
Example::
# strip HTML links from normal text
text = '<td>More info at the <a href="http://pyparsing.wikispaces.com">pyparsing</a> wiki page</td>'
td,td_end = makeHTMLTags("TD")
table_text = td + SkipTo(td_end).setParseAction(pyparsing_common.stripHTMLTags)("body") + td_end
print(table_text.parseString(text).body) # -> 'More info at the pyparsing wiki page'
"""
return pyparsing_common._html_stripper.transformString(tokens[0])
_commasepitem = Combine(OneOrMore(~Literal(",") + ~LineEnd() + Word(printables, excludeChars=',')
+ Optional( White(" \t") ) ) ).streamline().setName("commaItem")
comma_separated_list = delimitedList( Optional( quotedString.copy() | _commasepitem, default="") ).setName("comma separated list")
"""Predefined expression of 1 or more printable words or quoted strings, separated by commas."""
upcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).upper()))
"""Parse action to convert tokens to upper case."""
downcaseTokens = staticmethod(tokenMap(lambda t: _ustr(t).lower()))
"""Parse action to convert tokens to lower case."""
if __name__ == "__main__":
selectToken = CaselessLiteral("select")
fromToken = CaselessLiteral("from")
ident = Word(alphas, alphanums + "_$")
columnName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens)
columnNameList = Group(delimitedList(columnName)).setName("columns")
columnSpec = ('*' | columnNameList)
tableName = delimitedList(ident, ".", combine=True).setParseAction(upcaseTokens)
tableNameList = Group(delimitedList(tableName)).setName("tables")
simpleSQL = selectToken("command") + columnSpec("columns") + fromToken + tableNameList("tables")
# demo runTests method, including embedded comments in test string
simpleSQL.runTests("""
# '*' as column list and dotted table name
select * from SYS.XYZZY
# caseless match on "SELECT", and casts back to "select"
SELECT * from XYZZY, ABC
# list of column names, and mixed case SELECT keyword
Select AA,BB,CC from Sys.dual
# multiple tables
Select A, B, C from Sys.dual, Table2
# invalid SELECT keyword - should fail
Xelect A, B, C from Sys.dual
# incomplete command - should fail
Select
# invalid column name - should fail
Select ^^^ frox Sys.dual
""")
pyparsing_common.number.runTests("""
100
-100
+100
3.14159
6.02e23
1e-12
""")
# any int or real number, returned as float
pyparsing_common.fnumber.runTests("""
100
-100
+100
3.14159
6.02e23
1e-12
""")
pyparsing_common.hex_integer.runTests("""
100
FF
""")
import uuid
pyparsing_common.uuid.setParseAction(tokenMap(uuid.UUID))
pyparsing_common.uuid.runTests("""
12345678-1234-5678-1234-567812345678
""")
| gpl-3.0 |
andreaso/ansible | test/units/modules/network/junos/test_junos_rpc.py | 31 | 3374 | # (c) 2017 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 xml.etree.ElementTree import tostring
from ansible.compat.tests.mock import patch, MagicMock
from ansible.modules.network.junos import junos_rpc
from .junos_module import TestJunosModule, load_fixture, set_module_args
from ansible.module_utils._text import to_text
RPC_CLI_MAP = {
'get-software-information': 'show version',
'get-interface-information': 'show interfaces details',
'get-system-memory-information': 'show system memory',
'get-chassis-inventory': 'show chassis hardware',
'get-system-storage': 'show system storage'
}
class TestJunosCommandModule(TestJunosModule):
module = junos_rpc
def setUp(self):
self.mock_send_request = patch('ansible.modules.network.junos.junos_rpc.send_request')
self.send_request = self.mock_send_request.start()
def tearDown(self):
self.mock_send_request.stop()
def load_fixtures(self, commands=None, format='text', changed=False):
def load_from_file(*args, **kwargs):
module, element = args
if element.text:
path = str(element.text)
else:
tag = str(element.tag)
if tag.startswith('{'):
tag = tag.split('}', 1)[1]
path = RPC_CLI_MAP[tag]
filename = path.replace(' ', '_')
filename = '%s_%s.txt' % (filename, format)
return load_fixture(filename)
self.send_request.side_effect = load_from_file
def test_junos_rpc_xml(self):
set_module_args(dict(rpc='get-chassis-inventory'))
result = self.execute_module(format='xml')
self.assertTrue(result['xml'].find('<chassis-inventory>\n'))
def test_junos_rpc_text(self):
set_module_args(dict(rpc='get-software-information', output='text'))
result = self.execute_module(format='text')
self.assertTrue(result['output_lines'][0].startswith('Hostname: vsrx01'))
def test_junos_rpc_json(self):
set_module_args(dict(rpc='get-software-information', output='json'))
result = self.execute_module(format='json')
self.assertTrue('software-information' in result['output'])
def test_junos_rpc_args(self):
set_module_args(dict(rpc='get-software-information', args={'interface': 'em0', 'media': True}))
result = self.execute_module(format='xml')
args, kwargs = self.send_request.call_args
reply = tostring(args[1]).decode()
self.assertTrue(reply.find('<interface>em0</interface><media /></get-software-information>'))
| gpl-3.0 |
CubicERP/odoo | addons/product/__openerp__.py | 262 | 2504 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Products & Pricelists',
'version': '1.1',
'author': 'OpenERP SA',
'category': 'Sales Management',
'depends': ['base', 'decimal_precision', 'mail', 'report'],
'demo': [
'product_demo.xml',
'product_image_demo.xml',
],
'website': 'https://www.odoo.com',
'description': """
This is the base module for managing products and pricelists in OpenERP.
========================================================================
Products support variants, different pricing methods, suppliers information,
make to stock/order, different unit of measures, packaging and properties.
Pricelists support:
-------------------
* Multiple-level of discount (by product, category, quantities)
* Compute price based on different criteria:
* Other pricelist
* Cost price
* List price
* Supplier price
Pricelists preferences by product and/or partners.
Print product labels with barcode.
""",
'data': [
'security/product_security.xml',
'security/ir.model.access.csv',
'wizard/product_price_view.xml',
'product_data.xml',
'product_report.xml',
'product_view.xml',
'pricelist_view.xml',
'partner_view.xml',
'views/report_pricelist.xml',
],
'test': [
'product_pricelist_demo.yml',
'test/product_pricelist.yml',
],
'installable': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
kozko2001/existentialcomics | scrape/existentialcomics/pipeline/merge.py | 1 | 1721 | from scrapy.conf import settings
from PIL import Image
from os.path import isfile
class MergeImagesPipeline(object):
"""
Pipeline to merge multiple images into on single image
This is made specifically for the existential comics crawler
where the comic is made from multiple images in vertical.
If the item['images'] size from the pipeline is > 1 then we
do the merge of the multiple images, if not this pipeline does
nothing
"""
def process_item(self, item, spider):
if len(item['images']) > 1:
item = self.process_item_merge(item)
else:
item['image'] = '%s/%s' % (settings['IMAGES_STORE'], item['images'][0]['path'])
return item
def process_item_merge(self, item):
image_path = '%s/%s_%s.png' % (settings['IMAGES_STORE'], item['comic'], item['title'])
# if file already merge not do it again
if not isfile(image_path):
paths = map(lambda i: settings['IMAGES_STORE'] + '/' + i['path'], item['images'])
images = map(lambda path: Image.open(path), paths)
# Create an image of the sum of height
width = max(map(lambda i: i.width, images))
height = sum(map(lambda i: i.height, images))
merge_image = Image.new("RGB", (width, height))
# merge all the images in one
offset = 0
for image in images:
merge_image.paste(image, (0, offset))
offset = offset + image.height
image_path = '%s/%s_%s.png' % (settings['IMAGES_STORE'], item['comic'], item['title'])
merge_image.save(image_path)
item['image'] = image_path
return item
| mit |
duqiao/django | tests/gis_tests/gdal_tests/test_geom.py | 256 | 20748 | import json
import unittest
from binascii import b2a_hex
from unittest import skipUnless
from django.contrib.gis.gdal import HAS_GDAL
from django.utils.six.moves import range
from ..test_data import TestDataMixin
try:
from django.utils.six.moves import cPickle as pickle
except ImportError:
import pickle
if HAS_GDAL:
from django.contrib.gis.gdal import (OGRGeometry, OGRGeomType,
GDALException, OGRIndexError, SpatialReference, CoordTransform,
GDAL_VERSION)
@skipUnless(HAS_GDAL, "GDAL is required")
class OGRGeomTest(unittest.TestCase, TestDataMixin):
"This tests the OGR Geometry."
def test_geomtype(self):
"Testing OGRGeomType object."
# OGRGeomType should initialize on all these inputs.
OGRGeomType(1)
OGRGeomType(7)
OGRGeomType('point')
OGRGeomType('GeometrycollectioN')
OGRGeomType('LINearrING')
OGRGeomType('Unknown')
# Should throw TypeError on this input
self.assertRaises(GDALException, OGRGeomType, 23)
self.assertRaises(GDALException, OGRGeomType, 'fooD')
self.assertRaises(GDALException, OGRGeomType, 9)
# Equivalence can take strings, ints, and other OGRGeomTypes
self.assertEqual(OGRGeomType(1), OGRGeomType(1))
self.assertEqual(OGRGeomType(7), 'GeometryCollection')
self.assertEqual(OGRGeomType('point'), 'POINT')
self.assertNotEqual(OGRGeomType('point'), 2)
self.assertEqual(OGRGeomType('unknown'), 0)
self.assertEqual(OGRGeomType(6), 'MULtiPolyGON')
self.assertEqual(OGRGeomType(1), OGRGeomType('point'))
self.assertNotEqual(OGRGeomType('POINT'), OGRGeomType(6))
# Testing the Django field name equivalent property.
self.assertEqual('PointField', OGRGeomType('Point').django)
self.assertEqual('GeometryField', OGRGeomType('Geometry').django)
self.assertEqual('GeometryField', OGRGeomType('Unknown').django)
self.assertIsNone(OGRGeomType('none').django)
# 'Geometry' initialization implies an unknown geometry type.
gt = OGRGeomType('Geometry')
self.assertEqual(0, gt.num)
self.assertEqual('Unknown', gt.name)
def test_geomtype_25d(self):
"Testing OGRGeomType object with 25D types."
wkb25bit = OGRGeomType.wkb25bit
self.assertEqual(OGRGeomType(wkb25bit + 1), 'Point25D')
self.assertEqual(OGRGeomType('MultiLineString25D'), (5 + wkb25bit))
self.assertEqual('GeometryCollectionField', OGRGeomType('GeometryCollection25D').django)
def test_wkt(self):
"Testing WKT output."
for g in self.geometries.wkt_out:
geom = OGRGeometry(g.wkt)
self.assertEqual(g.wkt, geom.wkt)
def test_ewkt(self):
"Testing EWKT input/output."
for ewkt_val in ('POINT (1 2 3)', 'LINEARRING (0 0,1 1,2 1,0 0)'):
# First with ewkt output when no SRID in EWKT
self.assertEqual(ewkt_val, OGRGeometry(ewkt_val).ewkt)
# No test consumption with an SRID specified.
ewkt_val = 'SRID=4326;%s' % ewkt_val
geom = OGRGeometry(ewkt_val)
self.assertEqual(ewkt_val, geom.ewkt)
self.assertEqual(4326, geom.srs.srid)
def test_gml(self):
"Testing GML output."
for g in self.geometries.wkt_out:
geom = OGRGeometry(g.wkt)
exp_gml = g.gml
if GDAL_VERSION >= (1, 8):
# In GDAL 1.8, the non-conformant GML tag <gml:GeometryCollection> was
# replaced with <gml:MultiGeometry>.
exp_gml = exp_gml.replace('GeometryCollection', 'MultiGeometry')
self.assertEqual(exp_gml, geom.gml)
def test_hex(self):
"Testing HEX input/output."
for g in self.geometries.hex_wkt:
geom1 = OGRGeometry(g.wkt)
self.assertEqual(g.hex.encode(), geom1.hex)
# Constructing w/HEX
geom2 = OGRGeometry(g.hex)
self.assertEqual(geom1, geom2)
def test_wkb(self):
"Testing WKB input/output."
for g in self.geometries.hex_wkt:
geom1 = OGRGeometry(g.wkt)
wkb = geom1.wkb
self.assertEqual(b2a_hex(wkb).upper(), g.hex.encode())
# Constructing w/WKB.
geom2 = OGRGeometry(wkb)
self.assertEqual(geom1, geom2)
def test_json(self):
"Testing GeoJSON input/output."
for g in self.geometries.json_geoms:
geom = OGRGeometry(g.wkt)
if not hasattr(g, 'not_equal'):
# Loading jsons to prevent decimal differences
self.assertEqual(json.loads(g.json), json.loads(geom.json))
self.assertEqual(json.loads(g.json), json.loads(geom.geojson))
self.assertEqual(OGRGeometry(g.wkt), OGRGeometry(geom.json))
# Test input with some garbage content (but valid json) (#15529)
geom = OGRGeometry('{"type": "Point", "coordinates": [ 100.0, 0.0 ], "other": "<test>"}')
self.assertIsInstance(geom, OGRGeometry)
def test_points(self):
"Testing Point objects."
OGRGeometry('POINT(0 0)')
for p in self.geometries.points:
if not hasattr(p, 'z'): # No 3D
pnt = OGRGeometry(p.wkt)
self.assertEqual(1, pnt.geom_type)
self.assertEqual('POINT', pnt.geom_name)
self.assertEqual(p.x, pnt.x)
self.assertEqual(p.y, pnt.y)
self.assertEqual((p.x, p.y), pnt.tuple)
def test_multipoints(self):
"Testing MultiPoint objects."
for mp in self.geometries.multipoints:
mgeom1 = OGRGeometry(mp.wkt) # First one from WKT
self.assertEqual(4, mgeom1.geom_type)
self.assertEqual('MULTIPOINT', mgeom1.geom_name)
mgeom2 = OGRGeometry('MULTIPOINT') # Creating empty multipoint
mgeom3 = OGRGeometry('MULTIPOINT')
for g in mgeom1:
mgeom2.add(g) # adding each point from the multipoints
mgeom3.add(g.wkt) # should take WKT as well
self.assertEqual(mgeom1, mgeom2) # they should equal
self.assertEqual(mgeom1, mgeom3)
self.assertEqual(mp.coords, mgeom2.coords)
self.assertEqual(mp.n_p, mgeom2.point_count)
def test_linestring(self):
"Testing LineString objects."
prev = OGRGeometry('POINT(0 0)')
for ls in self.geometries.linestrings:
linestr = OGRGeometry(ls.wkt)
self.assertEqual(2, linestr.geom_type)
self.assertEqual('LINESTRING', linestr.geom_name)
self.assertEqual(ls.n_p, linestr.point_count)
self.assertEqual(ls.coords, linestr.tuple)
self.assertEqual(linestr, OGRGeometry(ls.wkt))
self.assertNotEqual(linestr, prev)
self.assertRaises(OGRIndexError, linestr.__getitem__, len(linestr))
prev = linestr
# Testing the x, y properties.
x = [tmpx for tmpx, tmpy in ls.coords]
y = [tmpy for tmpx, tmpy in ls.coords]
self.assertEqual(x, linestr.x)
self.assertEqual(y, linestr.y)
def test_multilinestring(self):
"Testing MultiLineString objects."
prev = OGRGeometry('POINT(0 0)')
for mls in self.geometries.multilinestrings:
mlinestr = OGRGeometry(mls.wkt)
self.assertEqual(5, mlinestr.geom_type)
self.assertEqual('MULTILINESTRING', mlinestr.geom_name)
self.assertEqual(mls.n_p, mlinestr.point_count)
self.assertEqual(mls.coords, mlinestr.tuple)
self.assertEqual(mlinestr, OGRGeometry(mls.wkt))
self.assertNotEqual(mlinestr, prev)
prev = mlinestr
for ls in mlinestr:
self.assertEqual(2, ls.geom_type)
self.assertEqual('LINESTRING', ls.geom_name)
self.assertRaises(OGRIndexError, mlinestr.__getitem__, len(mlinestr))
def test_linearring(self):
"Testing LinearRing objects."
prev = OGRGeometry('POINT(0 0)')
for rr in self.geometries.linearrings:
lr = OGRGeometry(rr.wkt)
# self.assertEqual(101, lr.geom_type.num)
self.assertEqual('LINEARRING', lr.geom_name)
self.assertEqual(rr.n_p, len(lr))
self.assertEqual(lr, OGRGeometry(rr.wkt))
self.assertNotEqual(lr, prev)
prev = lr
def test_polygons(self):
"Testing Polygon objects."
# Testing `from_bbox` class method
bbox = (-180, -90, 180, 90)
p = OGRGeometry.from_bbox(bbox)
self.assertEqual(bbox, p.extent)
prev = OGRGeometry('POINT(0 0)')
for p in self.geometries.polygons:
poly = OGRGeometry(p.wkt)
self.assertEqual(3, poly.geom_type)
self.assertEqual('POLYGON', poly.geom_name)
self.assertEqual(p.n_p, poly.point_count)
self.assertEqual(p.n_i + 1, len(poly))
# Testing area & centroid.
self.assertAlmostEqual(p.area, poly.area, 9)
x, y = poly.centroid.tuple
self.assertAlmostEqual(p.centroid[0], x, 9)
self.assertAlmostEqual(p.centroid[1], y, 9)
# Testing equivalence
self.assertEqual(poly, OGRGeometry(p.wkt))
self.assertNotEqual(poly, prev)
if p.ext_ring_cs:
ring = poly[0]
self.assertEqual(p.ext_ring_cs, ring.tuple)
self.assertEqual(p.ext_ring_cs, poly[0].tuple)
self.assertEqual(len(p.ext_ring_cs), ring.point_count)
for r in poly:
self.assertEqual('LINEARRING', r.geom_name)
def test_closepolygons(self):
"Testing closing Polygon objects."
# Both rings in this geometry are not closed.
poly = OGRGeometry('POLYGON((0 0, 5 0, 5 5, 0 5), (1 1, 2 1, 2 2, 2 1))')
self.assertEqual(8, poly.point_count)
with self.assertRaises(GDALException):
poly.centroid
poly.close_rings()
self.assertEqual(10, poly.point_count) # Two closing points should've been added
self.assertEqual(OGRGeometry('POINT(2.5 2.5)'), poly.centroid)
def test_multipolygons(self):
"Testing MultiPolygon objects."
OGRGeometry('POINT(0 0)')
for mp in self.geometries.multipolygons:
mpoly = OGRGeometry(mp.wkt)
self.assertEqual(6, mpoly.geom_type)
self.assertEqual('MULTIPOLYGON', mpoly.geom_name)
if mp.valid:
self.assertEqual(mp.n_p, mpoly.point_count)
self.assertEqual(mp.num_geom, len(mpoly))
self.assertRaises(OGRIndexError, mpoly.__getitem__, len(mpoly))
for p in mpoly:
self.assertEqual('POLYGON', p.geom_name)
self.assertEqual(3, p.geom_type)
self.assertEqual(mpoly.wkt, OGRGeometry(mp.wkt).wkt)
def test_srs(self):
"Testing OGR Geometries with Spatial Reference objects."
for mp in self.geometries.multipolygons:
# Creating a geometry w/spatial reference
sr = SpatialReference('WGS84')
mpoly = OGRGeometry(mp.wkt, sr)
self.assertEqual(sr.wkt, mpoly.srs.wkt)
# Ensuring that SRS is propagated to clones.
klone = mpoly.clone()
self.assertEqual(sr.wkt, klone.srs.wkt)
# Ensuring all children geometries (polygons and their rings) all
# return the assigned spatial reference as well.
for poly in mpoly:
self.assertEqual(sr.wkt, poly.srs.wkt)
for ring in poly:
self.assertEqual(sr.wkt, ring.srs.wkt)
# Ensuring SRS propagate in topological ops.
a = OGRGeometry(self.geometries.topology_geoms[0].wkt_a, sr)
b = OGRGeometry(self.geometries.topology_geoms[0].wkt_b, sr)
diff = a.difference(b)
union = a.union(b)
self.assertEqual(sr.wkt, diff.srs.wkt)
self.assertEqual(sr.srid, union.srs.srid)
# Instantiating w/an integer SRID
mpoly = OGRGeometry(mp.wkt, 4326)
self.assertEqual(4326, mpoly.srid)
mpoly.srs = SpatialReference(4269)
self.assertEqual(4269, mpoly.srid)
self.assertEqual('NAD83', mpoly.srs.name)
# Incrementing through the multipolygon after the spatial reference
# has been re-assigned.
for poly in mpoly:
self.assertEqual(mpoly.srs.wkt, poly.srs.wkt)
poly.srs = 32140
for ring in poly:
# Changing each ring in the polygon
self.assertEqual(32140, ring.srs.srid)
self.assertEqual('NAD83 / Texas South Central', ring.srs.name)
ring.srs = str(SpatialReference(4326)) # back to WGS84
self.assertEqual(4326, ring.srs.srid)
# Using the `srid` property.
ring.srid = 4322
self.assertEqual('WGS 72', ring.srs.name)
self.assertEqual(4322, ring.srid)
def test_srs_transform(self):
"Testing transform()."
orig = OGRGeometry('POINT (-104.609 38.255)', 4326)
trans = OGRGeometry('POINT (992385.4472045 481455.4944650)', 2774)
# Using an srid, a SpatialReference object, and a CoordTransform object
# or transformations.
t1, t2, t3 = orig.clone(), orig.clone(), orig.clone()
t1.transform(trans.srid)
t2.transform(SpatialReference('EPSG:2774'))
ct = CoordTransform(SpatialReference('WGS84'), SpatialReference(2774))
t3.transform(ct)
# Testing use of the `clone` keyword.
k1 = orig.clone()
k2 = k1.transform(trans.srid, clone=True)
self.assertEqual(k1, orig)
self.assertNotEqual(k1, k2)
prec = 3
for p in (t1, t2, t3, k2):
self.assertAlmostEqual(trans.x, p.x, prec)
self.assertAlmostEqual(trans.y, p.y, prec)
def test_transform_dim(self):
"Testing coordinate dimension is the same on transformed geometries."
ls_orig = OGRGeometry('LINESTRING(-104.609 38.255)', 4326)
ls_trans = OGRGeometry('LINESTRING(992385.4472045 481455.4944650)', 2774)
prec = 3
ls_orig.transform(ls_trans.srs)
# Making sure the coordinate dimension is still 2D.
self.assertEqual(2, ls_orig.coord_dim)
self.assertAlmostEqual(ls_trans.x[0], ls_orig.x[0], prec)
self.assertAlmostEqual(ls_trans.y[0], ls_orig.y[0], prec)
def test_difference(self):
"Testing difference()."
for i in range(len(self.geometries.topology_geoms)):
a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
d1 = OGRGeometry(self.geometries.diff_geoms[i].wkt)
d2 = a.difference(b)
self.assertEqual(d1, d2)
self.assertEqual(d1, a - b) # __sub__ is difference operator
a -= b # testing __isub__
self.assertEqual(d1, a)
def test_intersection(self):
"Testing intersects() and intersection()."
for i in range(len(self.geometries.topology_geoms)):
a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
i1 = OGRGeometry(self.geometries.intersect_geoms[i].wkt)
self.assertTrue(a.intersects(b))
i2 = a.intersection(b)
self.assertEqual(i1, i2)
self.assertEqual(i1, a & b) # __and__ is intersection operator
a &= b # testing __iand__
self.assertEqual(i1, a)
def test_symdifference(self):
"Testing sym_difference()."
for i in range(len(self.geometries.topology_geoms)):
a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
d1 = OGRGeometry(self.geometries.sdiff_geoms[i].wkt)
d2 = a.sym_difference(b)
self.assertEqual(d1, d2)
self.assertEqual(d1, a ^ b) # __xor__ is symmetric difference operator
a ^= b # testing __ixor__
self.assertEqual(d1, a)
def test_union(self):
"Testing union()."
for i in range(len(self.geometries.topology_geoms)):
a = OGRGeometry(self.geometries.topology_geoms[i].wkt_a)
b = OGRGeometry(self.geometries.topology_geoms[i].wkt_b)
u1 = OGRGeometry(self.geometries.union_geoms[i].wkt)
u2 = a.union(b)
self.assertEqual(u1, u2)
self.assertEqual(u1, a | b) # __or__ is union operator
a |= b # testing __ior__
self.assertEqual(u1, a)
def test_add(self):
"Testing GeometryCollection.add()."
# Can't insert a Point into a MultiPolygon.
mp = OGRGeometry('MultiPolygon')
pnt = OGRGeometry('POINT(5 23)')
self.assertRaises(GDALException, mp.add, pnt)
# GeometryCollection.add may take an OGRGeometry (if another collection
# of the same type all child geoms will be added individually) or WKT.
for mp in self.geometries.multipolygons:
mpoly = OGRGeometry(mp.wkt)
mp1 = OGRGeometry('MultiPolygon')
mp2 = OGRGeometry('MultiPolygon')
mp3 = OGRGeometry('MultiPolygon')
for poly in mpoly:
mp1.add(poly) # Adding a geometry at a time
mp2.add(poly.wkt) # Adding WKT
mp3.add(mpoly) # Adding a MultiPolygon's entire contents at once.
for tmp in (mp1, mp2, mp3):
self.assertEqual(mpoly, tmp)
def test_extent(self):
"Testing `extent` property."
# The xmin, ymin, xmax, ymax of the MultiPoint should be returned.
mp = OGRGeometry('MULTIPOINT(5 23, 0 0, 10 50)')
self.assertEqual((0.0, 0.0, 10.0, 50.0), mp.extent)
# Testing on the 'real world' Polygon.
poly = OGRGeometry(self.geometries.polygons[3].wkt)
ring = poly.shell
x, y = ring.x, ring.y
xmin, ymin = min(x), min(y)
xmax, ymax = max(x), max(y)
self.assertEqual((xmin, ymin, xmax, ymax), poly.extent)
def test_25D(self):
"Testing 2.5D geometries."
pnt_25d = OGRGeometry('POINT(1 2 3)')
self.assertEqual('Point25D', pnt_25d.geom_type.name)
self.assertEqual(3.0, pnt_25d.z)
self.assertEqual(3, pnt_25d.coord_dim)
ls_25d = OGRGeometry('LINESTRING(1 1 1,2 2 2,3 3 3)')
self.assertEqual('LineString25D', ls_25d.geom_type.name)
self.assertEqual([1.0, 2.0, 3.0], ls_25d.z)
self.assertEqual(3, ls_25d.coord_dim)
def test_pickle(self):
"Testing pickle support."
g1 = OGRGeometry('LINESTRING(1 1 1,2 2 2,3 3 3)', 'WGS84')
g2 = pickle.loads(pickle.dumps(g1))
self.assertEqual(g1, g2)
self.assertEqual(4326, g2.srs.srid)
self.assertEqual(g1.srs.wkt, g2.srs.wkt)
def test_ogrgeometry_transform_workaround(self):
"Testing coordinate dimensions on geometries after transformation."
# A bug in GDAL versions prior to 1.7 changes the coordinate
# dimension of a geometry after it has been transformed.
# This test ensures that the bug workarounds employed within
# `OGRGeometry.transform` indeed work.
wkt_2d = "MULTILINESTRING ((0 0,1 1,2 2))"
wkt_3d = "MULTILINESTRING ((0 0 0,1 1 1,2 2 2))"
srid = 4326
# For both the 2D and 3D MultiLineString, ensure _both_ the dimension
# of the collection and the component LineString have the expected
# coordinate dimension after transform.
geom = OGRGeometry(wkt_2d, srid)
geom.transform(srid)
self.assertEqual(2, geom.coord_dim)
self.assertEqual(2, geom[0].coord_dim)
self.assertEqual(wkt_2d, geom.wkt)
geom = OGRGeometry(wkt_3d, srid)
geom.transform(srid)
self.assertEqual(3, geom.coord_dim)
self.assertEqual(3, geom[0].coord_dim)
self.assertEqual(wkt_3d, geom.wkt)
def test_equivalence_regression(self):
"Testing equivalence methods with non-OGRGeometry instances."
self.assertIsNotNone(OGRGeometry('POINT(0 0)'))
self.assertNotEqual(OGRGeometry('LINESTRING(0 0, 1 1)'), 3)
| bsd-3-clause |
openhealthcare/randomise.me | rm/trials/migrations/0030_auto__add_field_trial_instruction_hours_after__add_field_trial_instruc.py | 1 | 7280 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Trial.instruction_hours_after'
db.add_column(u'trials_trial', 'instruction_hours_after',
self.gf('django.db.models.fields.IntegerField')(null=True, blank=True),
keep_default=False)
# Adding field 'Trial.instruction_date'
db.add_column(u'trials_trial', 'instruction_date',
self.gf('django.db.models.fields.DateField')(null=True, blank=True),
keep_default=False)
def backwards(self, orm):
# Deleting field 'Trial.instruction_hours_after'
db.delete_column(u'trials_trial', 'instruction_hours_after')
# Deleting field 'Trial.instruction_date'
db.delete_column(u'trials_trial', 'instruction_date')
models = {
u'trials.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '1'}),
'trial': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Trial']"})
},
u'trials.participant': {
'Meta': {'object_name': 'Participant'},
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Group']", 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'trial': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Trial']"}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['userprofiles.RMUser']", 'null': 'True', 'blank': 'True'})
},
u'trials.report': {
'Meta': {'object_name': 'Report'},
'binary': ('django.db.models.fields.NullBooleanField', [], {'null': 'True', 'blank': 'True'}),
'count': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'date': ('django.db.models.fields.DateField', [], {}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Group']", 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'participant': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Participant']", 'null': 'True', 'blank': 'True'}),
'score': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'trial': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Trial']"}),
'variable': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Variable']"})
},
u'trials.trial': {
'Meta': {'object_name': 'Trial'},
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'featured': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'finish_date': ('django.db.models.fields.DateField', [], {}),
'group_a': ('django.db.models.fields.TextField', [], {}),
'group_a_desc': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'group_a_expected': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'group_b': ('django.db.models.fields.TextField', [], {}),
'group_b_desc': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'group_b_impressed': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'instruction_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'instruction_delivery': ('django.db.models.fields.TextField', [], {'default': "'im'", 'max_length': '2'}),
'instruction_hours_after': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_participants': ('django.db.models.fields.IntegerField', [], {}),
'min_participants': ('django.db.models.fields.IntegerField', [], {}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['userprofiles.RMUser']"}),
'participants': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'recruiting': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'recruitment': ('django.db.models.fields.CharField', [], {'default': "'an'", 'max_length': '2'}),
'start_date': ('django.db.models.fields.DateField', [], {}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'})
},
u'trials.variable': {
'Meta': {'object_name': 'Variable'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'question': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'style': ('django.db.models.fields.CharField', [], {'max_length': '2'}),
'trial': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['trials.Trial']"})
},
u'userprofiles.rmuser': {
'Meta': {'object_name': 'RMUser'},
'account': ('django.db.models.fields.CharField', [], {'default': "'st'", 'max_length': '2'}),
'dob': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '254'}),
'gender': ('django.db.models.fields.CharField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'postcode': ('django.db.models.fields.CharField', [], {'max_length': '20', 'null': 'True', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '40', 'db_index': 'True'})
}
}
complete_apps = ['trials'] | agpl-3.0 |
vingd/fiscal-hr-python | setup.py | 1 | 1194 | #!/usr/bin/env python
'''FiscalHr Setup'''
from distutils.core import setup
import fiscalhr
setup(
name=fiscalhr.__title__,
version=fiscalhr.__version__,
author=fiscalhr.__author__,
author_email=fiscalhr.__author_email__,
url=fiscalhr.__url__,
license=fiscalhr.__license__,
description=fiscalhr.__doc__,
long_description=open('README.rst').read(),
packages=['fiscalhr'],
package_data={
'fiscalhr': [
'fiskalizacija_service/certs/*.pem',
'fiskalizacija_service/wsdl/*.wsdl',
'fiskalizacija_service/schema/*.xsd',
],
},
dependency_links=['https://github.com/vingd/libxml2-python/archive/libxml2-python-2.7.8.zip'],
install_requires=[i.strip() for i in open('requirements.txt').readlines()],
platforms=['OS Independent'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Programming Language :: Python',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| mit |
lpawluczuk/summar.pl | Summarizer/nlp_tools/nerf/scripts/ner_service.py | 1 | 4254 | #-*- coding: utf-8 -*-
import sys
import os
import time
import re
from threading import Thread
from Queue import Queue
import string
from ner_io import line2sent, name2str
# Solution with no hard coded path would be welcome
sys.path.append(os.path.dirname(os.path.abspath(sys.argv[0])) + "/../")
from ..ner.nerecognizer import NERecognizer
from ..ner.data import Segment
from ..ner.features import sent2features
# Word or punctuation character
word_regex = re.compile('([^%s]+|[%s])' %
( re.escape(string.whitespace + string.punctuation)
, re.escape(string.punctuation)))
def words(line):
return [(m.group(), m.span()) for m in word_regex.finditer(line)]
class SegmentStruct(Segment):
def __init__(self, span, *args, **kwargs):
self.span = span
Segment.__init__(self, *args, **kwargs)
class NERService(object):
def __init__(self, ner, input, output):
self.ner = ner
self.input = input
self.output = output
def group_input(self):
result = []
while True:
line = self.input.get()
if line is None:
break
yield [SegmentStruct(span, id=str(i), orth=orth)
for i, (orth, span) in enumerate(words(line))]
def name2str(self, name):
segs = sorted(name.get_segs(), key=lambda seg: seg.span)
npss = [True] + [prev.span[1] == curr.span[0]
for (prev, curr) in zip(segs, segs[1:])]
segstr = "".join(
("" if nps else " ") + seg.orth
for (seg, nps) in zip(segs, npss))
p = min(seg.span[0] for seg in segs)
q = max(seg.span[1] for seg in segs)
span_str = "(" + str(p) + ", " + str(q) + ")"
return (".".join(filter(lambda x: x is not None,
[name.type, name.subtype, name.derivType]))
+ " : " + segstr + " " + span_str)
def output_names(self, root_names):
names = [ name
for root_name in root_names
for name in root_name.get_descendant_names_and_self() ]
self.output.put(len(names))
for name in names:
namestr = self.name2str(name)
self.output.put(namestr)
def run(self):
for sent in self.group_input():
print "."
# features = sent2features(sent, self.ner.features)
# print >> self.output, "FEATURES:"
# for elem in features:
# print >> self.output, " ".join(elem).encode('utf-8')
names = self.ner.recognize_named_entities(sent)
self.output_names(names)
def init_model(model_name):
print "Loading NER model..."
ner = NERecognizer.load(model_name)
print "Done\n"
return ner
def recognize(ner, sentence):
line = sentence
sent = line2sent(line.strip())
names = ner.recognize_named_entities(sent)
res = print_names(names)
result = []
for r in res:
cat = r[:r.index(":")]
cat = cat[:cat.index(".")].strip() if "." in cat else cat.strip()
result.append((r[r.index(":")+2:r.index("(")].strip(), cat))
return result
#return [r[r.index(":")+2:r.index("(")].strip() for r in res]
def print_names(names):
for root_name in names:
for name in root_name.get_descendant_names_and_self():
yield name2str(name)
if __name__ == "__main__":
from optparse import OptionParser
optparser = OptionParser(usage="""usage: %prog MODEL
Run NER service using given model.""")
(options, args) = optparser.parse_args()
if len(args) != 1:
optparser.print_help()
sys.exit(0)
model_name = args[0]
print "Loading model..."
ner = NERecognizer.load(model_name)
print "Done\n"
input = Queue()
output = Queue()
service = NERService(ner, input=input, output=output)
thread = Thread(target=service.run, args=())
thread.start()
try:
while True:
line = raw_input("> ")
input.put(line.decode('utf-8'))
k = output.get()
for _ in range(k):
print output.get().encode('utf-8')
except KeyboardInterrupt:
input.put(None)
thread.join()
| mit |
dfunckt/django | tests/view_tests/tests/test_defaults.py | 12 | 5797 | from __future__ import unicode_literals
import datetime
from django.contrib.sites.models import Site
from django.http import Http404
from django.template import TemplateDoesNotExist
from django.test import RequestFactory, TestCase
from django.test.utils import override_settings
from django.views.defaults import (
bad_request, page_not_found, permission_denied, server_error,
)
from ..models import Article, Author, UrlArticle
@override_settings(ROOT_URLCONF='view_tests.urls')
class DefaultsTests(TestCase):
"""Test django views in django/views/defaults.py"""
non_existing_urls = ['/non_existing_url/', # this is in urls.py
'/other_non_existing_url/'] # this NOT in urls.py
@classmethod
def setUpTestData(cls):
Author.objects.create(name='Boris')
Article.objects.create(
title='Old Article', slug='old_article', author_id=1,
date_created=datetime.datetime(2001, 1, 1, 21, 22, 23)
)
Article.objects.create(
title='Current Article', slug='current_article', author_id=1,
date_created=datetime.datetime(2007, 9, 17, 21, 22, 23)
)
Article.objects.create(
title='Future Article', slug='future_article', author_id=1,
date_created=datetime.datetime(3000, 1, 1, 21, 22, 23)
)
UrlArticle.objects.create(
title='Old Article', slug='old_article', author_id=1,
date_created=datetime.datetime(2001, 1, 1, 21, 22, 23)
)
Site(id=1, domain='testserver', name='testserver').save()
def test_page_not_found(self):
"A 404 status is returned by the page_not_found view"
for url in self.non_existing_urls:
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'loaders': [
('django.template.loaders.locmem.Loader', {
'404.html': '{{ csrf_token }}',
}),
],
},
}])
def test_csrf_token_in_404(self):
"""
The 404 page should have the csrf_token available in the context
"""
# See ticket #14565
for url in self.non_existing_urls:
response = self.client.get(url)
self.assertNotEqual(response.content, 'NOTPROVIDED')
self.assertNotEqual(response.content, '')
def test_server_error(self):
"The server_error view raises a 500 status"
response = self.client.get('/server_error/')
self.assertEqual(response.status_code, 500)
@override_settings(TEMPLATES=[{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'loaders': [
('django.template.loaders.locmem.Loader', {
'404.html': 'This is a test template for a 404 error '
'(path: {{ request_path }}, exception: {{ exception }}).',
'500.html': 'This is a test template for a 500 error.',
}),
],
},
}])
def test_custom_templates(self):
"""
404.html and 500.html templates are picked by their respective handler.
"""
response = self.client.get('/server_error/')
self.assertContains(response, "test template for a 500 error", status_code=500)
response = self.client.get('/no_such_url/')
self.assertContains(response, 'path: /no_such_url/', status_code=404)
self.assertContains(response, 'exception: Resolver404', status_code=404)
response = self.client.get('/technical404/')
self.assertContains(response, 'exception: Testing technical 404.', status_code=404)
def test_get_absolute_url_attributes(self):
"A model can set attributes on the get_absolute_url method"
self.assertTrue(getattr(UrlArticle.get_absolute_url, 'purge', False),
'The attributes of the original get_absolute_url must be added.')
article = UrlArticle.objects.get(pk=1)
self.assertTrue(getattr(article.get_absolute_url, 'purge', False),
'The attributes of the original get_absolute_url must be added.')
@override_settings(DEFAULT_CONTENT_TYPE="text/xml")
def test_default_content_type_is_text_html(self):
"""
Content-Type of the default error responses is text/html. Refs #20822.
"""
response = self.client.get('/raises400/')
self.assertEqual(response['Content-Type'], 'text/html')
response = self.client.get('/raises403/')
self.assertEqual(response['Content-Type'], 'text/html')
response = self.client.get('/non_existing_url/')
self.assertEqual(response['Content-Type'], 'text/html')
response = self.client.get('/server_error/')
self.assertEqual(response['Content-Type'], 'text/html')
def test_custom_templates_wrong(self):
"""
Default error views should raise TemplateDoesNotExist when passed a
template that doesn't exist.
"""
rf = RequestFactory()
request = rf.get('/')
with self.assertRaises(TemplateDoesNotExist):
bad_request(request, Exception(), template_name='nonexistent')
with self.assertRaises(TemplateDoesNotExist):
permission_denied(request, Exception(), template_name='nonexistent')
with self.assertRaises(TemplateDoesNotExist):
page_not_found(request, Http404(), template_name='nonexistent')
with self.assertRaises(TemplateDoesNotExist):
server_error(request, template_name='nonexistent')
| bsd-3-clause |
2ndQuadrant/ansible | test/units/modules/network/fortimanager/test_fmgr_secprof_av.py | 38 | 2705 | # Copyright 2018 Fortinet, Inc.
#
# 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 Ansible. If not, see <https://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
from ansible.module_utils.network.fortimanager.fortimanager import FortiManagerHandler
import pytest
try:
from ansible.modules.network.fortimanager import fmgr_secprof_av
except ImportError:
pytest.skip("Could not load required modules for testing", allow_module_level=True)
def load_fixtures():
fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures') + "/{filename}.json".format(
filename=os.path.splitext(os.path.basename(__file__))[0])
try:
with open(fixture_path, "r") as fixture_file:
fixture_data = json.load(fixture_file)
except IOError:
return []
return [fixture_data]
@pytest.fixture(autouse=True)
def module_mock(mocker):
connection_class_mock = mocker.patch('ansible.module_utils.basic.AnsibleModule')
return connection_class_mock
@pytest.fixture(autouse=True)
def connection_mock(mocker):
connection_class_mock = mocker.patch('ansible.modules.network.fortimanager.fmgr_secprof_av.Connection')
return connection_class_mock
@pytest.fixture(scope="function", params=load_fixtures())
def fixture_data(request):
func_name = request.function.__name__.replace("test_", "")
return request.param.get(func_name, None)
fmg_instance = FortiManagerHandler(connection_mock, module_mock)
def test_fmgr_antivirus_profile_modify(fixture_data, mocker):
mocker.patch("ansible.module_utils.network.fortimanager.fortimanager.FortiManagerHandler.process_request",
side_effect=fixture_data)
# Test using fixture 1 #
output = fmgr_secprof_av.fmgr_antivirus_profile_modify(fmg_instance, fixture_data[0]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0
# Test using fixture 2 #
output = fmgr_secprof_av.fmgr_antivirus_profile_modify(fmg_instance, fixture_data[1]['paramgram_used'])
assert output['raw_response']['status']['code'] == 0
| gpl-3.0 |
BromiumLabs/PackerAttacker | src/experiments/unpack.py | 11 | 2979 | """
This script is supposed to be run from the host
it will submit the file for unpacking to the VM armed
with The Packer Attacker. It communicates to agent.py
"""
import sys
import os
import subprocess
import struct
import requests
import urllib
import time
# CONFIGURATION #################################
# If you're using VirtualBox just put the name of the VM (not supported)
vm_path = '/path/to/your/vm.vmx'
# IP address and port of your VM (should be accessible from the host)
vm_agent_url = 'http://<VM IP>:<port>'
submission_url = vm_agent_url+'/submit'
retrieval_url = vm_agent_url+'/retrieve'
# If you're using VirtualBox
# vm_manager = 'VBoxManage'
# You might need to include full path if running on Windows
vm_manager = 'vmrun'
# Name of snapshot to restore
snapshot = 'snapshot name'
# vm_type = 'vbox' not supported
vm_type = 'vmware'
# Time to unpack (in seconds)
timeout = 20
###############################################
IMAGE_FILE_DLL = 0x2000
def main():
if len(sys.argv)!=2:
exit('Usage: %s <exe>'%sys.argv[0])
exe = sys.argv[1]
if not os.path.exists(exe):
exit('%s does not exist'%exe)
if os.path.isdir(exe):
exit('%s is a directory'%exe)
fd = open(exe, 'rb')
data = fd.read()
#fd.close()
if data[:2]!='MZ':
exit('%s: Invalide file - MZ header missing'%exe)
pe_offset = struct.unpack('<H', data[0x3C:0x3E])[0]
machine_offset = pe_offset+4
characteristics_offset = pe_offset+0x16
machine_val = struct.unpack('<H', data[machine_offset:machine_offset+2])[0]
characteristics_value = struct.unpack('<H', data[characteristics_offset:characteristics_offset+2])[0]
if characteristics_value&IMAGE_FILE_DLL:
exit('%s is a DLL'%exe)
if machine_val!=0x14c:
exit('%s is not a 32 bit application'%exe)
sys.stdout.write('Restoring snapshot and starting the VM...')
subprocess.call([vm_manager, 'revertToSnapshot', vm_path, snapshot])
subprocess.call([vm_manager, 'start', vm_path])
sys.stdout.write('done\n')
fd.seek(0)
files = {
'file': (os.path.basename(exe), fd)
}
sys.stdout.write('Submitting...')
try:
r = requests.post(submission_url, data=None, files=files)
except requests.exceptions.ConnectionError as e:
exit(str(e))
if r.status_code!=200:
exit('Failed to submit file for analysis')
sys.stdout.write('done\n')
sys.stdout.write('Analyzing...')
time.sleep(timeout)
sys.stdout.write('done\n')
sys.stdout.write('Retrieveing the dumps...')
file = urllib.URLopener()
dumps_path = exe+'.zip'
try:
file.retrieve(retrieval_url, dumps_path)
except IOError as e:
exit(str(e))
sys.stdout.write('done\n')
print 'Dumps saved at %s'%dumps_path
print 'Shutting down the VM'
subprocess.call([vm_manager, 'stop', vm_path])
if __name__ == '__main__':
main() | gpl-2.0 |
tycoo/moto_x_kernel | scripts/gcc-wrapper.py | 23 | 3958 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2011-2012, The Linux Foundation. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of The Linux Foundation nor
# the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written
# permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# Invoke gcc, looking for warnings, and causing a failure if there are
# non-whitelisted warnings.
import errno
import re
import os
import sys
import subprocess
# Note that gcc uses unicode, which may depend on the locale. TODO:
# force LANG to be set to en_US.UTF-8 to get consistent warnings.
allowed_warnings = set([
"alignment.c:327",
"mmu.c:602",
"return_address.c:62",
"swab.h:49",
"SemaLambda.cpp:946",
"CGObjCGNU.cpp:1414",
"BugReporter.h:146",
"RegionStore.cpp:1904",
"SymbolManager.cpp:484",
"RewriteObjCFoundationAPI.cpp:737",
"RewriteObjCFoundationAPI.cpp:696",
"CommentParser.cpp:394",
"CommentParser.cpp:391",
"CommentParser.cpp:356",
"LegalizeDAG.cpp:3646",
"IRBuilder.h:844",
"DataLayout.cpp:193",
"transport.c:653",
"xt_socket.c:307",
"xt_socket.c:161",
"inet_hashtables.h:356",
"xc4000.c:1049",
"xc4000.c:1063",
"workqueue.c:480"
])
# Capture the name of the object file, can find it.
ofile = None
warning_re = re.compile(r'''(.*/|)([^/]+\.[a-z]+:\d+):(\d+:)? warning:''')
def interpret_warning(line):
"""Decode the message from gcc. The messages we care about have a filename, and a warning"""
line = line.rstrip('\n')
m = warning_re.match(line)
if m and m.group(2) not in allowed_warnings:
print "error, forbidden warning:", m.group(2)
# If there is a warning, remove any object if it exists.
if ofile:
try:
os.remove(ofile)
except OSError:
pass
sys.exit(1)
def run_gcc():
args = sys.argv[1:]
# Look for -o
try:
i = args.index('-o')
global ofile
ofile = args[i+1]
except (ValueError, IndexError):
pass
compiler = sys.argv[0]
try:
proc = subprocess.Popen(args, stderr=subprocess.PIPE)
for line in proc.stderr:
print line,
interpret_warning(line)
result = proc.wait()
except OSError as e:
result = e.errno
if result == errno.ENOENT:
print args[0] + ':',e.strerror
print 'Is your PATH set correctly?'
else:
print ' '.join(args), str(e)
return result
if __name__ == '__main__':
status = run_gcc()
sys.exit(status)
| gpl-2.0 |
Hodorable/0602 | horizon/tables/views.py | 60 | 13018 | # Copyright 2012 Nebula, 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 collections import defaultdict
from django import shortcuts
from horizon import views
from horizon.templatetags.horizon import has_permissions # noqa
class MultiTableMixin(object):
"""A generic mixin which provides methods for handling DataTables."""
data_method_pattern = "get_%s_data"
def __init__(self, *args, **kwargs):
super(MultiTableMixin, self).__init__(*args, **kwargs)
self.table_classes = getattr(self, "table_classes", [])
self._data = {}
self._tables = {}
self._data_methods = defaultdict(list)
self.get_data_methods(self.table_classes, self._data_methods)
def _get_data_dict(self):
if not self._data:
for table in self.table_classes:
data = []
name = table._meta.name
func_list = self._data_methods.get(name, [])
for func in func_list:
data.extend(func())
self._data[name] = data
return self._data
def get_data_methods(self, table_classes, methods):
for table in table_classes:
name = table._meta.name
if table._meta.mixed_data_type:
for data_type in table._meta.data_types:
func = self.check_method_exist(self.data_method_pattern,
data_type)
if func:
type_name = table._meta.data_type_name
methods[name].append(self.wrap_func(func,
type_name,
data_type))
else:
func = self.check_method_exist(self.data_method_pattern,
name)
if func:
methods[name].append(func)
def wrap_func(self, data_func, type_name, data_type):
def final_data():
data = data_func()
self.assign_type_string(data, type_name, data_type)
return data
return final_data
def check_method_exist(self, func_pattern="%s", *names):
func_name = func_pattern % names
func = getattr(self, func_name, None)
if not func or not callable(func):
cls_name = self.__class__.__name__
raise NotImplementedError("You must define a %s method "
"in %s." % (func_name, cls_name))
else:
return func
def assign_type_string(self, data, type_name, data_type):
for datum in data:
setattr(datum, type_name, data_type)
def get_tables(self):
if not self.table_classes:
raise AttributeError('You must specify one or more DataTable '
'classes for the "table_classes" attribute '
'on %s.' % self.__class__.__name__)
if not self._tables:
for table in self.table_classes:
if not has_permissions(self.request.user,
table._meta):
continue
func_name = "get_%s_table" % table._meta.name
table_func = getattr(self, func_name, None)
if table_func is None:
tbl = table(self.request, **self.kwargs)
else:
tbl = table_func(self, self.request, **self.kwargs)
self._tables[table._meta.name] = tbl
return self._tables
def get_context_data(self, **kwargs):
context = super(MultiTableMixin, self).get_context_data(**kwargs)
tables = self.get_tables()
for name, table in tables.items():
context["%s_table" % name] = table
return context
def has_prev_data(self, table):
return False
def has_more_data(self, table):
return False
def handle_table(self, table):
name = table.name
data = self._get_data_dict()
self._tables[name].data = data[table._meta.name]
self._tables[name]._meta.has_more_data = self.has_more_data(table)
self._tables[name]._meta.has_prev_data = self.has_prev_data(table)
handled = self._tables[name].maybe_handle()
return handled
class MultiTableView(MultiTableMixin, views.HorizonTemplateView):
"""A class-based generic view to handle the display and processing of
multiple :class:`~horizon.tables.DataTable` classes in a single view.
Three steps are required to use this view: set the ``table_classes``
attribute with a tuple of the desired
:class:`~horizon.tables.DataTable` classes;
define a ``get_{{ table_name }}_data`` method for each table class
which returns a set of data for that table; and specify a template for
the ``template_name`` attribute.
"""
def construct_tables(self):
tables = self.get_tables().values()
# Early out before data is loaded
for table in tables:
preempted = table.maybe_preempt()
if preempted:
return preempted
# Load data into each table and check for action handlers
for table in tables:
handled = self.handle_table(table)
if handled:
return handled
# If we didn't already return a response, returning None continues
# with the view as normal.
return None
def get(self, request, *args, **kwargs):
handled = self.construct_tables()
if handled:
return handled
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def post(self, request, *args, **kwargs):
# GET and POST handling are the same
return self.get(request, *args, **kwargs)
class DataTableView(MultiTableView):
"""A class-based generic view to handle basic DataTable processing.
Three steps are required to use this view: set the ``table_class``
attribute with the desired :class:`~horizon.tables.DataTable` class;
define a ``get_data`` method which returns a set of data for the
table; and specify a template for the ``template_name`` attribute.
Optionally, you can override the ``has_more_data`` method to trigger
pagination handling for APIs that support it.
"""
table_class = None
context_object_name = 'table'
def _get_data_dict(self):
if not self._data:
self.update_server_filter_action()
self._data = {self.table_class._meta.name: self.get_data()}
return self._data
def get_data(self):
return []
def get_tables(self):
if not self._tables:
self._tables = {}
if has_permissions(self.request.user,
self.table_class._meta):
self._tables[self.table_class._meta.name] = self.get_table()
return self._tables
def get_table(self):
# Note: this method cannot be easily memoized, because get_context_data
# uses its cached value directly.
if not self.table_class:
raise AttributeError('You must specify a DataTable class for the '
'"table_class" attribute on %s.'
% self.__class__.__name__)
if not hasattr(self, "table"):
self.table = self.table_class(self.request, **self.kwargs)
return self.table
def get_context_data(self, **kwargs):
context = super(DataTableView, self).get_context_data(**kwargs)
if hasattr(self, "table"):
context[self.context_object_name] = self.table
return context
def post(self, request, *args, **kwargs):
# If the server side table filter changed then go back to the first
# page of data. Otherwise GET and POST handling are the same.
if self.handle_server_filter(request):
return shortcuts.redirect(self.get_table().get_absolute_url())
return self.get(request, *args, **kwargs)
def get_server_filter_info(self, request):
filter_action = self.get_table()._meta._filter_action
if filter_action is None or filter_action.filter_type != 'server':
return None
param_name = filter_action.get_param_name()
filter_string = request.POST.get(param_name)
filter_string_session = request.session.get(param_name, "")
changed = (filter_string is not None
and filter_string != filter_string_session)
if filter_string is None:
filter_string = filter_string_session
filter_field_param = param_name + '_field'
filter_field = request.POST.get(filter_field_param)
filter_field_session = request.session.get(filter_field_param)
if filter_field is None and filter_field_session is not None:
filter_field = filter_field_session
filter_info = {
'action': filter_action,
'value_param': param_name,
'value': filter_string,
'field_param': filter_field_param,
'field': filter_field,
'changed': changed
}
return filter_info
def handle_server_filter(self, request):
"""Update the table server filter information in the session and
determine if the filter has been changed.
"""
filter_info = self.get_server_filter_info(request)
if filter_info is None:
return False
request.session[filter_info['value_param']] = filter_info['value']
if filter_info['field_param']:
request.session[filter_info['field_param']] = filter_info['field']
return filter_info['changed']
def update_server_filter_action(self):
"""Update the table server side filter action based on the current
filter. The filter info may be stored in the session and this will
restore it.
"""
filter_info = self.get_server_filter_info(self.request)
if filter_info is not None:
action = filter_info['action']
setattr(action, 'filter_string', filter_info['value'])
if filter_info['field_param']:
setattr(action, 'filter_field', filter_info['field'])
class MixedDataTableView(DataTableView):
"""A class-based generic view to handle DataTable with mixed data
types.
Basic usage is the same as DataTableView.
Three steps are required to use this view:
#. Set the ``table_class`` attribute with desired
:class:`~horizon.tables.DataTable` class. In the class the
``data_types`` list should have at least two elements.
#. Define a ``get_{{ data_type }}_data`` method for each data type
which returns a set of data for the table.
#. Specify a template for the ``template_name`` attribute.
"""
table_class = None
context_object_name = 'table'
def _get_data_dict(self):
if not self._data:
table = self.table_class
self._data = {table._meta.name: []}
for data_type in table.data_types:
func_name = "get_%s_data" % data_type
data_func = getattr(self, func_name, None)
if data_func is None:
cls_name = self.__class__.__name__
raise NotImplementedError("You must define a %s method "
"for %s data type in %s." %
(func_name, data_type, cls_name))
data = data_func()
self.assign_type_string(data, data_type)
self._data[table._meta.name].extend(data)
return self._data
def assign_type_string(self, data, type_string):
for datum in data:
setattr(datum, self.table_class.data_type_name,
type_string)
def get_table(self):
self.table = super(MixedDataTableView, self).get_table()
if not self.table._meta.mixed_data_type:
raise AttributeError('You must have at least two elements in '
'the data_types attribute '
'in table %s to use MixedDataTableView.'
% self.table._meta.name)
return self.table
| apache-2.0 |
davidyezsetz/kuma | vendor/packages/nose/nose/importer.py | 14 | 5984 | """Implements an importer that looks only in specific path (ignoring
sys.path), and uses a per-path cache in addition to sys.modules. This is
necessary because test modules in different directories frequently have the
same names, which means that the first loaded would mask the rest when using
the builtin importer.
"""
import logging
import os
import sys
from nose.config import Config
from imp import find_module, load_module, acquire_lock, release_lock
log = logging.getLogger(__name__)
try:
_samefile = os.path.samefile
except AttributeError:
def _samefile(src, dst):
return (os.path.normcase(os.path.realpath(src)) ==
os.path.normcase(os.path.realpath(dst)))
class Importer(object):
"""An importer class that does only path-specific imports. That
is, the given module is not searched for on sys.path, but only at
the path or in the directory specified.
"""
def __init__(self, config=None):
if config is None:
config = Config()
self.config = config
def importFromPath(self, path, fqname):
"""Import a dotted-name package whose tail is at path. In other words,
given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then
bar from path/to/foo/bar, returning bar.
"""
# find the base dir of the package
path_parts = os.path.normpath(os.path.abspath(path)).split(os.sep)
name_parts = fqname.split('.')
if path_parts[-1].startswith('__init__'):
path_parts.pop()
path_parts = path_parts[:-(len(name_parts))]
dir_path = os.sep.join(path_parts)
# then import fqname starting from that dir
return self.importFromDir(dir_path, fqname)
def importFromDir(self, dir, fqname):
"""Import a module *only* from path, ignoring sys.path and
reloading if the version in sys.modules is not the one we want.
"""
dir = os.path.normpath(os.path.abspath(dir))
log.debug("Import %s from %s", fqname, dir)
# FIXME reimplement local per-dir cache?
# special case for __main__
if fqname == '__main__':
return sys.modules[fqname]
if self.config.addPaths:
add_path(dir, self.config)
path = [dir]
parts = fqname.split('.')
part_fqname = ''
mod = parent = fh = None
for part in parts:
if part_fqname == '':
part_fqname = part
else:
part_fqname = "%s.%s" % (part_fqname, part)
try:
acquire_lock()
log.debug("find module part %s (%s) in %s",
part, part_fqname, path)
fh, filename, desc = find_module(part, path)
old = sys.modules.get(part_fqname)
if old is not None:
# test modules frequently have name overlap; make sure
# we get a fresh copy of anything we are trying to load
# from a new path
log.debug("sys.modules has %s as %s", part_fqname, old)
if (self.sameModule(old, filename)
or (self.config.firstPackageWins and
getattr(old, '__path__', None))):
mod = old
else:
del sys.modules[part_fqname]
mod = load_module(part_fqname, fh, filename, desc)
else:
mod = load_module(part_fqname, fh, filename, desc)
finally:
if fh:
fh.close()
release_lock()
if parent:
setattr(parent, part, mod)
if hasattr(mod, '__path__'):
path = mod.__path__
parent = mod
return mod
def _dirname_if_file(self, filename):
# We only take the dirname if we have a path to a non-dir,
# because taking the dirname of a symlink to a directory does not
# give the actual directory parent.
if os.path.isdir(filename):
return filename
else:
return os.path.dirname(filename)
def sameModule(self, mod, filename):
mod_paths = []
if hasattr(mod, '__path__'):
for path in mod.__path__:
mod_paths.append(self._dirname_if_file(path))
elif hasattr(mod, '__file__'):
mod_paths.append(self._dirname_if_file(mod.__file__))
else:
# builtin or other module-like object that
# doesn't have __file__; must be new
return False
new_path = self._dirname_if_file(filename)
for mod_path in mod_paths:
log.debug(
"module already loaded? mod: %s new: %s",
mod_path, new_path)
if _samefile(mod_path, new_path):
return True
return False
def add_path(path, config=None):
"""Ensure that the path, or the root of the current package (if
path is in a package), is in sys.path.
"""
# FIXME add any src-looking dirs seen too... need to get config for that
log.debug('Add path %s' % path)
if not path:
return []
added = []
parent = os.path.dirname(path)
if (parent
and os.path.exists(os.path.join(path, '__init__.py'))):
added.extend(add_path(parent, config))
elif not path in sys.path:
log.debug("insert %s into sys.path", path)
sys.path.insert(0, path)
added.append(path)
if config and config.srcDirs:
for dirname in config.srcDirs:
dirpath = os.path.join(path, dirname)
if os.path.isdir(dirpath):
sys.path.insert(0, dirpath)
added.append(dirpath)
return added
def remove_path(path):
log.debug('Remove path %s' % path)
if path in sys.path:
sys.path.remove(path)
| mpl-2.0 |
ssudholt/phocnet | examples/prediction_example.py | 1 | 2767 | import caffe
import numpy as np
def main():
# This example is going to show you how you can use the API to predict
# PHOCs from a trained PHOCNet for your own word images.
# First we need to load the trained PHOCNet. We are going to use the trained
# PHOCNet supplied at
# http://patrec.cs.tu-dortmund.de/files/cnns/phocnet_gw_cv1.binaryproto
deploy_path = 'deploy_phocnet.prototxt'
trainet_net_path = 'phocnet_gw_cv1.binaryproto'
phocnet = caffe.Net(deploy_path, caffe.TEST, weights=trainet_net_path)
# Now you can supply your own images. For the sake of example, we use
# random arrays. We generate 4 images of shape 60 x 160, each having one
# channel. The pixel range is 0 - 255
images = [np.around(np.random.rand(60, 160, 1)*255)
for _ in xrange(4)]
# Note that the image ndarray arrays are now in the typical shape and pixel
# range of what you would get if you were to load your images with the
# standard tools such as OpenCV or skimage. For Caffe, we need to translate
# it into a 4D tensor of shape (num. images, channels, height, width)
for idx in xrange(4):
images[idx] = np.transpose(images[idx], (2, 0, 1))
images[idx] = np.reshape(images[idx], (1, 1, 60, 160))
# The PHOCNet accepts images in a pixel range of 0 (white) to 1 (black).
# Typically, the pixel intensities are inverted i.e. white is 255 and
# black is 0. We thus need to prepare our word images to be in the
# correct range. If your images are already in 0 (white) to 1 (black)
# you can skip this step.
images[idx] -= 255.0
images[idx] /= -255.0
# Now we are all set to shove the images through the PHOCNet.
# As we usually have different image sizes, we need to predict them
# one by one from the net.
# First, you need to reshape the input layer blob (word_images) to match
# the current word image shape you want to process.
phocs = []
for image in images:
phocnet.blobs['word_images'].reshape(*image.shape)
phocnet.reshape()
# Put the current image into the input layer...
phocnet.blobs['word_images'].data[...] = image
# ... and predict the PHOC (flatten automatically returns a copy)
phoc = phocnet.forward()['sigmoid'].flatten()
phocs.append(phoc)
# Congrats, you have a set of PHOCs for your word images.
# If you run into errors with the code above, make sure that your word images are
# shape (num. images, channels, height, width).
# Only in cases where you have images of the exact same size should num. images
# be different from 1
if __name__ == '__main__':
main() | bsd-3-clause |
ModdedPA/android_external_chromium_org | tools/perf/metrics/histogram_util.py | 23 | 1928 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import json
import logging
def SubtractHistogram(histogram_json, start_histogram_json):
"""Subtracts a previous histogram from a histogram. Both parameters are json
serializations of histograms."""
start_histogram = json.loads(start_histogram_json)
# It's ok if the start histogram is empty (we had no data, maybe even no
# histogram at all, at the start of the test).
if 'buckets' not in start_histogram:
return histogram_json
histogram = json.loads(histogram_json)
if ('pid' in start_histogram and 'pid' in histogram
and start_histogram['pid'] != histogram['pid']):
raise Exception(
'Trying to compare histograms from different processes (%d and %d)'
% (start_histogram['pid'], histogram['pid']))
start_histogram_buckets = dict()
for b in start_histogram['buckets']:
start_histogram_buckets[b['low']] = b['count']
new_buckets = []
for b in histogram['buckets']:
new_bucket = b
low = b['low']
if low in start_histogram_buckets:
new_bucket['count'] = b['count'] - start_histogram_buckets[low]
if new_bucket['count'] < 0:
logging.error('Histogram subtraction error, starting histogram most '
'probably invalid.')
if new_bucket['count']:
new_buckets.append(new_bucket)
histogram['buckets'] = new_buckets
histogram['count'] -= start_histogram['count']
return json.dumps(histogram)
def GetHistogramFromDomAutomation(function, name, tab):
# TODO(jeremy): Remove references to
# domAutomationController when we update the reference builds.
js = ('(window.statsCollectionController ? '
'statsCollectionController : '
'domAutomationController).%s("%s")' %
(function, name))
return tab.EvaluateJavaScript(js)
| bsd-3-clause |
Cinntax/home-assistant | tests/components/automation/test_time.py | 4 | 6379 | """The tests for the time automation."""
from datetime import timedelta
from unittest.mock import patch
import pytest
from homeassistant.setup import async_setup_component
import homeassistant.util.dt as dt_util
import homeassistant.components.automation as automation
from tests.common import async_fire_time_changed, assert_setup_component, mock_component
from tests.common import async_mock_service
@pytest.fixture
def calls(hass):
"""Track calls to a mock serivce."""
return async_mock_service(hass, "test", "automation")
@pytest.fixture(autouse=True)
def setup_comp(hass):
"""Initialize components."""
mock_component(hass, "group")
async def test_if_fires_using_at(hass, calls):
"""Test for firing at."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "time", "at": "5:00:00"},
"action": {
"service": "test.automation",
"data_template": {
"some": "{{ trigger.platform }} - " "{{ trigger.now.hour }}"
},
},
}
},
)
async_fire_time_changed(hass, dt_util.utcnow().replace(hour=5, minute=0, second=0))
await hass.async_block_till_done()
assert 1 == len(calls)
assert "time - 5" == calls[0].data["some"]
async def test_if_not_fires_using_wrong_at(hass, calls):
"""YAML translates time values to total seconds.
This should break the before rule.
"""
with assert_setup_component(0, automation.DOMAIN):
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {
"platform": "time",
"at": 3605,
# Total seconds. Hour = 3600 second
},
"action": {"service": "test.automation"},
}
},
)
async_fire_time_changed(hass, dt_util.utcnow().replace(hour=1, minute=0, second=5))
await hass.async_block_till_done()
assert 0 == len(calls)
async def test_if_action_before(hass, calls):
"""Test for if action before."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {"condition": "time", "before": "10:00"},
"action": {"service": "test.automation"},
}
},
)
before_10 = dt_util.now().replace(hour=8)
after_10 = dt_util.now().replace(hour=14)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=before_10):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 1 == len(calls)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=after_10):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 1 == len(calls)
async def test_if_action_after(hass, calls):
"""Test for if action after."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {"condition": "time", "after": "10:00"},
"action": {"service": "test.automation"},
}
},
)
before_10 = dt_util.now().replace(hour=8)
after_10 = dt_util.now().replace(hour=14)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=before_10):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 0 == len(calls)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=after_10):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 1 == len(calls)
async def test_if_action_one_weekday(hass, calls):
"""Test for if action with one weekday."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {"condition": "time", "weekday": "mon"},
"action": {"service": "test.automation"},
}
},
)
days_past_monday = dt_util.now().weekday()
monday = dt_util.now() - timedelta(days=days_past_monday)
tuesday = monday + timedelta(days=1)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=monday):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 1 == len(calls)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=tuesday):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 1 == len(calls)
async def test_if_action_list_weekday(hass, calls):
"""Test for action with a list of weekdays."""
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {"condition": "time", "weekday": ["mon", "tue"]},
"action": {"service": "test.automation"},
}
},
)
days_past_monday = dt_util.now().weekday()
monday = dt_util.now() - timedelta(days=days_past_monday)
tuesday = monday + timedelta(days=1)
wednesday = tuesday + timedelta(days=1)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=monday):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 1 == len(calls)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=tuesday):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 2 == len(calls)
with patch("homeassistant.helpers.condition.dt_util.now", return_value=wednesday):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert 2 == len(calls)
| apache-2.0 |
naterh/cloud-init-rax-pkg | cloudinit/config/cc_byobu.py | 10 | 2886 | # vi: ts=4 expandtab
#
# Copyright (C) 2009-2010 Canonical Ltd.
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
#
# Author: Scott Moser <scott.moser@canonical.com>
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Ensure this is aliased to a name not 'distros'
# since the module attribute 'distros'
# is a list of distros that are supported, not a sub-module
from cloudinit import distros as ds
from cloudinit import util
distros = ['ubuntu', 'debian']
def handle(name, cfg, cloud, log, args):
if len(args) != 0:
value = args[0]
else:
value = util.get_cfg_option_str(cfg, "byobu_by_default", "")
if not value:
log.debug("Skipping module named %s, no 'byobu' values found", name)
return
if value == "user" or value == "system":
value = "enable-%s" % value
valid = ("enable-user", "enable-system", "enable",
"disable-user", "disable-system", "disable")
if value not in valid:
log.warn("Unknown value %s for byobu_by_default", value)
mod_user = value.endswith("-user")
mod_sys = value.endswith("-system")
if value.startswith("enable"):
bl_inst = "install"
dc_val = "byobu byobu/launch-by-default boolean true"
mod_sys = True
else:
if value == "disable":
mod_user = True
mod_sys = True
bl_inst = "uninstall"
dc_val = "byobu byobu/launch-by-default boolean false"
shcmd = ""
if mod_user:
(users, _groups) = ds.normalize_users_groups(cfg, cloud.distro)
(user, _user_config) = ds.extract_default(users)
if not user:
log.warn(("No default byobu user provided, "
"can not launch %s for the default user"), bl_inst)
else:
shcmd += " sudo -Hu \"%s\" byobu-launcher-%s" % (user, bl_inst)
shcmd += " || X=$(($X+1)); "
if mod_sys:
shcmd += "echo \"%s\" | debconf-set-selections" % dc_val
shcmd += " && dpkg-reconfigure byobu --frontend=noninteractive"
shcmd += " || X=$(($X+1)); "
if len(shcmd):
cmd = ["/bin/sh", "-c", "%s %s %s" % ("X=0;", shcmd, "exit $X")]
log.debug("Setting byobu to %s", value)
util.subp(cmd, capture=False)
| gpl-3.0 |
wemanuel/smry | server-auth/ls/google-cloud-sdk/platform/gsutil/third_party/boto/boto/emr/connection.py | 79 | 28623 | # Copyright (c) 2010 Spotify AB
# Copyright (c) 2010-2011 Yelp
#
# 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.
"""
Represents a connection to the EMR service
"""
import types
import boto
import boto.utils
from boto.ec2.regioninfo import RegionInfo
from boto.emr.emrobject import AddInstanceGroupsResponse, BootstrapActionList, \
Cluster, ClusterSummaryList, HadoopStep, \
InstanceGroupList, InstanceList, JobFlow, \
JobFlowStepList, \
ModifyInstanceGroupsResponse, \
RunJobFlowResponse, StepSummaryList
from boto.emr.step import JarStep
from boto.connection import AWSQueryConnection
from boto.exception import EmrResponseError
from boto.compat import six
class EmrConnection(AWSQueryConnection):
APIVersion = boto.config.get('Boto', 'emr_version', '2009-03-31')
DefaultRegionName = boto.config.get('Boto', 'emr_region_name', 'us-east-1')
DefaultRegionEndpoint = boto.config.get('Boto', 'emr_region_endpoint',
'elasticmapreduce.us-east-1.amazonaws.com')
ResponseError = EmrResponseError
# Constants for AWS Console debugging
DebuggingJar = 's3n://us-east-1.elasticmapreduce/libs/script-runner/script-runner.jar'
DebuggingArgs = 's3n://us-east-1.elasticmapreduce/libs/state-pusher/0.1/fetch'
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
proxy_user=None, proxy_pass=None, debug=0,
https_connection_factory=None, region=None, path='/',
security_token=None, validate_certs=True, profile_name=None):
if not region:
region = RegionInfo(self, self.DefaultRegionName,
self.DefaultRegionEndpoint)
self.region = region
super(EmrConnection, self).__init__(aws_access_key_id,
aws_secret_access_key,
is_secure, port, proxy, proxy_port,
proxy_user, proxy_pass,
self.region.endpoint, debug,
https_connection_factory, path,
security_token,
validate_certs=validate_certs,
profile_name=profile_name)
# Many of the EMR hostnames are of the form:
# <region>.<service_name>.amazonaws.com
# rather than the more common:
# <service_name>.<region>.amazonaws.com
# so we need to explicitly set the region_name and service_name
# for the SigV4 signing.
self.auth_region_name = self.region.name
self.auth_service_name = 'elasticmapreduce'
def _required_auth_capability(self):
return ['hmac-v4']
def describe_cluster(self, cluster_id):
"""
Describes an Elastic MapReduce cluster
:type cluster_id: str
:param cluster_id: The cluster id of interest
"""
params = {
'ClusterId': cluster_id
}
return self.get_object('DescribeCluster', params, Cluster)
def describe_jobflow(self, jobflow_id):
"""
Describes a single Elastic MapReduce job flow
:type jobflow_id: str
:param jobflow_id: The job flow id of interest
"""
jobflows = self.describe_jobflows(jobflow_ids=[jobflow_id])
if jobflows:
return jobflows[0]
def describe_jobflows(self, states=None, jobflow_ids=None,
created_after=None, created_before=None):
"""
Retrieve all the Elastic MapReduce job flows on your account
:type states: list
:param states: A list of strings with job flow states wanted
:type jobflow_ids: list
:param jobflow_ids: A list of job flow IDs
:type created_after: datetime
:param created_after: Bound on job flow creation time
:type created_before: datetime
:param created_before: Bound on job flow creation time
"""
params = {}
if states:
self.build_list_params(params, states, 'JobFlowStates.member')
if jobflow_ids:
self.build_list_params(params, jobflow_ids, 'JobFlowIds.member')
if created_after:
params['CreatedAfter'] = created_after.strftime(
boto.utils.ISO8601)
if created_before:
params['CreatedBefore'] = created_before.strftime(
boto.utils.ISO8601)
return self.get_list('DescribeJobFlows', params, [('member', JobFlow)])
def describe_step(self, cluster_id, step_id):
"""
Describe an Elastic MapReduce step
:type cluster_id: str
:param cluster_id: The cluster id of interest
:type step_id: str
:param step_id: The step id of interest
"""
params = {
'ClusterId': cluster_id,
'StepId': step_id
}
return self.get_object('DescribeStep', params, HadoopStep)
def list_bootstrap_actions(self, cluster_id, marker=None):
"""
Get a list of bootstrap actions for an Elastic MapReduce cluster
:type cluster_id: str
:param cluster_id: The cluster id of interest
:type marker: str
:param marker: Pagination marker
"""
params = {
'ClusterId': cluster_id
}
if marker:
params['Marker'] = marker
return self.get_object('ListBootstrapActions', params, BootstrapActionList)
def list_clusters(self, created_after=None, created_before=None,
cluster_states=None, marker=None):
"""
List Elastic MapReduce clusters with optional filtering
:type created_after: datetime
:param created_after: Bound on cluster creation time
:type created_before: datetime
:param created_before: Bound on cluster creation time
:type cluster_states: list
:param cluster_states: Bound on cluster states
:type marker: str
:param marker: Pagination marker
"""
params = {}
if created_after:
params['CreatedAfter'] = created_after.strftime(
boto.utils.ISO8601)
if created_before:
params['CreatedBefore'] = created_before.strftime(
boto.utils.ISO8601)
if marker:
params['Marker'] = marker
if cluster_states:
self.build_list_params(params, cluster_states, 'ClusterStates.member')
return self.get_object('ListClusters', params, ClusterSummaryList)
def list_instance_groups(self, cluster_id, marker=None):
"""
List EC2 instance groups in a cluster
:type cluster_id: str
:param cluster_id: The cluster id of interest
:type marker: str
:param marker: Pagination marker
"""
params = {
'ClusterId': cluster_id
}
if marker:
params['Marker'] = marker
return self.get_object('ListInstanceGroups', params, InstanceGroupList)
def list_instances(self, cluster_id, instance_group_id=None,
instance_group_types=None, marker=None):
"""
List EC2 instances in a cluster
:type cluster_id: str
:param cluster_id: The cluster id of interest
:type instance_group_id: str
:param instance_group_id: The EC2 instance group id of interest
:type instance_group_types: list
:param instance_group_types: Filter by EC2 instance group type
:type marker: str
:param marker: Pagination marker
"""
params = {
'ClusterId': cluster_id
}
if instance_group_id:
params['InstanceGroupId'] = instance_group_id
if marker:
params['Marker'] = marker
if instance_group_types:
self.build_list_params(params, instance_group_types,
'InstanceGroupTypeList.member')
return self.get_object('ListInstances', params, InstanceList)
def list_steps(self, cluster_id, step_states=None, marker=None):
"""
List cluster steps
:type cluster_id: str
:param cluster_id: The cluster id of interest
:type step_states: list
:param step_states: Filter by step states
:type marker: str
:param marker: Pagination marker
"""
params = {
'ClusterId': cluster_id
}
if marker:
params['Marker'] = marker
if step_states:
self.build_list_params(params, step_states, 'StepStateList.member')
return self.get_object('ListSteps', params, StepSummaryList)
def add_tags(self, resource_id, tags):
"""
Create new metadata tags for the specified resource id.
:type resource_id: str
:param resource_id: The cluster id
:type tags: dict
:param tags: A dictionary containing the name/value pairs.
If you want to create only a tag name, the
value for that tag should be the empty string
(e.g. '') or None.
"""
assert isinstance(resource_id, six.string_types)
params = {
'ResourceId': resource_id,
}
params.update(self._build_tag_list(tags))
return self.get_status('AddTags', params, verb='POST')
def remove_tags(self, resource_id, tags):
"""
Remove metadata tags for the specified resource id.
:type resource_id: str
:param resource_id: The cluster id
:type tags: list
:param tags: A list of tag names to remove.
"""
params = {
'ResourceId': resource_id,
}
params.update(self._build_string_list('TagKeys', tags))
return self.get_status('RemoveTags', params, verb='POST')
def terminate_jobflow(self, jobflow_id):
"""
Terminate an Elastic MapReduce job flow
:type jobflow_id: str
:param jobflow_id: A jobflow id
"""
self.terminate_jobflows([jobflow_id])
def terminate_jobflows(self, jobflow_ids):
"""
Terminate an Elastic MapReduce job flow
:type jobflow_ids: list
:param jobflow_ids: A list of job flow IDs
"""
params = {}
self.build_list_params(params, jobflow_ids, 'JobFlowIds.member')
return self.get_status('TerminateJobFlows', params, verb='POST')
def add_jobflow_steps(self, jobflow_id, steps):
"""
Adds steps to a jobflow
:type jobflow_id: str
:param jobflow_id: The job flow id
:type steps: list(boto.emr.Step)
:param steps: A list of steps to add to the job
"""
if not isinstance(steps, list):
steps = [steps]
params = {}
params['JobFlowId'] = jobflow_id
# Step args
step_args = [self._build_step_args(step) for step in steps]
params.update(self._build_step_list(step_args))
return self.get_object(
'AddJobFlowSteps', params, JobFlowStepList, verb='POST')
def add_instance_groups(self, jobflow_id, instance_groups):
"""
Adds instance groups to a running cluster.
:type jobflow_id: str
:param jobflow_id: The id of the jobflow which will take the
new instance groups
:type instance_groups: list(boto.emr.InstanceGroup)
:param instance_groups: A list of instance groups to add to the job
"""
if not isinstance(instance_groups, list):
instance_groups = [instance_groups]
params = {}
params['JobFlowId'] = jobflow_id
params.update(self._build_instance_group_list_args(instance_groups))
return self.get_object('AddInstanceGroups', params,
AddInstanceGroupsResponse, verb='POST')
def modify_instance_groups(self, instance_group_ids, new_sizes):
"""
Modify the number of nodes and configuration settings in an
instance group.
:type instance_group_ids: list(str)
:param instance_group_ids: A list of the ID's of the instance
groups to be modified
:type new_sizes: list(int)
:param new_sizes: A list of the new sizes for each instance group
"""
if not isinstance(instance_group_ids, list):
instance_group_ids = [instance_group_ids]
if not isinstance(new_sizes, list):
new_sizes = [new_sizes]
instance_groups = zip(instance_group_ids, new_sizes)
params = {}
for k, ig in enumerate(instance_groups):
# could be wrong - the example amazon gives uses
# InstanceRequestCount, while the api documentation
# says InstanceCount
params['InstanceGroups.member.%d.InstanceGroupId' % (k+1) ] = ig[0]
params['InstanceGroups.member.%d.InstanceCount' % (k+1) ] = ig[1]
return self.get_object('ModifyInstanceGroups', params,
ModifyInstanceGroupsResponse, verb='POST')
def run_jobflow(self, name, log_uri=None, ec2_keyname=None,
availability_zone=None,
master_instance_type='m1.small',
slave_instance_type='m1.small', num_instances=1,
action_on_failure='TERMINATE_JOB_FLOW', keep_alive=False,
enable_debugging=False,
hadoop_version=None,
steps=[],
bootstrap_actions=[],
instance_groups=None,
additional_info=None,
ami_version=None,
api_params=None,
visible_to_all_users=None,
job_flow_role=None,
service_role=None):
"""
Runs a job flow
:type name: str
:param name: Name of the job flow
:type log_uri: str
:param log_uri: URI of the S3 bucket to place logs
:type ec2_keyname: str
:param ec2_keyname: EC2 key used for the instances
:type availability_zone: str
:param availability_zone: EC2 availability zone of the cluster
:type master_instance_type: str
:param master_instance_type: EC2 instance type of the master
:type slave_instance_type: str
:param slave_instance_type: EC2 instance type of the slave nodes
:type num_instances: int
:param num_instances: Number of instances in the Hadoop cluster
:type action_on_failure: str
:param action_on_failure: Action to take if a step terminates
:type keep_alive: bool
:param keep_alive: Denotes whether the cluster should stay
alive upon completion
:type enable_debugging: bool
:param enable_debugging: Denotes whether AWS console debugging
should be enabled.
:type hadoop_version: str
:param hadoop_version: Version of Hadoop to use. This no longer
defaults to '0.20' and now uses the AMI default.
:type steps: list(boto.emr.Step)
:param steps: List of steps to add with the job
:type bootstrap_actions: list(boto.emr.BootstrapAction)
:param bootstrap_actions: List of bootstrap actions that run
before Hadoop starts.
:type instance_groups: list(boto.emr.InstanceGroup)
:param instance_groups: Optional list of instance groups to
use when creating this job.
NB: When provided, this argument supersedes num_instances
and master/slave_instance_type.
:type ami_version: str
:param ami_version: Amazon Machine Image (AMI) version to use
for instances. Values accepted by EMR are '1.0', '2.0', and
'latest'; EMR currently defaults to '1.0' if you don't set
'ami_version'.
:type additional_info: JSON str
:param additional_info: A JSON string for selecting additional features
:type api_params: dict
:param api_params: a dictionary of additional parameters to pass
directly to the EMR API (so you don't have to upgrade boto to
use new EMR features). You can also delete an API parameter
by setting it to None.
:type visible_to_all_users: bool
:param visible_to_all_users: Whether the job flow is visible to all IAM
users of the AWS account associated with the job flow. If this
value is set to ``True``, all IAM users of that AWS
account can view and (if they have the proper policy permissions
set) manage the job flow. If it is set to ``False``, only
the IAM user that created the job flow can view and manage
it.
:type job_flow_role: str
:param job_flow_role: An IAM role for the job flow. The EC2
instances of the job flow assume this role. The default role is
``EMRJobflowDefault``. In order to use the default role,
you must have already created it using the CLI.
:type service_role: str
:param service_role: The IAM role that will be assumed by the Amazon
EMR service to access AWS resources on your behalf.
:rtype: str
:return: The jobflow id
"""
params = {}
if action_on_failure:
params['ActionOnFailure'] = action_on_failure
if log_uri:
params['LogUri'] = log_uri
params['Name'] = name
# Common instance args
common_params = self._build_instance_common_args(ec2_keyname,
availability_zone,
keep_alive,
hadoop_version)
params.update(common_params)
# NB: according to the AWS API's error message, we must
# "configure instances either using instance count, master and
# slave instance type or instance groups but not both."
#
# Thus we switch here on the truthiness of instance_groups.
if not instance_groups:
# Instance args (the common case)
instance_params = self._build_instance_count_and_type_args(
master_instance_type,
slave_instance_type,
num_instances)
params.update(instance_params)
else:
# Instance group args (for spot instances or a heterogenous cluster)
list_args = self._build_instance_group_list_args(instance_groups)
instance_params = dict(
('Instances.%s' % k, v) for k, v in six.iteritems(list_args)
)
params.update(instance_params)
# Debugging step from EMR API docs
if enable_debugging:
debugging_step = JarStep(name='Setup Hadoop Debugging',
action_on_failure='TERMINATE_JOB_FLOW',
main_class=None,
jar=self.DebuggingJar,
step_args=self.DebuggingArgs)
steps.insert(0, debugging_step)
# Step args
if steps:
step_args = [self._build_step_args(step) for step in steps]
params.update(self._build_step_list(step_args))
if bootstrap_actions:
bootstrap_action_args = [self._build_bootstrap_action_args(bootstrap_action) for bootstrap_action in bootstrap_actions]
params.update(self._build_bootstrap_action_list(bootstrap_action_args))
if ami_version:
params['AmiVersion'] = ami_version
if additional_info is not None:
params['AdditionalInfo'] = additional_info
if api_params:
for key, value in six.iteritems(api_params):
if value is None:
params.pop(key, None)
else:
params[key] = value
if visible_to_all_users is not None:
if visible_to_all_users:
params['VisibleToAllUsers'] = 'true'
else:
params['VisibleToAllUsers'] = 'false'
if job_flow_role is not None:
params['JobFlowRole'] = job_flow_role
if service_role is not None:
params['ServiceRole'] = service_role
response = self.get_object(
'RunJobFlow', params, RunJobFlowResponse, verb='POST')
return response.jobflowid
def set_termination_protection(self, jobflow_id,
termination_protection_status):
"""
Set termination protection on specified Elastic MapReduce job flows
:type jobflow_ids: list or str
:param jobflow_ids: A list of job flow IDs
:type termination_protection_status: bool
:param termination_protection_status: Termination protection status
"""
assert termination_protection_status in (True, False)
params = {}
params['TerminationProtected'] = (termination_protection_status and "true") or "false"
self.build_list_params(params, [jobflow_id], 'JobFlowIds.member')
return self.get_status('SetTerminationProtection', params, verb='POST')
def set_visible_to_all_users(self, jobflow_id, visibility):
"""
Set whether specified Elastic Map Reduce job flows are visible to all IAM users
:type jobflow_ids: list or str
:param jobflow_ids: A list of job flow IDs
:type visibility: bool
:param visibility: Visibility
"""
assert visibility in (True, False)
params = {}
params['VisibleToAllUsers'] = (visibility and "true") or "false"
self.build_list_params(params, [jobflow_id], 'JobFlowIds.member')
return self.get_status('SetVisibleToAllUsers', params, verb='POST')
def _build_bootstrap_action_args(self, bootstrap_action):
bootstrap_action_params = {}
bootstrap_action_params['ScriptBootstrapAction.Path'] = bootstrap_action.path
try:
bootstrap_action_params['Name'] = bootstrap_action.name
except AttributeError:
pass
args = bootstrap_action.args()
if args:
self.build_list_params(bootstrap_action_params, args, 'ScriptBootstrapAction.Args.member')
return bootstrap_action_params
def _build_step_args(self, step):
step_params = {}
step_params['ActionOnFailure'] = step.action_on_failure
step_params['HadoopJarStep.Jar'] = step.jar()
main_class = step.main_class()
if main_class:
step_params['HadoopJarStep.MainClass'] = main_class
args = step.args()
if args:
self.build_list_params(step_params, args, 'HadoopJarStep.Args.member')
step_params['Name'] = step.name
return step_params
def _build_bootstrap_action_list(self, bootstrap_actions):
if not isinstance(bootstrap_actions, list):
bootstrap_actions = [bootstrap_actions]
params = {}
for i, bootstrap_action in enumerate(bootstrap_actions):
for key, value in six.iteritems(bootstrap_action):
params['BootstrapActions.member.%s.%s' % (i + 1, key)] = value
return params
def _build_step_list(self, steps):
if not isinstance(steps, list):
steps = [steps]
params = {}
for i, step in enumerate(steps):
for key, value in six.iteritems(step):
params['Steps.member.%s.%s' % (i+1, key)] = value
return params
def _build_string_list(self, field, items):
if not isinstance(items, list):
items = [items]
params = {}
for i, item in enumerate(items):
params['%s.member.%s' % (field, i + 1)] = item
return params
def _build_tag_list(self, tags):
assert isinstance(tags, dict)
params = {}
for i, key_value in enumerate(sorted(six.iteritems(tags)), start=1):
key, value = key_value
current_prefix = 'Tags.member.%s' % i
params['%s.Key' % current_prefix] = key
if value:
params['%s.Value' % current_prefix] = value
return params
def _build_instance_common_args(self, ec2_keyname, availability_zone,
keep_alive, hadoop_version):
"""
Takes a number of parameters used when starting a jobflow (as
specified in run_jobflow() above). Returns a comparable dict for
use in making a RunJobFlow request.
"""
params = {
'Instances.KeepJobFlowAliveWhenNoSteps': str(keep_alive).lower(),
}
if hadoop_version:
params['Instances.HadoopVersion'] = hadoop_version
if ec2_keyname:
params['Instances.Ec2KeyName'] = ec2_keyname
if availability_zone:
params['Instances.Placement.AvailabilityZone'] = availability_zone
return params
def _build_instance_count_and_type_args(self, master_instance_type,
slave_instance_type, num_instances):
"""
Takes a master instance type (string), a slave instance type
(string), and a number of instances. Returns a comparable dict
for use in making a RunJobFlow request.
"""
params = {'Instances.MasterInstanceType': master_instance_type,
'Instances.SlaveInstanceType': slave_instance_type,
'Instances.InstanceCount': num_instances}
return params
def _build_instance_group_args(self, instance_group):
"""
Takes an InstanceGroup; returns a dict that, when its keys are
properly prefixed, can be used for describing InstanceGroups in
RunJobFlow or AddInstanceGroups requests.
"""
params = {'InstanceCount': instance_group.num_instances,
'InstanceRole': instance_group.role,
'InstanceType': instance_group.type,
'Name': instance_group.name,
'Market': instance_group.market}
if instance_group.market == 'SPOT':
params['BidPrice'] = instance_group.bidprice
return params
def _build_instance_group_list_args(self, instance_groups):
"""
Takes a list of InstanceGroups, or a single InstanceGroup. Returns
a comparable dict for use in making a RunJobFlow or AddInstanceGroups
request.
"""
if not isinstance(instance_groups, list):
instance_groups = [instance_groups]
params = {}
for i, instance_group in enumerate(instance_groups):
ig_dict = self._build_instance_group_args(instance_group)
for key, value in six.iteritems(ig_dict):
params['InstanceGroups.member.%d.%s' % (i+1, key)] = value
return params
| apache-2.0 |
odootr/odoo | addons/point_of_sale/report/pos_users_product.py | 380 | 3336 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.osv import osv
from openerp.report import report_sxw
class pos_user_product(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(pos_user_product, self).__init__(cr, uid, name, context)
self.localcontext.update({
'time': time,
'get_data':self._get_data,
'get_user':self._get_user,
'get_total':self._get_total,
})
def _get_data(self, o):
self.total = 0.0
data={}
sql1=""" SELECT distinct(o.id) from account_bank_statement s, account_bank_statement_line l,pos_order o,pos_order_line i where i.order_id=o.id and o.state='paid' and l.statement_id=s.id and l.pos_statement_id=o.id and s.id=%d"""%(o.id)
self.cr.execute(sql1)
data = self.cr.dictfetchall()
a_l=[]
for r in data:
a_l.append(r['id'])
if len(a_l):
sql2="""SELECT sum(qty) as qty,l.price_unit*sum(l.qty) as amt,t.name as name, p.default_code as code, pu.name as uom from product_product p, product_template t,product_uom pu,pos_order_line l where order_id = %d and p.product_tmpl_id=t.id and l.product_id=p.id and pu.id=t.uom_id group by t.name,p.default_code,pu.name,l.price_unit"""%(o.id)
self.cr.execute(sql2)
data = self.cr.dictfetchall()
for d in data:
self.total += d['amt']
return data
def _get_user(self, object):
names = []
users_obj = self.pool['res.users']
for o in object:
sql = """select ru.id from account_bank_statement as abs,res_users ru
where abs.user_id = ru.id
and abs.id = %d"""%(o.id)
self.cr.execute(sql)
data = self.cr.fetchone()
if data:
user = users_obj.browse(self.cr, self.uid, data[0])
names.append(user.partner_id.name)
return list(set(names))
def _get_total(self, o):
return self.total
class report_pos_user_product(osv.AbstractModel):
_name = 'report.point_of_sale.report_usersproduct'
_inherit = 'report.abstract_report'
_template = 'point_of_sale.report_usersproduct'
_wrapped_report_class = pos_user_product
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
JCROM-Android/jcrom_kernel_omap | tools/perf/scripts/python/sctop.py | 11180 | 1924 | # system call top
# (c) 2010, Tom Zanussi <tzanussi@gmail.com>
# Licensed under the terms of the GNU GPL License version 2
#
# Periodically displays system-wide system call totals, broken down by
# syscall. If a [comm] arg is specified, only syscalls called by
# [comm] are displayed. If an [interval] arg is specified, the display
# will be refreshed every [interval] seconds. The default interval is
# 3 seconds.
import os, sys, thread, time
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 *
usage = "perf script -s sctop.py [comm] [interval]\n";
for_comm = None
default_interval = 3
interval = default_interval
if len(sys.argv) > 3:
sys.exit(usage)
if len(sys.argv) > 2:
for_comm = sys.argv[1]
interval = int(sys.argv[2])
elif len(sys.argv) > 1:
try:
interval = int(sys.argv[1])
except ValueError:
for_comm = sys.argv[1]
interval = default_interval
syscalls = autodict()
def trace_begin():
thread.start_new_thread(print_syscall_totals, (interval,))
pass
def raw_syscalls__sys_enter(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
id, args):
if for_comm is not None:
if common_comm != for_comm:
return
try:
syscalls[id] += 1
except TypeError:
syscalls[id] = 1
def print_syscall_totals(interval):
while 1:
clear_term()
if for_comm is not None:
print "\nsyscall events for %s:\n\n" % (for_comm),
else:
print "\nsyscall events:\n\n",
print "%-40s %10s\n" % ("event", "count"),
print "%-40s %10s\n" % ("----------------------------------------", \
"----------"),
for id, val in sorted(syscalls.iteritems(), key = lambda(k, v): (v, k), \
reverse = True):
try:
print "%-40s %10d\n" % (syscall_name(id), val),
except TypeError:
pass
syscalls.clear()
time.sleep(interval)
| gpl-2.0 |
gkarlin/django-jenkins | build/Django/django/contrib/gis/gdal/__init__.py | 104 | 2130 | """
This module houses ctypes interfaces for GDAL objects. The following GDAL
objects are supported:
CoordTransform: Used for coordinate transformations from one spatial
reference system to another.
Driver: Wraps an OGR data source driver.
DataSource: Wrapper for the OGR data source object, supports
OGR-supported data sources.
Envelope: A ctypes structure for bounding boxes (GDAL library
not required).
OGRGeometry: Object for accessing OGR Geometry functionality.
OGRGeomType: A class for representing the different OGR Geometry
types (GDAL library not required).
SpatialReference: Represents OSR Spatial Reference objects.
The GDAL library will be imported from the system path using the default
library name for the current OS. The default library path may be overridden
by setting `GDAL_LIBRARY_PATH` in your settings with the path to the GDAL C
library on your system.
GDAL links to a large number of external libraries that consume RAM when
loaded. Thus, it may desirable to disable GDAL on systems with limited
RAM resources -- this may be accomplished by setting `GDAL_LIBRARY_PATH`
to a non-existant file location (e.g., `GDAL_LIBRARY_PATH='/null/path'`;
setting to None/False/'' will not work as a string must be given).
"""
# Attempting to import objects that depend on the GDAL library. The
# HAS_GDAL flag will be set to True if the library is present on
# the system.
try:
from django.contrib.gis.gdal.driver import Driver
from django.contrib.gis.gdal.datasource import DataSource
from django.contrib.gis.gdal.libgdal import gdal_version, gdal_full_version, GDAL_VERSION
from django.contrib.gis.gdal.srs import SpatialReference, CoordTransform
from django.contrib.gis.gdal.geometries import OGRGeometry
HAS_GDAL = True
except Exception:
HAS_GDAL = False
try:
from django.contrib.gis.gdal.envelope import Envelope
except ImportError:
# No ctypes, but don't raise an exception.
pass
from django.contrib.gis.gdal.error import check_err, OGRException, OGRIndexError, SRSException
from django.contrib.gis.gdal.geomtype import OGRGeomType
| lgpl-3.0 |
markflyhigh/incubator-beam | sdks/python/apache_beam/runners/dataflow/dataflow_exercise_streaming_metrics_pipeline_test.py | 1 | 7291 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""A word-counting workflow."""
from __future__ import absolute_import
import logging
import unittest
import uuid
from hamcrest.core.core.allof import all_of
from nose.plugins.attrib import attr
from apache_beam.io.gcp.tests.pubsub_matcher import PubSubMessageMatcher
from apache_beam.runners.dataflow import dataflow_exercise_streaming_metrics_pipeline
from apache_beam.runners.runner import PipelineState
from apache_beam.testing import metric_result_matchers
from apache_beam.testing import test_utils
from apache_beam.testing.metric_result_matchers import DistributionMatcher
from apache_beam.testing.metric_result_matchers import MetricResultMatcher
from apache_beam.testing.pipeline_verifiers import PipelineStateMatcher
from apache_beam.testing.test_pipeline import TestPipeline
INPUT_TOPIC = 'exercise_streaming_metrics_topic_input'
INPUT_SUB = 'exercise_streaming_metrics_subscription_input'
OUTPUT_TOPIC = 'exercise_streaming_metrics_topic_output'
OUTPUT_SUB = 'exercise_streaming_metrics_subscription_output'
WAIT_UNTIL_FINISH_DURATION = 1 * 60 * 1000 # in milliseconds
MESSAGES_TO_PUBLISH = ["message a", "message b b", "message c"]
SLEEP_TIME_SECS = 1
class ExerciseStreamingMetricsPipelineTest(unittest.TestCase):
def setUp(self):
"""Creates all required topics and subs."""
self.test_pipeline = TestPipeline(is_integration_test=True)
self.project = self.test_pipeline.get_option('project')
self.uuid = str(uuid.uuid4())
# Set up PubSub environment.
from google.cloud import pubsub
self.pub_client = pubsub.PublisherClient()
self.input_topic_name = INPUT_TOPIC + self.uuid
self.input_topic = self.pub_client.create_topic(
self.pub_client.topic_path(self.project, self.input_topic_name))
self.output_topic_name = OUTPUT_TOPIC + self.uuid
self.output_topic = self.pub_client.create_topic(
self.pub_client.topic_path(self.project, self.output_topic_name))
self.sub_client = pubsub.SubscriberClient()
self.input_sub_name = INPUT_SUB + self.uuid
self.input_sub = self.sub_client.create_subscription(
self.sub_client.subscription_path(self.project, self.input_sub_name),
self.input_topic.name)
self.output_sub_name = OUTPUT_SUB + self.uuid
self.output_sub = self.sub_client.create_subscription(
self.sub_client.subscription_path(self.project, self.output_sub_name),
self.output_topic.name,
ack_deadline_seconds=60)
def _inject_words(self, topic, messages):
"""Inject messages as test data to PubSub."""
logging.debug('Injecting messages to topic %s', topic.name)
for msg in messages:
self.pub_client.publish(self.input_topic.name, msg.encode('utf-8'))
logging.debug('Done. Injecting messages to topic %s', topic.name)
def tearDown(self):
"""Delete all created topics and subs."""
test_utils.cleanup_subscriptions(self.sub_client,
[self.input_sub, self.output_sub])
test_utils.cleanup_topics(self.pub_client,
[self.input_topic, self.output_topic])
def run_pipeline(self):
# Waits for messages to appear in output topic.
expected_msg = [msg.encode('utf-8') for msg in MESSAGES_TO_PUBLISH]
pubsub_msg_verifier = PubSubMessageMatcher(self.project,
self.output_sub.name,
expected_msg,
timeout=600)
# Checks that pipeline initializes to RUNNING state.
state_verifier = PipelineStateMatcher(PipelineState.RUNNING)
extra_opts = {'wait_until_finish_duration': WAIT_UNTIL_FINISH_DURATION,
'on_success_matcher': all_of(state_verifier,
pubsub_msg_verifier),
'experiment': 'beam_fn_api',
'input_subscription': self.input_sub.name,
'output_topic': self.output_topic.name,
}
argv = self.test_pipeline.get_full_options_as_args(**extra_opts)
return dataflow_exercise_streaming_metrics_pipeline.run(argv)
@attr('IT', 'ValidatesRunner')
def test_streaming_pipeline_returns_expected_user_metrics_fnapi_it(self):
"""
Runs streaming Dataflow job and verifies that user metrics are reported
correctly.
"""
self._inject_words(self.input_topic, MESSAGES_TO_PUBLISH)
result = self.run_pipeline()
METRIC_NAMESPACE = \
('apache_beam.runners.dataflow.'
'dataflow_exercise_streaming_metrics_pipeline.StreamingUserMetricsDoFn')
matchers = [
# System metrics
MetricResultMatcher(
name='ElementCount',
labels={"output_user_name": "generate_metrics-out0",
"original_name": "generate_metrics-out0-ElementCount"},
attempted=len(MESSAGES_TO_PUBLISH),
committed=len(MESSAGES_TO_PUBLISH),
),
MetricResultMatcher(
name='ElementCount',
labels={"output_user_name": "ReadFromPubSub/Read-out0",
"original_name": "ReadFromPubSub/Read-out0-ElementCount"},
attempted=len(MESSAGES_TO_PUBLISH),
committed=len(MESSAGES_TO_PUBLISH),
),
# User Counter Metrics.
MetricResultMatcher(
name='double_msg_counter_name',
namespace=METRIC_NAMESPACE,
step='generate_metrics',
attempted=len(MESSAGES_TO_PUBLISH) * 2,
committed=len(MESSAGES_TO_PUBLISH) * 2
),
MetricResultMatcher(
name='msg_len_dist_metric_name',
namespace=METRIC_NAMESPACE,
step='generate_metrics',
attempted=DistributionMatcher(
sum_value=len(''.join(MESSAGES_TO_PUBLISH)),
count_value=len(MESSAGES_TO_PUBLISH),
min_value=len(MESSAGES_TO_PUBLISH[0]),
max_value=len(MESSAGES_TO_PUBLISH[1])
),
committed=DistributionMatcher(
sum_value=len(''.join(MESSAGES_TO_PUBLISH)),
count_value=len(MESSAGES_TO_PUBLISH),
min_value=len(MESSAGES_TO_PUBLISH[0]),
max_value=len(MESSAGES_TO_PUBLISH[1])
)
),
]
metrics = result.metrics().all_metrics()
errors = metric_result_matchers.verify_all(metrics, matchers)
self.assertFalse(errors, str(errors))
if __name__ == '__main__':
unittest.main()
| apache-2.0 |
trondhindenes/ansible | test/units/modules/network/nxos/test_nxos_ip_interface.py | 33 | 3374 | # (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.nxos import _nxos_ip_interface
from .nxos_module import TestNxosModule, load_fixture, set_module_args
class TestNxosIPInterfaceModule(TestNxosModule):
module = _nxos_ip_interface
def setUp(self):
super(TestNxosIPInterfaceModule, self).setUp()
self.mock_get_interface_mode = patch(
'ansible.modules.network.nxos._nxos_ip_interface.get_interface_mode')
self.get_interface_mode = self.mock_get_interface_mode.start()
self.mock_send_show_command = patch(
'ansible.modules.network.nxos._nxos_ip_interface.send_show_command')
self.send_show_command = self.mock_send_show_command.start()
self.mock_load_config = patch('ansible.modules.network.nxos._nxos_ip_interface.load_config')
self.load_config = self.mock_load_config.start()
self.mock_get_capabilities = patch('ansible.modules.network.nxos._nxos_ip_interface.get_capabilities')
self.get_capabilities = self.mock_get_capabilities.start()
self.get_capabilities.return_value = {'network_api': 'cliconf'}
def tearDown(self):
super(TestNxosIPInterfaceModule, self).tearDown()
self.mock_get_interface_mode.stop()
self.mock_send_show_command.stop()
self.mock_load_config.stop()
self.mock_get_capabilities.stop()
def load_fixtures(self, commands=None, device=''):
self.get_interface_mode.return_value = 'layer3'
self.send_show_command.return_value = [load_fixture('', '_nxos_ip_interface.cfg')]
self.load_config.return_value = None
def test_nxos_ip_interface_ip_present(self):
set_module_args(dict(interface='eth2/1', addr='1.1.1.2', mask=8))
result = self.execute_module(changed=True)
self.assertEqual(result['commands'],
['interface eth2/1',
'no ip address 192.0.2.1/8',
'ip address 1.1.1.2/8'])
def test_nxos_ip_interface_ip_idempotent(self):
set_module_args(dict(interface='eth2/1', addr='192.0.2.1', mask=8))
result = self.execute_module(changed=False)
self.assertEqual(result['commands'], [])
def test_nxos_ip_interface_ip_absent(self):
set_module_args(dict(interface='eth2/1', state='absent',
addr='192.0.2.1', mask=8))
result = self.execute_module(changed=True)
self.assertEqual(result['commands'],
['interface eth2/1', 'no ip address 192.0.2.1/8'])
| gpl-3.0 |
pranner/CMPUT410-Lab6-Django | v1/lib/python2.7/site-packages/django/contrib/admin/tests.py | 301 | 6166 | import os
from unittest import SkipTest
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.utils.module_loading import import_string
from django.utils.translation import ugettext as _
class AdminSeleniumWebDriverTestCase(StaticLiveServerTestCase):
available_apps = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
]
webdriver_class = 'selenium.webdriver.firefox.webdriver.WebDriver'
@classmethod
def setUpClass(cls):
if not os.environ.get('DJANGO_SELENIUM_TESTS', False):
raise SkipTest('Selenium tests not requested')
try:
cls.selenium = import_string(cls.webdriver_class)()
except Exception as e:
raise SkipTest('Selenium webdriver "%s" not installed or not '
'operational: %s' % (cls.webdriver_class, str(e)))
# This has to be last to ensure that resources are cleaned up properly!
super(AdminSeleniumWebDriverTestCase, cls).setUpClass()
@classmethod
def _tearDownClassInternal(cls):
if hasattr(cls, 'selenium'):
cls.selenium.quit()
super(AdminSeleniumWebDriverTestCase, cls)._tearDownClassInternal()
def wait_until(self, callback, timeout=10):
"""
Helper function that blocks the execution of the tests until the
specified callback returns a value that is not falsy. This function can
be called, for example, after clicking a link or submitting a form.
See the other public methods that call this function for more details.
"""
from selenium.webdriver.support.wait import WebDriverWait
WebDriverWait(self.selenium, timeout).until(callback)
def wait_loaded_tag(self, tag_name, timeout=10):
"""
Helper function that blocks until the element with the given tag name
is found on the page.
"""
self.wait_for(tag_name, timeout)
def wait_for(self, css_selector, timeout=10):
"""
Helper function that blocks until a CSS selector is found on the page.
"""
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
self.wait_until(
ec.presence_of_element_located((By.CSS_SELECTOR, css_selector)),
timeout
)
def wait_for_text(self, css_selector, text, timeout=10):
"""
Helper function that blocks until the text is found in the CSS selector.
"""
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
self.wait_until(
ec.text_to_be_present_in_element(
(By.CSS_SELECTOR, css_selector), text),
timeout
)
def wait_for_value(self, css_selector, text, timeout=10):
"""
Helper function that blocks until the value is found in the CSS selector.
"""
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
self.wait_until(
ec.text_to_be_present_in_element_value(
(By.CSS_SELECTOR, css_selector), text),
timeout
)
def wait_page_loaded(self):
"""
Block until page has started to load.
"""
from selenium.common.exceptions import TimeoutException
try:
# Wait for the next page to be loaded
self.wait_loaded_tag('body')
except TimeoutException:
# IE7 occasionally returns an error "Internet Explorer cannot
# display the webpage" and doesn't load the next page. We just
# ignore it.
pass
def admin_login(self, username, password, login_url='/admin/'):
"""
Helper function to log into the admin.
"""
self.selenium.get('%s%s' % (self.live_server_url, login_url))
username_input = self.selenium.find_element_by_name('username')
username_input.send_keys(username)
password_input = self.selenium.find_element_by_name('password')
password_input.send_keys(password)
login_text = _('Log in')
self.selenium.find_element_by_xpath(
'//input[@value="%s"]' % login_text).click()
self.wait_page_loaded()
def get_css_value(self, selector, attribute):
"""
Helper function that returns the value for the CSS attribute of an
DOM element specified by the given selector. Uses the jQuery that ships
with Django.
"""
return self.selenium.execute_script(
'return django.jQuery("%s").css("%s")' % (selector, attribute))
def get_select_option(self, selector, value):
"""
Returns the <OPTION> with the value `value` inside the <SELECT> widget
identified by the CSS selector `selector`.
"""
from selenium.common.exceptions import NoSuchElementException
options = self.selenium.find_elements_by_css_selector('%s > option' % selector)
for option in options:
if option.get_attribute('value') == value:
return option
raise NoSuchElementException('Option "%s" not found in "%s"' % (value, selector))
def assertSelectOptions(self, selector, values):
"""
Asserts that the <SELECT> widget identified by `selector` has the
options with the given `values`.
"""
options = self.selenium.find_elements_by_css_selector('%s > option' % selector)
actual_values = []
for option in options:
actual_values.append(option.get_attribute('value'))
self.assertEqual(values, actual_values)
def has_css_class(self, selector, klass):
"""
Returns True if the element identified by `selector` has the CSS class
`klass`.
"""
return (self.selenium.find_element_by_css_selector(selector)
.get_attribute('class').find(klass) != -1)
| apache-2.0 |
ofermend/medicare-demo | socialite/jython/Lib/test/bugs/bugs101.py | 24 | 1113 | import sys
import os
dir = os.path.dirname(sys.argv[0])
scriptsdir = os.path.normpath(os.path.join(dir, os.pardir, 'scripts'))
sys.path.append(scriptsdir)
from test_support import *
def test931():
'''exec and eval are not thread safe'''
from java.lang import Thread
class TestThread(Thread):
def run(self):
for i in range(30):
exec("x=2+2")
testers = []
for i in range(10):
testers.append(TestThread())
for tester in testers:
tester.start()
for tester in testers:
tester.join()
code32 = """\
def foo():
try:
2+2
finally:
return 4
"""
def test32():
'return in finally clause causes java.lang.VerifyError at compile time'
exec code32
print 'Bug Fixes'
print 'From 1.0.1 to 1.0.2'
items = locals().items()
items.sort()
errors = 0
for name, value in items:
if name[:4] == 'test':
print value.__doc__+' #'+name[4:]
try:
value()
except:
print 'Error!', sys.exc_type, sys.exc_value
errors = errors+1
print errors, 'errors'
| apache-2.0 |
ganeshgore/myremolab | server/src/weblab/data/dto/experiments.py | 2 | 2359 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# listed below:
#
# Author: Pablo Orduña <pablo@ordunya.com>
# Jaime Irurzun <jaime.irurzun@gmail.com>
#
from weblab.data.experiments import ExperimentInstanceId
from weblab.data.experiments import ExperimentId
from voodoo.representable import Representable
class ExperimentCategory(object):
__metaclass__ = Representable
def __init__(self, name):
super(ExperimentCategory,self).__init__()
self.name = unicode(name)
class Experiment(object):
__metaclass__ = Representable
def __init__(self, name, category, start_date, end_date, id=None):
super(Experiment,self).__init__()
self.name = unicode(name)
self.category = category
self.start_date = start_date
self.end_date = end_date
self.id = id
def get_experiment_instance_id(self):
return ExperimentInstanceId(None, self.name, self.category.name)
def to_experiment_id(self):
return ExperimentId(self.name, self.category.name)
def get_unique_name(self):
return self.name + "@" + self.category.name
class ExperimentUse(object):
__metaclass__ = Representable
def __init__(self, start_date, end_date, experiment, agent, origin, id=None):
self.start_date = start_date
self.end_date = end_date
self.experiment = experiment
self.agent = agent # user
self.origin = origin
self.id = id
DEFAULT_PRIORITY = 5
DEFAULT_INITIALIZATION_IN_ACCOUNTING = True
class ExperimentAllowed(object):
__metaclass__ = Representable
def __init__(self, experiment, time_allowed, priority, initialization_in_accounting, permanent_id):
super(ExperimentAllowed,self).__init__()
self.experiment = experiment
self.time_allowed = time_allowed
self.priority = priority
self.initialization_in_accounting = initialization_in_accounting
self.permanent_id = permanent_id
| bsd-2-clause |
ATIX-AG/ansible | lib/ansible/modules/network/onyx/onyx_mlag_vip.py | 66 | 5498 | #!/usr/bin/python
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: onyx_mlag_vip
version_added: "2.5"
author: "Samer Deeb (@samerd)"
short_description: Configures MLAG VIP on Mellanox ONYX network devices
description:
- This module provides declarative management of MLAG virtual IPs
on Mellanox ONYX network devices.
notes:
- Tested on ONYX 3.6.4000
options:
ipaddress:
description:
- Virtual IP address of the MLAG. Required if I(state=present).
group_name:
description:
- MLAG group name. Required if I(state=present).
mac_address:
description:
- MLAG system MAC address. Required if I(state=present).
state:
description:
- MLAG VIP state.
choices: ['present', 'absent']
delay:
description:
- Delay interval, in seconds, waiting for the changes on mlag VIP to take
effect.
default: 12
"""
EXAMPLES = """
- name: configure mlag-vip
onyx_mlag_vip:
ipaddress: 50.3.3.1/24
group_name: ansible-test-group
mac_address: 00:11:12:23:34:45
"""
RETURN = """
commands:
description: The list of configuration mode commands to send to the device.
returned: always
type: list
sample:
- mlag-vip ansible_test_group ip 50.3.3.1 /24 force
- no mlag shutdown
"""
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.onyx.onyx import BaseOnyxModule
from ansible.module_utils.network.onyx.onyx import show_cmd
class OnyxMLagVipModule(BaseOnyxModule):
def init_module(self):
""" initialize module
"""
element_spec = dict(
ipaddress=dict(),
group_name=dict(),
mac_address=dict(),
delay=dict(type='int', default=12),
state=dict(choices=['present', 'absent'], default='present'),
)
argument_spec = dict()
argument_spec.update(element_spec)
self._module = AnsibleModule(
argument_spec=argument_spec,
supports_check_mode=True)
def get_required_config(self):
module_params = self._module.params
lag_params = {
'ipaddress': module_params['ipaddress'],
'group_name': module_params['group_name'],
'mac_address': module_params['mac_address'],
'delay': module_params['delay'],
'state': module_params['state'],
}
self.validate_param_values(lag_params)
self._required_config = lag_params
def _show_mlag_cmd(self, cmd):
return show_cmd(self._module, cmd, json_fmt=True, fail_on_error=False)
def _show_mlag(self):
cmd = "show mlag"
return self._show_mlag_cmd(cmd)
def _show_mlag_vip(self):
cmd = "show mlag-vip"
return self._show_mlag_cmd(cmd)
def load_current_config(self):
self._current_config = dict()
mlag_config = self._show_mlag()
mlag_vip_config = self._show_mlag_vip()
if mlag_vip_config:
mlag_vip = mlag_vip_config.get("MLAG-VIP", {})
self._current_config['group_name'] = \
mlag_vip.get("MLAG group name")
self._current_config['ipaddress'] = \
mlag_vip.get("MLAG VIP address")
if mlag_config:
self._current_config['mac_address'] = \
mlag_config.get("System-mac")
def generate_commands(self):
state = self._required_config['state']
if state == 'present':
self._generate_mlag_vip_cmds()
else:
self._generate_no_mlag_vip_cmds()
def _generate_mlag_vip_cmds(self):
current_group = self._current_config.get('group_name')
current_ip = self._current_config.get('ipaddress')
current_mac = self._current_config.get('mac_address')
if current_mac:
current_mac = current_mac.lower()
req_group = self._required_config.get('group_name')
req_ip = self._required_config.get('ipaddress')
req_mac = self._required_config.get('mac_address')
if req_mac:
req_mac = req_mac.lower()
if req_group != current_group or req_ip != current_ip:
ipaddr, mask = req_ip.split('/')
self._commands.append(
'mlag-vip %s ip %s /%s force' % (req_group, ipaddr, mask))
if req_mac != current_mac:
self._commands.append(
'mlag system-mac %s' % (req_mac))
if self._commands:
self._commands.append('no mlag shutdown')
def _generate_no_mlag_vip_cmds(self):
if self._current_config.get('group_name'):
self._commands.append('no mlag-vip')
def check_declarative_intent_params(self, result):
if not result['changed']:
return
delay_interval = self._required_config.get('delay')
if delay_interval > 0:
time.sleep(delay_interval)
for cmd in ("show mlag-vip", ""):
show_cmd(self._module, cmd, json_fmt=False, fail_on_error=False)
def main():
""" main entry point for module execution
"""
OnyxMLagVipModule.main()
if __name__ == '__main__':
main()
| gpl-3.0 |
jss-emr/openerp-7-src | openerp/addons/plugin_thunderbird/__openerp__.py | 92 | 2064 | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# Copyright (c) 2004 Axelor SPRL. (http://www.axelor.com) All Rights Reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 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/>.
#
##############################################################################
{
'name' : 'Thunderbird Plug-In',
'version' : '1.0',
'author' : ['OpenERP SA', 'Axelor'],
'website' : 'http://www.openerp.com/',
'depends' : ['base','mail', 'plugin'],
'category' : 'Customer Relationship Management',
'description': """
This module is required for the Thuderbird Plug-in to work properly.
====================================================================
The plugin allows you archive email and its attachments to the selected
OpenERP objects. You can select a partner, a task, a project, an analytical
account, or any other object and attach the selected mail as a .eml file in
the attachment of a selected record. You can create documents for CRM Lead,
HR Applicant and Project Issue from selected mails.
""",
'demo' : [],
'data' : ['plugin_thunderbird.xml'],
'auto_install': False,
'installable': True,
'images': ['images/config_thunderbird.jpeg','images/config_thunderbird_plugin.jpeg','images/thunderbird_document.jpeg'],
}
| agpl-3.0 |
ArtsiomCh/tensorflow | tensorflow/python/kernel_tests/sparse_xent_op_test.py | 103 | 13989 | # 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.
# ==============================================================================
"""Tests for SparseSoftmaxCrossEntropyWithLogits op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import time
import numpy as np
from tensorflow.core.protobuf import config_pb2
from tensorflow.python.client import session
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops as ops_lib
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import sparse_ops
from tensorflow.python.ops import variables
import tensorflow.python.ops.nn_grad # pylint: disable=unused-import
from tensorflow.python.platform import app
from tensorflow.python.platform import test
class SparseXentTest(test.TestCase):
def _npXent(self, features, labels):
features = np.reshape(features, [-1, features.shape[-1]])
labels = np.reshape(labels, [-1])
batch_dim = 0
class_dim = 1
batch_size = features.shape[batch_dim]
e = np.exp(features - np.reshape(
np.amax(
features, axis=class_dim), [batch_size, 1]))
probs = e / np.reshape(np.sum(e, axis=class_dim), [batch_size, 1])
labels_mat = np.zeros_like(probs).astype(probs.dtype)
labels_mat[np.arange(batch_size), labels] = 1.0
bp = (probs - labels_mat)
l = -np.sum(labels_mat * np.log(probs + 1.0e-20), axis=1)
return l, bp
def _testXent(self, np_features, np_labels):
np_loss, np_backprop = self._npXent(np_features, np_labels)
with self.test_session(use_gpu=True) as sess:
loss, backprop = gen_nn_ops._sparse_softmax_cross_entropy_with_logits(
np_features, np_labels)
tf_loss, tf_backprop = sess.run([loss, backprop])
self.assertAllCloseAccordingToType(np_loss, tf_loss)
self.assertAllCloseAccordingToType(np_backprop, tf_backprop)
def testSingleClass(self):
for label_dtype in np.int32, np.int64:
with self.test_session(use_gpu=True) as sess:
loss, backprop = gen_nn_ops._sparse_softmax_cross_entropy_with_logits(
np.array([[1.], [-1.], [0.]]).astype(np.float32),
np.array([0, 0, 0]).astype(label_dtype))
tf_loss, tf_backprop = sess.run([loss, backprop])
self.assertAllClose([0.0, 0.0, 0.0], tf_loss)
self.assertAllClose([[0.0], [0.0], [0.0]], tf_backprop)
def testInvalidLabel(self):
features = [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 2., 3., 4.],
[1., 2., 3., 4.]]
labels = [4, 3, 0, -1]
if test.is_built_with_cuda() and test.is_gpu_available():
with self.test_session(use_gpu=True) as sess:
loss, backprop = (gen_nn_ops._sparse_softmax_cross_entropy_with_logits(
features, labels))
tf_loss, tf_backprop = sess.run([loss, backprop])
self.assertAllClose(
[[np.nan] * 4, [0.25, 0.25, 0.25, -0.75],
[-0.968, 0.087, 0.237, 0.6439], [np.nan] * 4],
tf_backprop,
rtol=1e-3,
atol=1e-3)
self.assertAllClose(
[np.nan, 1.3862, 3.4420, np.nan], tf_loss, rtol=1e-3, atol=1e-3)
with self.test_session(use_gpu=False) as sess:
loss, backprop = (gen_nn_ops._sparse_softmax_cross_entropy_with_logits(
features, labels))
with self.assertRaisesOpError("Received a label value of"):
sess.run([loss, backprop])
def testNpXent(self):
# We create 2 batches of logits for testing.
# batch 0 is the boring uniform distribution: 1, 1, 1, 1, with target 3.
# batch 1 has a bit of difference: 1, 2, 3, 4, with target 0.
features = [[1., 1., 1., 1.], [1., 2., 3., 4.]]
labels = [3, 0]
# For batch 0, we expect the uniform distribution: 0.25, 0.25, 0.25, 0.25
# With a hard target 3, the backprop is [0.25, 0.25, 0.25, -0.75]
# The loss for this batch is -log(0.25) = 1.386
#
# For batch 1, we have:
# exp(0) = 1
# exp(1) = 2.718
# exp(2) = 7.389
# exp(3) = 20.085
# SUM = 31.192
# So we have as probabilities:
# exp(0) / SUM = 0.032
# exp(1) / SUM = 0.087
# exp(2) / SUM = 0.237
# exp(3) / SUM = 0.644
# With a hard 1, the backprop is [0.032 - 1.0 = -0.968, 0.087, 0.237, 0.644]
# The loss for this batch is [1.0 * -log(0.25), 1.0 * -log(0.032)]
# = [1.3862, 3.4420]
np_loss, np_backprop = self._npXent(np.array(features), np.array(labels))
self.assertAllClose(
np.array([[0.25, 0.25, 0.25, -0.75], [-0.968, 0.087, 0.237, 0.6439]]),
np_backprop,
rtol=1.e-3,
atol=1.e-3)
self.assertAllClose(
np.array([1.3862, 3.4420]), np_loss, rtol=1.e-3, atol=1.e-3)
def testShapeMismatch(self):
with self.test_session(use_gpu=True):
with self.assertRaisesRegexp(ValueError, ".*Rank mismatch:*"):
nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=[[0, 2]], logits=[[0., 1.], [2., 3.], [2., 3.]])
def testScalar(self):
with self.test_session(use_gpu=True):
with self.assertRaisesRegexp(ValueError, ".*Logits cannot be scalars*"):
nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=constant_op.constant(0), logits=constant_op.constant(1.0))
def testLabelsPlaceholderScalar(self):
with self.test_session(use_gpu=True):
labels = array_ops.placeholder(np.int32)
y = nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=labels, logits=[[7.]])
with self.assertRaisesOpError("labels must be 1-D"):
y.eval(feed_dict={labels: 0})
def testVector(self):
with self.test_session(use_gpu=True):
loss = nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=constant_op.constant(0), logits=constant_op.constant([1.0]))
self.assertAllClose(0.0, loss.eval())
def testFloat(self):
for label_dtype in np.int32, np.int64:
self._testXent(
np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float32),
np.array([3, 0]).astype(label_dtype))
def testDouble(self):
for label_dtype in np.int32, np.int64:
self._testXent(
np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float64),
np.array([0, 3]).astype(label_dtype))
def testHalf(self):
for label_dtype in np.int32, np.int64:
self._testXent(
np.array([[1., 1., 1., 1.], [1., 2., 3., 4.]]).astype(np.float16),
np.array([3, 0]).astype(label_dtype))
def testEmpty(self):
self._testXent(np.zeros((0, 3)), np.zeros((0,), dtype=np.int32))
def testGradient(self):
with self.test_session(use_gpu=True):
l = constant_op.constant([3, 0, 1], name="l")
f = constant_op.constant(
[0.1, 0.2, 0.3, 0.4, 0.1, 0.4, 0.9, 1.6, 0.1, 0.8, 2.7, 6.4],
shape=[3, 4],
dtype=dtypes.float64,
name="f")
x = nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=l, logits=f, name="xent")
err = gradient_checker.compute_gradient_error(f, [3, 4], x, [3])
print("cross entropy gradient err = ", err)
self.assertLess(err, 5e-8)
def testSecondGradient(self):
images_placeholder = array_ops.placeholder(dtypes.float32, shape=(3, 2))
labels_placeholder = array_ops.placeholder(dtypes.int32, shape=(3))
weights = variables.Variable(random_ops.truncated_normal([2], stddev=1.0))
weights_with_zeros = array_ops.stack([array_ops.zeros([2]), weights],
axis=1)
logits = math_ops.matmul(images_placeholder, weights_with_zeros)
cross_entropy = nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=labels_placeholder, logits=logits)
loss = math_ops.reduce_mean(cross_entropy)
# Taking ths second gradient should fail, since it is not
# yet supported.
with self.assertRaisesRegexp(LookupError,
"explicitly disabled"):
_ = gradients_impl.hessians(loss, [weights])
def _testHighDim(self, features, labels):
np_loss, np_backprop = self._npXent(np.array(features), np.array(labels))
# manually reshape loss
np_loss = np.reshape(np_loss, np.array(labels).shape)
with self.test_session(use_gpu=True) as sess:
loss = nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=labels, logits=features)
backprop = loss.op.inputs[0].op.outputs[1]
tf_loss, tf_backprop = sess.run([loss, backprop])
self.assertAllCloseAccordingToType(np_loss, tf_loss)
self.assertAllCloseAccordingToType(np_backprop, tf_backprop)
def testHighDim(self):
features = [[[1., 1., 1., 1.]], [[1., 2., 3., 4.]]]
labels = [[3], [0]]
self._testHighDim(features, labels)
def testHighDim2(self):
features = [[[1., 1., 1., 1.], [2., 2., 2., 2.]],
[[1., 2., 3., 4.], [5., 6., 7., 8.]]]
labels = [[3, 2], [0, 3]]
self._testHighDim(features, labels)
def testScalarHandling(self):
with self.test_session(use_gpu=False) as sess:
with self.assertRaisesRegexp(errors_impl.InvalidArgumentError,
".*labels must be 1-D.*"):
labels = array_ops.placeholder(dtypes.int32, shape=[None, 1])
logits = array_ops.placeholder(dtypes.float32, shape=[None, 3])
ce = nn_ops.sparse_softmax_cross_entropy_with_logits(
labels=array_ops.squeeze(labels), logits=logits)
labels_v2 = np.zeros((1, 1), dtype=np.int32)
logits_v2 = np.random.randn(1, 3)
sess.run([ce], feed_dict={labels: labels_v2, logits: logits_v2})
def _sparse_vs_dense_xent_benchmark_dense(labels, logits):
labels = array_ops.identity(labels)
logits = array_ops.identity(logits)
with ops_lib.device("/cpu:0"): # Sparse-to-dense must be on CPU
batch_size = array_ops.shape(logits)[0]
num_entries = array_ops.shape(logits)[1]
length = batch_size * num_entries
labels += num_entries * math_ops.range(batch_size)
target = sparse_ops.sparse_to_dense(labels,
array_ops.stack([length]), 1.0, 0.0)
target = array_ops.reshape(target, array_ops.stack([-1, num_entries]))
crossent = nn_ops.softmax_cross_entropy_with_logits(
labels=target, logits=logits, name="SequenceLoss/CrossEntropy")
crossent_sum = math_ops.reduce_sum(crossent)
grads = gradients_impl.gradients([crossent_sum], [logits])[0]
return (crossent_sum, grads)
def _sparse_vs_dense_xent_benchmark_sparse(labels, logits):
# Using sparse_softmax_cross_entropy_with_logits
labels = labels.astype(np.int64)
labels = array_ops.identity(labels)
logits = array_ops.identity(logits)
crossent = nn_ops.sparse_softmax_cross_entropy_with_logits(
logits, labels, name="SequenceLoss/CrossEntropy")
crossent_sum = math_ops.reduce_sum(crossent)
grads = gradients_impl.gradients([crossent_sum], [logits])[0]
return (crossent_sum, grads)
def sparse_vs_dense_xent_benchmark(batch_size, num_entries, use_gpu):
config = config_pb2.ConfigProto()
config.allow_soft_placement = True
config.gpu_options.per_process_gpu_memory_fraction = 0.3
labels = np.random.randint(num_entries, size=batch_size).astype(np.int32)
logits = np.random.randn(batch_size, num_entries).astype(np.float32)
def _timer(sess, ops):
# Warm in
for _ in range(20):
sess.run(ops)
# Timing run
start = time.time()
for _ in range(20):
sess.run(ops)
end = time.time()
return (end - start) / 20.0 # Average runtime per iteration
# Using sparse_to_dense and softmax_cross_entropy_with_logits
with session.Session(config=config) as sess:
if not use_gpu:
with ops_lib.device("/cpu:0"):
ops = _sparse_vs_dense_xent_benchmark_dense(labels, logits)
else:
ops = _sparse_vs_dense_xent_benchmark_dense(labels, logits)
delta_dense = _timer(sess, ops)
# Using sparse_softmax_cross_entropy_with_logits
with session.Session(config=config) as sess:
if not use_gpu:
with ops_lib.device("/cpu:0"):
ops = _sparse_vs_dense_xent_benchmark_sparse(labels, logits)
else:
ops = _sparse_vs_dense_xent_benchmark_sparse(labels, logits)
delta_sparse = _timer(sess, ops)
print("%d \t %d \t %s \t %f \t %f \t %f" % (batch_size, num_entries, use_gpu,
delta_dense, delta_sparse,
delta_sparse / delta_dense))
def main(_):
print("Sparse Xent vs. SparseToDense + Xent")
print("batch \t depth \t gpu \t dt(dense) \t dt(sparse) "
"\t dt(sparse)/dt(dense)")
for use_gpu in (False, True):
for batch_size in (32, 64, 128):
for num_entries in (100, 1000, 10000):
sparse_vs_dense_xent_benchmark(batch_size, num_entries, use_gpu)
sparse_vs_dense_xent_benchmark(32, 100000, use_gpu)
sparse_vs_dense_xent_benchmark(8, 1000000, use_gpu)
if __name__ == "__main__":
if "--benchmarks" in sys.argv:
sys.argv.remove("--benchmarks")
app.run()
else:
test.main()
| apache-2.0 |
Cloud-Elasticity-Services/as-libcloud | libcloud/test/compute/test_softlayer.py | 1 | 10385 | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import sys
try:
import Crypto
Crypto
crypto = True
except ImportError:
crypto = False
from libcloud.common.types import InvalidCredsError
from libcloud.utils.py3 import httplib
from libcloud.utils.py3 import xmlrpclib
from libcloud.utils.py3 import next
from libcloud.compute.drivers.softlayer import SoftLayerNodeDriver as SoftLayer
from libcloud.compute.drivers.softlayer import SoftLayerException, \
NODE_STATE_MAP
from libcloud.compute.types import NodeState, KeyPairDoesNotExistError
from libcloud.test import MockHttp # pylint: disable-msg=E0611
from libcloud.test.file_fixtures import ComputeFileFixtures
from libcloud.test.secrets import SOFTLAYER_PARAMS
null_fingerprint = '00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:' + \
'00:00:00:00:00'
DELETE_GROUP_CALLS = 0
class SoftLayerTests(unittest.TestCase):
def setUp(self):
SoftLayer.connectionCls.conn_classes = (
SoftLayerMockHttp, SoftLayerMockHttp)
SoftLayerMockHttp.type = None
SoftLayerMockHttp.test = self
self.driver = SoftLayer(*SOFTLAYER_PARAMS)
def test_list_nodes(self):
nodes = self.driver.list_nodes()
node = nodes[0]
self.assertEqual(node.name, 'libcloud-testing1.example.com')
self.assertEqual(node.state, NodeState.RUNNING)
self.assertEqual(node.extra['password'], 'L3TJVubf')
def test_initializing_state(self):
nodes = self.driver.list_nodes()
node = nodes[1]
self.assertEqual(node.state, NODE_STATE_MAP['INITIATING'])
def test_list_locations(self):
locations = self.driver.list_locations()
dal = next(l for l in locations if l.id == 'dal05')
self.assertEqual(dal.country, 'US')
self.assertEqual(dal.id, 'dal05')
self.assertEqual(dal.name, 'Dallas - Central U.S.')
def test_list_images(self):
images = self.driver.list_images()
image = images[0]
self.assertEqual(image.id, 'CENTOS_6_64')
def test_list_sizes(self):
sizes = self.driver.list_sizes()
self.assertEqual(len(sizes), 13)
def test_create_node(self):
node = self.driver.create_node(name="libcloud-testing",
location=self.driver.list_locations()[0],
size=self.driver.list_sizes()[0],
image=self.driver.list_images()[0])
self.assertEqual(node.name, 'libcloud-testing.example.com')
self.assertEqual(node.state, NODE_STATE_MAP['RUNNING'])
def test_create_fail(self):
SoftLayerMockHttp.type = "SOFTLAYEREXCEPTION"
self.assertRaises(
SoftLayerException,
self.driver.create_node,
name="SOFTLAYEREXCEPTION",
location=self.driver.list_locations()[0],
size=self.driver.list_sizes()[0],
image=self.driver.list_images()[0])
def test_create_creds_error(self):
SoftLayerMockHttp.type = "INVALIDCREDSERROR"
self.assertRaises(
InvalidCredsError,
self.driver.create_node,
name="INVALIDCREDSERROR",
location=self.driver.list_locations()[0],
size=self.driver.list_sizes()[0],
image=self.driver.list_images()[0])
def test_create_node_no_location(self):
self.driver.create_node(name="Test",
size=self.driver.list_sizes()[0],
image=self.driver.list_images()[0])
def test_create_node_no_image(self):
self.driver.create_node(name="Test", size=self.driver.list_sizes()[0])
def test_create_node_san(self):
self.driver.create_node(name="Test", ex_local_disk=False)
def test_create_node_domain_for_name(self):
self.driver.create_node(name="libcloud.org")
def test_create_node_ex_options(self):
self.driver.create_node(name="Test",
location=self.driver.list_locations()[0],
size=self.driver.list_sizes()[0],
image=self.driver.list_images()[0],
ex_domain='libcloud.org',
ex_cpus=2,
ex_ram=2048,
ex_disk=100,
ex_key='test1',
ex_bandwidth=10,
ex_local_disk=False,
ex_datacenter='Dal05',
ex_os='UBUNTU_LATEST')
def test_reboot_node(self):
node = self.driver.list_nodes()[0]
self.driver.reboot_node(node)
def test_destroy_node(self):
node = self.driver.list_nodes()[0]
self.driver.destroy_node(node)
def test_list_keypairs(self):
keypairs = self.driver.list_key_pairs()
self.assertEqual(len(keypairs), 2)
self.assertEqual(keypairs[0].name, 'test1')
self.assertEqual(keypairs[0].fingerprint, null_fingerprint)
def test_get_key_pair(self):
key_pair = self.driver.get_key_pair(name='test1')
self.assertEqual(key_pair.name, 'test1')
def test_get_key_pair_does_not_exist(self):
self.assertRaises(KeyPairDoesNotExistError, self.driver.get_key_pair,
name='test-key-pair')
def test_create_key_pair(self):
if crypto:
key_pair = self.driver.create_key_pair(name='my-key-pair')
fingerprint = ('1f:51:ae:28:bf:89:e9:d8:1f:25:5d'
':37:2d:7d:b8:ca:9f:f5:f1:6f')
self.assertEqual(key_pair.name, 'my-key-pair')
self.assertEqual(key_pair.fingerprint, fingerprint)
self.assertTrue(key_pair.private_key is not None)
else:
self.assertRaises(NotImplementedError, self.driver.create_key_pair,
name='my-key-pair')
def test_delete_key_pair(self):
success = self.driver.delete_key_pair('test1')
self.assertTrue(success)
class SoftLayerMockHttp(MockHttp):
fixtures = ComputeFileFixtures('softlayer')
def _get_method_name(self, type, use_param, qs, path):
return "_xmlrpc"
def _xmlrpc(self, method, url, body, headers):
params, meth_name = xmlrpclib.loads(body)
url = url.replace("/", "_")
meth_name = "%s_%s" % (url, meth_name)
return getattr(self, meth_name)(method, url, body, headers)
def _xmlrpc_v3_SoftLayer_Virtual_Guest_getCreateObjectOptions(
self, method, url, body, headers):
body = self.fixtures.load(
'v3__SoftLayer_Virtual_Guest_getCreateObjectOptions.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Account_getVirtualGuests(
self, method, url, body, headers):
body = self.fixtures.load('v3_SoftLayer_Account_getVirtualGuests.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Location_Datacenter_getDatacenters(
self, method, url, body, headers):
body = self.fixtures.load(
'v3_SoftLayer_Location_Datacenter_getDatacenters.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Virtual_Guest_createObject(
self, method, url, body, headers):
fixture = {
None: 'v3__SoftLayer_Virtual_Guest_createObject.xml',
'INVALIDCREDSERROR': 'SoftLayer_Account.xml',
'SOFTLAYEREXCEPTION': 'fail.xml',
}[self.type]
body = self.fixtures.load(fixture)
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Virtual_Guest_getObject(
self, method, url, body, headers):
body = self.fixtures.load(
'v3__SoftLayer_Virtual_Guest_getObject.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Virtual_Guest_rebootSoft(
self, method, url, body, headers):
body = self.fixtures.load('empty.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Virtual_Guest_deleteObject(
self, method, url, body, headers):
body = self.fixtures.load('empty.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Account_getSshKeys(
self, method, url, body, headers):
body = self.fixtures.load('v3__SoftLayer_Account_getSshKeys.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Security_Ssh_Key_getObject(
self, method, url, body, headers):
body = self.fixtures.load('v3__SoftLayer_Security_Ssh_Key_getObject.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Security_Ssh_Key_createObject(
self, method, url, body, headers):
body = self.fixtures.load('v3__SoftLayer_Security_Ssh_Key_createObject.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
def _xmlrpc_v3_SoftLayer_Security_Ssh_Key_deleteObject(
self, method, url, body, headers):
body = self.fixtures.load('v3__SoftLayer_Security_Ssh_Key_deleteObject.xml')
return (httplib.OK, body, {}, httplib.responses[httplib.OK])
if __name__ == '__main__':
sys.exit(unittest.main())
| apache-2.0 |
fboxerappdev/Corporate-Web-App---Bootstrap-Wordpress | node_modules/npm-shrinkwrap/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/gypsh.py | 2779 | 1665 | # Copyright (c) 2011 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""gypsh output module
gypsh is a GYP shell. It's not really a generator per se. All it does is
fire up an interactive Python session with a few local variables set to the
variables passed to the generator. Like gypd, it's intended as a debugging
aid, to facilitate the exploration of .gyp structures after being processed
by the input module.
The expected usage is "gyp -f gypsh -D OS=desired_os".
"""
import code
import sys
# All of this stuff about generator variables was lovingly ripped from gypd.py.
# That module has a much better description of what's going on and why.
_generator_identity_variables = [
'EXECUTABLE_PREFIX',
'EXECUTABLE_SUFFIX',
'INTERMEDIATE_DIR',
'PRODUCT_DIR',
'RULE_INPUT_ROOT',
'RULE_INPUT_DIRNAME',
'RULE_INPUT_EXT',
'RULE_INPUT_NAME',
'RULE_INPUT_PATH',
'SHARED_INTERMEDIATE_DIR',
]
generator_default_variables = {
}
for v in _generator_identity_variables:
generator_default_variables[v] = '<(%s)' % v
def GenerateOutput(target_list, target_dicts, data, params):
locals = {
'target_list': target_list,
'target_dicts': target_dicts,
'data': data,
}
# Use a banner that looks like the stock Python one and like what
# code.interact uses by default, but tack on something to indicate what
# locals are available, and identify gypsh.
banner='Python %s on %s\nlocals.keys() = %s\ngypsh' % \
(sys.version, sys.platform, repr(sorted(locals.keys())))
code.interact(banner, local=locals)
| mit |
Komport/Data_Structures_Algo_Python | Source_Code/python_kodlar/fesil7/fesil7_linked_list_queue.py | 2 | 3178 | class Node:
# konstruktor
def __init__(self, data=None, next_node=None):
self.data = data
self.next_node = next_node
# node-un data field-ini mənimsətmək üçün metod
def set_data(self, data):
self.data = data
# node-un data field-ini almaq üçün metod
def get_data(self):
return self.data
# node-un növbəti field-ini mənimsətmək üçün metod
def set_next_node(self, next_node):
self.next_node = next_node
# node-un növbəti field-ini almaq üçün metod
def get_next_node(self):
return self.next_node
# əgər bir node sonrakına point edirsə, true qaytar
def has_next(self):
return self.next_node is not None
class LinkedListQueue:
def __init__(self, head=None):
self.front = None
self.rear = None
self.head = head
def size(self):
current = self.head
count = 0
while current:
count += 1
current = current.get_next_node()
return count
def en_queue(self, data):
# Listin sonuna node daxil edirik
print("Növbəyə daxil edirik...")
new_node = Node()
new_node.set_data(data)
if self.size() == 0:
self.head = new_node
# List-də heç bir element olmadığı üçün front və rear eyni yerdədirlər.
self.front = self.head
self.rear = self.front
else:
current = self.head
while current.get_next_node() is not None:
current = current.get_next_node()
current.set_next_node(new_node)
# Rear-i burda sonuncu node edirik
self.rear = current.get_next_node()
def de_queue(self):
# Listin əvvəlindən node silirik
if self.size() == 0:
print("Növbə boşdur...")
else:
print("Növbədən çıxardırıq...")
# Müvəqqəti node
temp = self.head
# Head node-u əvvəlki head-dən sonrakı node-a mənimsədirik.
# Bununla da faktiki olaraq, əvvəlki head-i arxada qoyuruq.
self.head = self.head.get_next_node()
# Həmçinin front-u da yeni head-ə bərabər edirik, faktiki olaraq irəli sürüşdürürük.
self.front = self.head
# Müvəqqəti node-u silirik.
del(temp)
def queue_rear(self):
if self.rear is None:
print("Növbə boşdur...")
else:
return self.rear.get_data()
def queue_front(self):
if self.front is None:
print("Növbə boşdur...")
else:
return self.front.get_data()
if __name__ == "__main__":
obj = LinkedListQueue()
obj.en_queue(56)
obj.en_queue(44)
obj.en_queue(85)
obj.en_queue(66)
print("Növbənin uzunluğu: ", obj.size())
obj.en_queue(99)
obj.en_queue(111)
obj.de_queue()
obj.de_queue()
obj.en_queue(222)
print("Növbənin uzunluğu: ", obj.size())
print("Növbənin ilk elementi: ", obj.queue_front())
print("Növbənin son elementi: ", obj.queue_rear()) | mit |
arista-eosplus/ansible | test/units/module_utils/basic/test_no_log.py | 60 | 6904 | # -*- coding: utf-8 -*-
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division)
__metaclass__ = type
import json
import sys
import syslog
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import patch, MagicMock
from ansible.module_utils import basic
from ansible.module_utils.basic import heuristic_log_sanitize
from ansible.module_utils.basic import return_values, remove_values
class TestReturnValues(unittest.TestCase):
dataset = (
('string', frozenset(['string'])),
('', frozenset()),
(1, frozenset(['1'])),
(1.0, frozenset(['1.0'])),
(False, frozenset()),
(['1', '2', '3'], frozenset(['1', '2', '3'])),
(('1', '2', '3'), frozenset(['1', '2', '3'])),
({'one': 1, 'two': 'dos'}, frozenset(['1', 'dos'])),
(
{
'one': 1,
'two': 'dos',
'three': [
'amigos', 'musketeers', None, {
'ping': 'pong',
'base': (
'balls', 'raquets'
)
}
]
},
frozenset(['1', 'dos', 'amigos', 'musketeers', 'pong', 'balls', 'raquets'])
),
(u'Toshio くらとみ', frozenset(['Toshio くらとみ'])),
('Toshio くらとみ', frozenset(['Toshio くらとみ'])),
)
def test_return_values(self):
for data, expected in self.dataset:
self.assertEquals(frozenset(return_values(data)), expected)
def test_unknown_type(self):
self.assertRaises(TypeError, frozenset, return_values(object()))
class TestRemoveValues(unittest.TestCase):
OMIT = 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
dataset_no_remove = (
('string', frozenset(['nope'])),
(1234, frozenset(['4321'])),
(False, frozenset(['4321'])),
(1.0, frozenset(['4321'])),
(['string', 'strang', 'strung'], frozenset(['nope'])),
({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['nope'])),
(
{
'one': 1,
'two': 'dos',
'three': [
'amigos', 'musketeers', None, {
'ping': 'pong', 'base': ['balls', 'raquets']
}
]
},
frozenset(['nope'])
),
(u'Toshio くら'.encode('utf-8'), frozenset([u'とみ'.encode('utf-8')])),
(u'Toshio くら', frozenset([u'とみ'])),
)
dataset_remove = (
('string', frozenset(['string']), OMIT),
(1234, frozenset(['1234']), OMIT),
(1234, frozenset(['23']), OMIT),
(1.0, frozenset(['1.0']), OMIT),
(['string', 'strang', 'strung'], frozenset(['strang']), ['string', OMIT, 'strung']),
(['string', 'strang', 'strung'], frozenset(['strang', 'string', 'strung']), [OMIT, OMIT, OMIT]),
(('string', 'strang', 'strung'), frozenset(['string', 'strung']), [OMIT, 'strang', OMIT]),
((1234567890, 345678, 987654321), frozenset(['1234567890']), [OMIT, 345678, 987654321]),
((1234567890, 345678, 987654321), frozenset(['345678']), [OMIT, OMIT, 987654321]),
({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key']), {'one': 1, 'two': 'dos', 'secret': OMIT}),
({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {'one': OMIT, 'two': OMIT, 'secret': OMIT}),
({'one': 1, 'two': 'dos', 'secret': 'key'}, frozenset(['key', 'dos', '1']), {'one': OMIT, 'two': OMIT, 'secret': OMIT}),
(
{
'one': 1,
'two': 'dos',
'three': [
'amigos', 'musketeers', None, {
'ping': 'pong', 'base': [
'balls', 'raquets'
]
}
]
},
frozenset(['balls', 'base', 'pong', 'amigos']),
{
'one': 1,
'two': 'dos',
'three': [
OMIT, 'musketeers', None, {
'ping': OMIT,
'base': [
OMIT, 'raquets'
]
}
]
}
),
(
'This sentence has an enigma wrapped in a mystery inside of a secret. - mr mystery',
frozenset(['enigma', 'mystery', 'secret']),
'This sentence has an ******** wrapped in a ******** inside of a ********. - mr ********'
),
(u'Toshio くらとみ'.encode('utf-8'), frozenset([u'くらとみ'.encode('utf-8')]), u'Toshio ********'.encode('utf-8')),
(u'Toshio くらとみ', frozenset([u'くらとみ']), u'Toshio ********'),
)
def test_no_removal(self):
for value, no_log_strings in self.dataset_no_remove:
self.assertEquals(remove_values(value, no_log_strings), value)
def test_strings_to_remove(self):
for value, no_log_strings, expected in self.dataset_remove:
self.assertEquals(remove_values(value, no_log_strings), expected)
def test_unknown_type(self):
self.assertRaises(TypeError, remove_values, object(), frozenset())
def test_hit_recursion_limit(self):
""" Check that we do not hit a recursion limit"""
data_list = []
inner_list = data_list
for i in range(0, 10000):
new_list = []
inner_list.append(new_list)
inner_list = new_list
inner_list.append('secret')
# Check that this does not hit a recursion limit
actual_data_list = remove_values(data_list, frozenset(('secret',)))
levels = 0
inner_list = actual_data_list
while inner_list:
if isinstance(inner_list, list):
self.assertEquals(len(inner_list), 1)
else:
levels -= 1
break
inner_list = inner_list[0]
levels += 1
self.assertEquals(inner_list, self.OMIT)
self.assertEquals(levels, 10000)
| gpl-3.0 |
vnsofthe/odoo-dev | addons/hr_payroll/__openerp__.py | 260 | 2421 | #-*- coding:utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# d$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Payroll',
'version': '1.0',
'category': 'Human Resources',
'sequence': 38,
'description': """
Generic Payroll system.
=======================
* Employee Details
* Employee Contracts
* Passport based Contract
* Allowances/Deductions
* Allow to configure Basic/Gross/Net Salary
* Employee Payslip
* Monthly Payroll Register
* Integrated with Holiday Management
""",
'author': 'OpenERP SA',
'website': 'https://www.odoo.com/page/employees',
'depends': [
'hr',
'hr_contract',
'hr_holidays',
'decimal_precision',
'report',
],
'data': [
'security/hr_security.xml',
'wizard/hr_payroll_payslips_by_employees.xml',
'hr_payroll_view.xml',
'hr_payroll_workflow.xml',
'hr_payroll_sequence.xml',
'hr_payroll_report.xml',
'hr_payroll_data.xml',
'security/ir.model.access.csv',
'wizard/hr_payroll_contribution_register_report.xml',
'res_config_view.xml',
'views/report_contributionregister.xml',
'views/report_payslip.xml',
'views/report_payslipdetails.xml',
],
'test': [
'test/payslip.yml',
],
'demo': ['hr_payroll_demo.xml'],
'installable': True,
'auto_install': False,
'application': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
windyuuy/opera | chromium/src/third_party/python_26/Lib/os2emxpath.py | 60 | 4498 | # Module 'os2emxpath' -- common operations on OS/2 pathnames
"""Common pathname manipulations, OS/2 EMX version.
Instead of importing this module directly, import os and refer to this
module as os.path.
"""
import os
import stat
from genericpath import *
from ntpath import (expanduser, expandvars, isabs, islink, splitdrive,
splitext, split, walk)
__all__ = ["normcase","isabs","join","splitdrive","split","splitext",
"basename","dirname","commonprefix","getsize","getmtime",
"getatime","getctime", "islink","exists","lexists","isdir","isfile",
"ismount","walk","expanduser","expandvars","normpath","abspath",
"splitunc","curdir","pardir","sep","pathsep","defpath","altsep",
"extsep","devnull","realpath","supports_unicode_filenames"]
# strings representing various path-related bits and pieces
curdir = '.'
pardir = '..'
extsep = '.'
sep = '/'
altsep = '\\'
pathsep = ';'
defpath = '.;C:\\bin'
devnull = 'nul'
# Normalize the case of a pathname and map slashes to backslashes.
# Other normalizations (such as optimizing '../' away) are not done
# (this is done by normpath).
def normcase(s):
"""Normalize case of pathname.
Makes all characters lowercase and all altseps into seps."""
return s.replace('\\', '/').lower()
# Join two (or more) paths.
def join(a, *p):
"""Join two or more pathname components, inserting sep as needed"""
path = a
for b in p:
if isabs(b):
path = b
elif path == '' or path[-1:] in '/\\:':
path = path + b
else:
path = path + '/' + b
return path
# Parse UNC paths
def splitunc(p):
"""Split a pathname into UNC mount point and relative path specifiers.
Return a 2-tuple (unc, rest); either part may be empty.
If unc is not empty, it has the form '//host/mount' (or similar
using backslashes). unc+rest is always the input path.
Paths containing drive letters never have an UNC part.
"""
if p[1:2] == ':':
return '', p # Drive letter present
firstTwo = p[0:2]
if firstTwo == '/' * 2 or firstTwo == '\\' * 2:
# is a UNC path:
# vvvvvvvvvvvvvvvvvvvv equivalent to drive letter
# \\machine\mountpoint\directories...
# directory ^^^^^^^^^^^^^^^
normp = normcase(p)
index = normp.find('/', 2)
if index == -1:
##raise RuntimeError, 'illegal UNC path: "' + p + '"'
return ("", p)
index = normp.find('/', index + 1)
if index == -1:
index = len(p)
return p[:index], p[index:]
return '', p
# Return the tail (basename) part of a path.
def basename(p):
"""Returns the final component of a pathname"""
return split(p)[1]
# Return the head (dirname) part of a path.
def dirname(p):
"""Returns the directory component of a pathname"""
return split(p)[0]
# alias exists to lexists
lexists = exists
# Is a path a directory?
# Is a path a mount point? Either a root (with or without drive letter)
# or an UNC path with at most a / or \ after the mount point.
def ismount(path):
"""Test whether a path is a mount point (defined as root of drive)"""
unc, rest = splitunc(path)
if unc:
return rest in ("", "/", "\\")
p = splitdrive(path)[1]
return len(p) == 1 and p[0] in '/\\'
# Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B.
def normpath(path):
"""Normalize path, eliminating double slashes, etc."""
path = path.replace('\\', '/')
prefix, path = splitdrive(path)
while path[:1] == '/':
prefix = prefix + '/'
path = path[1:]
comps = path.split('/')
i = 0
while i < len(comps):
if comps[i] == '.':
del comps[i]
elif comps[i] == '..' and i > 0 and comps[i-1] not in ('', '..'):
del comps[i-1:i+1]
i = i - 1
elif comps[i] == '' and i > 0 and comps[i-1] != '':
del comps[i]
else:
i = i + 1
# If the path is now empty, substitute '.'
if not prefix and not comps:
comps.append('.')
return prefix + '/'.join(comps)
# Return an absolute path.
def abspath(path):
"""Return the absolute version of a path"""
if not isabs(path):
path = join(os.getcwd(), path)
return normpath(path)
# realpath is a no-op on systems without islink support
realpath = abspath
supports_unicode_filenames = False
| bsd-3-clause |
capitalaslash/moose | gui/vtk/ClippedActor.py | 25 | 1354 | from PeacockActor import PeacockActor
import vtk
from vtk.util.colors import peacock, tomato, red, white, black
class ClippedActor(PeacockActor):
def __init__(self, original_actor, plane):
PeacockActor.__init__(self, original_actor.renderer)
self.original_actor = original_actor
self.plane = plane
self.clipper = vtk.vtkTableBasedClipDataSet()
self.clipper.SetInput(self.original_actor.mesh)
self.clipper.SetClipFunction(self.plane)
self.clipper.Update()
self.clip_mapper = vtk.vtkDataSetMapper()
self.clip_mapper.SetInput(self.clipper.GetOutput())
self.clip_actor = vtk.vtkActor()
self.clip_actor.SetMapper(self.clip_mapper)
def getBounds(self):
return self.original_actor.getBounds()
def movePlane(self):
pass
def _show(self):
self.original_actor.renderer.AddActor(self.clip_actor)
def _hide(self):
self.original_actor.renderer.RemoveActor(self.clip_actor)
def _showEdges(self):
self.clip_actor.GetProperty().EdgeVisibilityOn()
def _hideEdges(self):
self.clip_actor.GetProperty().EdgeVisibilityOff()
def _goSolid(self):
self.clip_actor.GetProperty().SetRepresentationToSurface()
def _goWireframe(self):
self.clip_actor.GetProperty().SetRepresentationToWireframe()
def _setColor(self, color):
self.clip_actor.GetProperty().SetColor(color)
| lgpl-2.1 |
ktraw2/TVBot | modules/audio_player.py | 1 | 11873 | import discord
import config
from enum import Enum
class Generic:
@staticmethod
def embed_text(**kwargs):
return "Audio"
@staticmethod
def now_playing(**kwargs):
if "show" in kwargs and "channel" in kwargs:
return ":speaker::notes: Now playing audio `{0}` in voice channel `{1}`.".format(kwargs["show"],
kwargs["channel"].name)
else:
return "Invalid format."
@staticmethod
def added_to_queue(**kwargs):
if "show" in kwargs:
return ":white_check_mark: The audio `{0}` has been added to the queue.".format(kwargs["show"])
else:
return "Invalid format."
@staticmethod
def queue_entry(**kwargs):
if "show" in kwargs:
return "Audio {0}".format(kwargs["show"])
else:
return "Invalid format."
class Theme:
@staticmethod
def embed_text(**kwargs):
return "Theme Song"
@staticmethod
def now_playing(**kwargs):
if "show" in kwargs and "channel" in kwargs:
return ":speaker::notes: Now playing the theme song for `{0}` in voice channel `{1}`.".format(
kwargs["show"], kwargs["channel"].name)
else:
return "Invalid format."
@staticmethod
def added_to_queue(**kwargs):
if "show" in kwargs:
return ":white_check_mark: The theme song for `{0}` has been added to the queue.".format(kwargs["show"])
else:
return "Invalid format."
@staticmethod
def queue_entry(**kwargs):
if "show" in kwargs:
return "Theme song for {0}".format(kwargs["show"])
else:
return "Invalid format."
class Episode:
@staticmethod
def embed_text(**kwargs):
if "season" in kwargs and "number" in kwargs and "episode" in kwargs:
return "Season {0}, Episode {1}: {2}".format(str(kwargs["season"]),
str(kwargs["number"]),
kwargs["episode"])
else:
return "Invalid format."
@staticmethod
def now_playing(**kwargs):
if "show" in kwargs and "channel" in kwargs and "episode" in kwargs:
return ":speaker::notes: Now playing the audio of the episode `{2}` from the show `{0}` " \
"in voice channel `{1}`.".format(kwargs["show"], kwargs["channel"].name, kwargs["episode"])
else:
return "Invalid format."
@staticmethod
def added_to_queue(**kwargs):
if "show" in kwargs and "episode" in kwargs:
return ":white_check_mark: The audio of the episode `{1}` from the show `{0}` " \
"has been added to the queue.".format(kwargs["show"], kwargs["episode"])
else:
return "Invalid format."
@staticmethod
def queue_entry(**kwargs):
if "show" in kwargs and "episode" in kwargs:
return "Audio of the episode {1} from the show {0}".format(kwargs["show"], kwargs["episode"])
else:
return "Invalid format."
class Type(Enum):
generic = Generic
theme = Theme
episode = Episode
class AudioPlayer:
""""Represents a TVBot audio player, one instance per guild that is using the TVBot voice features"""
def __init__(self, guild):
self.guild = guild
self.voice_client = None
self.queue = []
self.now_playing = None
self.notification_channel = None
self.currently_seeking = False
def next_audio_track(self, error):
if self.guild.voice_client is not None and not self.currently_seeking:
if len(self.queue) > 0:
next_in_queue = self.queue.pop(0)
self.voice_client.play(discord.FFmpegPCMAudio(next_in_queue["file"]), after=self.next_audio_track)
self.now_playing = next_in_queue
elif self.currently_seeking:
self.currently_seeking = False
async def play(self, channel, audio_type, file, metadata, episode_metadata=None, feedback_channel=None):
# determine if the client needs to move channels within the guild, otherwise connect
if self.guild.voice_client is not None:
self.voice_client = self.guild.voice_client
if self.voice_client.channel is not channel:
await self.voice_client.move_to(channel)
else:
self.voice_client = await channel.connect()
# create the embed object that is sent when a user asks what is playing
now_playing_embed = discord.Embed(title=":arrow_forward: Now Playing", color=config.embed_color)
if metadata["image"]["original"] is not None:
now_playing_embed.set_thumbnail(url=metadata["image"]["original"])
if episode_metadata is not None:
season = episode_metadata["season"]
number = episode_metadata["number"]
episode = episode_metadata["name"]
else:
season, number, episode = None, None, None
now_playing_embed.add_field(name=metadata["name"], value=audio_type.value.embed_text(season=season,
number=number,
episode=episode))
# if the client is playing something, add the audio to the queue, otherwise start playback
if self.voice_client.is_playing():
if feedback_channel is not None:
await feedback_channel.send(audio_type.value.added_to_queue(show=metadata["name"], episode=episode))
self.notification_channel = feedback_channel
self.queue.append({
"qtext": audio_type.value.queue_entry(show=metadata["name"], episode=episode),
"embed": now_playing_embed,
"file": file
})
else:
if feedback_channel is not None:
await feedback_channel.send(audio_type.value.now_playing(show=metadata["name"],
channel=channel,
episode=episode))
self.notification_channel = feedback_channel
self.queue = []
self.now_playing = {
"qtext": audio_type.value.queue_entry(show=metadata["name"], episode=episode),
"embed": now_playing_embed,
"file": file
}
self.voice_client.play(discord.FFmpegPCMAudio(file), after=self.next_audio_track)
async def seek(self, user, timestamp, feedback_channel=None, output_message=None):
if self.guild.voice_client is not None:
if user.voice.channel == self.voice_client.channel:
self.currently_seeking = True
self.voice_client.stop()
self.voice_client.play(discord.FFmpegPCMAudio(self.now_playing["file"],
before_options="-ss " + timestamp),
after=self.next_audio_track)
if feedback_channel is not None and output_message is not None:
await feedback_channel.send(output_message)
elif feedback_channel is not None:
await feedback_channel.send(":x: You must be in the same voice channel as TVBot "
"to be able to run this command.")
elif feedback_channel is not None:
await feedback_channel.send(":x: TVBot is currently not in a voice channel.")
async def leave(self, user, feedback_channel=None):
"""Returns if the bot was able to leave"""
if self.guild.voice_client is not None:
if user.voice.channel == self.voice_client.channel:
self.voice_client.stop()
await self.voice_client.disconnect()
if feedback_channel is not None:
await feedback_channel.send(":mute: Left voice channel `" + self.voice_client.channel.name + "`.")
return True
elif feedback_channel is not None:
await feedback_channel.send(":x: You must be in the same voice channel as TVBot "
"to be able to run this command.")
elif feedback_channel is not None:
await feedback_channel.send(":x: TVBot is currently not in a voice channel.")
return False
async def move(self, user, feedback_channel=None):
if self.guild.voice_client is not None:
if user.voice.channel != self.voice_client.channel:
await self.voice_client.move_to(user.voice.channel)
if feedback_channel is not None:
await feedback_channel.send(":mute: Moved to voice channel `" + user.voice.channel.name + "`.")
elif feedback_channel is not None:
await feedback_channel.send(":x: You must be in a different voice channel form TVBot "
"to be able to run this command.")
elif feedback_channel is not None:
await feedback_channel.send(":x: TVBot is currently not in a voice channel.")
async def skip(self, user, feedback_channel=None):
if user.voice.channel == self.voice_client.channel:
if feedback_channel is not None:
await feedback_channel.send(":white_check_mark: Skipping to next entry in the queue...")
self.voice_client.stop()
elif feedback_channel is not None:
await feedback_channel.send(":x: You must be in the same voice channel as TVBot "
"to be able to run this command.")
async def pause(self, user, feedback_channel=None):
if self.voice_client.is_playing():
if user.voice.channel == self.voice_client.channel:
self.voice_client.pause()
if feedback_channel is not None:
await feedback_channel.send(":pause_button: TVBot player paused.")
elif feedback_channel is not None:
await feedback_channel.send(":x: You must be in the same voice channel as TVBot "
"to be able to run this command.")
elif feedback_channel is not None:
await feedback_channel.send(":x: The player is already paused.")
async def resume(self, user, feedback_channel=None):
if not self.voice_client.is_playing():
if user.voice.channel == self.voice_client.channel:
self.voice_client.resume()
if feedback_channel is not None:
await feedback_channel.send(":arrow_forward: TVBot player resumed.")
elif feedback_channel is not None:
await feedback_channel.send(":x: You must be in the same voice channel as TVBot "
"to be able to run this command.")
elif feedback_channel is not None:
await feedback_channel.send(":x: The player is already playing.")
async def get_queue_string(self):
if len(self.queue) > 0:
output_string = "**TVBot audio queue:**```"
iterator = 1
for entry in self.queue:
output_string = output_string + "\n" + str(iterator) + ". " + entry["qtext"]
iterator += 1
output_string = output_string + "```"
return output_string
else:
return ":x: The queue is empty."
| gpl-3.0 |
xbezdick/tempest | tempest/api/object_storage/test_account_bulk.py | 25 | 6297 | # Copyright 2013 NTT Corporation
#
# 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 tarfile
import tempfile
from tempest.api.object_storage import base
from tempest.common import custom_matchers
from tempest import test
class BulkTest(base.BaseObjectTest):
def setUp(self):
super(BulkTest, self).setUp()
self.containers = []
def tearDown(self):
self.delete_containers(self.containers)
super(BulkTest, self).tearDown()
def _create_archive(self):
# Create an archived file for bulk upload testing.
# Directory and files contained in the directory correspond to
# container and subsidiary objects.
tmp_dir = tempfile.mkdtemp()
tmp_file = tempfile.mkstemp(dir=tmp_dir)
# Extract a container name and an object name
container_name = tmp_dir.split("/")[-1]
object_name = tmp_file[1].split("/")[-1]
# Create tar file
tarpath = tempfile.NamedTemporaryFile(suffix=".tar")
tar = tarfile.open(None, 'w', tarpath)
tar.add(tmp_dir, arcname=container_name)
tar.close()
tarpath.flush()
return tarpath.name, container_name, object_name
def _upload_archive(self, filepath):
# upload an archived file
params = {'extract-archive': 'tar'}
with open(filepath) as fh:
mydata = fh.read()
resp, body = self.account_client.create_account(data=mydata,
params=params)
return resp, body
def _check_contents_deleted(self, container_name):
param = {'format': 'txt'}
resp, body = self.account_client.list_account_containers(param)
self.assertHeaders(resp, 'Account', 'GET')
self.assertNotIn(container_name, body)
@test.idempotent_id('a407de51-1983-47cc-9f14-47c2b059413c')
@test.requires_ext(extension='bulk', service='object')
def test_extract_archive(self):
# Test bulk operation of file upload with an archived file
filepath, container_name, object_name = self._create_archive()
resp, _ = self._upload_archive(filepath)
self.containers.append(container_name)
# When uploading an archived file with the bulk operation, the response
# does not contain 'content-length' header. This is the special case,
# therefore the existence of response headers is checked without
# custom matcher.
self.assertIn('transfer-encoding', resp)
self.assertIn('content-type', resp)
self.assertIn('x-trans-id', resp)
self.assertIn('date', resp)
# Check only the format of common headers with custom matcher
self.assertThat(resp, custom_matchers.AreAllWellFormatted())
param = {'format': 'json'}
resp, body = self.account_client.list_account_containers(param)
self.assertHeaders(resp, 'Account', 'GET')
self.assertIn(container_name, [b['name'] for b in body])
param = {'format': 'json'}
resp, contents_list = self.container_client.list_container_contents(
container_name, param)
self.assertHeaders(resp, 'Container', 'GET')
self.assertIn(object_name, [c['name'] for c in contents_list])
@test.idempotent_id('c075e682-0d2a-43b2-808d-4116200d736d')
@test.requires_ext(extension='bulk', service='object')
def test_bulk_delete(self):
# Test bulk operation of deleting multiple files
filepath, container_name, object_name = self._create_archive()
self._upload_archive(filepath)
data = '%s/%s\n%s' % (container_name, object_name, container_name)
params = {'bulk-delete': ''}
resp, body = self.account_client.delete_account(data=data,
params=params)
# When deleting multiple files using the bulk operation, the response
# does not contain 'content-length' header. This is the special case,
# therefore the existence of response headers is checked without
# custom matcher.
self.assertIn('transfer-encoding', resp)
self.assertIn('content-type', resp)
self.assertIn('x-trans-id', resp)
self.assertIn('date', resp)
# Check only the format of common headers with custom matcher
self.assertThat(resp, custom_matchers.AreAllWellFormatted())
# Check if uploaded contents are completely deleted
self._check_contents_deleted(container_name)
@test.idempotent_id('dbea2bcb-efbb-4674-ac8a-a5a0e33d1d79')
@test.requires_ext(extension='bulk', service='object')
def test_bulk_delete_by_POST(self):
# Test bulk operation of deleting multiple files
filepath, container_name, object_name = self._create_archive()
self._upload_archive(filepath)
data = '%s/%s\n%s' % (container_name, object_name, container_name)
params = {'bulk-delete': ''}
resp, body = self.account_client.create_account_metadata(
{}, data=data, params=params)
# When deleting multiple files using the bulk operation, the response
# does not contain 'content-length' header. This is the special case,
# therefore the existence of response headers is checked without
# custom matcher.
self.assertIn('transfer-encoding', resp)
self.assertIn('content-type', resp)
self.assertIn('x-trans-id', resp)
self.assertIn('date', resp)
# Check only the format of common headers with custom matcher
self.assertThat(resp, custom_matchers.AreAllWellFormatted())
# Check if uploaded contents are completely deleted
self._check_contents_deleted(container_name)
| apache-2.0 |
petrus-v/odoo | addons/lunch/tests/__init__.py | 260 | 1077 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Business Applications
# Copyright (c) 2012-TODAY OpenERP S.A. <http://openerp.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from . import test_lunch
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
jeroanan/zoetrope | config.py | 1 | 1117 | # Copyright (c) David Wilson 2016, 2017, 2021
#
# Licensed under the GPL version 3
import os
import logging
gui_rpc_file_location = '/etc/boinc-client/gui_rpc_auth.cfg'
boinc_data_dir = '/var/lib/boinc-client'
cpu_temperature_file = '/sys/class/thermal/thermal_zone0/temp'
log_file_name = 'zoetrope.log'
log_level = logging.DEBUG
log_message_format = '%(asctime)s %(message)s'
WorkingDirectory = os.path.dirname(os.path.abspath(__file__))
database_file = WorkingDirectory + '/zoetrope.db'
authentication_enabled = False
# Should we daemonize cherrpy on start?
# When running in Docker we shouldn't; if you're just running
# in the console then maybe you'd want to.
daemonize = False
# If you're running boinc on the same server as this site then
# leave rpc_hostname as blank, otherwise set to the hostname:port
# that boinc runs on.
rpc_hostname = "192.168.0.88"
# if boinc is running on the same server as this site then
# you should able to set the rpc_password to None (no quotes).
rpc_password = "123"
# The following two should be changed.
default_username = 'user'
default_password = 'password'
| gpl-3.0 |
LeZhang2016/openthread | tools/harness-automation/cases/ed_6_5_2.py | 16 | 2084 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
import time
import unittest
import re
from autothreadharness.harness_case import HarnessCase
class ED_6_5_2(HarnessCase):
role = HarnessCase.ROLE_ED
case = '6 5 2'
golden_devices_required = 2
def on_dialog(self, dialog, title):
if title.startswith('Reset DUT'):
self.dut.stop()
return False
elif title.startswith('Rejoin Now'):
self.dut.start()
return False
if __name__ == '__main__':
unittest.main()
| bsd-3-clause |
imankulov/sentry | src/sentry/api/endpoints/project_rule_details.py | 14 | 1525 | from __future__ import absolute_import
from rest_framework import status
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.api.serializers.rest_framework import RuleSerializer
from sentry.models import Rule
class ProjectRuleDetailsEndpoint(ProjectEndpoint):
def get(self, request, project, rule_id):
"""
Retrieve a rule
Return details on an individual rule.
{method} {path}
"""
rule = Rule.objects.get(
project=project,
id=rule_id,
)
return Response(serialize(rule, request.user))
def put(self, request, project, rule_id):
"""
Update a rule
Update various attributes for the given rule.
{method} {path}
{{
"name": "My rule name",
"conditions": [],
"actions": [],
"actionMatch": "all"
}}
"""
rule = Rule.objects.get(
project=project,
id=rule_id,
)
serializer = RuleSerializer({
'actionMatch': rule.data.get('action_match', 'all'),
}, context={'project': project}, data=request.DATA, partial=True)
if serializer.is_valid():
rule = serializer.save(rule=rule)
return Response(serialize(rule, request.user))
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
| bsd-3-clause |
cvium/Flexget | tests/test_lazy_fields.py | 13 | 1581 | from __future__ import unicode_literals, division, absolute_import
from flexget.entry import Entry
from flexget.plugin import PluginError
class TestLazyFields(object):
def test_lazy_queue(self):
"""Tests behavior when multiple plugins register lazy lookups for the same field"""
def lazy_a(entry):
if 'fail' in entry:
raise PluginError('oh no!')
for f in ['a_field', 'ab_field', 'a_fail']:
entry[f] = 'a'
def lazy_b(entry):
for f in ['b_field', 'ab_field', 'a_fail']:
entry[f] = 'b'
def setup_entry():
entry = Entry()
entry.register_lazy_func(lazy_a, ['ab_field', 'a_field', 'a_fail'])
entry.register_lazy_func(lazy_b, ['ab_field', 'b_field', 'a_fail'])
return entry
entry = setup_entry()
assert entry['b_field'] == 'b', 'Lazy lookup failed'
assert entry['ab_field'] == 'b', 'ab_field should be `b` when lazy_b is run first'
# Now cause 'a' lookup to occur
assert entry['a_field'] == 'a'
# TODO: What is the desired result when a lookup has information that is already populated?
#assert entry['ab_field'] == 'b'
# Test fallback when first lookup fails
entry = setup_entry()
entry['fail'] = True
assert entry['a_fail'] == 'b', 'Lookup should have fallen back to b'
assert entry['a_field'] is None, 'a_field should be None after failed lookup'
assert entry['ab_field'] == 'b', 'ab_field should be `b`'
| mit |
ifduyue/sentry | src/sentry/api/endpoints/user_password.py | 2 | 2840 | from __future__ import absolute_import
from django.utils.crypto import constant_time_compare
from rest_framework import serializers, status
from rest_framework.response import Response
from sentry.api.bases.user import UserEndpoint
from sentry.auth import password_validation
from sentry.models import User
from sentry.security import capture_security_activity
class UserPasswordSerializer(serializers.ModelSerializer):
password = serializers.CharField(required=True)
passwordNew = serializers.CharField(required=True)
passwordVerify = serializers.CharField(required=True)
class Meta:
model = User
fields = ('password', 'passwordNew', 'passwordVerify', )
def validate_password(self, attrs, source):
if self.context['has_usable_password'] and not self.object.check_password(
attrs.get('password')):
raise serializers.ValidationError('The password you entered is not correct.')
return attrs
def validate_passwordNew(self, attrs, source):
# this will raise a ValidationError if password is invalid
password_validation.validate_password(attrs[source])
if self.context['is_managed']:
raise serializers.ValidationError(
'This account is managed and the password cannot be changed via Sentry.')
return attrs
def validate(self, attrs):
attrs = super(UserPasswordSerializer, self).validate(attrs)
# make sure `passwordNew` matches `passwordVerify`
if not constant_time_compare(attrs.get('passwordNew'), attrs.get('passwordVerify')):
raise serializers.ValidationError(
'The passwords you entered did not match.')
return attrs
class UserPasswordEndpoint(UserEndpoint):
def put(self, request, user):
# pass some context to serializer otherwise when we create a new serializer instance,
# user.password gets set to new plaintext password from request and
# `user.has_usable_password` becomes False
serializer = UserPasswordSerializer(user, data=request.DATA, context={
'is_managed': user.is_managed,
'has_usable_password': user.has_usable_password(),
})
if not serializer.is_valid():
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
result = serializer.object
user.set_password(result.passwordNew)
user.refresh_session_nonce(request._request)
user.clear_lost_passwords()
user = serializer.save()
capture_security_activity(
account=user,
type='password-changed',
actor=request.user,
ip_address=request.META['REMOTE_ADDR'],
send_email=True,
)
return Response(status=status.HTTP_204_NO_CONTENT)
| bsd-3-clause |
mixturemodel-flow/tensorflow | tensorflow/contrib/tensor_forest/client/eval_metrics_test.py | 65 | 3849 | # 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.client.eval_metrics."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.tensor_forest.client import eval_metrics
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import test_util
from tensorflow.python.ops import variables
from tensorflow.python.platform import googletest
class EvalMetricsTest(test_util.TensorFlowTestCase):
def testTop2(self):
top_2_fn = eval_metrics._top_k_generator(2)
probabilities = constant_op.constant([[0.1, 0.2, 0.3], [0.4, 0.7, 0.5],
[0.9, 0.8, 0.2], [0.6, 0.4, 0.8]])
targets = constant_op.constant([[0], [2], [1], [1]])
in_top_2_op, update_op = top_2_fn(probabilities, targets)
with self.test_session():
# initializes internal accuracy vars
variables.local_variables_initializer().run()
# need to call in order to run the in_top_2_op internal operations because
# it is a streaming function
update_op.eval()
self.assertNear(0.5, in_top_2_op.eval(), 0.0001)
def testTop3(self):
top_3_fn = eval_metrics._top_k_generator(3)
probabilities = constant_op.constant([[0.1, 0.2, 0.6, 0.3, 0.5, 0.5],
[0.1, 0.4, 0.7, 0.3, 0.5, 0.2],
[0.1, 0.3, 0.8, 0.7, 0.4, 0.9],
[0.9, 0.8, 0.1, 0.8, 0.2, 0.7],
[0.3, 0.6, 0.9, 0.4, 0.8, 0.6]])
targets = constant_op.constant([3, 0, 2, 5, 1])
in_top_3_op, update_op = top_3_fn(probabilities, targets)
with self.test_session():
# initializes internal accuracy vars
variables.local_variables_initializer().run()
# need to call in order to run the in_top_3_op internal operations because
# it is a streaming function
update_op.eval()
self.assertNear(0.4, in_top_3_op.eval(), 0.0001)
def testAccuracy(self):
predictions = constant_op.constant([0, 1, 3, 6, 5, 2, 7, 6, 4, 9])
targets = constant_op.constant([0, 1, 4, 6, 5, 1, 7, 5, 4, 8])
accuracy_op, update_op = eval_metrics._accuracy(predictions, targets)
with self.test_session():
variables.local_variables_initializer().run()
# need to call in order to run the accuracy_op internal operations because
# it is a streaming function
update_op.eval()
self.assertNear(0.6, accuracy_op.eval(), 0.0001)
def testR2(self):
scores = constant_op.constant(
[1.2, 3.9, 2.1, 0.9, 2.2, 0.1, 6.0, 4.0, 0.9])
targets = constant_op.constant(
[1.0, 4.3, 2.6, 0.5, 1.1, 0.7, 5.1, 3.4, 1.8])
r2_op, update_op = eval_metrics._r2(scores, targets)
with self.test_session():
# initializes internal accuracy vars
variables.local_variables_initializer().run()
# need to call in order to run the r2_op internal operations because
# it is a streaming function
update_op.eval()
self.assertNear(0.813583, r2_op.eval(), 0.0001)
if __name__ == '__main__':
googletest.main()
| apache-2.0 |
nanolearningllc/edx-platform-cypress-2 | openedx/core/djangoapps/profile_images/tests/helpers.py | 117 | 1742 | """
Helper methods for use in profile image tests.
"""
from contextlib import contextmanager
import os
from tempfile import NamedTemporaryFile
from django.core.files.uploadedfile import UploadedFile
from PIL import Image
@contextmanager
def make_image_file(dimensions=(320, 240), extension=".jpeg", force_size=None):
"""
Yields a named temporary file created with the specified image type and
options.
Note the default dimensions are unequal (not a square) ensuring that center-square
cropping logic will be exercised during tests.
The temporary file will be closed and deleted automatically upon exiting
the `with` block.
"""
image = Image.new('RGB', dimensions, "green")
image_file = NamedTemporaryFile(suffix=extension)
try:
image.save(image_file)
if force_size is not None:
image_file.seek(0, os.SEEK_END)
bytes_to_pad = force_size - image_file.tell()
# write in hunks of 256 bytes
hunk, byte_ = bytearray([0] * 256), bytearray([0])
num_hunks, remainder = divmod(bytes_to_pad, 256)
for _ in xrange(num_hunks):
image_file.write(hunk)
for _ in xrange(remainder):
image_file.write(byte_)
image_file.flush()
image_file.seek(0)
yield image_file
finally:
image_file.close()
@contextmanager
def make_uploaded_file(content_type, *a, **kw):
"""
Wrap the result of make_image_file in a django UploadedFile.
"""
with make_image_file(*a, **kw) as image_file:
yield UploadedFile(
image_file,
content_type=content_type,
size=os.path.getsize(image_file.name),
)
| agpl-3.0 |
geerlingguy/ansible | lib/ansible/plugins/action/copy.py | 6 | 26889 | # (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
# (c) 2017 Toshio Kuratomi <tkuraotmi@ansible.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import os
import os.path
import stat
import tempfile
import traceback
from ansible import constants as C
from ansible.errors import AnsibleError, AnsibleFileNotFound
from ansible.module_utils.basic import FILE_COMMON_ARGUMENTS
from ansible.module_utils._text import to_bytes, to_native, to_text
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.plugins.action import ActionBase
from ansible.utils.hashing import checksum
# Supplement the FILE_COMMON_ARGUMENTS with arguments that are specific to file
REAL_FILE_ARGS = frozenset(FILE_COMMON_ARGUMENTS.keys()).union(
('state', 'path', '_original_basename', 'recurse', 'force',
'_diff_peek', 'src'))
def _create_remote_file_args(module_args):
"""remove keys that are not relevant to file"""
return dict((k, v) for k, v in module_args.items() if k in REAL_FILE_ARGS)
def _create_remote_copy_args(module_args):
"""remove action plugin only keys"""
return dict((k, v) for k, v in module_args.items() if k not in ('content', 'decrypt'))
def _walk_dirs(topdir, base_path=None, local_follow=False, trailing_slash_detector=None):
"""
Walk a filesystem tree returning enough information to copy the files
:arg topdir: The directory that the filesystem tree is rooted at
:kwarg base_path: The initial directory structure to strip off of the
files for the destination directory. If this is None (the default),
the base_path is set to ``top_dir``.
:kwarg local_follow: Whether to follow symlinks on the source. When set
to False, no symlinks are dereferenced. When set to True (the
default), the code will dereference most symlinks. However, symlinks
can still be present if needed to break a circular link.
:kwarg trailing_slash_detector: Function to determine if a path has
a trailing directory separator. Only needed when dealing with paths on
a remote machine (in which case, pass in a function that is aware of the
directory separator conventions on the remote machine).
:returns: dictionary of tuples. All of the path elements in the structure are text strings.
This separates all the files, directories, and symlinks along with
important information about each::
{ 'files': [('/absolute/path/to/copy/from', 'relative/path/to/copy/to'), ...],
'directories': [('/absolute/path/to/copy/from', 'relative/path/to/copy/to'), ...],
'symlinks': [('/symlink/target/path', 'relative/path/to/copy/to'), ...],
}
The ``symlinks`` field is only populated if ``local_follow`` is set to False
*or* a circular symlink cannot be dereferenced.
"""
# Convert the path segments into byte strings
r_files = {'files': [], 'directories': [], 'symlinks': []}
def _recurse(topdir, rel_offset, parent_dirs, rel_base=u''):
"""
This is a closure (function utilizing variables from it's parent
function's scope) so that we only need one copy of all the containers.
Note that this function uses side effects (See the Variables used from
outer scope).
:arg topdir: The directory we are walking for files
:arg rel_offset: Integer defining how many characters to strip off of
the beginning of a path
:arg parent_dirs: Directories that we're copying that this directory is in.
:kwarg rel_base: String to prepend to the path after ``rel_offset`` is
applied to form the relative path.
Variables used from the outer scope
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:r_files: Dictionary of files in the hierarchy. See the return value
for :func:`walk` for the structure of this dictionary.
:local_follow: Read-only inside of :func:`_recurse`. Whether to follow symlinks
"""
for base_path, sub_folders, files in os.walk(topdir):
for filename in files:
filepath = os.path.join(base_path, filename)
dest_filepath = os.path.join(rel_base, filepath[rel_offset:])
if os.path.islink(filepath):
# Dereference the symlnk
real_file = os.path.realpath(filepath)
if local_follow and os.path.isfile(real_file):
# Add the file pointed to by the symlink
r_files['files'].append((real_file, dest_filepath))
else:
# Mark this file as a symlink to copy
r_files['symlinks'].append((os.readlink(filepath), dest_filepath))
else:
# Just a normal file
r_files['files'].append((filepath, dest_filepath))
for dirname in sub_folders:
dirpath = os.path.join(base_path, dirname)
dest_dirpath = os.path.join(rel_base, dirpath[rel_offset:])
real_dir = os.path.realpath(dirpath)
dir_stats = os.stat(real_dir)
if os.path.islink(dirpath):
if local_follow:
if (dir_stats.st_dev, dir_stats.st_ino) in parent_dirs:
# Just insert the symlink if the target directory
# exists inside of the copy already
r_files['symlinks'].append((os.readlink(dirpath), dest_dirpath))
else:
# Walk the dirpath to find all parent directories.
new_parents = set()
parent_dir_list = os.path.dirname(dirpath).split(os.path.sep)
for parent in range(len(parent_dir_list), 0, -1):
parent_stat = os.stat(u'/'.join(parent_dir_list[:parent]))
if (parent_stat.st_dev, parent_stat.st_ino) in parent_dirs:
# Reached the point at which the directory
# tree is already known. Don't add any
# more or we might go to an ancestor that
# isn't being copied.
break
new_parents.add((parent_stat.st_dev, parent_stat.st_ino))
if (dir_stats.st_dev, dir_stats.st_ino) in new_parents:
# This was a a circular symlink. So add it as
# a symlink
r_files['symlinks'].append((os.readlink(dirpath), dest_dirpath))
else:
# Walk the directory pointed to by the symlink
r_files['directories'].append((real_dir, dest_dirpath))
offset = len(real_dir) + 1
_recurse(real_dir, offset, parent_dirs.union(new_parents), rel_base=dest_dirpath)
else:
# Add the symlink to the destination
r_files['symlinks'].append((os.readlink(dirpath), dest_dirpath))
else:
# Just a normal directory
r_files['directories'].append((dirpath, dest_dirpath))
# Check if the source ends with a "/" so that we know which directory
# level to work at (similar to rsync)
source_trailing_slash = False
if trailing_slash_detector:
source_trailing_slash = trailing_slash_detector(topdir)
else:
source_trailing_slash = topdir.endswith(os.path.sep)
# Calculate the offset needed to strip the base_path to make relative
# paths
if base_path is None:
base_path = topdir
if not source_trailing_slash:
base_path = os.path.dirname(base_path)
if topdir.startswith(base_path):
offset = len(base_path)
# Make sure we're making the new paths relative
if trailing_slash_detector and not trailing_slash_detector(base_path):
offset += 1
elif not base_path.endswith(os.path.sep):
offset += 1
if os.path.islink(topdir) and not local_follow:
r_files['symlinks'] = (os.readlink(topdir), os.path.basename(topdir))
return r_files
dir_stats = os.stat(topdir)
parents = frozenset(((dir_stats.st_dev, dir_stats.st_ino),))
# Actually walk the directory hierarchy
_recurse(topdir, offset, parents)
return r_files
class ActionModule(ActionBase):
TRANSFERS_FILES = True
def _ensure_invocation(self, result):
# NOTE: adding invocation arguments here needs to be kept in sync with
# any no_log specified in the argument_spec in the module.
# This is not automatic.
if 'invocation' not in result:
if self._play_context.no_log:
result['invocation'] = "CENSORED: no_log is set"
else:
# NOTE: Should be removed in the future. For now keep this broken
# behaviour, have a look in the PR 51582
result['invocation'] = self._task.args.copy()
result['invocation']['module_args'] = self._task.args.copy()
if isinstance(result['invocation'], dict) and 'content' in result['invocation']:
result['invocation']['content'] = 'CENSORED: content is a no_log parameter'
return result
def _copy_file(self, source_full, source_rel, content, content_tempfile,
dest, task_vars, follow):
decrypt = boolean(self._task.args.get('decrypt', True), strict=False)
force = boolean(self._task.args.get('force', 'yes'), strict=False)
raw = boolean(self._task.args.get('raw', 'no'), strict=False)
result = {}
result['diff'] = []
# If the local file does not exist, get_real_file() raises AnsibleFileNotFound
try:
source_full = self._loader.get_real_file(source_full, decrypt=decrypt)
except AnsibleFileNotFound as e:
result['failed'] = True
result['msg'] = "could not find src=%s, %s" % (source_full, to_text(e))
return result
# Get the local mode and set if user wanted it preserved
# https://github.com/ansible/ansible-modules-core/issues/1124
lmode = None
if self._task.args.get('mode', None) == 'preserve':
lmode = '0%03o' % stat.S_IMODE(os.stat(source_full).st_mode)
# This is kind of optimization - if user told us destination is
# dir, do path manipulation right away, otherwise we still check
# for dest being a dir via remote call below.
if self._connection._shell.path_has_trailing_slash(dest):
dest_file = self._connection._shell.join_path(dest, source_rel)
else:
dest_file = dest
# Attempt to get remote file info
dest_status = self._execute_remote_stat(dest_file, all_vars=task_vars, follow=follow, checksum=force)
if dest_status['exists'] and dest_status['isdir']:
# The dest is a directory.
if content is not None:
# If source was defined as content remove the temporary file and fail out.
self._remove_tempfile_if_content_defined(content, content_tempfile)
result['failed'] = True
result['msg'] = "can not use content with a dir as dest"
return result
else:
# Append the relative source location to the destination and get remote stats again
dest_file = self._connection._shell.join_path(dest, source_rel)
dest_status = self._execute_remote_stat(dest_file, all_vars=task_vars, follow=follow, checksum=force)
if dest_status['exists'] and not force:
# remote_file exists so continue to next iteration.
return None
# Generate a hash of the local file.
local_checksum = checksum(source_full)
if local_checksum != dest_status['checksum']:
# The checksums don't match and we will change or error out.
if self._play_context.diff and not raw:
result['diff'].append(self._get_diff_data(dest_file, source_full, task_vars))
if self._play_context.check_mode:
self._remove_tempfile_if_content_defined(content, content_tempfile)
result['changed'] = True
return result
# Define a remote directory that we will copy the file to.
tmp_src = self._connection._shell.join_path(self._connection._shell.tmpdir, 'source')
remote_path = None
if not raw:
remote_path = self._transfer_file(source_full, tmp_src)
else:
self._transfer_file(source_full, dest_file)
# We have copied the file remotely and no longer require our content_tempfile
self._remove_tempfile_if_content_defined(content, content_tempfile)
self._loader.cleanup_tmp_file(source_full)
# FIXME: I don't think this is needed when PIPELINING=0 because the source is created
# world readable. Access to the directory itself is controlled via fixup_perms2() as
# part of executing the module. Check that umask with scp/sftp/piped doesn't cause
# a problem before acting on this idea. (This idea would save a round-trip)
# fix file permissions when the copy is done as a different user
if remote_path:
self._fixup_perms2((self._connection._shell.tmpdir, remote_path))
if raw:
# Continue to next iteration if raw is defined.
return None
# Run the copy module
# src and dest here come after original and override them
# we pass dest only to make sure it includes trailing slash in case of recursive copy
new_module_args = _create_remote_copy_args(self._task.args)
new_module_args.update(
dict(
src=tmp_src,
dest=dest,
_original_basename=source_rel,
follow=follow
)
)
if not self._task.args.get('checksum'):
new_module_args['checksum'] = local_checksum
if lmode:
new_module_args['mode'] = lmode
module_return = self._execute_module(module_name='copy', module_args=new_module_args, task_vars=task_vars)
else:
# no need to transfer the file, already correct hash, but still need to call
# the file module in case we want to change attributes
self._remove_tempfile_if_content_defined(content, content_tempfile)
self._loader.cleanup_tmp_file(source_full)
if raw:
return None
# Fix for https://github.com/ansible/ansible-modules-core/issues/1568.
# If checksums match, and follow = True, find out if 'dest' is a link. If so,
# change it to point to the source of the link.
if follow:
dest_status_nofollow = self._execute_remote_stat(dest_file, all_vars=task_vars, follow=False)
if dest_status_nofollow['islnk'] and 'lnk_source' in dest_status_nofollow.keys():
dest = dest_status_nofollow['lnk_source']
# Build temporary module_args.
new_module_args = _create_remote_file_args(self._task.args)
new_module_args.update(
dict(
dest=dest,
_original_basename=source_rel,
recurse=False,
state='file',
)
)
# src is sent to the file module in _original_basename, not in src
try:
del new_module_args['src']
except KeyError:
pass
if lmode:
new_module_args['mode'] = lmode
# Execute the file module.
module_return = self._execute_module(module_name='file', module_args=new_module_args, task_vars=task_vars)
if not module_return.get('checksum'):
module_return['checksum'] = local_checksum
result.update(module_return)
return result
def _create_content_tempfile(self, content):
''' Create a tempfile containing defined content '''
fd, content_tempfile = tempfile.mkstemp(dir=C.DEFAULT_LOCAL_TMP)
f = os.fdopen(fd, 'wb')
content = to_bytes(content)
try:
f.write(content)
except Exception as err:
os.remove(content_tempfile)
raise Exception(err)
finally:
f.close()
return content_tempfile
def _remove_tempfile_if_content_defined(self, content, content_tempfile):
if content is not None:
os.remove(content_tempfile)
def run(self, tmp=None, task_vars=None):
''' handler for file transfer operations '''
if task_vars is None:
task_vars = dict()
result = super(ActionModule, self).run(tmp, task_vars)
del tmp # tmp no longer has any effect
source = self._task.args.get('src', None)
content = self._task.args.get('content', None)
dest = self._task.args.get('dest', None)
remote_src = boolean(self._task.args.get('remote_src', False), strict=False)
local_follow = boolean(self._task.args.get('local_follow', True), strict=False)
result['failed'] = True
if not source and content is None:
result['msg'] = 'src (or content) is required'
elif not dest:
result['msg'] = 'dest is required'
elif source and content is not None:
result['msg'] = 'src and content are mutually exclusive'
elif content is not None and dest is not None and dest.endswith("/"):
result['msg'] = "can not use content with a dir as dest"
else:
del result['failed']
if result.get('failed'):
return self._ensure_invocation(result)
# Define content_tempfile in case we set it after finding content populated.
content_tempfile = None
# If content is defined make a tmp file and write the content into it.
if content is not None:
try:
# If content comes to us as a dict it should be decoded json.
# We need to encode it back into a string to write it out.
if isinstance(content, dict) or isinstance(content, list):
content_tempfile = self._create_content_tempfile(json.dumps(content))
else:
content_tempfile = self._create_content_tempfile(content)
source = content_tempfile
except Exception as err:
result['failed'] = True
result['msg'] = "could not write content temp file: %s" % to_native(err)
return self._ensure_invocation(result)
# if we have first_available_file in our vars
# look up the files and use the first one we find as src
elif remote_src:
result.update(self._execute_module(module_name='copy', task_vars=task_vars))
return self._ensure_invocation(result)
else:
# find_needle returns a path that may not have a trailing slash on
# a directory so we need to determine that now (we use it just
# like rsync does to figure out whether to include the directory
# or only the files inside the directory
trailing_slash = source.endswith(os.path.sep)
try:
# find in expected paths
source = self._find_needle('files', source)
except AnsibleError as e:
result['failed'] = True
result['msg'] = to_text(e)
result['exception'] = traceback.format_exc()
return self._ensure_invocation(result)
if trailing_slash != source.endswith(os.path.sep):
if source[-1] == os.path.sep:
source = source[:-1]
else:
source = source + os.path.sep
# A list of source file tuples (full_path, relative_path) which will try to copy to the destination
source_files = {'files': [], 'directories': [], 'symlinks': []}
# If source is a directory populate our list else source is a file and translate it to a tuple.
if os.path.isdir(to_bytes(source, errors='surrogate_or_strict')):
# Get a list of the files we want to replicate on the remote side
source_files = _walk_dirs(source, local_follow=local_follow,
trailing_slash_detector=self._connection._shell.path_has_trailing_slash)
# If it's recursive copy, destination is always a dir,
# explicitly mark it so (note - copy module relies on this).
if not self._connection._shell.path_has_trailing_slash(dest):
dest = self._connection._shell.join_path(dest, '')
# FIXME: Can we optimize cases where there's only one file, no
# symlinks and any number of directories? In the original code,
# empty directories are not copied....
else:
source_files['files'] = [(source, os.path.basename(source))]
changed = False
module_return = dict(changed=False)
# A register for if we executed a module.
# Used to cut down on command calls when not recursive.
module_executed = False
# expand any user home dir specifier
dest = self._remote_expand_user(dest)
implicit_directories = set()
for source_full, source_rel in source_files['files']:
# copy files over. This happens first as directories that have
# a file do not need to be created later
# We only follow symlinks for files in the non-recursive case
if source_files['directories']:
follow = False
else:
follow = boolean(self._task.args.get('follow', False), strict=False)
module_return = self._copy_file(source_full, source_rel, content, content_tempfile, dest, task_vars, follow)
if module_return is None:
continue
if module_return.get('failed'):
result.update(module_return)
return self._ensure_invocation(result)
paths = os.path.split(source_rel)
dir_path = ''
for dir_component in paths:
os.path.join(dir_path, dir_component)
implicit_directories.add(dir_path)
if 'diff' in result and not result['diff']:
del result['diff']
module_executed = True
changed = changed or module_return.get('changed', False)
for src, dest_path in source_files['directories']:
# Find directories that are leaves as they might not have been
# created yet.
if dest_path in implicit_directories:
continue
# Use file module to create these
new_module_args = _create_remote_file_args(self._task.args)
new_module_args['path'] = os.path.join(dest, dest_path)
new_module_args['state'] = 'directory'
new_module_args['mode'] = self._task.args.get('directory_mode', None)
new_module_args['recurse'] = False
del new_module_args['src']
module_return = self._execute_module(module_name='file', module_args=new_module_args, task_vars=task_vars)
if module_return.get('failed'):
result.update(module_return)
return self._ensure_invocation(result)
module_executed = True
changed = changed or module_return.get('changed', False)
for target_path, dest_path in source_files['symlinks']:
# Copy symlinks over
new_module_args = _create_remote_file_args(self._task.args)
new_module_args['path'] = os.path.join(dest, dest_path)
new_module_args['src'] = target_path
new_module_args['state'] = 'link'
new_module_args['force'] = True
# Only follow remote symlinks in the non-recursive case
if source_files['directories']:
new_module_args['follow'] = False
# file module cannot deal with 'preserve' mode and is meaningless
# for symlinks anyway, so just don't pass it.
if new_module_args.get('mode', None) == 'preserve':
new_module_args.pop('mode')
module_return = self._execute_module(module_name='file', module_args=new_module_args, task_vars=task_vars)
module_executed = True
if module_return.get('failed'):
result.update(module_return)
return self._ensure_invocation(result)
changed = changed or module_return.get('changed', False)
if module_executed and len(source_files['files']) == 1:
result.update(module_return)
# the file module returns the file path as 'path', but
# the copy module uses 'dest', so add it if it's not there
if 'path' in result and 'dest' not in result:
result['dest'] = result['path']
else:
result.update(dict(dest=dest, src=source, changed=changed))
# Delete tmp path
self._remove_tmp_path(self._connection._shell.tmpdir)
return self._ensure_invocation(result)
| gpl-3.0 |
nelmiux/CarnotKE | jyhton/lib-python/2.7/lib-tk/test/test_ttk/test_functions.py | 48 | 17473 | # -*- encoding: utf-8 -*-
import sys
import unittest
import ttk
class MockTclObj(object):
typename = 'test'
def __init__(self, val):
self.val = val
def __str__(self):
return unicode(self.val)
class MockStateSpec(object):
typename = 'StateSpec'
def __init__(self, *args):
self.val = args
def __str__(self):
return ' '.join(self.val)
class InternalFunctionsTest(unittest.TestCase):
def test_format_optdict(self):
def check_against(fmt_opts, result):
for i in range(0, len(fmt_opts), 2):
self.assertEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1])
if result:
self.fail("result still got elements: %s" % result)
# passing an empty dict should return an empty object (tuple here)
self.assertFalse(ttk._format_optdict({}))
# check list formatting
check_against(
ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}),
{'-fg': 'blue', '-padding': '1 2 3 4'})
# check tuple formatting (same as list)
check_against(
ttk._format_optdict({'test': (1, 2, '', 0)}),
{'-test': '1 2 {} 0'})
# check untouched values
check_against(
ttk._format_optdict({'test': {'left': 'as is'}}),
{'-test': {'left': 'as is'}})
# check script formatting
check_against(
ttk._format_optdict(
{'test': [1, -1, '', '2m', 0], 'test2': 3,
'test3': '', 'test4': 'abc def',
'test5': '"abc"', 'test6': '{}',
'test7': '} -spam {'}, script=True),
{'-test': '{1 -1 {} 2m 0}', '-test2': '3',
'-test3': '{}', '-test4': '{abc def}',
'-test5': '{"abc"}', '-test6': r'\{\}',
'-test7': r'\}\ -spam\ \{'})
opts = {u'αβγ': True, u'á': False}
orig_opts = opts.copy()
# check if giving unicode keys is fine
check_against(ttk._format_optdict(opts), {u'-αβγ': True, u'-á': False})
# opts should remain unchanged
self.assertEqual(opts, orig_opts)
# passing values with spaces inside a tuple/list
check_against(
ttk._format_optdict(
{'option': ('one two', 'three')}),
{'-option': '{one two} three'})
check_against(
ttk._format_optdict(
{'option': ('one\ttwo', 'three')}),
{'-option': '{one\ttwo} three'})
# passing empty strings inside a tuple/list
check_against(
ttk._format_optdict(
{'option': ('', 'one')}),
{'-option': '{} one'})
# passing values with braces inside a tuple/list
check_against(
ttk._format_optdict(
{'option': ('one} {two', 'three')}),
{'-option': r'one\}\ \{two three'})
# passing quoted strings inside a tuple/list
check_against(
ttk._format_optdict(
{'option': ('"one"', 'two')}),
{'-option': '{"one"} two'})
check_against(
ttk._format_optdict(
{'option': ('{one}', 'two')}),
{'-option': r'\{one\} two'})
# ignore an option
amount_opts = len(ttk._format_optdict(opts, ignore=(u'á'))) // 2
self.assertEqual(amount_opts, len(opts) - 1)
# ignore non-existing options
amount_opts = len(ttk._format_optdict(opts, ignore=(u'á', 'b'))) // 2
self.assertEqual(amount_opts, len(opts) - 1)
# ignore every option
self.assertFalse(ttk._format_optdict(opts, ignore=opts.keys()))
def test_format_mapdict(self):
opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]}
result = ttk._format_mapdict(opts)
self.assertEqual(len(result), len(opts.keys()) * 2)
self.assertEqual(result, ('-a', '{b c} val d otherval {} single'))
self.assertEqual(ttk._format_mapdict(opts, script=True),
('-a', '{{b c} val d otherval {} single}'))
self.assertEqual(ttk._format_mapdict({2: []}), ('-2', ''))
opts = {u'üñíćódè': [(u'á', u'vãl')]}
result = ttk._format_mapdict(opts)
self.assertEqual(result, (u'-üñíćódè', u'á vãl'))
# empty states
valid = {'opt': [('', u'', 'hi')]}
self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi'))
# when passing multiple states, they all must be strings
invalid = {'opt': [(1, 2, 'valid val')]}
self.assertRaises(TypeError, ttk._format_mapdict, invalid)
invalid = {'opt': [([1], '2', 'valid val')]}
self.assertRaises(TypeError, ttk._format_mapdict, invalid)
# but when passing a single state, it can be anything
valid = {'opt': [[1, 'value']]}
self.assertEqual(ttk._format_mapdict(valid), ('-opt', '1 value'))
# special attention to single states which evalute to False
for stateval in (None, 0, False, '', set()): # just some samples
valid = {'opt': [(stateval, 'value')]}
self.assertEqual(ttk._format_mapdict(valid),
('-opt', '{} value'))
# values must be iterable
opts = {'a': None}
self.assertRaises(TypeError, ttk._format_mapdict, opts)
# items in the value must have size >= 2
self.assertRaises(IndexError, ttk._format_mapdict,
{'a': [('invalid', )]})
def test_format_elemcreate(self):
self.assertTrue(ttk._format_elemcreate(None), (None, ()))
## Testing type = image
# image type expects at least an image name, so this should raise
# IndexError since it tries to access the index 0 of an empty tuple
self.assertRaises(IndexError, ttk._format_elemcreate, 'image')
# don't format returned values as a tcl script
# minimum acceptable for image type
self.assertEqual(ttk._format_elemcreate('image', False, 'test'),
("test ", ()))
# specifying a state spec
self.assertEqual(ttk._format_elemcreate('image', False, 'test',
('', 'a')), ("test {} a", ()))
# state spec with multiple states
self.assertEqual(ttk._format_elemcreate('image', False, 'test',
('a', 'b', 'c')), ("test {a b} c", ()))
# state spec and options
res = ttk._format_elemcreate('image', False, 'test',
('a', 'b'), a='x', b='y')
self.assertEqual(res[0], "test a b")
self.assertEqual(set(res[1]), {"-a", "x", "-b", "y"})
# format returned values as a tcl script
# state spec with multiple states and an option with a multivalue
self.assertEqual(ttk._format_elemcreate('image', True, 'test',
('a', 'b', 'c', 'd'), x=[2, 3]), ("{test {a b c} d}", "-x {2 3}"))
## Testing type = vsapi
# vsapi type expects at least a class name and a part_id, so this
# should raise an ValueError since it tries to get two elements from
# an empty tuple
self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi')
# don't format returned values as a tcl script
# minimum acceptable for vsapi
self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'),
("a b ", ()))
# now with a state spec with multiple states
self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
('a', 'b', 'c')), ("a b {a b} c", ()))
# state spec and option
self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b',
('a', 'b'), opt='x'), ("a b a b", ("-opt", "x")))
# format returned values as a tcl script
# state spec with a multivalue and an option
self.assertEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b',
('a', 'b', [1, 2]), opt='x'), ("{a b {a b} {1 2}}", "-opt x"))
# Testing type = from
# from type expects at least a type name
self.assertRaises(IndexError, ttk._format_elemcreate, 'from')
self.assertEqual(ttk._format_elemcreate('from', False, 'a'),
('a', ()))
self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'),
('a', ('b', )))
self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'),
('{a}', 'b'))
def test_format_layoutlist(self):
def sample(indent=0, indent_size=2):
return ttk._format_layoutlist(
[('a', {'other': [1, 2, 3], 'children':
[('b', {'children':
[('c', {'children':
[('d', {'nice': 'opt'})], 'something': (1, 2)
})]
})]
})], indent=indent, indent_size=indent_size)[0]
def sample_expected(indent=0, indent_size=2):
spaces = lambda amount=0: ' ' * (amount + indent)
return (
"%sa -other {1 2 3} -children {\n"
"%sb -children {\n"
"%sc -something {1 2} -children {\n"
"%sd -nice opt\n"
"%s}\n"
"%s}\n"
"%s}" % (spaces(), spaces(indent_size),
spaces(2 * indent_size), spaces(3 * indent_size),
spaces(2 * indent_size), spaces(indent_size), spaces()))
# empty layout
self.assertEqual(ttk._format_layoutlist([])[0], '')
# smallest (after an empty one) acceptable layout
smallest = ttk._format_layoutlist([('a', None)], indent=0)
self.assertEqual(smallest,
ttk._format_layoutlist([('a', '')], indent=0))
self.assertEqual(smallest[0], 'a')
# testing indentation levels
self.assertEqual(sample(), sample_expected())
for i in range(4):
self.assertEqual(sample(i), sample_expected(i))
self.assertEqual(sample(i, i), sample_expected(i, i))
# invalid layout format, different kind of exceptions will be
# raised
# plain wrong format
self.assertRaises(ValueError, ttk._format_layoutlist,
['bad', 'format'])
self.assertRaises(TypeError, ttk._format_layoutlist, None)
# _format_layoutlist always expects the second item (in every item)
# to act like a dict (except when the value evalutes to False).
self.assertRaises(AttributeError,
ttk._format_layoutlist, [('a', 'b')])
# bad children formatting
self.assertRaises(ValueError, ttk._format_layoutlist,
[('name', {'children': {'a': None}})])
def test_script_from_settings(self):
# empty options
self.assertFalse(ttk._script_from_settings({'name':
{'configure': None, 'map': None, 'element create': None}}))
# empty layout
self.assertEqual(
ttk._script_from_settings({'name': {'layout': None}}),
"ttk::style layout name {\nnull\n}")
configdict = {u'αβγ': True, u'á': False}
self.assertTrue(
ttk._script_from_settings({'name': {'configure': configdict}}))
mapdict = {u'üñíćódè': [(u'á', u'vãl')]}
self.assertTrue(
ttk._script_from_settings({'name': {'map': mapdict}}))
# invalid image element
self.assertRaises(IndexError,
ttk._script_from_settings, {'name': {'element create': ['image']}})
# minimal valid image
self.assertTrue(ttk._script_from_settings({'name':
{'element create': ['image', 'name']}}))
image = {'thing': {'element create':
['image', 'name', ('state1', 'state2', 'val')]}}
self.assertEqual(ttk._script_from_settings(image),
"ttk::style element create thing image {name {state1 state2} val} ")
image['thing']['element create'].append({'opt': 30})
self.assertEqual(ttk._script_from_settings(image),
"ttk::style element create thing image {name {state1 state2} val} "
"-opt 30")
image['thing']['element create'][-1]['opt'] = [MockTclObj(3),
MockTclObj('2m')]
self.assertEqual(ttk._script_from_settings(image),
"ttk::style element create thing image {name {state1 state2} val} "
"-opt {3 2m}")
def test_dict_from_tcltuple(self):
fakettuple = ('-a', '{1 2 3}', '-something', 'foo')
self.assertEqual(ttk._dict_from_tcltuple(fakettuple, False),
{'-a': '{1 2 3}', '-something': 'foo'})
self.assertEqual(ttk._dict_from_tcltuple(fakettuple),
{'a': '{1 2 3}', 'something': 'foo'})
# passing a tuple with a single item should return an empty dict,
# since it tries to break the tuple by pairs.
self.assertFalse(ttk._dict_from_tcltuple(('single', )))
sspec = MockStateSpec('a', 'b')
self.assertEqual(ttk._dict_from_tcltuple(('-a', (sspec, 'val'))),
{'a': [('a', 'b', 'val')]})
self.assertEqual(ttk._dict_from_tcltuple((MockTclObj('-padding'),
[MockTclObj('1'), 2, MockTclObj('3m')])),
{'padding': [1, 2, '3m']})
def test_list_from_statespec(self):
def test_it(sspec, value, res_value, states):
self.assertEqual(ttk._list_from_statespec(
(sspec, value)), [states + (res_value, )])
states_even = tuple('state%d' % i for i in range(6))
statespec = MockStateSpec(*states_even)
test_it(statespec, 'val', 'val', states_even)
test_it(statespec, MockTclObj('val'), 'val', states_even)
states_odd = tuple('state%d' % i for i in range(5))
statespec = MockStateSpec(*states_odd)
test_it(statespec, 'val', 'val', states_odd)
test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c'))
def test_list_from_layouttuple(self):
# empty layout tuple
self.assertFalse(ttk._list_from_layouttuple(()))
# shortest layout tuple
self.assertEqual(ttk._list_from_layouttuple(('name', )),
[('name', {})])
# not so interesting ltuple
sample_ltuple = ('name', '-option', 'value')
self.assertEqual(ttk._list_from_layouttuple(sample_ltuple),
[('name', {'option': 'value'})])
# empty children
self.assertEqual(ttk._list_from_layouttuple(
('something', '-children', ())),
[('something', {'children': []})]
)
# more interesting ltuple
ltuple = (
'name', '-option', 'niceone', '-children', (
('otherone', '-children', (
('child', )), '-otheropt', 'othervalue'
)
)
)
self.assertEqual(ttk._list_from_layouttuple(ltuple),
[('name', {'option': 'niceone', 'children':
[('otherone', {'otheropt': 'othervalue', 'children':
[('child', {})]
})]
})]
)
# bad tuples
self.assertRaises(ValueError, ttk._list_from_layouttuple,
('name', 'no_minus'))
self.assertRaises(ValueError, ttk._list_from_layouttuple,
('name', 'no_minus', 'value'))
self.assertRaises(ValueError, ttk._list_from_layouttuple,
('something', '-children')) # no children
self.assertRaises(ValueError, ttk._list_from_layouttuple,
('something', '-children', 'value')) # invalid children
def test_val_or_dict(self):
def func(opt, val=None):
if val is None:
return "test val"
return (opt, val)
options = {'test': None}
self.assertEqual(ttk._val_or_dict(options, func), "test val")
options = {'test': 3}
self.assertEqual(ttk._val_or_dict(options, func), options)
def test_convert_stringval(self):
tests = (
(0, 0), ('09', 9), ('a', 'a'), (u'áÚ', u'áÚ'), ([], '[]'),
(None, 'None')
)
for orig, expected in tests:
self.assertEqual(ttk._convert_stringval(orig), expected)
if sys.getdefaultencoding() == 'ascii':
self.assertRaises(UnicodeDecodeError,
ttk._convert_stringval, 'á')
class TclObjsToPyTest(unittest.TestCase):
def test_unicode(self):
adict = {'opt': u'välúè'}
self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})
adict['opt'] = MockTclObj(adict['opt'])
self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': u'välúè'})
def test_multivalues(self):
adict = {'opt': [1, 2, 3, 4]}
self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]})
adict['opt'] = [1, 'xm', 3]
self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]})
adict['opt'] = (MockStateSpec('a', 'b'), u'válũè')
self.assertEqual(ttk.tclobjs_to_py(adict),
{'opt': [('a', 'b', u'válũè')]})
self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}),
{'x': ['y z']})
def test_nosplit(self):
self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}),
{'text': 'some text'})
tests_nogui = (InternalFunctionsTest, TclObjsToPyTest)
if __name__ == "__main__":
from test.test_support import run_unittest
run_unittest(*tests_nogui)
| apache-2.0 |
mxjl620/scikit-learn | benchmarks/bench_20newsgroups.py | 377 | 3555 | from __future__ import print_function, division
from time import time
import argparse
import numpy as np
from sklearn.dummy import DummyClassifier
from sklearn.datasets import fetch_20newsgroups_vectorized
from sklearn.metrics import accuracy_score
from sklearn.utils.validation import check_array
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import MultinomialNB
ESTIMATORS = {
"dummy": DummyClassifier(),
"random_forest": RandomForestClassifier(n_estimators=100,
max_features="sqrt",
min_samples_split=10),
"extra_trees": ExtraTreesClassifier(n_estimators=100,
max_features="sqrt",
min_samples_split=10),
"logistic_regression": LogisticRegression(),
"naive_bayes": MultinomialNB(),
"adaboost": AdaBoostClassifier(n_estimators=10),
}
###############################################################################
# Data
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--estimators', nargs="+", required=True,
choices=ESTIMATORS)
args = vars(parser.parse_args())
data_train = fetch_20newsgroups_vectorized(subset="train")
data_test = fetch_20newsgroups_vectorized(subset="test")
X_train = check_array(data_train.data, dtype=np.float32,
accept_sparse="csc")
X_test = check_array(data_test.data, dtype=np.float32, accept_sparse="csr")
y_train = data_train.target
y_test = data_test.target
print("20 newsgroups")
print("=============")
print("X_train.shape = {0}".format(X_train.shape))
print("X_train.format = {0}".format(X_train.format))
print("X_train.dtype = {0}".format(X_train.dtype))
print("X_train density = {0}"
"".format(X_train.nnz / np.product(X_train.shape)))
print("y_train {0}".format(y_train.shape))
print("X_test {0}".format(X_test.shape))
print("X_test.format = {0}".format(X_test.format))
print("X_test.dtype = {0}".format(X_test.dtype))
print("y_test {0}".format(y_test.shape))
print()
print("Classifier Training")
print("===================")
accuracy, train_time, test_time = {}, {}, {}
for name in sorted(args["estimators"]):
clf = ESTIMATORS[name]
try:
clf.set_params(random_state=0)
except (TypeError, ValueError):
pass
print("Training %s ... " % name, end="")
t0 = time()
clf.fit(X_train, y_train)
train_time[name] = time() - t0
t0 = time()
y_pred = clf.predict(X_test)
test_time[name] = time() - t0
accuracy[name] = accuracy_score(y_test, y_pred)
print("done")
print()
print("Classification performance:")
print("===========================")
print()
print("%s %s %s %s" % ("Classifier ", "train-time", "test-time",
"Accuracy"))
print("-" * 44)
for name in sorted(accuracy, key=accuracy.get):
print("%s %s %s %s" % (name.ljust(16),
("%.4fs" % train_time[name]).center(10),
("%.4fs" % test_time[name]).center(10),
("%.4f" % accuracy[name]).center(10)))
print()
| bsd-3-clause |
Pantsworth/political-pundits | browser/kango-1.7.6/kango/builders/chrome.py | 11 | 12272 | import struct
import os
import shutil
import sys
import json
import codecs
import subprocess
import xml
from array import array
from kango import logger, die
from kango.utils import zip as zip_file
from kango.builders import ExtensionBuilderBase
from kango.settings import KEYWORDS
class ExtensionBuilder(ExtensionBuilderBase):
key = 'chrome'
package_extension = '.crx'
_manifest_filename = 'manifest.json'
_background_host_filename = 'background.html'
_info = None
_kango_path = None
_permission_table = {
'context_menu': 'contextMenus',
'web_navigation': 'webNavigation',
'notifications': 'notifications',
'cookies': 'cookies',
'tabs': 'tabs',
'native_messaging': 'nativeMessaging'
}
def __init__(self, info, kango_path):
self._info = info
self._kango_path = kango_path
def _unix_find_app(self, prog_filename):
bdirs = (
'$HOME/Environment/local/bin/',
'$HOME/bin/',
'/share/apps/bin/',
'/usr/local/bin/',
'/usr/bin/'
)
for dir in bdirs:
path = os.path.expandvars(os.path.join(dir, prog_filename))
if os.path.exists(path):
return path
return None
def get_chrome_path(self):
if sys.platform.startswith('win'):
root_pathes = (
'${LOCALAPPDATA}',
'${APPDATA}',
'${ProgramFiles(x86)}',
'${ProgramFiles}'
)
app_pathes = (os.path.join('Google', 'Chrome', 'Application', 'chrome.exe'),
os.path.join('Chromium', 'Application', 'chrome.exe'))
for root_path in root_pathes:
for app_path in app_pathes:
path = os.path.expandvars(os.path.join(root_path, app_path))
if os.path.exists(path):
return path
elif sys.platform.startswith('linux'):
for apppath in ('chromium-browser', 'google-chrome', 'chromium'):
path = self._unix_find_app(apppath)
if path is not None:
return path
elif sys.platform.startswith('darwin'):
if os.path.exists('/Applications/Google Chrome.app'):
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
elif os.path.exists('/Applications/Chromium.app'):
return '/Applications/Chromium.app/Contents/MacOS/Chromium'
return None
def _load_manifest(self, manifest_path):
with open(manifest_path, 'r') as f:
manifest = json.load(f)
return manifest
def _save_manifest(self, manifest, manifest_path):
with open(manifest_path, 'w') as f:
json.dump(manifest, f, skipkeys=True, indent=4)
def _patch_manifest(self, info, manifest):
if info.update_url == '':
del manifest['update_url']
if info.homepage_url == '':
del manifest['homepage_url']
if info.chrome_public_key != '':
manifest['key'] = info.chrome_public_key
for elem in manifest:
if elem not in('content_scripts', 'permissions') and hasattr(info, elem):
manifest[elem] = getattr(info, elem)
if info.browser_button is None:
del manifest['browser_action']
else:
manifest['browser_action']['default_icon'] = info.browser_button['icon']
manifest['browser_action']['default_title'] = info.browser_button['tooltipText']
if 'popup' not in info.browser_button:
del manifest['browser_action']['default_popup']
if not info.content_scripts:
del manifest['content_scripts']
if info.options_page is None:
del manifest['options_page']
if info.context_menu_item is None and 'context_menu' not in info.permissions:
manifest['permissions'].remove('contextMenus')
if info.permissions['xhr'] != self.DEFAULT_XHR_PERMISSIONS:
for key in self.DEFAULT_XHR_PERMISSIONS:
manifest['permissions'].remove(key)
manifest['permissions'].extend(info.permissions['xhr'])
if info.permissions['content_scripts'] != self.DEFAULT_CONTENT_SCRIPTS_MATCHES:
manifest['content_scripts'][0]['matches'] = info.permissions['content_scripts']
for key in self._permission_table:
if not info.permissions[key]:
manifest['permissions'].remove(self._permission_table[key])
def _process_includes(self, manifest, out_path):
includes_path = os.path.join(out_path, 'includes')
if 'content_scripts' in manifest:
self.merge_files(os.path.join(includes_path, 'content.js'),
map(lambda path: os.path.join(out_path, path), manifest['content_scripts'][0]['js']))
os.remove(os.path.join(includes_path, 'content_%s.js') % KEYWORDS['product'])
manifest['content_scripts'][0]['js'] = ['includes/content.js']
else:
shutil.rmtree(includes_path, True)
def _zip2crx(self, zipPath, keyPath, crxPath):
"""
:param zipPath: path to .zip file
:param keyPath: path to .pem file
:param crxPath: path to .crx file to be created
"""
# Sign the zip file with the private key in PEM format
signature = subprocess.Popen(['openssl', 'sha1', '-sign', keyPath, zipPath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
# Convert the PEM key to DER (and extract the public form) for inclusion in the CRX header
derkey = subprocess.Popen(['openssl', 'rsa', '-pubout', '-inform', 'PEM', '-outform', 'DER', '-in', keyPath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]
with open(crxPath, 'wb') as out:
out.write('Cr24') # Extension file magic number
header = array('L') if struct.calcsize('L') == 4 else array('I')
header.append(2) # Version 2
header.append(len(derkey))
header.append(len(signature))
header.tofile(out)
out.write(derkey)
out.write(signature)
with open(zipPath, 'rb') as zipFile:
out.write(zipFile.read())
def _generate_private_key(self, keyPath):
subprocess.Popen(['openssl', 'genrsa', '-out', './out.pem', '1024'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
subprocess.Popen(['openssl', 'pkey', '-in', './out.pem', '-out', keyPath], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
os.remove('./out.pem')
def _pack_via_open_ssl(self, zipPath, keyPath, crxPath):
if not os.path.isfile(keyPath):
self._generate_private_key(keyPath)
self._zip2crx(zipPath, keyPath, crxPath)
def _pack_zip(self, dst, src):
filename = self.get_package_name(self._info) + '_chrome_webstore.zip'
outpath = os.path.abspath(os.path.join(dst, filename))
zip_file.pack_directory(src, outpath)
return outpath
def _build_locales(self, manifest, out_path):
if len(self._info.locales) > 0:
special_keys = ('name', 'description')
locale_keys = ['__info_%s__' % key for key in special_keys]
chrome_keys = ['info_%s' % key for key in special_keys]
locales = self.get_locales(self._info.locales, out_path)
for name, locale in locales:
chrome_locale = {}
for key, locale_key, chrome_key in zip(special_keys, locale_keys, chrome_keys):
if locale_key in locale:
chrome_locale[chrome_key] = {'message': locale[locale_key]}
manifest[key] = '__MSG_%s__' % chrome_key
locale_dir = os.path.join(out_path, '_locales', name)
os.makedirs(locale_dir)
with open(os.path.join(locale_dir, 'messages.json'), 'w') as f:
json.dump(chrome_locale, f, skipkeys=True, indent=4)
manifest['default_locale'] = self._info.default_locale
def _validate(self, info):
if len(info.description) > 132:
logger.warning('description should be no more than 132 characters')
if info.context_menu_item is not None and not info.permissions['context_menu']:
die('context_menu_item used, but permissions.context_menu set to false')
def build(self, out_path, project_src_path, certificates_path, cmd_args):
self._validate(self._info)
manifest_path = os.path.join(out_path, self._manifest_filename)
manifest = self._load_manifest(manifest_path)
self._patch_manifest(self._info, manifest)
self._build_locales(manifest, out_path)
self._process_includes(manifest, out_path)
self._save_manifest(manifest, manifest_path)
self.patch_background_host(os.path.join(out_path, self._background_host_filename), self._info.modules)
return out_path
def pack(self, output_path, extension_path, project_src_path, certificates_path, cmd_args):
if not os.path.exists(certificates_path):
os.makedirs(certificates_path)
pem_path = os.path.join(certificates_path, 'chrome.pem')
extension_dst = os.path.abspath(os.path.join(extension_path, '../', 'chrome.crx'))
crx_path = os.path.join(output_path, self.get_full_package_name(self._info))
chrome_path = self.get_chrome_path()
if chrome_path is not None:
args = [chrome_path, '--pack-extension=%s' % extension_path, '--no-message-box']
if os.path.isfile(pem_path):
args.append('--pack-extension-key=%s' % pem_path)
subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
try:
shutil.move(os.path.abspath(os.path.join(extension_path, '../', 'chrome.pem')), pem_path)
except:
pass
shutil.move(extension_dst, crx_path)
else:
logger.info('Chrome/Chromium is not installed, trying OpenSSL...')
try:
zip_path = self._pack_zip(output_path, extension_path)
self._pack_via_open_ssl(zip_path, pem_path, crx_path)
except:
logger.error("Can't build extension with OpenSSL")
if self._info.update_url != '':
manifest_path = os.path.join(extension_path, self._manifest_filename)
manifest = self._load_manifest(manifest_path)
del manifest['update_url']
self._save_manifest(manifest, manifest_path)
self._pack_zip(output_path, extension_path)
def setup_update(self, output_path):
if self._info.update_url != '' or self._info.update_path_url != '':
update_xml_filename = 'update_chrome.xml'
xml_path = os.path.join(self._kango_path, 'src', 'xml', update_xml_filename)
doc = xml.dom.minidom.parse(xml_path)
app = doc.getElementsByTagName('app')[0]
app.setAttribute('appid', self._info.id)
updatecheck = app.getElementsByTagName('updatecheck')[0]
updatecheck.setAttribute('codebase', self._info.update_path_url + self.get_full_package_name(self._info))
updatecheck.setAttribute('version', self._info.version)
with codecs.open(os.path.join(output_path, update_xml_filename), 'w', 'utf-8') as f:
doc.writexml(f, encoding='utf-8')
self._info.update_url = self._info.update_url if self._info.update_url != '' else self._info.update_path_url + update_xml_filename
def migrate(self, src_path):
pass
| mit |
prds21/barrial-movie | servers/vidspot.py | 40 | 6587 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para vidspot
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os
import re
from core import scrapertools
from core import logger
from core import config
def test_video_exists( page_url ):
logger.info("[vidspot.py] test_video_exists(page_url='%s')" % page_url)
# No existe / borrado: http://vidspot.net/8jcgbrzhujri
data = scrapertools.cache_page(page_url)
#logger.info("data="+data)
if "<b>File Not Found</b>" in data or "<b>Archivo no encontrado</b>" in data or '<b class="err">Deleted' in data or '<b class="err">Removed' in data or '<font class="err">No such' in data:
return False,"No existe o ha sido borrado de vidspot"
else:
# Existe: http://vidspot.net/6ltw8v1zaa7o
patron = '<META NAME="description" CONTENT="(Archivo para descargar[^"]+)">'
matches = re.compile(patron,re.DOTALL).findall(data)
if len(matches)>0:
return True,""
return True,""
def get_video_url( page_url , premium = False , user="" , password="", video_password="" ):
logger.info("[vidspot.py] url="+page_url)
# Normaliza la URL
videoid = scrapertools.get_match(page_url,"http://vidspot.net/([a-z0-9A-Z]+)")
page_url = "http://vidspot.net/embed-"+videoid+"-728x400.html"
data = scrapertools.cache_page(page_url)
# Extrae la URL
match = re.compile('"file" : "(.+?)",').findall(data)
media_url = ""
if len(match) > 0:
for tempurl in match:
if not tempurl.endswith(".png") and not tempurl.endswith(".srt"):
media_url = tempurl
if media_url == "":
media_url = match[0]
video_urls = []
if media_url!="":
media_url+= "&direct=false"
video_urls.append( [ scrapertools.get_filename_from_url(media_url)[-4:]+" [vidspot]",media_url])
for video_url in video_urls:
logger.info("[vidspot.py] %s - %s" % (video_url[0],video_url[1]))
return video_urls
# Encuentra vídeos del servidor en el texto pasado
def find_videos(data):
# Añade manualmente algunos erróneos para evitarlos
encontrados = set()
encontrados.add("http://vidspot.net/embed-theme.html")
encontrados.add("http://vidspot.net/embed-jquery.html")
encontrados.add("http://vidspot.net/embed-s.html")
encontrados.add("http://vidspot.net/embed-images.html")
encontrados.add("http://vidspot.net/embed-faq.html")
encontrados.add("http://vidspot.net/embed-embed.html")
encontrados.add("http://vidspot.net/embed-ri.html")
encontrados.add("http://vidspot.net/embed-d.html")
encontrados.add("http://vidspot.net/embed-css.html")
encontrados.add("http://vidspot.net/embed-js.html")
encontrados.add("http://vidspot.net/embed-player.html")
encontrados.add("http://vidspot.net/embed-cgi.html")
encontrados.add("http://vidspot.net/embed-i.html")
encontrados.add("http://vidspot.net/images")
encontrados.add("http://vidspot.net/theme")
encontrados.add("http://vidspot.net/xupload")
encontrados.add("http://vidspot.net/s")
encontrados.add("http://vidspot.net/js")
encontrados.add("http://vidspot.net/jquery")
encontrados.add("http://vidspot.net/login")
encontrados.add("http://vidspot.net/make")
encontrados.add("http://vidspot.net/i")
encontrados.add("http://vidspot.net/faq")
encontrados.add("http://vidspot.net/tos")
encontrados.add("http://vidspot.net/premium")
encontrados.add("http://vidspot.net/checkfiles")
encontrados.add("http://vidspot.net/privacy")
encontrados.add("http://vidspot.net/refund")
encontrados.add("http://vidspot.net/links")
encontrados.add("http://vidspot.net/contact")
devuelve = []
# http://vidspot.net/3sw6tewl21sn
patronvideos = 'vidspot.net/([a-z0-9]+)'
logger.info("[vidspot.py] find_videos #"+patronvideos+"#")
matches = re.compile(patronvideos,re.DOTALL).findall(data)
if len(matches)>0:
for match in matches:
titulo = "[vidspot]"
url = "http://vidspot.net/"+match
if url not in encontrados and "embed" not in match:
logger.info(" url="+url)
devuelve.append( [ titulo , url , 'vidspot' ] )
encontrados.add(url)
else:
logger.info(" url duplicada="+url)
# http://vidspot.net/embed-3sw6tewl21sn.html
patronvideos = 'vidspot.net/embed-([a-z0-9]+).html'
logger.info("[vidspot.py] find_videos #"+patronvideos+"#")
matches = re.compile(patronvideos,re.DOTALL).findall(data)
if len(matches)>0:
for match in matches:
titulo = "[vidspot]"
url = "http://vidspot.net/"+match
if url not in encontrados and "-728x400" not in match:
logger.info(" url="+url)
devuelve.append( [ titulo , url , 'vidspot' ] )
encontrados.add(url)
else:
logger.info(" url duplicada="+url)
# http://vidspot.net/embed-3sw6tewl21sn-728x400.html
patronvideos = 'vidspot.net/embed-([a-z0-9]+)-728x400.html'
logger.info("[vidspot.py] find_videos #"+patronvideos+"#")
matches = re.compile(patronvideos,re.DOTALL).findall(data)
if len(matches)>0:
for match in matches:
titulo = "[vidspot]"
url = "http://vidspot.net/"+match
if url not in encontrados:
logger.info(" url="+url)
devuelve.append( [ titulo , url , 'vidspot' ] )
encontrados.add(url)
else:
logger.info(" url duplicada="+url)
# http://www.cinetux.org/video/vidspot.php?id=3sw6tewl21sn
patronvideos = 'vidspot.php\?id\=([a-z0-9]+)'
logger.info("[vidspot.py] find_videos #"+patronvideos+"#")
matches = re.compile(patronvideos,re.DOTALL).findall(data)
if len(matches)>0:
for match in matches:
titulo = "[vidspot]"
url = "http://vidspot.net/"+match
if url not in encontrados:
logger.info(" url="+url)
devuelve.append( [ titulo , url , 'vidspot' ] )
encontrados.add(url)
else:
logger.info(" url duplicada="+url)
return devuelve
def test():
video_urls = get_video_url("http://vidspot.net/uhah7dmq2ydp")
return len(video_urls)>0 | gpl-3.0 |
blampe/M2M | reportlab-2.5/build/lib.win32-2.7/reportlab/graphics/barcode/usps4s.py | 16 | 13167 | #copyright ReportLab Inc. 2000-2006
#see license.txt for license details
__version__=''' $Id: usps4s.py 2966 2006-08-31 15:20:29Z rgbecker $ '''
__all__ = ('USPS_4State',)
from reportlab.lib.colors import black
from common import Barcode
class USPS_4State(Barcode):
''' USPS 4-State OneView (TM) barcode. All info from USPS-B-3200A
'''
_widthSize = 1
_heightSize = 1
_fontSize = 11
_humanReadable = 0
tops = dict(
F = (0.067,0.115),
T = (0.021,0.040),
A = (0.067,0.115),
D = (0.021,0.040),
)
bottoms = dict(
F = (-0.067,-0.115),
D = (-0.067,-0.115),
T = (-0.021,-0.040),
A = (-0.021,-0.040),
)
dimensions = dict(
width = (0.015, 0.025),
pitch = (0.0416,0.050),
hcz = (0.125,0.125),
vcz = (0.040,0.040),
)
def __init__(self,value='01234567094987654321',routing='',**kwd):
self._init()
self.tracking = value
self.routing = routing
self._setKeywords(**kwd)
def _init(self):
self._bvalue = None
self._codewords = None
self._characters = None
self._barcodes = None
def scale(kind,D,s):
V = D[kind]
return 72*(V[0]*(1-s)+s*V[1])
scale = staticmethod(scale)
def tracking(self,tracking):
self._init()
self._tracking = value
tracking = property(lambda self: self._tracking,tracking)
def routing(self,routing):
self._init()
self._routing = value
routing = property(lambda self: self._routing,routing)
def widthSize(self,value):
self._sized = None
self._widthSize = value
widthSize = property(lambda self: self._widthSize,widthSize)
def heightSize(self,value):
self._sized = None
self._heightSize = value
heightSize = property(lambda self: self._heightSize,heightSize)
def fontSize(self,value):
self._sized = None
self._fontSize = value
fontSize = property(lambda self: self._fontSize,fontSize)
def humanReadable(self,value):
self._sized = None
self._humanReadable = value
humanReadable = property(lambda self: self._humanReadable,humanReadable)
def binary(self):
'''convert the 4 state string values to binary
>>> print hex(USPS_4State('01234567094987654321','').binary)
0x1122103B5C2004B1L
>>> print hex(USPS_4State('01234567094987654321','01234').binary)
0xD138A87BAB5CF3804B1L
>>> print hex(USPS_4State('01234567094987654321','012345678').binary)
0x202BDC097711204D21804B1L
>>> print hex(USPS_4State('01234567094987654321','01234567891').binary)
0x16907B2A24ABC16A2E5C004B1L
'''
value = self._bvalue
if not value:
routing = self.routing
n = len(routing)
try:
if n==0:
value = 0
elif n==5:
value = int(routing)+1
elif n==9:
value = int(routing)+100001
elif n==11:
value = int(routing)+1000100001
else:
raise ValueError
except:
raise ValueError('Problem converting %s, routing code must be 0, 5, 9 or 11 digits' % routing)
tracking = self.tracking
svalue = tracking[0:2]
try:
value *= 10
value += int(svalue[0])
value *= 5
value += int(svalue[1])
except:
raise ValueError('Problem converting %s, barcode identifier must be 2 digits' % svalue)
i = 2
for name,nd in (('special services',3), ('customer identifier',6), ('sequence number',9)):
j = i
i += nd
svalue = tracking[j:i]
try:
if len(svalue)!=nd: raise ValueError
for j in xrange(nd):
value *= 10
value += int(svalue[j])
except:
raise ValueError('Problem converting %s, %s must be %d digits' % (svalue,name,nd))
self._bvalue = value
return value
binary = property(binary)
def codewords(self):
'''convert binary value into codewords
>>> print USPS_4State('01234567094987654321','01234567891').codewords)
(673, 787, 607, 1022, 861, 19, 816, 1294, 35, 602)
'''
if not self._codewords:
value = self.binary
A, J = divmod(value,636)
A, I = divmod(A,1365)
A, H = divmod(A,1365)
A, G = divmod(A,1365)
A, F = divmod(A,1365)
A, E = divmod(A,1365)
A, D = divmod(A,1365)
A, C = divmod(A,1365)
A, B = divmod(A,1365)
assert 0<=A<=658, 'improper value %s passed to _2codewords A-->%s' % (hex(long(value)),A)
self._fcs = _crc11(value)
if self._fcs&1024: A += 659
J *= 2
self._codewords = tuple(map(int,(A,B,C,D,E,F,G,H,I,J)))
return self._codewords
codewords = property(codewords)
def table1(self):
self.__class__.table1 = _initNof13Table(5,1287)
return self.__class__.table1
table1 = property(table1)
def table2(self):
self.__class__.table2 = _initNof13Table(2,78)
return self.__class__.table2
table2 = property(table2)
def characters(self):
''' convert own codewords to characters
>>> print ' '.join(hex(c)[2:] for c in USPS_4State('01234567094987654321','01234567891').characters)
dcb 85c 8e4 b06 6dd 1740 17c6 1200 123f 1b2b
'''
if not self._characters:
codewords = self.codewords
fcs = self._fcs
C = []
aC = C.append
table1 = self.table1
table2 = self.table2
for i in xrange(10):
cw = codewords[i]
if cw<=1286:
c = table1[cw]
else:
c = table2[cw-1287]
if (fcs>>i)&1:
c = ~c & 0x1fff
aC(c)
self._characters = tuple(C)
return self._characters
characters = property(characters)
def barcodes(self):
'''Get 4 state bar codes for current routing and tracking
>>> print USPS_4State('01234567094987654321','01234567891').barcodes
AADTFFDFTDADTAADAATFDTDDAAADDTDTTDAFADADDDTFFFDDTTTADFAAADFTDAADA
'''
if not self._barcodes:
C = self.characters
B = []
aB = B.append
bits2bars = self._bits2bars
for dc,db,ac,ab in self.table4:
aB(bits2bars[((C[dc]>>db)&1)+2*((C[ac]>>ab)&1)])
self._barcodes = ''.join(B)
return self._barcodes
barcodes = property(barcodes)
table4 = ((7, 2, 4, 3), (1, 10, 0, 0), (9, 12, 2, 8), (5, 5, 6, 11),
(8, 9, 3, 1), (0, 1, 5, 12), (2, 5, 1, 8), (4, 4, 9, 11),
(6, 3, 8, 10), (3, 9, 7, 6), (5, 11, 1, 4), (8, 5, 2, 12),
(9, 10, 0, 2), (7, 1, 6, 7), (3, 6, 4, 9), (0, 3, 8, 6),
(6, 4, 2, 7), (1, 1, 9, 9), (7, 10, 5, 2), (4, 0, 3, 8),
(6, 2, 0, 4), (8, 11, 1, 0), (9, 8, 3, 12), (2, 6, 7, 7),
(5, 1, 4, 10), (1, 12, 6, 9), (7, 3, 8, 0), (5, 8, 9, 7),
(4, 6, 2, 10), (3, 4, 0, 5), (8, 4, 5, 7), (7, 11, 1, 9),
(6, 0, 9, 6), (0, 6, 4, 8), (2, 1, 3, 2), (5, 9, 8, 12),
(4, 11, 6, 1), (9, 5, 7, 4), (3, 3, 1, 2), (0, 7, 2, 0),
(1, 3, 4, 1), (6, 10, 3, 5), (8, 7, 9, 4), (2, 11, 5, 6),
(0, 8, 7, 12), (4, 2, 8, 1), (5, 10, 3, 0), (9, 3, 0, 9),
(6, 5, 2, 4), (7, 8, 1, 7), (5, 0, 4, 5), (2, 3, 0, 10),
(6, 12, 9, 2), (3, 11, 1, 6), (8, 8, 7, 9), (5, 4, 0, 11),
(1, 5, 2, 2), (9, 1, 4, 12), (8, 3, 6, 6), (7, 0, 3, 7),
(4, 7, 7, 5), (0, 12, 1, 11), (2, 9, 9, 0), (6, 8, 5, 3),
(3, 10, 8, 2))
_bits2bars = 'T','D','A','F'
horizontalClearZone = property(lambda self: self.scale('hcz',self.dimensions,self.widthScale))
verticalClearZone = property(lambda self: self.scale('vcz',self.dimensions,self.heightScale))
pitch = property(lambda self: self.scale('pitch',self.dimensions,self.widthScale))
barWidth = property(lambda self: self.scale('width',self.dimensions,self.widthScale))
barHeight = property(lambda self: self.scale('F',self.tops,self.heightScale) - self.scale('F',self.bottoms,self.heightScale))
widthScale = property(lambda self: min(1,max(0,self.widthSize)))
heightScale = property(lambda self: min(1,max(0,self.heightSize)))
def width(self):
self.computeSize()
return self._width
width = property(width)
def height(self):
self.computeSize()
return self._height
height = property(height)
def computeSize(self):
if not getattr(self,'_sized',None):
ws = self.widthScale
hs = self.heightScale
barHeight = self.barHeight
barWidth = self.barWidth
pitch = self.pitch
hcz = self.horizontalClearZone
vcz = self.verticalClearZone
self._width = 2*hcz + barWidth + 64*pitch
self._height = 2*vcz+barHeight
if self.humanReadable:
self._height += self.fontSize*1.2+vcz
self._sized = True
def wrap(self,aW,aH):
self.computeSize()
return self.width, self.height
def _getBarVInfo(self,y0=0):
vInfo = {}
hs = self.heightScale
for b in ('T','D','A','F'):
y = self.scale(b,self.bottoms,hs)+y0
vInfo[b] = y,self.scale(b,self.tops,hs)+y0 - y
return vInfo
def draw(self):
self.computeSize()
hcz = self.horizontalClearZone
vcz = self.verticalClearZone
bw = self.barWidth
x = hcz
y0 = vcz+self.barHeight*0.5
dw = self.pitch
vInfo = self._getBarVInfo(y0)
for b in self.barcodes:
yb, hb = vInfo[b]
self.rect(x,yb,bw,hb)
x += dw
self.drawHumanReadable()
def value(self):
tracking = self.tracking
routing = self.routing
routing = routing and (routing,) or ()
return ' '.join((tracking[0:2],tracking[2:5],tracking[5:11],tracking[11:])+routing)
value = property(value,lambda self,value: self.__dict__.__setitem__('tracking',value))
def drawHumanReadable(self):
if self.humanReadable:
hcz = self.horizontalClearZone
vcz = self.verticalClearZone
fontName = self.fontName
fontSize = self.fontSize
y = self.barHeight+2*vcz+0.2*fontSize
self.annotate(hcz,y,self.value,fontName,fontSize)
def annotate(self,x,y,text,fontName,fontSize,anchor='middle'):
Barcode.annotate(self,x,y,text,fontName,fontSize,anchor='start')
def _crc11(value):
'''
>>> print ' '.join(hex(_crc11(USPS_4State('01234567094987654321',x).binary)) for x in ('','01234','012345678','01234567891'))
0x51 0x65 0x606 0x751
'''
bytes = hex(long(value))[2:-1]
bytes = '0'*(26-len(bytes))+bytes
gp = 0x0F35
fcs = 0x07FF
data = int(bytes[:2],16)<<5
for b in xrange(2,8):
if (fcs ^ data)&0x400:
fcs = (fcs<<1)^gp
else:
fcs = fcs<<1
fcs &= 0x7ff
data <<= 1
for x in xrange(2,2*13,2):
data = int(bytes[x:x+2],16)<<3
for b in xrange(8):
if (fcs ^ data)&0x400:
fcs = (fcs<<1)^gp
else:
fcs = fcs<<1
fcs &= 0x7ff
data <<= 1
return fcs
def _ru13(i):
'''reverse unsigned 13 bit number
>>> print _ru13(7936), _ru13(31), _ru13(47), _ru13(7808)
31 7936 7808 47
'''
r = 0
for x in xrange(13):
r <<= 1
r |= i & 1
i >>= 1
return r
def _initNof13Table(N,lenT):
'''create and return table of 13 bit values with N bits on
>>> T = _initNof13Table(5,1287)
>>> print ' '.join('T[%d]=%d' % (i, T[i]) for i in (0,1,2,3,4,1271,1272,1284,1285,1286))
T[0]=31 T[1]=7936 T[2]=47 T[3]=7808 T[4]=55 T[1271]=6275 T[1272]=6211 T[1284]=856 T[1285]=744 T[1286]=496
'''
T = lenT*[None]
l = 0
u = lenT-1
for c in xrange(8192):
bc = 0
for b in xrange(13):
bc += (c&(1<<b))!=0
if bc!=N: continue
r = _ru13(c)
if r<c: continue #we already looked at this pair
if r==c:
T[u] = c
u -= 1
else:
T[l] = c
l += 1
T[l] = r
l += 1
assert l==(u+1), 'u+1(%d)!=l(%d) for %d of 13 table' % (u+1,l,N)
return T
def _test():
import doctest
return doctest.testmod()
if __name__ == "__main__":
_test()
| mit |
EdgarSun/Django-Demo | django/contrib/gis/gdal/prototypes/srs.py | 321 | 3378 | from ctypes import c_char_p, c_int, c_void_p, POINTER
from django.contrib.gis.gdal.libgdal import lgdal, std_call
from django.contrib.gis.gdal.prototypes.generation import \
const_string_output, double_output, int_output, \
srs_output, string_output, void_output
## Shortcut generation for routines with known parameters.
def srs_double(f):
"""
Creates a function prototype for the OSR routines that take
the OSRSpatialReference object and
"""
return double_output(f, [c_void_p, POINTER(c_int)], errcheck=True)
def units_func(f):
"""
Creates a ctypes function prototype for OSR units functions, e.g.,
OSRGetAngularUnits, OSRGetLinearUnits.
"""
return double_output(f, [c_void_p, POINTER(c_char_p)], strarg=True)
# Creation & destruction.
clone_srs = srs_output(std_call('OSRClone'), [c_void_p])
new_srs = srs_output(std_call('OSRNewSpatialReference'), [c_char_p])
release_srs = void_output(lgdal.OSRRelease, [c_void_p], errcheck=False)
destroy_srs = void_output(std_call('OSRDestroySpatialReference'), [c_void_p], errcheck=False)
srs_validate = void_output(lgdal.OSRValidate, [c_void_p])
# Getting the semi_major, semi_minor, and flattening functions.
semi_major = srs_double(lgdal.OSRGetSemiMajor)
semi_minor = srs_double(lgdal.OSRGetSemiMinor)
invflattening = srs_double(lgdal.OSRGetInvFlattening)
# WKT, PROJ, EPSG, XML importation routines.
from_wkt = void_output(lgdal.OSRImportFromWkt, [c_void_p, POINTER(c_char_p)])
from_proj = void_output(lgdal.OSRImportFromProj4, [c_void_p, c_char_p])
from_epsg = void_output(std_call('OSRImportFromEPSG'), [c_void_p, c_int])
from_xml = void_output(lgdal.OSRImportFromXML, [c_void_p, c_char_p])
from_user_input = void_output(std_call('OSRSetFromUserInput'), [c_void_p, c_char_p])
# Morphing to/from ESRI WKT.
morph_to_esri = void_output(lgdal.OSRMorphToESRI, [c_void_p])
morph_from_esri = void_output(lgdal.OSRMorphFromESRI, [c_void_p])
# Identifying the EPSG
identify_epsg = void_output(lgdal.OSRAutoIdentifyEPSG, [c_void_p])
# Getting the angular_units, linear_units functions
linear_units = units_func(lgdal.OSRGetLinearUnits)
angular_units = units_func(lgdal.OSRGetAngularUnits)
# For exporting to WKT, PROJ.4, "Pretty" WKT, and XML.
to_wkt = string_output(std_call('OSRExportToWkt'), [c_void_p, POINTER(c_char_p)])
to_proj = string_output(std_call('OSRExportToProj4'), [c_void_p, POINTER(c_char_p)])
to_pretty_wkt = string_output(std_call('OSRExportToPrettyWkt'), [c_void_p, POINTER(c_char_p), c_int], offset=-2)
# Memory leak fixed in GDAL 1.5; still exists in 1.4.
to_xml = string_output(lgdal.OSRExportToXML, [c_void_p, POINTER(c_char_p), c_char_p], offset=-2)
# String attribute retrival routines.
get_attr_value = const_string_output(std_call('OSRGetAttrValue'), [c_void_p, c_char_p, c_int])
get_auth_name = const_string_output(lgdal.OSRGetAuthorityName, [c_void_p, c_char_p])
get_auth_code = const_string_output(lgdal.OSRGetAuthorityCode, [c_void_p, c_char_p])
# SRS Properties
isgeographic = int_output(lgdal.OSRIsGeographic, [c_void_p])
islocal = int_output(lgdal.OSRIsLocal, [c_void_p])
isprojected = int_output(lgdal.OSRIsProjected, [c_void_p])
# Coordinate transformation
new_ct= srs_output(std_call('OCTNewCoordinateTransformation'), [c_void_p, c_void_p])
destroy_ct = void_output(std_call('OCTDestroyCoordinateTransformation'), [c_void_p], errcheck=False)
| mit |
edmorley/django | tests/defer_regress/models.py | 85 | 2537 | """
Regression tests for defer() / only() behavior.
"""
from django.db import models
class Item(models.Model):
name = models.CharField(max_length=15)
text = models.TextField(default="xyzzy")
value = models.IntegerField()
other_value = models.IntegerField(default=0)
def __str__(self):
return self.name
class RelatedItem(models.Model):
item = models.ForeignKey(Item, models.CASCADE)
class ProxyRelated(RelatedItem):
class Meta:
proxy = True
class Child(models.Model):
name = models.CharField(max_length=10)
value = models.IntegerField()
class Leaf(models.Model):
name = models.CharField(max_length=10)
child = models.ForeignKey(Child, models.CASCADE)
second_child = models.ForeignKey(Child, models.SET_NULL, related_name="other", null=True)
value = models.IntegerField(default=42)
def __str__(self):
return self.name
class ResolveThis(models.Model):
num = models.FloatField()
name = models.CharField(max_length=16)
class Proxy(Item):
class Meta:
proxy = True
class SimpleItem(models.Model):
name = models.CharField(max_length=15)
value = models.IntegerField()
def __str__(self):
return self.name
class Feature(models.Model):
item = models.ForeignKey(SimpleItem, models.CASCADE)
class SpecialFeature(models.Model):
feature = models.ForeignKey(Feature, models.CASCADE)
class OneToOneItem(models.Model):
item = models.OneToOneField(Item, models.CASCADE, related_name="one_to_one_item")
name = models.CharField(max_length=15)
class ItemAndSimpleItem(models.Model):
item = models.ForeignKey(Item, models.CASCADE)
simple = models.ForeignKey(SimpleItem, models.CASCADE)
class Profile(models.Model):
profile1 = models.CharField(max_length=255, default='profile1')
class Location(models.Model):
location1 = models.CharField(max_length=255, default='location1')
class Request(models.Model):
profile = models.ForeignKey(Profile, models.SET_NULL, null=True, blank=True)
location = models.ForeignKey(Location, models.CASCADE)
items = models.ManyToManyField(Item)
request1 = models.CharField(default='request1', max_length=255)
request2 = models.CharField(default='request2', max_length=255)
request3 = models.CharField(default='request3', max_length=255)
request4 = models.CharField(default='request4', max_length=255)
class Base(models.Model):
text = models.TextField()
class Derived(Base):
other_text = models.TextField()
| bsd-3-clause |
welshjf/bitcoin | qa/rpc-tests/invalidateblock.py | 146 | 3110 | #!/usr/bin/env python2
# Copyright (c) 2014 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test InvalidateBlock code
#
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
class InvalidateTest(BitcoinTestFramework):
def setup_chain(self):
print("Initializing test directory "+self.options.tmpdir)
initialize_chain_clean(self.options.tmpdir, 3)
def setup_network(self):
self.nodes = []
self.is_network_split = False
self.nodes.append(start_node(0, self.options.tmpdir, ["-debug"]))
self.nodes.append(start_node(1, self.options.tmpdir, ["-debug"]))
self.nodes.append(start_node(2, self.options.tmpdir, ["-debug"]))
def run_test(self):
print "Make sure we repopulate setBlockIndexCandidates after InvalidateBlock:"
print "Mine 4 blocks on Node 0"
self.nodes[0].generate(4)
assert(self.nodes[0].getblockcount() == 4)
besthash = self.nodes[0].getbestblockhash()
print "Mine competing 6 blocks on Node 1"
self.nodes[1].generate(6)
assert(self.nodes[1].getblockcount() == 6)
print "Connect nodes to force a reorg"
connect_nodes_bi(self.nodes,0,1)
sync_blocks(self.nodes[0:2])
assert(self.nodes[0].getblockcount() == 6)
badhash = self.nodes[1].getblockhash(2)
print "Invalidate block 2 on node 0 and verify we reorg to node 0's original chain"
self.nodes[0].invalidateblock(badhash)
newheight = self.nodes[0].getblockcount()
newhash = self.nodes[0].getbestblockhash()
if (newheight != 4 or newhash != besthash):
raise AssertionError("Wrong tip for node0, hash %s, height %d"%(newhash,newheight))
print "\nMake sure we won't reorg to a lower work chain:"
connect_nodes_bi(self.nodes,1,2)
print "Sync node 2 to node 1 so both have 6 blocks"
sync_blocks(self.nodes[1:3])
assert(self.nodes[2].getblockcount() == 6)
print "Invalidate block 5 on node 1 so its tip is now at 4"
self.nodes[1].invalidateblock(self.nodes[1].getblockhash(5))
assert(self.nodes[1].getblockcount() == 4)
print "Invalidate block 3 on node 2, so its tip is now 2"
self.nodes[2].invalidateblock(self.nodes[2].getblockhash(3))
assert(self.nodes[2].getblockcount() == 2)
print "..and then mine a block"
self.nodes[2].generate(1)
print "Verify all nodes are at the right height"
time.sleep(5)
for i in xrange(3):
print i,self.nodes[i].getblockcount()
assert(self.nodes[2].getblockcount() == 3)
assert(self.nodes[0].getblockcount() == 4)
node1height = self.nodes[1].getblockcount()
if node1height < 4:
raise AssertionError("Node 1 reorged to a lower height: %d"%node1height)
if __name__ == '__main__':
InvalidateTest().main()
| mit |
LitleCo/litle-sdk-for-python | litleSdkPythonTest/functional/TestAuthReversal.py | 1 | 1804 | #Copyright (c) 2017 Vantiv eCommerce
#
#Permission is hereby granted, free of charge, to any person
#obtaining a copy of this software and associated documentation
#files (the "Software"), to deal in the Software without
#restriction, including without limitation the rights to use,
#copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the
#Software is furnished to do so, subject to the following
#conditions:
#
#The above copyright notice and this permission notice shall be
#included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
#OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
#NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
#HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
#WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
#FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
#OTHER DEALINGS IN THE SOFTWARE.
import os, sys
lib_path = os.path.abspath('../all')
sys.path.append(lib_path)
from SetupTest import *
import unittest
class TestAuthReversal(unittest.TestCase):
def testSimpleAuthReversal(self):
reversal = litleXmlFields.authReversal()
reversal.litleTxnId = 12345678000
reversal.amount = 106
reversal.payPalNotes = "Notes"
litleXml = litleOnlineRequest(config)
response = litleXml.sendRequest(reversal)
self.assertEquals("Approved",response.message)
def suite():
suite = unittest.TestSuite()
suite = unittest.TestLoader().loadTestsFromTestCase(TestAuthReversal)
return suite
if __name__ =='__main__':
unittest.main() | mit |
bykoianko/omim | tools/unix/diff_size.py | 25 | 1026 | #!/usr/bin/python
import os, sys
if len(sys.argv) < 3:
print('This tool shows very different file sizes')
print('Usage: {0} <newdir> <olddir> [threshold_in_%]'.format(sys.argv[0]))
sys.exit(0)
new_path = sys.argv[1]
old_path = sys.argv[2]
threshold = (int(sys.argv[3]) if len(sys.argv) > 3 else 10) / 100.0 + 1
min_diff = 1024 * 1024
for f in sorted(os.listdir(old_path)):
new_file = os.path.join(new_path, f)
old_file = os.path.join(old_path, f)
if '.mwm' not in new_file:
continue
if os.path.isfile(new_file) and os.path.isfile(old_file):
new_size = os.path.getsize(new_file)
old_size = os.path.getsize(old_file)
if new_size + old_size > 0:
if new_size == 0 or old_size == 0 or max(new_size, old_size) / float(min(new_size, old_size)) > threshold and abs(new_size - old_size) > min_diff:
print('{0}: {1} {2} to {3} MB'.format(f, old_size / 1024 / 1024, 'up' if new_size > old_size else 'down', new_size / 1024 / 1024))
else:
print('Not found a mirror for {0}'.format(f))
| apache-2.0 |
garrettcap/Bulletproof-Backup | wx/tools/helpviewer.py | 3 | 2453 | #----------------------------------------------------------------------
# Name: wx.tools.helpviewer
# Purpose: HTML Help viewer
#
# Author: Robin Dunn
#
# Created: 11-Dec-2002
# RCS-ID: $Id$
# Copyright: (c) 2002 by Total Control Software
# Licence: wxWindows license
#----------------------------------------------------------------------
"""
helpviewer.py -- Displays HTML Help in a wxHtmlHelpController window.
Usage:
helpviewer [--cache=path] helpfile [helpfile(s)...]
Where helpfile is the path to either a .hhp file or a .zip file
which contians a .hhp file. The .hhp files are the same as those
used by Microsoft's HTML Help Workshop for creating CHM files.
"""
import sys, os
#---------------------------------------------------------------------------
def makeOtherFrame(helpctrl):
import wx
parent = helpctrl.GetFrame()
otherFrame = wx.Frame(parent)
def main(args=sys.argv):
if len(args) < 2:
print __doc__
return
args = args[1:]
cachedir = None
if args[0][:7] == '--cache':
cachedir = os.path.expanduser(args[0].split('=')[1])
args = args[1:]
if len(args) == 0:
print __doc__
return
import wx
import wx.html
app = wx.App()
#wx.Log.SetActiveTarget(wx.LogStderr())
wx.Log.SetLogLevel(wx.LOG_Error)
# Set up the default config so the htmlhelp frame can save its preferences
app.SetVendorName('wxWindows')
app.SetAppName('helpviewer')
cfg = wx.ConfigBase.Get()
# Add the Zip filesystem
wx.FileSystem.AddHandler(wx.ZipFSHandler())
# Create the viewer
helpctrl = wx.html.HtmlHelpController()
if cachedir:
helpctrl.SetTempDir(cachedir)
# and add the books
for helpfile in args:
print "Adding %s..." % helpfile
helpctrl.AddBook(helpfile, 1)
# The frame used by the HtmlHelpController is set to not prevent
# app exit, so in the case of a standalone helpviewer like this
# when the about box or search box is closed the help frame will
# be the only one left and the app will close unexpectedly. To
# work around this we'll create another frame that is never shown,
# but which will be closed when the helpviewer frame is closed.
wx.CallAfter(makeOtherFrame, helpctrl)
# start it up!
helpctrl.DisplayContents()
app.MainLoop()
if __name__ == '__main__':
main()
| gpl-2.0 |
pythononwheels/pow_devel | pythononwheels/start/stuff/comment.py | 2 | 1289 | #
# Model Comment
#
from sqlalchemy import Column, Integer, String, Boolean, Sequence
from sqlalchemy import BigInteger, Date, DateTime, Float, Numeric
from pow_comments.powlib import relation
from pow_comments.sqldblib import Base
#@relation.has_many("<plural_other_models>")
@relation.is_tree()
@relation.setup_schema()
class Comment(Base):
#
# put your column definition here:
#
#
# sqlalchemy classic style
# which offer you all sqlalchemy options
#
#title = Column(String(50))
#text = Column(String)
#
# or the new (cerberus) schema style
# which offer you immediate validation
#
schema = {
# string sqltypes can be TEXT or UNICODE or nothing
'author': {
'type': 'string', 'maxlength' : 35,
# the sql "sub"key lets you declare "raw" sql(alchemy) Column options
# the options below are implemented so far.
"sql" : {
"primary_key" : False,
"default" : "No Author Name",
"unique" : True,
"nullable" : False
}
},
'text': {'type': 'string'}
}
# init
def __init__(self, **kwargs):
self.init_on_load(**kwargs)
# your methods down here
| mit |
ulaskaraoren/namebench | tools/convert_servers_to_csv.py | 174 | 3169 | #!/usr/bin/env python
# Copyright 2009 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.
"""Tool to convert listing to CSV format."""
__author__ = 'tstromberg@google.com (Thomas Stromberg)'
import csv
import re
import sys
import check_nameserver_popularity
import GeoIP
sys.path.append('..')
#sys.path.append('/Users/tstromberg/namebench')
import third_party
from libnamebench import addr_util
from libnamebench import nameserver_list
from libnamebench import config
output = csv.writer(open('output.csv', 'w'))
#output.writerow(['IP', 'Name', 'Hostname', 'Country/Region/City', 'Coords', 'ASN', 'Label', 'Status', 'Refs'])
gi = GeoIP.open('/usr/local/share/GeoLiteCity.dat', GeoIP.GEOIP_MEMORY_CACHE)
asn_lookup = GeoIP.open('/usr/local/share/GeoIPASNum.dat', GeoIP.GEOIP_MEMORY_CACHE)
ns_hash = config.GetLocalNameServerList()
for ip in ns_hash:
try:
details = gi.record_by_addr(ip)
except SystemError:
pass
if not details:
details = {}
city = details.get('city', '')
if city:
city = city.decode('latin-1')
country = details.get('country_name', '')
if country:
country = country.decode('latin-1')
latitude = details.get('latitude', '')
longitude = details.get('longitude', '')
country_code = details.get('country_code', '')
region = details.get('region_name', '')
if region:
region = region.decode('latin-1')
hostname = ns_hash[ip].get('hostname', '')
geo = '/'.join([x for x in [country_code, region, city] if x and not x.isdigit()]).encode('utf-8')
coords = ','.join(map(str, [latitude,longitude]))
status = ns_hash[ip].get('notes', '')
refs = None
asn = asn_lookup.org_by_addr(ip)
labels = ' '.join(list(ns_hash[ip]['labels']))
urls = check_nameserver_popularity.GetUrls(ip)
use_keywords = set()
if ns_hash[ip]['name'] and 'UNKNOWN' not in ns_hash[ip]['name']:
for word in ns_hash[ip]['name'].split(' ')[0].split('/'):
use_keywords.add(word.lower())
use_keywords.add(re.sub('[\W_]', '', word.lower()))
if '-' in word:
use_keywords.add(word.lower().replace('-', ''))
if hostname and hostname != ip:
use_keywords.add(addr_util.GetDomainPartOfHostname(ip))
for bad_word in ('ns', 'dns'):
if bad_word in use_keywords:
use_keywords.remove(bad_word)
print use_keywords
context_urls = []
for url in urls:
for keyword in use_keywords:
if re.search(keyword, url, re.I):
context_urls.append(url)
break
if context_urls:
urls = context_urls
row = [ip, labels, ns_hash[ip]['name'], hostname, geo, coords, asn, status[0:30], ' '.join(urls[:2])]
print row
output.writerow(row)
| apache-2.0 |
YingHsuan/termite_data_server | web2py/applications-original/admin/languages/zh.py | 19 | 14083 | # coding: utf8
{
'!langcode!': 'zh-cn',
'!langname!': '中文',
'"browse"': '游览',
'"save"': '"保存"',
'"submit"': '"提交"',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新"是可配置项 如 "field1=\'newvalue\'",你无法在JOIN 中更新或删除',
'%Y-%m-%d': '%Y-%m-%d',
'%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S',
'%s %%{row} deleted': '%s 行已删',
'%s %%{row} updated': '%s 行更新',
'(requires internet access)': '(requires internet access)',
'(something like "it-it")': '(就酱 "it-it")',
'@markmin\x01Searching: **%s** %%{file}': 'Searching: **%s** files',
'A new version of web2py is available': '新版本web2py已经可用',
'A new version of web2py is available: %s': '新版本web2py已经可用: %s',
'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': '',
'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': '',
'ATTENTION: you cannot edit the running application!': '注意: 不能修改正在运行中的应用!',
'About': '关于',
'About application': '关于这个应用',
'Admin is disabled because insecure channel': '管理因不安全通道而关闭',
'Admin is disabled because unsecure channel': '管理因不稳定通道而关闭',
'Admin language': 'Admin language',
'Administrator Password:': '管理员密码:',
'Application name:': 'Application name:',
'Are you sure you want to delete file "%s"?': '你真想删除文件"%s"?',
'Are you sure you want to delete plugin "%s"?': 'Are you sure you want to delete plugin "%s"?',
'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?',
'Are you sure you want to uninstall application "%s"': '你真确定要卸载应用 "%s"',
'Are you sure you want to uninstall application "%s"?': '你真确定要卸载应用 "%s" ?',
'Are you sure you want to upgrade web2py now?': 'Are you sure you want to upgrade web2py now?',
'Available databases and tables': '可用数据库/表',
'Cannot be empty': '不能不填',
'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': '无法编译: 应用中有错误,请修订后再试.',
'Cannot compile: there are errors in your app:': 'Cannot compile: there are errors in your app:',
'Change Password': '修改密码',
'Change admin password': 'change admin password',
'Check for upgrades': 'check for upgrades',
'Check to delete': '检验删除',
'Checking for upgrades...': '是否有升级版本检查ing...',
'Clean': '清除',
'Client IP': '客户端IP',
'Compile': '编译',
'Controllers': '控制器s',
'Create': 'create',
'Create new simple application': '创建一个新应用',
'Current request': '当前请求',
'Current response': '当前返回',
'Current session': '当前会话',
'DESIGN': '设计',
'Date and Time': '时间日期',
'Debug': 'Debug',
'Delete': '删除',
'Delete:': '删除:',
'Deploy': 'deploy',
'Deploy on Google App Engine': '部署到GAE',
'Deploy to OpenShift': 'Deploy to OpenShift',
'Description': '描述',
'Design for': '设计:',
'Disable': 'Disable',
'E-mail': '邮箱:',
'EDIT': '编辑',
'Edit': '修改',
'Edit Profile': '修订配置',
'Edit application': '修订应用',
'Edit current record': '修订当前记录',
'Editing Language file': '修订语言文件',
'Editing file': '修订文件',
'Editing file "%s"': '修订文件 %s',
'Enterprise Web Framework': '强悍的网络开发框架',
'Error logs for "%(app)s"': '"%(app)s" 的错误日志',
'Errors': '错误',
'Exception instance attributes': 'Exception instance attributes',
'First name': '姓',
'Functions with no doctests will result in [passed] tests.': '',
'Get from URL:': 'Get from URL:',
'Group ID': '组ID',
'Hello World': '道可道,非常道;名可名,非常名',
'Help': '帮助',
'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.',
'Import/Export': '导入/导出',
'Install': 'install',
'Installed applications': '已安装的应用',
'Internal State': '内部状态',
'Invalid Query': '无效查询',
'Invalid action': '无效动作',
'Invalid email': '无效的email',
'Language files (static strings) updated': '语言文件(静态部分)已更新',
'Languages': '语言',
'Last name': '名',
'Last saved on:': '最后保存于:',
'License for': '许可证',
'Login': '登录',
'Login to the Administrative Interface': '登录到管理员界面',
'Logout': '注销',
'Lost Password': '忘记密码',
'Models': '模型s',
'Modules': '模块s',
'NO': '不',
'Name': '姓名',
'New Record': '新记录',
'New application wizard': 'New application wizard',
'New simple application': 'New simple application',
'No databases in this application': '这应用没有数据库',
'Origin': '起源',
'Original/Translation': '原始文件/翻译文件',
'Overwrite installed app': 'overwrite installed app',
'PAM authenticated user, cannot change password here': 'PAM authenticated user, cannot change password here',
'Pack all': '全部打包',
'Pack compiled': '包编译完',
'Password': '密码',
'Peeking at file': '选个文件',
'Plugin "%s" in application': 'Plugin "%s" in application',
'Plugins': 'Plugins',
'Powered by': '',
'Query:': '查询',
'Record ID': '记录ID',
'Register': '注册',
'Registration key': '注册密匙',
'Reload routes': 'Reload routes',
'Remove compiled': '已移除',
'Resolve Conflict file': '解决冲突文件',
'Role': '角色',
'Rows in table': '表行',
'Rows selected': '行选择',
'Running on %s': 'Running on %s',
'Saved file hash:': '已存文件Hash:',
'Site': '总站',
'Start wizard': 'start wizard',
'Static files': '静态文件',
'Sure you want to delete this object?': '真的要删除这个对象?',
'TM': '',
'Table name': '表名',
'Testing application': '应用测试',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '',
'There are no controllers': '冇控制器',
'There are no models': '冇模型s',
'There are no modules': '冇模块s',
'There are no static files': '冇静态文件',
'There are no translators, only default language is supported': '没有找到相应翻译,只能使用默认语言',
'There are no views': '冇视图',
'This is the %(filename)s template': '这是 %(filename)s 模板',
'Ticket': '传票',
'Timestamp': '时间戳',
'To create a plugin, name a file/folder plugin_[name]': 'To create a plugin, name a file/folder plugin_[name]',
'Unable to check for upgrades': '无法检查是否需要升级',
'Unable to download': '无法下载',
'Unable to download app': '无法下载应用',
'Unable to download app because:': 'Unable to download app because:',
'Unable to download because': 'Unable to download because',
'Uninstall': '卸载',
'Update:': '更新:',
'Upload & install packed application': 'Upload & install packed application',
'Upload a package:': 'Upload a package:',
'Upload and install packed application': 'Upload and install packed application',
'Upload existing application': '上传已有应用',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': '',
'Use an url:': 'Use an url:',
'User ID': '用户ID',
'Version': '版本',
'Views': '视图',
'Welcome to web2py': '欢迎使用web2py',
'YES': '是',
'additional code for your application': '给你的应用附加代码',
'admin disabled because no admin password': '管理员需要设定密码,否则无法管理',
'admin disabled because not supported on google app engine': '未支持GAE,无法管理',
'admin disabled because unable to access password file': '需要可以操作密码文件,否则无法进行管理',
'administrative interface': 'administrative interface',
'and rename it (required):': '重命名为 (必须):',
'and rename it:': ' 重命名为:',
'appadmin': '应用管理',
'appadmin is disabled because insecure channel': '应用管理因非法通道失效',
'application "%s" uninstalled': '应用"%s" 已被卸载',
'application compiled': '应用已编译完',
'application is compiled and cannot be designed': '应用已编译完无法设计',
'arguments': 'arguments',
'back': 'back',
'cache': 'cache',
'cache, errors and sessions cleaned': '缓存、错误、sesiones已被清空',
'cannot create file': '无法创建文件',
'cannot upload file "%(filename)s"': '无法上传文件 "%(filename)s"',
'check all': '检查所有',
'click here for online examples': '猛击此处,查看在线实例',
'click here for the administrative interface': '猛击此处,进入管理界面',
'click to check for upgrades': '猛击查看是否有升级版本',
'code': 'code',
'compiled application removed': '已编译应用已移走',
'controllers': '控制器',
'create file with filename:': '创建文件用这名:',
'create new application:': '创建新应用:',
'created by': '创建自',
'crontab': '定期事务',
'currently running': 'currently running',
'currently saved or': '保存当前的或',
'customize me!': '定制俺!',
'data uploaded': '数据已上传',
'database': '数据库',
'database %s select': '数据库 %s 选择',
'database administration': '数据库管理',
'db': '',
'defines tables': '已定义表',
'delete': '删除',
'delete all checked': '删除所有选择的',
'delete plugin': 'delete plugin',
'design': '设计',
'direction: ltr': 'direction: ltr',
'done!': '搞定!',
'edit controller': '修订控制器',
'edit views:': 'edit views:',
'export as csv file': '导出为CSV文件',
'exposes': '暴露',
'extends': '扩展',
'failed to reload module': '重新加载模块失败',
'failed to reload module because:': 'failed to reload module because:',
'file "%(filename)s" created': '文件 "%(filename)s" 已创建',
'file "%(filename)s" deleted': '文件 "%(filename)s" 已删除',
'file "%(filename)s" uploaded': '文件 "%(filename)s" 已上传',
'file "%(filename)s" was not deleted': '文件 "%(filename)s" 没删除',
'file "%s" of %s restored': '文件"%s" 有关 %s 已重存',
'file changed on disk': '硬盘上的文件已经修改',
'file does not exist': '文件并不存在',
'file saved on %(time)s': '文件保存于 %(time)s',
'file saved on %s': '文件保存在 %s',
'htmledit': 'html编辑',
'includes': '包含',
'insert new': '新插入',
'insert new %s': '新插入 %s',
'internal error': '内部错误',
'invalid password': '无效密码',
'invalid request': '无效请求',
'invalid ticket': '无效传票',
'language file "%(filename)s" created/updated': '语言文件 "%(filename)s"被创建/更新',
'languages': '语言',
'languages updated': '语言已被刷新',
'loading...': '载入中...',
'login': '登录',
'merge': '合并',
'models': '模型s',
'modules': '模块s',
'new application "%s" created': '新应用 "%s"已被创建',
'new plugin installed': 'new plugin installed',
'new record inserted': '新记录被插入',
'next 100 rows': '后100行',
'no match': 'no match',
'or import from csv file': '或者,从csv文件导入',
'or provide app url:': 'or provide app url:',
'or provide application url:': '或者,提供应用所在地址链接:',
'pack plugin': 'pack plugin',
'password changed': 'password changed',
'plugin "%(plugin)s" deleted': 'plugin "%(plugin)s" deleted',
'previous 100 rows': '前100行',
'record': 'record',
'record does not exist': '记录并不存在',
'record id': '记录ID',
'restore': '重存',
'revert': '恢复',
'save': '保存',
'selected': '已选',
'session expired': '会话过期',
'shell': '',
'some files could not be removed': '有些文件无法被移除',
'state': '状态',
'static': '静态文件',
'submit': '提交',
'table': '表',
'test': '测试',
'the application logic, each URL path is mapped in one exposed function in the controller': '应用逻辑:每个URL由控制器暴露的函式完成映射',
'the data representation, define database tables and sets': '数据表达式,定义数据库/表',
'the presentations layer, views are also known as templates': '提交层/视图都在模板中可知',
'these files are served without processing, your images go here': '',
'to previous version.': 'to previous version.',
'to previous version.': '退回前一版本',
'translation strings for the application': '应用的翻译字串',
'try': '尝试',
'try something like': '尝试',
'unable to create application "%s"': '无法创建应用 "%s"',
'unable to delete file "%(filename)s"': '无法删除文件 "%(filename)s"',
'unable to delete file plugin "%(plugin)s"': 'unable to delete file plugin "%(plugin)s"',
'unable to parse csv file': '无法生成 cvs',
'unable to uninstall "%s"': '无法卸载 "%s"',
'unable to upgrade because "%s"': 'unable to upgrade because "%s"',
'uncheck all': '反选全部',
'update': '更新',
'update all languages': '更新所有语言',
'upgrade web2py now': 'upgrade web2py now',
'upload application:': '提交已有的应用:',
'upload file:': '提交文件:',
'upload plugin file:': 'upload plugin file:',
'variables': 'variables',
'versioning': '版本',
'view': '视图',
'views': '视图s',
'web2py Recent Tweets': 'twitter上的web2py进展实播',
'web2py is up to date': 'web2py现在已经是最新的版本了',
'web2py upgraded; please restart it': 'web2py upgraded; please restart it',
}
| bsd-3-clause |
voidfiles/ansible-1 | contrib/inventory/ovirt.py | 112 | 9522 | #!/usr/bin/env python
# Copyright 2015 IIX 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/>.
"""
ovirt external inventory script
=================================
Generates inventory that Ansible can understand by making API requests to
oVirt via the ovirt-engine-sdk-python library.
When run against a specific host, this script returns the following variables
based on the data obtained from the ovirt_sdk Node object:
- ovirt_uuid
- ovirt_id
- ovirt_image
- ovirt_machine_type
- ovirt_ips
- ovirt_name
- ovirt_description
- ovirt_status
- ovirt_zone
- ovirt_tags
- ovirt_stats
When run in --list mode, instances are grouped by the following categories:
- zone:
zone group name.
- instance tags:
An entry is created for each tag. For example, if you have two instances
with a common tag called 'foo', they will both be grouped together under
the 'tag_foo' name.
- network name:
the name of the network is appended to 'network_' (e.g. the 'default'
network will result in a group named 'network_default')
- running status:
group name prefixed with 'status_' (e.g. status_up, status_down,..)
Examples:
Execute uname on all instances in the us-central1-a zone
$ ansible -i ovirt.py us-central1-a -m shell -a "/bin/uname -a"
Use the ovirt inventory script to print out instance specific information
$ contrib/inventory/ovirt.py --host my_instance
Author: Josha Inglis <jinglis@iix.net> based on the gce.py by Eric Johnson <erjohnso@google.com>
Version: 0.0.1
"""
USER_AGENT_PRODUCT = "Ansible-ovirt_inventory_plugin"
USER_AGENT_VERSION = "v1"
import sys
import os
import argparse
import ConfigParser
from collections import defaultdict
try:
import json
except ImportError:
# noinspection PyUnresolvedReferences,PyPackageRequirements
import simplejson as json
try:
# noinspection PyUnresolvedReferences
from ovirtsdk.api import API
# noinspection PyUnresolvedReferences
from ovirtsdk.xml import params
except ImportError:
print("ovirt inventory script requires ovirt-engine-sdk-python")
sys.exit(1)
class OVirtInventory(object):
def __init__(self):
# Read settings and parse CLI arguments
self.args = self.parse_cli_args()
self.driver = self.get_ovirt_driver()
# Just display data for specific host
if self.args.host:
print(self.json_format_dict(
self.node_to_dict(self.get_instance(self.args.host)),
pretty=self.args.pretty
))
sys.exit(0)
# Otherwise, assume user wants all instances grouped
print(
self.json_format_dict(
data=self.group_instances(),
pretty=self.args.pretty
)
)
sys.exit(0)
@staticmethod
def get_ovirt_driver():
"""
Determine the ovirt authorization settings and return a ovirt_sdk driver.
:rtype : ovirtsdk.api.API
"""
kwargs = {}
ovirt_ini_default_path = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "ovirt.ini")
ovirt_ini_path = os.environ.get('OVIRT_INI_PATH', ovirt_ini_default_path)
# Create a ConfigParser.
# This provides empty defaults to each key, so that environment
# variable configuration (as opposed to INI configuration) is able
# to work.
config = ConfigParser.SafeConfigParser(defaults={
'ovirt_url': '',
'ovirt_username': '',
'ovirt_password': '',
'ovirt_api_secrets': '',
})
if 'ovirt' not in config.sections():
config.add_section('ovirt')
config.read(ovirt_ini_path)
# Attempt to get ovirt params from a configuration file, if one
# exists.
secrets_path = config.get('ovirt', 'ovirt_api_secrets')
secrets_found = False
try:
# noinspection PyUnresolvedReferences,PyPackageRequirements
import secrets
kwargs = getattr(secrets, 'OVIRT_KEYWORD_PARAMS', {})
secrets_found = True
except ImportError:
pass
if not secrets_found and secrets_path:
if not secrets_path.endswith('secrets.py'):
err = "Must specify ovirt_sdk secrets file as /absolute/path/to/secrets.py"
print(err)
sys.exit(1)
sys.path.append(os.path.dirname(secrets_path))
try:
# noinspection PyUnresolvedReferences,PyPackageRequirements
import secrets
kwargs = getattr(secrets, 'OVIRT_KEYWORD_PARAMS', {})
except ImportError:
pass
if not secrets_found:
kwargs = {
'url': config.get('ovirt', 'ovirt_url'),
'username': config.get('ovirt', 'ovirt_username'),
'password': config.get('ovirt', 'ovirt_password'),
}
# If the appropriate environment variables are set, they override
# other configuration; process those into our args and kwargs.
kwargs['url'] = os.environ.get('OVIRT_URL')
kwargs['username'] = os.environ.get('OVIRT_EMAIL')
kwargs['password'] = os.environ.get('OVIRT_PASS')
# Retrieve and return the ovirt driver.
return API(insecure=True, **kwargs)
@staticmethod
def parse_cli_args():
"""
Command line argument processing
:rtype : argparse.Namespace
"""
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on ovirt')
parser.add_argument('--list', action='store_true', default=True, help='List instances (default: True)')
parser.add_argument('--host', action='store', help='Get all information about an instance')
parser.add_argument('--pretty', action='store_true', default=False, help='Pretty format (default: False)')
return parser.parse_args()
def node_to_dict(self, inst):
"""
:type inst: params.VM
"""
if inst is None:
return {}
inst.get_custom_properties()
ips = [ip.get_address() for ip in inst.get_guest_info().get_ips().get_ip()] \
if inst.get_guest_info() is not None else []
stats = {}
for stat in inst.get_statistics().list():
stats[stat.get_name()] = stat.get_values().get_value()[0].get_datum()
return {
'ovirt_uuid': inst.get_id(),
'ovirt_id': inst.get_id(),
'ovirt_image': inst.get_os().get_type(),
'ovirt_machine_type': inst.get_instance_type(),
'ovirt_ips': ips,
'ovirt_name': inst.get_name(),
'ovirt_description': inst.get_description(),
'ovirt_status': inst.get_status().get_state(),
'ovirt_zone': inst.get_cluster().get_id(),
'ovirt_tags': self.get_tags(inst),
'ovirt_stats': stats,
# Hosts don't have a public name, so we add an IP
'ansible_ssh_host': ips[0] if len(ips) > 0 else None
}
@staticmethod
def get_tags(inst):
"""
:type inst: params.VM
"""
return [x.get_name() for x in inst.get_tags().list()]
# noinspection PyBroadException,PyUnusedLocal
def get_instance(self, instance_name):
"""Gets details about a specific instance """
try:
return self.driver.vms.get(name=instance_name)
except Exception as e:
return None
def group_instances(self):
"""Group all instances"""
groups = defaultdict(list)
meta = {"hostvars": {}}
for node in self.driver.vms.list():
assert isinstance(node, params.VM)
name = node.get_name()
meta["hostvars"][name] = self.node_to_dict(node)
zone = node.get_cluster().get_name()
groups[zone].append(name)
tags = self.get_tags(node)
for t in tags:
tag = 'tag_%s' % t
groups[tag].append(name)
nets = [x.get_name() for x in node.get_nics().list()]
for net in nets:
net = 'network_%s' % net
groups[net].append(name)
status = node.get_status().get_state()
stat = 'status_%s' % status.lower()
if stat in groups:
groups[stat].append(name)
else:
groups[stat] = [name]
groups["_meta"] = meta
return groups
@staticmethod
def json_format_dict(data, pretty=False):
""" Converts a dict to a JSON object and dumps it as a formatted
string """
if pretty:
return json.dumps(data, sort_keys=True, indent=2)
else:
return json.dumps(data)
# Run the script
OVirtInventory()
| gpl-3.0 |
georgemarshall/django | tests/forms_tests/widget_tests/test_textinput.py | 84 | 3150 | from django.forms import TextInput
from django.utils.safestring import mark_safe
from .base import WidgetTest
class TextInputTest(WidgetTest):
widget = TextInput()
def test_render(self):
self.check_html(self.widget, 'email', '', html='<input type="text" name="email">')
def test_render_none(self):
self.check_html(self.widget, 'email', None, html='<input type="text" name="email">')
def test_render_value(self):
self.check_html(self.widget, 'email', 'test@example.com', html=(
'<input type="text" name="email" value="test@example.com">'
))
def test_render_boolean(self):
"""
Boolean values are rendered to their string forms ("True" and
"False").
"""
self.check_html(self.widget, 'get_spam', False, html=(
'<input type="text" name="get_spam" value="False">'
))
self.check_html(self.widget, 'get_spam', True, html=(
'<input type="text" name="get_spam" value="True">'
))
def test_render_quoted(self):
self.check_html(
self.widget, 'email', 'some "quoted" & ampersanded value',
html='<input type="text" name="email" value="some "quoted" & ampersanded value">',
)
def test_render_custom_attrs(self):
self.check_html(
self.widget, 'email', 'test@example.com', attrs={'class': 'fun'},
html='<input type="text" name="email" value="test@example.com" class="fun">',
)
def test_render_unicode(self):
self.check_html(
self.widget, 'email', 'ŠĐĆŽćžšđ', attrs={'class': 'fun'},
html=(
'<input type="text" name="email" '
'value="\u0160\u0110\u0106\u017d\u0107\u017e\u0161\u0111" class="fun">'
),
)
def test_constructor_attrs(self):
widget = TextInput(attrs={'class': 'fun', 'type': 'email'})
self.check_html(widget, 'email', '', html='<input type="email" class="fun" name="email">')
self.check_html(
widget, 'email', 'foo@example.com',
html='<input type="email" class="fun" value="foo@example.com" name="email">',
)
def test_attrs_precedence(self):
"""
`attrs` passed to render() get precedence over those passed to the
constructor
"""
widget = TextInput(attrs={'class': 'pretty'})
self.check_html(
widget, 'email', '', attrs={'class': 'special'},
html='<input type="text" class="special" name="email">',
)
def test_attrs_safestring(self):
widget = TextInput(attrs={'onBlur': mark_safe("function('foo')")})
self.check_html(widget, 'email', '', html='<input onBlur="function(\'foo\')" type="text" name="email">')
def test_use_required_attribute(self):
# Text inputs can safely trigger the browser validation.
self.assertIs(self.widget.use_required_attribute(None), True)
self.assertIs(self.widget.use_required_attribute(''), True)
self.assertIs(self.widget.use_required_attribute('resume.txt'), True)
| bsd-3-clause |
aioue/ansible | lib/ansible/modules/system/filesystem.py | 48 | 9301 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Alexander Bulimov <lazywolf0@gmail.com>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
author: "Alexander Bulimov (@abulimov)"
module: filesystem
short_description: Makes file system on block device
description:
- This module creates file system.
version_added: "1.2"
options:
fstype:
description:
- File System type to be created.
- reiserfs support was added in 2.2.
required: true
dev:
description:
- Target block device.
required: true
force:
choices: [ "yes", "no" ]
default: "no"
description:
- If yes, allows to create new filesystem on devices that already has filesystem.
required: false
resizefs:
choices: [ "yes", "no" ]
default: "no"
description:
- If yes, if the block device and filessytem size differ, grow the filesystem into the space. Note, XFS Will only grow if mounted.
required: false
version_added: "2.0"
opts:
description:
- List of options to be passed to mkfs command.
notes:
- uses mkfs command
'''
EXAMPLES = '''
# Create a ext2 filesystem on /dev/sdb1.
- filesystem:
fstype: ext2
dev: /dev/sdb1
# Create a ext4 filesystem on /dev/sdb1 and check disk blocks.
- filesystem:
fstype: ext4
dev: /dev/sdb1
opts: -cc
'''
def _get_dev_size(dev, module):
""" Return size in bytes of device. Returns int """
blockdev_cmd = module.get_bin_path("blockdev", required=True)
rc, devsize_in_bytes, err = module.run_command("%s %s %s" % (blockdev_cmd, "--getsize64", dev))
return int(devsize_in_bytes)
def _get_fs_size(fssize_cmd, dev, module):
""" Return size in bytes of filesystem on device. Returns int """
cmd = module.get_bin_path(fssize_cmd, required=True)
if 'tune2fs' == fssize_cmd:
# Get Block count and Block size
rc, size, err = module.run_command("%s %s %s" % (cmd, '-l', dev))
if rc == 0:
for line in size.splitlines():
if 'Block count:' in line:
block_count = int(line.split(':')[1].strip())
elif 'Block size:' in line:
block_size = int(line.split(':')[1].strip())
break
else:
module.fail_json(msg="Failed to get block count and block size of %s with %s" % (dev, cmd), rc=rc, err=err )
elif 'xfs_info' == fssize_cmd:
# Get Block count and Block size
rc, size, err = module.run_command("%s %s" % (cmd, dev))
if rc == 0:
for line in size.splitlines():
col = line.split('=')
if col[0].strip() == 'data':
if col[1].strip() != 'bsize':
module.fail_json(msg='Unexpected output format from xfs_info (could not locate "bsize")')
if col[2].split()[1] != 'blocks':
module.fail_json(msg='Unexpected output format from xfs_info (could not locate "blocks")')
block_size = int(col[2].split()[0])
block_count = int(col[3].split(',')[0])
break
else:
module.fail_json(msg="Failed to get block count and block size of %s with %s" % (dev, cmd), rc=rc, err=err )
elif 'btrfs' == fssize_cmd:
#ToDo
# There is no way to get the blocksize and blockcount for btrfs filesystems
block_size = 1
block_count = 1
return block_size*block_count
def main():
module = AnsibleModule(
argument_spec = dict(
fstype=dict(required=True, aliases=['type']),
dev=dict(required=True, aliases=['device']),
opts=dict(),
force=dict(type='bool', default='no'),
resizefs=dict(type='bool', default='no'),
),
supports_check_mode=True,
)
# There is no "single command" to manipulate filesystems, so we map them all out and their options
fs_cmd_map = {
'ext2' : {
'mkfs' : 'mkfs.ext2',
'grow' : 'resize2fs',
'grow_flag' : None,
'force_flag' : '-F',
'fsinfo': 'tune2fs',
},
'ext3' : {
'mkfs' : 'mkfs.ext3',
'grow' : 'resize2fs',
'grow_flag' : None,
'force_flag' : '-F',
'fsinfo': 'tune2fs',
},
'ext4' : {
'mkfs' : 'mkfs.ext4',
'grow' : 'resize2fs',
'grow_flag' : None,
'force_flag' : '-F',
'fsinfo': 'tune2fs',
},
'reiserfs' : {
'mkfs' : 'mkfs.reiserfs',
'grow' : 'resize_reiserfs',
'grow_flag' : None,
'force_flag' : '-f',
'fsinfo': 'reiserfstune',
},
'ext4dev' : {
'mkfs' : 'mkfs.ext4',
'grow' : 'resize2fs',
'grow_flag' : None,
'force_flag' : '-F',
'fsinfo': 'tune2fs',
},
'xfs' : {
'mkfs' : 'mkfs.xfs',
'grow' : 'xfs_growfs',
'grow_flag' : None,
'force_flag' : '-f',
'fsinfo': 'xfs_info',
},
'btrfs' : {
'mkfs' : 'mkfs.btrfs',
'grow' : 'btrfs',
'grow_flag' : 'filesystem resize',
'force_flag' : '-f',
'fsinfo': 'btrfs',
}
}
dev = module.params['dev']
fstype = module.params['fstype']
opts = module.params['opts']
force = module.boolean(module.params['force'])
resizefs = module.boolean(module.params['resizefs'])
changed = False
try:
_ = fs_cmd_map[fstype]
except KeyError:
module.exit_json(changed=False, msg="WARNING: module does not support this filesystem yet. %s" % fstype)
mkfscmd = fs_cmd_map[fstype]['mkfs']
force_flag = fs_cmd_map[fstype]['force_flag']
growcmd = fs_cmd_map[fstype]['grow']
fssize_cmd = fs_cmd_map[fstype]['fsinfo']
if not os.path.exists(dev):
module.fail_json(msg="Device %s not found."%dev)
cmd = module.get_bin_path('blkid', required=True)
rc,raw_fs,err = module.run_command("%s -c /dev/null -o value -s TYPE %s" % (cmd, dev))
fs = raw_fs.strip()
if fs == fstype and resizefs is False and not force:
module.exit_json(changed=False)
elif fs == fstype and resizefs is True:
# Get dev and fs size and compare
devsize_in_bytes = _get_dev_size(dev, module)
fssize_in_bytes = _get_fs_size(fssize_cmd, dev, module)
if fssize_in_bytes < devsize_in_bytes:
fs_smaller = True
else:
fs_smaller = False
if module.check_mode and fs_smaller:
module.exit_json(changed=True, msg="Resizing filesystem %s on device %s" % (fstype,dev))
elif module.check_mode and not fs_smaller:
module.exit_json(changed=False, msg="%s filesystem is using the whole device %s" % (fstype, dev))
elif fs_smaller:
cmd = module.get_bin_path(growcmd, required=True)
rc,out,err = module.run_command("%s %s" % (cmd, dev))
# Sadly there is no easy way to determine if this has changed. For now, just say "true" and move on.
# in the future, you would have to parse the output to determine this.
# thankfully, these are safe operations if no change is made.
if rc == 0:
module.exit_json(changed=True, msg=out)
else:
module.fail_json(msg="Resizing filesystem %s on device '%s' failed"%(fstype,dev), rc=rc, err=err)
else:
module.exit_json(changed=False, msg="%s filesystem is using the whole device %s" % (fstype, dev))
elif fs and not force:
module.fail_json(msg="'%s' is already used as %s, use force=yes to overwrite"%(dev,fs), rc=rc, err=err)
### create fs
if module.check_mode:
changed = True
else:
mkfs = module.get_bin_path(mkfscmd, required=True)
cmd = None
if opts is None:
cmd = "%s %s '%s'" % (mkfs, force_flag, dev)
else:
cmd = "%s %s %s '%s'" % (mkfs, force_flag, opts, dev)
rc,_,err = module.run_command(cmd)
if rc == 0:
changed = True
else:
module.fail_json(msg="Creating filesystem %s on device '%s' failed"%(fstype,dev), rc=rc, err=err)
module.exit_json(changed=changed)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
| gpl-3.0 |
19kestier/taiga-back | taiga/export_import/throttling.py | 20 | 1039 | # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from taiga.base import throttling
class ImportModeRateThrottle(throttling.UserRateThrottle):
scope = "import-mode"
class ImportDumpModeRateThrottle(throttling.UserRateThrottle):
scope = "import-dump-mode"
| agpl-3.0 |
minghuascode/pyj | examples/misc/gaedjangononrelpuremvcblog/media/components.py | 8 | 5905 | """
By Scott Scites <scott.scites@railcar88.com>
Copyright(c) 2010 Scott Scites, Some rights reserved.
"""
from pyjamas.ui.Hidden import Hidden
from pyjamas.ui.TextArea import TextArea
from pyjamas.ui.TextBox import TextBox
from pyjamas.ui.AbsolutePanel import AbsolutePanel
from pyjamas.ui.DialogBox import DialogBox
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Button import Button
from pyjamas.ui.Label import Label
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.VerticalPanel import VerticalPanel
from pyjamas.ui.HTML import HTML
from pyjamas import Window
class PyJsApp(object):
app_frame = None
def __init__(self):
self.app_frame = AppFrame()
class AppFrame(object):
edit_panel = None
home_panel = None
write_panel = None
def __init__(self):
self.panel = AbsolutePanel()
self.edit_panel = EditPanel(self)
self.home_panel = HomePanel(self)
self.write_panel = WritePanel(self)
self.panel.add(self.edit_panel)
self.panel.add(self.home_panel)
self.panel.add(self.write_panel)
RootPanel().add(self.panel)
class EditPanel(AbsolutePanel):
def __init__(self, key, title, content):
AbsolutePanel.__init__(self)
self.edit_header = Label("Edit a Post", StyleName="header_label")
self.edit_title_label = Label("Title:")
self.edit_title = TextBox()
self.edit_title.setMaxLength(255)
self.edit_content = TextArea()
self.edit_content.setVisibleLines(2)
self.edit_button = Button("Save")
self.edit_cancel_button = Button("Cancel")
self.edit_hidden_key = Hidden()
self.error_message_label = Label("", StyleName="error_message_label")
edit_contents = VerticalPanel(StyleName="Contents", Spacing=4)
edit_contents.add(self.edit_header)
edit_contents.add(self.edit_title_label)
edit_contents.add(self.edit_title)
edit_contents.add(self.edit_content)
edit_contents.add(self.edit_button)
edit_contents.add(self.edit_cancel_button)
edit_contents.add(self.error_message_label)
edit_contents.add(self.edit_hidden_key)
self.edit_dialog = DialogBox(glass=True)
self.edit_dialog.setHTML('<b>Blog Post Form</b>')
self.edit_dialog.setWidget(edit_contents)
left = (Window.getClientWidth() - 900) / 2 + Window.getScrollLeft()
top = (Window.getClientHeight() - 600) / 2 + Window.getScrollTop()
self.edit_dialog.setPopupPosition(left, top)
self.edit_dialog.hide()
def clear_edit_panel(self):
self.edit_title.setText("")
self.edit_content.setText("")
self.error_message_label.setText("")
class HomePanel(AbsolutePanel):
def __init__(self, parent):
AbsolutePanel.__init__(self)
self.home_header = Label("Blogjamas", StyleName="header_label")
self.write_button = Button("Write a Post")
self.edit_hidden_button = Button("", StyleName="hidden_button")
self.delete_hidden_button = Button("", StyleName="hidden_button")
self.add(self.home_header)
self.add(self.write_button)
self.add(self.edit_hidden_button)
self.add(self.delete_hidden_button)
def update_posts(self, posts):
self.contents = VerticalPanel(Spacing=1)
for i in range(len(posts)):
self.divider = HTML("----------------------------------------------------")
self.contents.add(self.divider)
self.post_title = Label(posts[i].title, StyleName="title_label")
self.contents.add(self.post_title)
self.post_content = Label(posts[i].content, StyleName="content_label")
self.contents.add(self.post_content)
self.edit_button = Button("Edit")
self.edit_button.setID("edit_" + posts[i].post_id)
self.edit_button.addClickListener(self.show_edit_box)
self.contents.add(self.edit_button)
self.delete_button = Button("Delete")
self.delete_button.setID("delete_" + posts[i].post_id)
self.delete_button.addClickListener(self.delete_post)
self.contents.add(self.delete_button)
self.add(self.contents)
def show_edit_box(self, sender):
self.edit_hidden_button.setID(sender.getID())
self.edit_hidden_button.click(self)
def delete_post(self, sender):
self.delete_hidden_button.setID(sender.getID())
self.delete_hidden_button.click(self)
class WritePanel(AbsolutePanel):
def __init__(self, parent):
AbsolutePanel.__init__(self)
self.post_header = Label("Write a Post", StyleName="header_label")
self.post_write_title_label = Label("Title:")
self.post_title = TextBox()
self.post_content = TextArea()
self.post_button = Button("Post")
self.cancel_button = Button("Cancel")
self.error_message_label = Label("", StyleName="error_message_label")
contents = VerticalPanel(StyleName="Contents", Spacing=4)
contents.add(self.post_header)
contents.add(self.post_write_title_label)
contents.add(self.post_title)
contents.add(self.post_content)
contents.add(self.post_button)
contents.add(self.cancel_button)
contents.add(self.error_message_label)
self.dialog = DialogBox(glass=True)
self.dialog.setHTML('<b>Blog Post Form</b>')
self.dialog.setWidget(contents)
left = (Window.getClientWidth() - 900) / 2 + Window.getScrollLeft()
top = (Window.getClientHeight() - 600) / 2 + Window.getScrollTop()
self.dialog.setPopupPosition(left, top)
self.dialog.hide()
def clear_write_panel(self):
self.post_title.setText("")
self.post_content.setText("")
self.error_message_label.setText("")
| apache-2.0 |
cortesi/mitmproxy | mitmproxy/version.py | 3 | 1296 | import os
import subprocess
import sys
VERSION = "5.0.0.dev"
PATHOD = "pathod " + VERSION
MITMPROXY = "mitmproxy " + VERSION
# Serialization format version. This is displayed nowhere, it just needs to be incremented by one
# for each change in the file format.
FLOW_FORMAT_VERSION = 7
def get_dev_version() -> str:
"""
Return a detailed version string, sourced either from VERSION or obtained dynamically using git.
"""
mitmproxy_version = VERSION
here = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
try:
git_describe = subprocess.check_output(
['git', 'describe', '--long'],
stderr=subprocess.STDOUT,
cwd=here,
)
last_tag, tag_dist, commit = git_describe.decode().strip().rsplit("-", 2)
commit = commit.lstrip("g")[:7]
tag_dist = int(tag_dist)
except Exception:
pass
else:
# Add commit info for non-tagged releases
if tag_dist > 0:
mitmproxy_version += f" (+{tag_dist}, commit {commit})"
# PyInstaller build indicator, if using precompiled binary
if getattr(sys, 'frozen', False):
mitmproxy_version += " binary"
return mitmproxy_version
if __name__ == "__main__": # pragma: no cover
print(VERSION)
| mit |
alex1818/mraa | src/doxy2swig.py | 35 | 15325 | #!/usr/bin/env python2
"""Doxygen XML to SWIG docstring converter.
Usage:
doxy2swig.py [options] input.xml output.i
Converts Doxygen generated XML files into a file containing docstrings
that can be used by SWIG-1.3.x. Note that you need to get SWIG
version > 1.3.23 or use Robin Dunn's docstring patch to be able to use
the resulting output.
input.xml is your doxygen generated XML file and output.i is where the
output will be written (the file will be clobbered).
"""
#
#
# This code is implemented using Mark Pilgrim's code as a guideline:
# http://www.faqs.org/docs/diveintopython/kgp_divein.html
#
# Author: Prabhu Ramachandran
# License: BSD style
#
# Thanks:
# Johan Hake: the include_function_definition feature
# Bill Spotz: bug reports and testing.
# Sebastian Henschel: Misc. enhancements.
#
#
from xml.dom import minidom
import re
import textwrap
import sys
import os.path
import optparse
def my_open_read(source):
if hasattr(source, "read"):
return source
else:
return open(source)
def my_open_write(dest):
if hasattr(dest, "write"):
return dest
else:
return open(dest, 'w')
class Doxy2SWIG:
"""Converts Doxygen generated XML files into a file containing
docstrings that can be used by SWIG-1.3.x that have support for
feature("docstring"). Once the data is parsed it is stored in
self.pieces.
"""
def __init__(self, src, include_function_definition=True, quiet=False):
"""Initialize the instance given a source object. `src` can
be a file or filename. If you do not want to include function
definitions from doxygen then set
`include_function_definition` to `False`. This is handy since
this allows you to use the swig generated function definition
using %feature("autodoc", [0,1]).
"""
f = my_open_read(src)
self.my_dir = os.path.dirname(f.name)
self.xmldoc = minidom.parse(f).documentElement
f.close()
self.pieces = []
self.pieces.append('\n// File: %s\n' %
os.path.basename(f.name))
self.space_re = re.compile(r'\s+')
self.lead_spc = re.compile(r'^(%feature\S+\s+\S+\s*?)"\s+(\S)')
self.multi = 0
self.ignores = ['inheritancegraph', 'param', 'listofallmembers',
'innerclass', 'name', 'declname', 'incdepgraph',
'invincdepgraph', 'programlisting', 'type',
'references', 'referencedby', 'location',
'collaborationgraph', 'reimplements',
'reimplementedby', 'derivedcompoundref',
'basecompoundref']
#self.generics = []
self.include_function_definition = include_function_definition
if not include_function_definition:
self.ignores.append('argsstring')
self.quiet = quiet
def generate(self):
"""Parses the file set in the initialization. The resulting
data is stored in `self.pieces`.
"""
self.parse(self.xmldoc)
def parse(self, node):
"""Parse a given node. This function in turn calls the
`parse_<nodeType>` functions which handle the respective
nodes.
"""
pm = getattr(self, "parse_%s" % node.__class__.__name__)
pm(node)
def parse_Document(self, node):
self.parse(node.documentElement)
def parse_Text(self, node):
txt = node.data
txt = txt.replace('\\', r'\\\\')
txt = txt.replace('"', r'\"')
# ignore pure whitespace
m = self.space_re.match(txt)
if m and len(m.group()) == len(txt):
pass
else:
self.add_text(textwrap.fill(txt, break_long_words=False))
def parse_Element(self, node):
"""Parse an `ELEMENT_NODE`. This calls specific
`do_<tagName>` handers for different elements. If no handler
is available the `generic_parse` method is called. All
tagNames specified in `self.ignores` are simply ignored.
"""
name = node.tagName
ignores = self.ignores
if name in ignores:
return
attr = "do_%s" % name
if hasattr(self, attr):
handlerMethod = getattr(self, attr)
handlerMethod(node)
else:
self.generic_parse(node)
#if name not in self.generics: self.generics.append(name)
def parse_Comment(self, node):
"""Parse a `COMMENT_NODE`. This does nothing for now."""
return
def add_text(self, value):
"""Adds text corresponding to `value` into `self.pieces`."""
if isinstance(value, (list, tuple)):
self.pieces.extend(value)
else:
self.pieces.append(value)
def get_specific_nodes(self, node, names):
"""Given a node and a sequence of strings in `names`, return a
dictionary containing the names as keys and child
`ELEMENT_NODEs`, that have a `tagName` equal to the name.
"""
nodes = [(x.tagName, x) for x in node.childNodes
if x.nodeType == x.ELEMENT_NODE and
x.tagName in names]
return dict(nodes)
def generic_parse(self, node, pad=0):
"""A Generic parser for arbitrary tags in a node.
Parameters:
- node: A node in the DOM.
- pad: `int` (default: 0)
If 0 the node data is not padded with newlines. If 1 it
appends a newline after parsing the childNodes. If 2 it
pads before and after the nodes are processed. Defaults to
0.
"""
npiece = 0
if pad:
npiece = len(self.pieces)
if pad == 2:
self.add_text('\n')
for n in node.childNodes:
self.parse(n)
if pad:
if len(self.pieces) > npiece:
self.add_text('\n')
def space_parse(self, node):
self.add_text(' ')
self.generic_parse(node)
do_ref = space_parse
do_emphasis = space_parse
do_bold = space_parse
do_computeroutput = space_parse
do_formula = space_parse
def do_compoundname(self, node):
self.add_text('\n\n')
data = node.firstChild.data
self.add_text('%%feature("docstring") %s "\n' % data)
def do_compounddef(self, node):
kind = node.attributes['kind'].value
if kind in ('class', 'struct'):
prot = node.attributes['prot'].value
if prot != 'public':
return
names = ('compoundname', 'briefdescription',
'detaileddescription', 'includes')
first = self.get_specific_nodes(node, names)
for n in names:
if first.has_key(n):
self.parse(first[n])
self.add_text(['";', '\n'])
for n in node.childNodes:
if n not in first.values():
self.parse(n)
elif kind in ('file', 'namespace'):
nodes = node.getElementsByTagName('sectiondef')
for n in nodes:
self.parse(n)
def do_includes(self, node):
self.add_text('C++ includes: ')
self.generic_parse(node, pad=1)
def do_parameterlist(self, node):
text = 'unknown'
for key, val in node.attributes.items():
if key == 'kind':
if val == 'param':
text = 'Parameters'
elif val == 'exception':
text = 'Exceptions'
elif val == 'retval':
text = 'Returns'
else:
text = val
break
self.add_text(['\n', '\n', text, ':', '\n'])
self.generic_parse(node, pad=1)
def do_para(self, node):
self.add_text('\n')
self.generic_parse(node, pad=1)
def do_parametername(self, node):
self.add_text('\n')
try:
data = node.firstChild.data
except AttributeError: # perhaps a <ref> tag in it
data = node.firstChild.firstChild.data
if data.find('Exception') != -1:
self.add_text(data)
else:
self.add_text("%s: " % data)
def do_parameterdefinition(self, node):
self.generic_parse(node, pad=1)
def do_detaileddescription(self, node):
self.generic_parse(node, pad=1)
def do_briefdescription(self, node):
self.generic_parse(node, pad=1)
def do_memberdef(self, node):
prot = node.attributes['prot'].value
id = node.attributes['id'].value
kind = node.attributes['kind'].value
tmp = node.parentNode.parentNode.parentNode
compdef = tmp.getElementsByTagName('compounddef')[0]
cdef_kind = compdef.attributes['kind'].value
if prot == 'public':
first = self.get_specific_nodes(node, ('definition', 'name'))
name = first['name'].firstChild.data
if name[:8] == 'operator': # Don't handle operators yet.
return
if not 'definition' in first or \
kind in ['variable', 'typedef']:
return
if self.include_function_definition:
defn = first['definition'].firstChild.data
else:
defn = ""
self.add_text('\n')
self.add_text('%feature("docstring") ')
anc = node.parentNode.parentNode
if cdef_kind in ('file', 'namespace'):
ns_node = anc.getElementsByTagName('innernamespace')
if not ns_node and cdef_kind == 'namespace':
ns_node = anc.getElementsByTagName('compoundname')
if ns_node:
ns = ns_node[0].firstChild.data
self.add_text(' %s::%s "\n%s' % (ns, name, defn))
else:
self.add_text(' %s "\n%s' % (name, defn))
elif cdef_kind in ('class', 'struct'):
# Get the full function name.
anc_node = anc.getElementsByTagName('compoundname')
cname = anc_node[0].firstChild.data
self.add_text(' %s::%s "\n%s' % (cname, name, defn))
for n in node.childNodes:
if n not in first.values():
self.parse(n)
self.add_text(['";', '\n'])
def do_definition(self, node):
data = node.firstChild.data
self.add_text('%s "\n%s' % (data, data))
def do_sectiondef(self, node):
kind = node.attributes['kind'].value
if kind in ('public-func', 'func', 'user-defined', ''):
self.generic_parse(node)
def do_header(self, node):
"""For a user defined section def a header field is present
which should not be printed as such, so we comment it in the
output."""
data = node.firstChild.data
self.add_text('\n/*\n %s \n*/\n' % data)
# If our immediate sibling is a 'description' node then we
# should comment that out also and remove it from the parent
# node's children.
parent = node.parentNode
idx = parent.childNodes.index(node)
if len(parent.childNodes) >= idx + 2:
nd = parent.childNodes[idx + 2]
if nd.nodeName == 'description':
nd = parent.removeChild(nd)
self.add_text('\n/*')
self.generic_parse(nd)
self.add_text('\n*/\n')
def do_simplesect(self, node):
kind = node.attributes['kind'].value
if kind in ('date', 'rcs', 'version'):
pass
elif kind == 'warning':
self.add_text(['\n', 'WARNING: '])
self.generic_parse(node)
elif kind == 'see':
self.add_text('\n')
self.add_text('See: ')
self.generic_parse(node)
else:
self.generic_parse(node)
def do_argsstring(self, node):
self.generic_parse(node, pad=1)
def do_member(self, node):
kind = node.attributes['kind'].value
refid = node.attributes['refid'].value
if kind == 'function' and refid[:9] == 'namespace':
self.generic_parse(node)
def do_doxygenindex(self, node):
self.multi = 1
comps = node.getElementsByTagName('compound')
for c in comps:
refid = c.attributes['refid'].value
fname = refid + '.xml'
if not os.path.exists(fname):
fname = os.path.join(self.my_dir, fname)
if not self.quiet:
print("parsing file: %s" % fname)
p = Doxy2SWIG(fname, self.include_function_definition, self.quiet)
p.generate()
self.pieces.extend(self.clean_pieces(p.pieces))
def write(self, fname):
o = my_open_write(fname)
if self.multi:
o.write("".join(x.encode('utf-8') for x in self.pieces))
else:
o.write("".join(self.clean_pieces(self.pieces)))
o.close()
def clean_pieces(self, pieces):
"""Cleans the list of strings given as `pieces`. It replaces
multiple newlines by a maximum of 2 and returns a new list.
It also wraps the paragraphs nicely.
"""
ret = []
count = 0
for i in pieces:
if i == '\n':
count = count + 1
else:
if i == '";':
if count:
ret.append('\n')
elif count > 2:
ret.append('\n\n')
elif count:
ret.append('\n' * count)
count = 0
ret.append(i)
_data = "".join(ret)
ret = []
for i in _data.split('\n\n'):
if i == 'Parameters:' or i == 'Exceptions:' or i == 'Returns:':
ret.extend([i, '\n' + '-' * len(i), '\n\n'])
elif i.find('// File:') > -1: # leave comments alone.
ret.extend([i, '\n'])
else:
_tmp = textwrap.fill(i.strip(), break_long_words=False)
_tmp = self.lead_spc.sub(r'\1"\2', _tmp)
ret.extend([_tmp, '\n\n'])
return ret
def convert(input, output, include_function_definition=True, quiet=False):
p = Doxy2SWIG(input, include_function_definition, quiet)
p.generate()
p.write(output)
def main():
usage = __doc__
parser = optparse.OptionParser(usage)
parser.add_option("-n", '--no-function-definition',
action='store_true',
default=False,
dest='func_def',
help='do not include doxygen function definitions')
parser.add_option("-q", '--quiet',
action='store_true',
default=False,
dest='quiet',
help='be quiet and minimize output')
options, args = parser.parse_args()
if len(args) != 2:
parser.error("error: no input and output specified")
convert(args[0], args[1], not options.func_def, options.quiet)
if __name__ == '__main__':
main()
| mit |
kernsuite-debian/lofar | CEP/Pipeline/framework/lofarpipe/cuisine/WSRTrecipe.py | 1 | 14078 | #!/usr/bin/env python3
from . import ingredient, cook, parset
import sys
from optparse import OptionParser
from traceback import print_exc
####
# Use the standard Python logging module for flexibility.
# Standard error of external jobs goes to logging.WARN, standard output goes
# to logging.INFO.
import logging
from lofarpipe.support.pipelinelogging import getSearchingLogger
from traceback import format_exc
class RecipeError(cook.CookError):
pass
class NullLogHandler(logging.Handler):
"""
A handler for the logging module, which does nothing.
Provides a sink, so that loggers with no other handlers defined do
nothing rather than spewing unformatted garbage.
"""
def emit(self, record):
pass
class WSRTrecipe(object):
"""Base class for recipes, pipelines are created by calling the cook_*
methods. Most subclasses should only need to reimplement go() and add
inputs and outputs. Some might need to addlogger() to messages or
override main_results."""
def __init__(self):
## List of inputs, self.inputs[key] != True is considered valid input
self.inputs = ingredient.WSRTingredient()
## List of outputs, should only be filled on succesful execution
self.outputs = ingredient.WSRTingredient()
## All of these should do something sensible in their __str__ for
## simple print output
## Try using the standard Python system for handling options
self.optionparser = OptionParser(
usage = "usage: %prog [options]"
)
self.optionparser.remove_option('-h')
self.optionparser.add_option(
'-h', '--help', action = "store_true"
)
self.optionparser.add_option(
'-v', '--verbose',
action = "callback", callback = self.__setloglevel,
help = "verbose [Default: %default]"
)
self.optionparser.add_option(
'-d', '--debug',
action = "callback", callback = self.__setloglevel,
help = "debug [Default: %default]"
)
self.helptext = """LOFAR/WSRT pipeline framework"""
self.recipe_path = ['.']
def _log_error(self, e):
# Sometimes, an exception will be thrown before we have any loggers
# defined that can handle it. Check if that's the case, and, if so,
# dump it to stderr.
handled = len(self.logger.handlers) > 0
my_logger = self.logger
while my_logger.parent:
my_logger = my_logger.parent
if len(my_logger.handlers) > 0 and my_logger is not my_logger.root:
handled = True
if handled:
self.logger.exception('Exception caught: ' + str(e))
else:
print("***** Exception occurred with no log handlers", file=sys.stderr)
print("*****", str(e), file=sys.stderr)
print_exc()
def help(self):
"""Shows helptext and inputs and outputs of the recipe"""
print(self.helptext)
self.optionparser.print_help()
print('\nOutputs:')
for k in list(self._outfields.keys()):
print(' ' + k)
def main_init(self):
"""Main initialization for stand alone execution, reading input from
the command line"""
# The root logger has a null handler; we'll override in recipes.
logging.getLogger().addHandler(NullLogHandler())
self.logger = getSearchingLogger(self.name)
opts = sys.argv[1:]
try:
myParset = parset.Parset(self.name + ".parset")
for p in list(myParset.keys()):
opts[0:0] = "--" + p, myParset.getString(p)
except IOError:
logging.debug("Unable to open parset")
(options, args) = self.optionparser.parse_args(opts)
if options.help:
return 1
else:
for key, value in vars(options).items():
if value is not None:
self.inputs[key] = value
self.inputs['args'] = args
return 0
def main(self):
"""This function is to be run in standalone mode."""
import os.path
self.name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
status = self.main_init()
if not status:
status = self.run(self.name)
self.main_result()
else:
self.help()
logging.shutdown()
return status
def run(self, name):
"""This code will run if all inputs are valid, and wraps the actual
functionality in self.go() with some exception handling, might need
another name, like try_execute, because it's to similar to go()."""
self.name = name
self.logger.info('recipe ' + name + ' started')
try:
status = self.go()
if not self.outputs.complete():
self.logger.warn("Note: recipe outputs are not complete")
except Exception as e:
self._log_error(e)
self.outputs = None ## We're not generating any results we have
## confidence in
return 1
else:
if status == 0:
self.logger.info('recipe ' + name + ' completed')
else:
self.logger.warn('recipe ' + name + ' completed with errors')
return status
def get_run_info(self, filepath):
import pickle
try:
fd = open(filepath + '/pipeline.pickle')
results = pickle.load(fd)
except:
return None
fd.close()
if self.name in list(results.keys()):
return results[self.name]
else:
return None
def set_run_info(self, filepath):
import pickle
try:
fd = open(filepath + '/' + 'pipeline.pickle', 'w')
try:
results = pickle.load(fd)
except:
results = {}
results[self.name] = {'inputs':self.inputs, 'outputs':self.outputs}
pickle.dump(results, fd)
fd.close()
except:
return None
def rerun(self, name, directory):
"""Function that you can use to rerun a recipe from the point where it
ended. Not working completely yet. [untested]"""
self.name = name
self.logger.info('recipe ' + name + ' started')
try:
results = self.get_run_info(directory)
if not results: return
if not results[self.name]: return
self.inputs = results[self.name]['inputs']
self.outputs = results[self.name]['outputs']
self.run(name)
except Exception as e:
self._log_error(e)
self.outputs = None ## We're not generating any results we have
## confidence in
return 0
else:
self.logger.info('recipe ' + name + ' completed')
return 1
def go(self):
"""Main functionality, this empty placeholder only shows help"""
self.help()
def main_result(self):
"""Main results display for stand alone execution, displaying results
on stdout"""
if self.outputs == None:
print('No results')
else:
print('Results:')
for o in list(self.outputs.keys()):
print(str(o) + ' = ' + str(self.outputs[o]))
## Maybe these cooks should go in some subclass?
## Problem is you might need all of them in a recipe describing a pipeline
def cook_recipe(self, recipe, inputs, outputs):
"""Execute another recipe/pipeline as part of this one"""
c = cook.PipelineCook(recipe, inputs, outputs, self.logger, self.recipe_path)
c.spawn()
def cook_system(self, command, options):
"""Execute an arbitrairy system call, returns it's exitstatus"""
l = [command]
if type(options) == list:
l.extend(options)
else: ## we assume it's a string
l.extend(options.split())
self.print_debug('running ' + command + ' ' + str(options))
c = cook.SystemCook(command, l, {})
c.spawn()
while c.handle_messages():
pass ## we could have a timer here
c.wait()
return c.exitstatus ## just returning the exitstatus, the programmer
## must decide what to do
def cook_interactive(self, command, options, expect):
"""Execute an arbitrairy system call, returns it's exitstatus, expect
can define some functions to call if certain strings are written to
the terminal stdout of the called program.
Whatever such functions return is written to the stdin of the called
program."""
commandline = [command]
if type(options) == list:
commandline.extend(options)
else: ## we assume it's a string
commandline.extend(options.split())
self.print_debug('running ' + command + ' ' + str(options))
c = cook.SystemCook(command, commandline, {})
c.set_expect(expect)
c.spawn()
while c.handle_messages():
pass ## we could have a timer here
c.wait()
return c.exitstatus ## just returning the exitstatus, the programmer
## must decide what to do
def cook_miriad(self, command, options):
"""Execute a Miriad task, uses MRIBIN, returns it's exitstatus"""
l = [command]
if type(options) == list:
l.extend(options)
else: ## we assume it's a string
l.extend(options.split())
self.print_debug('running ' + command + str(options))
c = cook.MiriadCook(command, l, {})
c.spawn()
while c.handle_messages():
pass ## we could have a timer here
c.wait()
# should probably parse the messages on '### Fatal Error'
if c.exitstatus:
raise RecipeError('%s failed with error: %s' %
(command, c.exitstatus))
return c.exitstatus ## just returning the exitstatus, the programmer
## must decide what to do
## def cook_aips(self, command, options):
## """Execute an AIPS task, returns it's exitstatus"""
## l = [command]
## if type(options) == list:
## l.extend(options)
## else: ## we assume it's a string
## l.extend(options.split())
## self.print_debug('running ' + command + str(options))
## c = cook.AIPSCook(command, l, {}, self.messages)
## c.spawn()
## while c.handle_messages():
## pass ## we could have a timer here
## c.wait()
## return c.exitstatus ## just returning the exitstatus, the programmer must decide what to do
##
## def cook_aips2(self, command, options):
## """Execute an AIPS++ tool, returns it's exitstatus""" #?
## l = [command]
## if type(options) == list:
## l.extend(options)
## else: ## we assume it's a string
## l.extend(options.split())
## self.print_debug('running ' + command + str(options))
## c = cook.AIPS2Cook(command, l, {}, self.messages)
## c.spawn()
## while c.handle_messages():
## pass ## we could have a timer here
## c.wait()
## return c.exitstatus ## just returning the exitstatus, the programmer must decide what to do
def cook_glish(self, command, options):
"""Execute a Glish script, uses AIPSPATH, returns it's exitstatus"""
l = ['glish', '-l', command + '.g']
if type(options) == list:
l.extend(options)
else: ## we assume it's a string
l.extend(options.split())
self.print_debug('running ' + command + str(options))
c = cook.GlishCook('glish', l, {})
c.spawn()
while c.handle_messages():
pass ## we could have a timer here
c.wait()
return c.exitstatus ## just returning the exitstatus, the programmer
## must decide what to do
def print_debug(self, text):
"""Add a message at the debug level"""
self.logger.debug(text)
def print_message(self, text):
"""Add a message at the verbose level"""
self.logger.info(text)
print_notification = print_message # backwards compatibility
def print_warning(self, text):
"""Add a message at the warning level."""
self.logger.warn(text)
def print_error(self, text):
"""Add a message at the error level"""
self.logger.error(text)
def print_critical(self, text):
"""Add a message at the critical level"""
self.logger.crit(text)
# The feeling is this needs to be part of the ingredient, or separate module,
# not the recipe
def zap(self, filepath):
import os #, exception
# if filepath == '/' or filepath == '~/':
# raise Exception
# else:
# for root, dirs, files in os.walk(filepath, topdown=False):
# for name in files:
# os.remove(join(root, name))
# for name in dirs:
# os.rmdir(join(root, name))
if os.path.isdir(filepath):
self.cook_system('rm', ' -rf ' + filepath)
elif os.path.isfile(filepath):
self.cook_system('rm', ' -f ' + filepath)
else:
self.print_debug(filepath + ' doesn\'t seem to exist')
def __setloglevel(self, option, opt_str, value, parser):
"""Callback for setting log level based on command line arguments"""
if str(option) == '-v/--verbose':
self.logger.setLevel(logging.INFO)
elif str(option) == '-d/--debug':
self.logger.setLevel(logging.DEBUG)
# Stand alone execution code ------------------------------------------
if __name__ == '__main__':
standalone = WSRTrecipe()
sys.exit(standalone.main())
| gpl-3.0 |
tiposaurio/venton | apps/params/migrations/0001_initial.py | 4 | 1796 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Person',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('identity_type', models.CharField(default=b'NID', max_length=10, verbose_name='Identity type', choices=[(b'NID', 'N.I.D.'), (b'FC', 'Foreign card'), (b'CB', 'Certificate birth'), (b'OTHER', 'Other')])),
('identity_num', models.CharField(blank=True, max_length=20, null=True, verbose_name='Identity num', error_messages={b'unique': b'eeeee ee'})),
('first_name', models.CharField(max_length=50, null=True, verbose_name='First name', blank=True)),
('last_name', models.CharField(max_length=50, null=True, verbose_name='Last name', blank=True)),
('birth_date', models.DateField(null=True, verbose_name='birth date', blank=True)),
('photo', models.ImageField(default=b'persons/default.png', upload_to=b'persons', null=True, verbose_name='Photo', blank=True)),
('photo2', models.ImageField(default=b'persons/default.png', upload_to=b'persons', null=True, verbose_name='Photo2', blank=True)),
],
options={
'verbose_name': 'Person',
'verbose_name_plural': 'Persons',
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='person',
unique_together=set([('first_name', 'last_name', 'identity_type', 'identity_num'), ('identity_type', 'identity_num')]),
),
]
| bsd-3-clause |
nekulin/arangodb | 3rdParty/V8-4.3.61/third_party/python_26/Lib/site-packages/win32com/test/testPyComTest.py | 17 | 19795 | # NOTE - Still seems to be a leak here somewhere
# gateway count doesnt hit zero. Hence the print statements!
import sys; sys.coinit_flags=0 # Must be free-threaded!
import win32api, types, pythoncom, time
import sys, os, win32com, win32com.client.connect
from win32com.test.util import CheckClean
from win32com.client import constants
import win32com
from util import RegisterPythonServer
importMsg = "**** PyCOMTest is not installed ***\n PyCOMTest is a Python test specific COM client and server.\n It is likely this server is not installed on this machine\n To install the server, you must get the win32com sources\n and build it using MS Visual C++"
error = Exception
# This test uses a Python implemented COM server - ensure correctly registered.
RegisterPythonServer(os.path.join(os.path.dirname(__file__), '..', "servers", "test_pycomtest.py"))
from win32com.client import gencache
try:
gencache.EnsureModule('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', 0, 1, 1)
except pythoncom.com_error:
print "The PyCOMTest module can not be located or generated."
print importMsg
raise RuntimeError, importMsg
# We had a bg where RegisterInterfaces would fail if gencache had
# already been run - exercise that here
from win32com import universal
universal.RegisterInterfaces('{6BCDCB60-5605-11D0-AE5F-CADD4C000000}', 0, 1, 1)
verbose = 0
def progress(*args):
if verbose:
for arg in args:
print arg,
print
def TestApplyResult(fn, args, result):
try:
import string
fnName = string.split(str(fn))[1]
except:
fnName = str(fn)
progress("Testing ", fnName)
pref = "function " + fnName
rc = apply(fn, args)
if rc != result:
raise error, "%s failed - result not %r but %r" % (pref, result, rc)
def TestConstant(constName, pyConst):
try:
comConst = getattr(constants, constName)
except:
raise error, "Constant %s missing" % (constName,)
if comConst != pyConst:
raise error, "Constant value wrong for %s - got %s, wanted %s" % (constName, comConst, pyConst)
# Simple handler class. This demo only fires one event.
class RandomEventHandler:
def _Init(self):
self.fireds = {}
def OnFire(self, no):
try:
self.fireds[no] = self.fireds[no] + 1
except KeyError:
self.fireds[no] = 0
def OnFireWithNamedParams(self, no, a_bool, out1, out2):
# This test exists mainly to help with an old bug, where named
# params would come in reverse.
Missing = pythoncom.Missing
if no is not Missing:
# We know our impl called 'OnFire' with the same ID
assert no in self.fireds
assert no+1==out1, "expecting 'out1' param to be ID+1"
assert no+2==out2, "expecting 'out2' param to be ID+2"
# The middle must be a boolean.
assert a_bool is Missing or type(a_bool)==bool, "middle param not a bool"
return out1+2, out2+2
def _DumpFireds(self):
if not self.fireds:
print "ERROR: Nothing was received!"
for firedId, no in self.fireds.items():
progress("ID %d fired %d times" % (firedId, no))
def TestDynamic():
progress("Testing Dynamic")
import win32com.client.dynamic
o = win32com.client.dynamic.DumbDispatch("PyCOMTest.PyCOMTest")
progress("Getting counter")
counter = o.GetSimpleCounter()
TestCounter(counter, 0)
progress("Checking default args")
rc = o.TestOptionals()
if rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01:
print rc
raise error, "Did not get the optional values correctly"
rc = o.TestOptionals("Hi", 2, 3, 1.1)
if rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01:
print rc
raise error, "Did not get the specified optional values correctly"
rc = o.TestOptionals2(0)
if rc != (0, "", 1):
print rc
raise error, "Did not get the optional2 values correctly"
rc = o.TestOptionals2(1.1, "Hi", 2)
if rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01:
print rc
raise error, "Did not get the specified optional2 values correctly"
# if verbose: print "Testing structs"
r = o.GetStruct()
assert r.int_value == 99 and str(r.str_value)=="Hello from C++"
counter = win32com.client.dynamic.DumbDispatch("PyCOMTest.SimpleCounter")
TestCounter(counter, 0)
assert o.DoubleString("foo") == "foofoo"
l=[]
TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
l=[1,2,3,4]
TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
# TestApplyResult(o.SetIntSafeArray, (l,), len(l)) Still fails, and probably always will.
TestApplyResult(o.CheckVariantSafeArray, ((1,2,3,4,),), 1)
o.LongProp = 3
if o.LongProp != 3 or o.IntProp != 3:
raise error, "Property value wrong - got %d/%d" % (o.LongProp,o.IntProp)
o.LongProp = o.IntProp = -3
if o.LongProp != -3 or o.IntProp != -3:
raise error, "Property value wrong - got %d/%d" % (o.LongProp,o.IntProp)
# This number fits in an unsigned long. Attempting to set it to a normal
# long will involve overflow, which is to be expected. But we do
# expect it to work in a property explicitly a VT_UI4.
check = 3 *10 **9
o.ULongProp = check
if o.ULongProp != check:
raise error, "Property value wrong - got %d (expected %d)" % (o.ULongProp, check)
# currency.
pythoncom.__future_currency__ = 1
if o.CurrencyProp != 0:
raise error, "Expecting 0, got %r" % (o.CurrencyProp,)
try:
import decimal
except ImportError:
import win32com.decimal_23 as decimal
o.CurrencyProp = decimal.Decimal("1234.5678")
if o.CurrencyProp != decimal.Decimal("1234.5678"):
raise error, "got %r" % (o.CurrencyProp,)
v1 = decimal.Decimal("1234.5678")
# can't do "DoubleCurrencyByVal" in dynamic files.
TestApplyResult(o.DoubleCurrency, (v1,), v1*2)
v2 = decimal.Decimal("9012.3456")
TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2)
# damn - props with params don't work for dynamic objects :(
# o.SetParamProp(0, 1)
# if o.ParamProp(0) != 1:
# raise RuntimeError, o.paramProp(0)
try:
import datetime
now = datetime.datetime.now()
expect = pythoncom.MakeTime(now)
TestApplyResult(o.EarliestDate, (now, now), expect)
except ImportError:
pass # py 2.2 - no datetime
def TestGenerated():
# Create an instance of the server.
from win32com.client.gencache import EnsureDispatch
o = EnsureDispatch("PyCOMTest.PyCOMTest")
counter = o.GetSimpleCounter()
TestCounter(counter, 1)
counter = EnsureDispatch("PyCOMTest.SimpleCounter")
TestCounter(counter, 1)
i1, i2 = o.GetMultipleInterfaces()
if type(i1) != types.InstanceType or type(i2) != types.InstanceType:
# Yay - is now an instance returned!
raise error, "GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2)
del i1
del i2
progress("Checking default args")
rc = o.TestOptionals()
if rc[:-1] != ("def", 0, 1) or abs(rc[-1]-3.14)>.01:
print rc
raise error, "Did not get the optional values correctly"
rc = o.TestOptionals("Hi", 2, 3, 1.1)
if rc[:-1] != ("Hi", 2, 3) or abs(rc[-1]-1.1)>.01:
print rc
raise error, "Did not get the specified optional values correctly"
rc = o.TestOptionals2(0)
if rc != (0, "", 1):
print rc
raise error, "Did not get the optional2 values correctly"
rc = o.TestOptionals2(1.1, "Hi", 2)
if rc[1:] != ("Hi", 2) or abs(rc[0]-1.1)>.01:
print rc
raise error, "Did not get the specified optional2 values correctly"
progress("Checking var args")
o.SetVarArgs("Hi", "There", "From", "Python", 1)
if o.GetLastVarArgs() != ("Hi", "There", "From", "Python", 1):
raise error, "VarArgs failed -" + str(o.GetLastVarArgs())
progress("Checking getting/passing IUnknown")
if o.GetSetUnknown(o) != o:
raise error, "GetSetUnknown failed"
progress("Checking getting/passing IDispatch")
if type(o.GetSetDispatch(o)) !=types.InstanceType:
raise error, "GetSetDispatch failed"
progress("Checking getting/passing IDispatch of known type")
if o.GetSetInterface(o).__class__ != o.__class__:
raise error, "GetSetDispatch failed"
if o.GetSetVariant(4) != 4:
raise error, "GetSetVariant (int) failed"
if o.GetSetVariant("foo") != "foo":
raise error, "GetSetVariant (str) failed"
if o.GetSetVariant(o) != o:
raise error, "GetSetVariant (dispatch) failed"
for l in sys.maxint, sys.maxint+1, 1 << 65L:
if o.GetSetVariant(l) != l:
raise error, "GetSetVariant (long) failed"
if o.TestByRefVariant(2) != 4:
raise error, "TestByRefVariant failed"
if o.TestByRefString("Foo") != "FooFoo":
raise error, "TestByRefString failed"
# Pass some non-sequence objects to our array decoder, and watch it fail.
try:
o.SetVariantSafeArray("foo")
raise error, "Expected a type error"
except TypeError:
pass
try:
o.SetVariantSafeArray(666)
raise error, "Expected a type error"
except TypeError:
pass
o.GetSimpleSafeArray(None)
TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10)))
resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20))
TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck)
l=[1,2,3,4]
TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
TestApplyResult(o.SetIntSafeArray, (l,), len(l))
l=[]
TestApplyResult(o.SetVariantSafeArray, (l,), len(l))
TestApplyResult(o.SetIntSafeArray, (l,), len(l))
# Tell the server to do what it does!
TestApplyResult(o.Test, ("Unused", 99), 1) # A bool function
TestApplyResult(o.Test, ("Unused", -1), 1) # A bool function
TestApplyResult(o.Test, ("Unused", 1==1), 1) # A bool function
TestApplyResult(o.Test, ("Unused", 0), 0)
TestApplyResult(o.Test, ("Unused", 1==0), 0)
TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2)
TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2)
TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2)
TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2)
TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1)
TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2)
TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3)
TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4)
TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5)
TestConstant("ULongTest1", 0xFFFFFFFFL)
TestConstant("ULongTest2", 0x7FFFFFFFL)
TestConstant("LongTest1", -0x7FFFFFFFL)
TestConstant("LongTest2", 0x7FFFFFFFL)
TestConstant("UCharTest", 255)
TestConstant("CharTest", -1)
TestConstant("StringTest", "Hello Loraine")
now = pythoncom.MakeTime(time.gmtime(time.time()))
later = pythoncom.MakeTime(time.gmtime(time.time()+1))
TestApplyResult(o.EarliestDate, (now, later), now)
try:
import datetime
now = datetime.datetime.now()
expect = pythoncom.MakeTime(now)
TestApplyResult(o.EarliestDate, (now, now), expect)
except ImportError:
pass # py 2.2 - no datetime
assert o.DoubleString("foo") == "foofoo"
assert o.DoubleInOutString("foo") == "foofoo"
o.LongProp = 3
if o.LongProp != 3 or o.IntProp != 3:
raise error, "Property value wrong - got %d/%d" % (o.LongProp,o.IntProp)
o.LongProp = o.IntProp = -3
if o.LongProp != -3 or o.IntProp != -3:
raise error, "Property value wrong - got %d/%d" % (o.LongProp,o.IntProp)
check = 3 *10 **9
o.ULongProp = check
if o.ULongProp != check:
raise error, "Property value wrong - got %d (expected %d)" % (o.ULongProp, check)
# currency.
pythoncom.__future_currency__ = 1
if o.CurrencyProp != 0:
raise error, "Expecting 0, got %r" % (o.CurrencyProp,)
try:
import decimal
except ImportError:
import win32com.decimal_23 as decimal
for val in ("1234.5678", "1234.56", "1234"):
o.CurrencyProp = decimal.Decimal(val)
if o.CurrencyProp != decimal.Decimal(val):
raise error, "%s got %r" % (val, o.CurrencyProp)
v1 = decimal.Decimal("1234.5678")
TestApplyResult(o.DoubleCurrency, (v1,), v1*2)
TestApplyResult(o.DoubleCurrencyByVal, (v1,), v1*2)
v2 = decimal.Decimal("9012.3456")
TestApplyResult(o.AddCurrencies, (v1, v2), v1+v2)
o.SetParamProp(0, 1)
if o.ParamProp(0) != 1:
raise RuntimeError, o.paramProp(0)
# Do the connection point thing...
# Create a connection object.
progress("Testing connection points")
sessions = []
o = win32com.client.DispatchWithEvents( o, RandomEventHandler)
o._Init()
try:
for i in range(3):
session = o.Start()
sessions.append(session)
time.sleep(.5)
finally:
# Stop the servers
for session in sessions:
o.Stop(session)
o._DumpFireds()
progress("Finished generated .py test.")
def TestCounter(counter, bIsGenerated):
# Test random access into container
progress("Testing counter", `counter`)
import random
for i in xrange(50):
num = int(random.random() * len(counter))
try:
ret = counter[num]
if ret != num+1:
raise error, "Random access into element %d failed - return was %s" % (num,`ret`)
except IndexError:
raise error, "** IndexError accessing collection element %d" % num
num = 0
if bIsGenerated:
counter.SetTestProperty(1)
counter.TestProperty = 1 # Note this has a second, default arg.
counter.SetTestProperty(1,2)
if counter.TestPropertyWithDef != 0:
raise error, "Unexpected property set value!"
if counter.TestPropertyNoDef(1) != 1:
raise error, "Unexpected property set value!"
else:
pass
# counter.TestProperty = 1
counter.LBound=1
counter.UBound=10
if counter.LBound <> 1 or counter.UBound<>10:
print "** Error - counter did not keep its properties"
if bIsGenerated:
bounds = counter.GetBounds()
if bounds[0]<>1 or bounds[1]<>10:
raise error, "** Error - counter did not give the same properties back"
counter.SetBounds(bounds[0], bounds[1])
for item in counter:
num = num + 1
if num <> len(counter):
raise error, "*** Length of counter and loop iterations dont match ***"
if num <> 10:
raise error, "*** Unexpected number of loop iterations ***"
counter = counter._enum_.Clone() # Test Clone() and enum directly
counter.Reset()
num = 0
for item in counter:
num = num + 1
if num <> 10:
raise error, "*** Unexpected number of loop iterations - got %d ***" % num
progress("Finished testing counter")
def TestLocalVTable(ob):
# Python doesn't fully implement this interface.
if ob.DoubleString("foo") != "foofoo":
raise error("couldn't foofoo")
###############################
##
## Some vtable tests of the interface
##
def TestVTable(clsctx=pythoncom.CLSCTX_ALL):
# Any vtable interfaces marked as dual *should* be able to be
# correctly implemented as IDispatch.
ob = win32com.client.Dispatch("Python.Test.PyCOMTest")
TestLocalVTable(ob)
# Now test it via vtable - use some C++ code to help here as Python can't do it directly yet.
tester = win32com.client.Dispatch("PyCOMTest.PyCOMTest")
testee = pythoncom.CoCreateInstance("Python.Test.PyCOMTest", None, clsctx, pythoncom.IID_IUnknown)
# check we fail gracefully with None passed.
try:
tester.TestMyInterface(None)
except pythoncom.com_error, details:
pass
# and a real object.
tester.TestMyInterface(testee)
def TestVTable2():
# We once crashed creating our object with the native interface as
# the first IID specified. We must do it _after_ the tests, so that
# Python has already had the gateway registered from last run.
ob = win32com.client.Dispatch("Python.Test.PyCOMTest")
iid = pythoncom.InterfaceNames["IPyCOMTest"]
clsid = "Python.Test.PyCOMTest"
clsctx = pythoncom.CLSCTX_SERVER
try:
testee = pythoncom.CoCreateInstance(clsid, None, clsctx, iid)
except TypeError:
# Python can't actually _use_ this interface yet, so this is
# "expected". Any COM error is not.
pass
def TestVTableMI():
clsctx = pythoncom.CLSCTX_SERVER
ob = pythoncom.CoCreateInstance("Python.Test.PyCOMTestMI", None, clsctx, pythoncom.IID_IUnknown)
# This inherits from IStream.
ob.QueryInterface(pythoncom.IID_IStream)
# This implements IStorage, specifying the IID as a string
ob.QueryInterface(pythoncom.IID_IStorage)
# IDispatch should always work
ob.QueryInterface(pythoncom.IID_IDispatch)
iid = pythoncom.InterfaceNames["IPyCOMTest"]
try:
ob.QueryInterface(iid)
except TypeError:
# Python can't actually _use_ this interface yet, so this is
# "expected". Any COM error is not.
pass
def TestQueryInterface(long_lived_server = 0, iterations=5):
tester = win32com.client.Dispatch("PyCOMTest.PyCOMTest")
if long_lived_server:
# Create a local server
t0 = win32com.client.Dispatch("Python.Test.PyCOMTest", clsctx=pythoncom.CLSCTX_LOCAL_SERVER)
# Request custom interfaces a number of times
prompt = [
"Testing QueryInterface without long-lived local-server #%d of %d...",
"Testing QueryInterface with long-lived local-server #%d of %d..."
]
for i in range(iterations):
progress(prompt[long_lived_server!=0] % (i+1, iterations))
tester.TestQueryInterface()
class Tester(win32com.test.util.TestCase):
def testVTableInProc(self):
# We used to crash running this the second time - do it a few times
for i in range(3):
progress("Testing VTables in-process #%d..." % (i+1))
TestVTable(pythoncom.CLSCTX_INPROC_SERVER)
def testVTableLocalServer(self):
for i in range(3):
progress("Testing VTables out-of-process #%d..." % (i+1))
TestVTable(pythoncom.CLSCTX_LOCAL_SERVER)
def testVTable2(self):
for i in range(3):
TestVTable2()
def testVTableMI(self):
for i in range(3):
TestVTableMI()
def testMultiQueryInterface(self):
TestQueryInterface(0,6)
# When we use the custom interface in the presence of a long-lived
# local server, i.e. a local server that is already running when
# we request an instance of our COM object, and remains afterwards,
# then after repeated requests to create an instance of our object
# the custom interface disappears -- i.e. QueryInterface fails with
# E_NOINTERFACE. Set the upper range of the following test to 2 to
# pass this test, i.e. TestQueryInterface(1,2)
TestQueryInterface(1,6)
def testDynamic(self):
TestDynamic()
def testGenerated(self):
TestGenerated()
if __name__=='__main__':
# XXX - todo - Complete hack to crank threading support.
# Should NOT be necessary
def NullThreadFunc():
pass
import thread
thread.start_new( NullThreadFunc, () )
if "-v" in sys.argv: verbose = 1
win32com.test.util.testmain()
| apache-2.0 |
CapOM/ChromiumGStreamerBackend | tools/telemetry/third_party/gsutilz/third_party/boto/boto/cloudsearch/layer2.py | 153 | 3010 | # Copyright (c) 2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates.
# All Rights Reserved
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
from boto.cloudsearch.layer1 import Layer1
from boto.cloudsearch.domain import Domain
class Layer2(object):
def __init__(self, aws_access_key_id=None, aws_secret_access_key=None,
is_secure=True, port=None, proxy=None, proxy_port=None,
host=None, debug=0, session_token=None, region=None,
validate_certs=True):
self.layer1 = Layer1(
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
is_secure=is_secure,
port=port,
proxy=proxy,
proxy_port=proxy_port,
host=host,
debug=debug,
security_token=session_token,
region=region,
validate_certs=validate_certs)
def list_domains(self, domain_names=None):
"""
Return a list of :class:`boto.cloudsearch.domain.Domain`
objects for each domain defined in the current account.
"""
domain_data = self.layer1.describe_domains(domain_names)
return [Domain(self.layer1, data) for data in domain_data]
def create_domain(self, domain_name):
"""
Create a new CloudSearch domain and return the corresponding
:class:`boto.cloudsearch.domain.Domain` object.
"""
data = self.layer1.create_domain(domain_name)
return Domain(self.layer1, data)
def lookup(self, domain_name):
"""
Lookup a single domain
:param domain_name: The name of the domain to look up
:type domain_name: str
:return: Domain object, or None if the domain isn't found
:rtype: :class:`boto.cloudsearch.domain.Domain`
"""
domains = self.list_domains(domain_names=[domain_name])
if len(domains) > 0:
return domains[0]
| bsd-3-clause |
wuvt/wuvt-site | wuvt/forms.py | 1 | 1166 | from flask import current_app
from flask_wtf import FlaskForm
from wtforms import BooleanField, StringField, ValidationError, validators
from .view_utils import slugify
def strip_field(val):
if isinstance(val, str):
return val.strip()
else:
return val
def slugify_field(val):
if isinstance(val, str):
return slugify(val)
else:
return val
class PageForm(FlaskForm):
title = StringField('Title', filters=[strip_field],
validators=[validators.Length(min=1, max=255),
validators.DataRequired()])
slug = StringField('Slug', filters=[slugify_field])
section = StringField('Section', validators=[validators.DataRequired()])
published = BooleanField('Published', default=False)
content = StringField('Content', filters=[strip_field],
validators=[validators.DataRequired()])
def validate_section(self, field):
for section in current_app.config['NAV_TOP_SECTIONS']:
if section['menu'] == field.data:
return
raise ValidationError("The specified section must exist.")
| agpl-3.0 |
pekeler/arangodb | 3rdParty/V8-4.3.61/third_party/python_26/Lib/site-packages/win32/Demos/CreateFileTransacted_MiniVersion.py | 17 | 2598 | """
This demonstrates the creation of miniversions of a file during a transaction.
The FSCTL_TXFS_CREATE_MINIVERSION control code saves any changes to a new
miniversion (effectively a savepoint within a transaction).
"""
import win32file, win32api, win32transaction
import win32con, winioctlcon
import struct
"""
Definition of buffer used with FSCTL_TXFS_CREATE_MINIVERSION:
typedef struct _TXFS_CREATE_MINIVERSION_INFO{
USHORT StructureVersion;
USHORT StructureLength;
ULONG BaseVersion;
USHORT MiniVersion;}
"""
buf_fmt='HHLH0L' ## buffer size must include struct padding
buf_size=struct.calcsize(buf_fmt)
tempdir=win32api.GetTempPath()
tempfile=win32api.GetTempFileName(tempdir,'cft')[0]
print tempfile
f=open(tempfile,'w')
f.write('This is original file.\n')
f.close()
trans=win32transaction.CreateTransaction(Description='Test creating miniversions of a file')
hfile=win32file.CreateFileW(tempfile, win32con.GENERIC_READ|win32con.GENERIC_WRITE,
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans)
win32file.WriteFile(hfile, 'This is first miniversion.\n')
buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,'',buf_size,None)
struct_ver, struct_len, base_ver, ver_1=struct.unpack(buf_fmt, buf)
win32file.SetFilePointer(hfile, 0, win32con.FILE_BEGIN)
win32file.WriteFile(hfile, 'This is second miniversion!\n')
buf=win32file.DeviceIoControl(hfile, winioctlcon.FSCTL_TXFS_CREATE_MINIVERSION,'',buf_size,None)
struct_ver, struct_len, base_ver, ver_2=struct.unpack(buf_fmt, buf)
hfile.Close()
## miniversions can't be opened with write access
hfile_0=win32file.CreateFileW(tempfile, win32con.GENERIC_READ,
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans, MiniVersion=base_ver)
print 'version:',base_ver,win32file.ReadFile(hfile_0, 100)
hfile_0.Close()
hfile_1=win32file.CreateFileW(tempfile, win32con.GENERIC_READ,
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans, MiniVersion=ver_1)
print 'version:',ver_1,win32file.ReadFile(hfile_1, 100)
hfile_1.Close()
hfile_2=win32file.CreateFileW(tempfile, win32con.GENERIC_READ,
win32con.FILE_SHARE_READ|win32con.FILE_SHARE_WRITE,
None, win32con.OPEN_EXISTING, 0 , None, Transaction=trans, MiniVersion=ver_2)
print 'version:',ver_2,win32file.ReadFile(hfile_2, 100)
hfile_2.Close()
## MiniVersions are destroyed when transaction is committed or rolled back
win32transaction.CommitTransaction(trans)
| apache-2.0 |
repotvsupertuga/tvsupertuga.repository | instal/script.module.schism.common/lib/js2py/constructors/jsfunction.py | 33 | 1485 | from js2py.base import *
try:
from js2py.translators.translator import translate_js
except:
pass
@Js
def Function():
# convert arguments to python list of strings
a = [e.to_string().value for e in arguments.to_list()]
body = ';'
args = ()
if len(a):
body = '%s;' % a[-1]
args = a[:-1]
# translate this function to js inline function
js_func = '(function (%s) {%s})' % (','.join(args), body)
# now translate js inline to python function
py_func = translate_js(js_func, '')
# add set func scope to global scope
# a but messy solution but works :)
globals()['var'] = PyJs.GlobalObject
# define py function and return it
temp = executor(py_func, globals())
temp.source = '{%s}'%body
temp.func_name = 'anonymous'
return temp
def executor(f, glob):
exec f in globals()
return globals()['PyJs_anonymous_0_']
#new statement simply calls Function
Function.create = Function
#set constructor property inside FunctionPrototype
fill_in_props(FunctionPrototype, {'constructor':Function}, default_attrs)
#attach prototype to Function constructor
Function.define_own_property('prototype', {'value': FunctionPrototype,
'enumerable': False,
'writable': False,
'configurable': False})
#Fix Function length (its 0 and should be 1)
Function.own['length']['value'] = Js(1)
| gpl-2.0 |
sachdevs/rmc | server/log_handler.py | 7 | 2906 | """Custom log handler for posting log messages to HipChat.
Adapted from https://gist.github.com/3176710
The API documentation is available at
https://www.hipchat.com/docs/api/method/rooms/message
The room id can be found by going to
https://{{your-account}}.hipchat.com/rooms/ids
The tokens can be set at https://{{your-account}}.hipchat.com/admin/api
Dependencies: Requests (http://docs.python-requests.org)
"""
import sys
import requests
import logging
class HipChatHandler(logging.Handler):
"""Log handler used to send notifications to HipChat"""
HIPCHAT_API_URL = 'https://api.hipchat.com/v1/rooms/message'
def __init__(self, token, room,
sender='Flask', notify=False, color='yellow', colors={}):
"""
:param token: the auth token for access to the API - see hipchat.com
:param room: the numerical id of the room to send the message to
:param sender (optional): the 'from' property of the message - appears
in the HipChat window
:param notify (optional): if True, HipChat pings / bleeps / flashes
when message is received
:param color (optional): sets the background color of the message in
the HipChat window
:param colors (optional): a dict of level:color pairs (eg.
{'DEBUG:'red'} used to override the default color)
"""
logging.Handler.__init__(self)
self.token = token
self.room = room
self.sender = sender
self.notify = notify
self.color = color
self.colors = colors
def emit(self, record):
"""Sends the record info to HipChat."""
if not self.token:
return
try:
# use a custom level-based color from self.colors, if it exists in
# the dict
color = self.colors.get(record.levelname, self.color)
msg = str(self.format(record))
if record.exc_info:
msg += "\n%s" % logging._defaultFormatter.formatException(
record.exc_info)
r = self._sendToHipChat(msg, color, self.notify)
# use print, not logging, as that would introduce a circular
# reference
print 'Message sent to room {0}: {1}\nResponse: {2}'.format(
self.room, record.getMessage(), r.text)
except:
print sys.exc_info()[1]
self.handleError(record)
def _sendToHipChat(self, msg, color, notify):
"""Does the actual sending of the message."""
payload = {
'auth_token': self.token,
'notify': 1 if notify else 0,
'color': color,
'from': self.sender,
'room_id': self.room,
'message': msg,
'message_format': 'text',
}
return requests.post(self.HIPCHAT_API_URL, msg, params=payload)
| mit |
tkanemoto/kombu | kombu/tests/transport/test_sqlalchemy.py | 9 | 2137 | from __future__ import absolute_import
from kombu import Connection
from kombu.tests.case import Case, SkipTest, patch, case_requires
@case_requires('sqlalchemy')
class test_sqlalchemy(Case):
def test_url_parser(self):
with patch('kombu.transport.sqlalchemy.Channel._open'):
url = 'sqlalchemy+sqlite:///celerydb.sqlite'
Connection(url).connect()
url = 'sqla+sqlite:///celerydb.sqlite'
Connection(url).connect()
# Should prevent regression fixed by f187ccd
url = 'sqlb+sqlite:///celerydb.sqlite'
with self.assertRaises(KeyError):
Connection(url).connect()
def test_simple_queueing(self):
conn = Connection('sqlalchemy+sqlite:///:memory:')
conn.connect()
channel = conn.channel()
self.assertEqual(
channel.queue_cls.__table__.name,
'kombu_queue'
)
self.assertEqual(
channel.message_cls.__table__.name,
'kombu_message'
)
channel._put('celery', 'DATA')
assert channel._get('celery') == 'DATA'
def test_custom_table_names(self):
raise SkipTest('causes global side effect')
conn = Connection('sqlalchemy+sqlite:///:memory:', transport_options={
'queue_tablename': 'my_custom_queue',
'message_tablename': 'my_custom_message'
})
conn.connect()
channel = conn.channel()
self.assertEqual(
channel.queue_cls.__table__.name,
'my_custom_queue'
)
self.assertEqual(
channel.message_cls.__table__.name,
'my_custom_message'
)
channel._put('celery', 'DATA')
assert channel._get('celery') == 'DATA'
def test_clone(self):
hostname = 'sqlite:///celerydb.sqlite'
x = Connection('+'.join(['sqla', hostname]))
self.assertEqual(x.uri_prefix, 'sqla')
self.assertEqual(x.hostname, hostname)
clone = x.clone()
self.assertEqual(clone.hostname, hostname)
self.assertEqual(clone.uri_prefix, 'sqla')
| bsd-3-clause |
mugizico/scikit-learn | sklearn/linear_model/stochastic_gradient.py | 130 | 50966 | # Authors: Peter Prettenhofer <peter.prettenhofer@gmail.com> (main author)
# Mathieu Blondel (partial_fit support)
#
# License: BSD 3 clause
"""Classification and regression using Stochastic Gradient Descent (SGD)."""
import numpy as np
import scipy.sparse as sp
from abc import ABCMeta, abstractmethod
from ..externals.joblib import Parallel, delayed
from .base import LinearClassifierMixin, SparseCoefMixin
from ..base import BaseEstimator, RegressorMixin
from ..feature_selection.from_model import _LearntSelectorMixin
from ..utils import (check_array, check_random_state, check_X_y,
deprecated)
from ..utils.extmath import safe_sparse_dot
from ..utils.multiclass import _check_partial_fit_first_call
from ..utils.validation import check_is_fitted
from ..externals import six
from .sgd_fast import plain_sgd, average_sgd
from ..utils.fixes import astype
from ..utils.seq_dataset import ArrayDataset, CSRDataset
from ..utils import compute_class_weight
from .sgd_fast import Hinge
from .sgd_fast import SquaredHinge
from .sgd_fast import Log
from .sgd_fast import ModifiedHuber
from .sgd_fast import SquaredLoss
from .sgd_fast import Huber
from .sgd_fast import EpsilonInsensitive
from .sgd_fast import SquaredEpsilonInsensitive
LEARNING_RATE_TYPES = {"constant": 1, "optimal": 2, "invscaling": 3,
"pa1": 4, "pa2": 5}
PENALTY_TYPES = {"none": 0, "l2": 2, "l1": 1, "elasticnet": 3}
SPARSE_INTERCEPT_DECAY = 0.01
"""For sparse data intercept updates are scaled by this decay factor to avoid
intercept oscillation."""
DEFAULT_EPSILON = 0.1
"""Default value of ``epsilon`` parameter. """
class BaseSGD(six.with_metaclass(ABCMeta, BaseEstimator, SparseCoefMixin)):
"""Base class for SGD classification and regression."""
def __init__(self, loss, penalty='l2', alpha=0.0001, C=1.0,
l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True,
verbose=0, epsilon=0.1, random_state=None,
learning_rate="optimal", eta0=0.0, power_t=0.5,
warm_start=False, average=False):
self.loss = loss
self.penalty = penalty
self.learning_rate = learning_rate
self.epsilon = epsilon
self.alpha = alpha
self.C = C
self.l1_ratio = l1_ratio
self.fit_intercept = fit_intercept
self.n_iter = n_iter
self.shuffle = shuffle
self.random_state = random_state
self.verbose = verbose
self.eta0 = eta0
self.power_t = power_t
self.warm_start = warm_start
self.average = average
self._validate_params()
self.coef_ = None
if self.average > 0:
self.standard_coef_ = None
self.average_coef_ = None
# iteration count for learning rate schedule
# must not be int (e.g. if ``learning_rate=='optimal'``)
self.t_ = None
def set_params(self, *args, **kwargs):
super(BaseSGD, self).set_params(*args, **kwargs)
self._validate_params()
return self
@abstractmethod
def fit(self, X, y):
"""Fit model."""
def _validate_params(self):
"""Validate input params. """
if not isinstance(self.shuffle, bool):
raise ValueError("shuffle must be either True or False")
if self.n_iter <= 0:
raise ValueError("n_iter must be > zero")
if not (0.0 <= self.l1_ratio <= 1.0):
raise ValueError("l1_ratio must be in [0, 1]")
if self.alpha < 0.0:
raise ValueError("alpha must be >= 0")
if self.learning_rate in ("constant", "invscaling"):
if self.eta0 <= 0.0:
raise ValueError("eta0 must be > 0")
# raises ValueError if not registered
self._get_penalty_type(self.penalty)
self._get_learning_rate_type(self.learning_rate)
if self.loss not in self.loss_functions:
raise ValueError("The loss %s is not supported. " % self.loss)
def _get_loss_function(self, loss):
"""Get concrete ``LossFunction`` object for str ``loss``. """
try:
loss_ = self.loss_functions[loss]
loss_class, args = loss_[0], loss_[1:]
if loss in ('huber', 'epsilon_insensitive',
'squared_epsilon_insensitive'):
args = (self.epsilon, )
return loss_class(*args)
except KeyError:
raise ValueError("The loss %s is not supported. " % loss)
def _get_learning_rate_type(self, learning_rate):
try:
return LEARNING_RATE_TYPES[learning_rate]
except KeyError:
raise ValueError("learning rate %s "
"is not supported. " % learning_rate)
def _get_penalty_type(self, penalty):
penalty = str(penalty).lower()
try:
return PENALTY_TYPES[penalty]
except KeyError:
raise ValueError("Penalty %s is not supported. " % penalty)
def _validate_sample_weight(self, sample_weight, n_samples):
"""Set the sample weight array."""
if sample_weight is None:
# uniform sample weights
sample_weight = np.ones(n_samples, dtype=np.float64, order='C')
else:
# user-provided array
sample_weight = np.asarray(sample_weight, dtype=np.float64,
order="C")
if sample_weight.shape[0] != n_samples:
raise ValueError("Shapes of X and sample_weight do not match.")
return sample_weight
def _allocate_parameter_mem(self, n_classes, n_features, coef_init=None,
intercept_init=None):
"""Allocate mem for parameters; initialize if provided."""
if n_classes > 2:
# allocate coef_ for multi-class
if coef_init is not None:
coef_init = np.asarray(coef_init, order="C")
if coef_init.shape != (n_classes, n_features):
raise ValueError("Provided ``coef_`` does not match dataset. ")
self.coef_ = coef_init
else:
self.coef_ = np.zeros((n_classes, n_features),
dtype=np.float64, order="C")
# allocate intercept_ for multi-class
if intercept_init is not None:
intercept_init = np.asarray(intercept_init, order="C")
if intercept_init.shape != (n_classes, ):
raise ValueError("Provided intercept_init "
"does not match dataset.")
self.intercept_ = intercept_init
else:
self.intercept_ = np.zeros(n_classes, dtype=np.float64,
order="C")
else:
# allocate coef_ for binary problem
if coef_init is not None:
coef_init = np.asarray(coef_init, dtype=np.float64,
order="C")
coef_init = coef_init.ravel()
if coef_init.shape != (n_features,):
raise ValueError("Provided coef_init does not "
"match dataset.")
self.coef_ = coef_init
else:
self.coef_ = np.zeros(n_features,
dtype=np.float64,
order="C")
# allocate intercept_ for binary problem
if intercept_init is not None:
intercept_init = np.asarray(intercept_init, dtype=np.float64)
if intercept_init.shape != (1,) and intercept_init.shape != ():
raise ValueError("Provided intercept_init "
"does not match dataset.")
self.intercept_ = intercept_init.reshape(1,)
else:
self.intercept_ = np.zeros(1, dtype=np.float64, order="C")
# initialize average parameters
if self.average > 0:
self.standard_coef_ = self.coef_
self.standard_intercept_ = self.intercept_
self.average_coef_ = np.zeros(self.coef_.shape,
dtype=np.float64,
order="C")
self.average_intercept_ = np.zeros(self.standard_intercept_.shape,
dtype=np.float64,
order="C")
def _make_dataset(X, y_i, sample_weight):
"""Create ``Dataset`` abstraction for sparse and dense inputs.
This also returns the ``intercept_decay`` which is different
for sparse datasets.
"""
if sp.issparse(X):
dataset = CSRDataset(X.data, X.indptr, X.indices, y_i, sample_weight)
intercept_decay = SPARSE_INTERCEPT_DECAY
else:
dataset = ArrayDataset(X, y_i, sample_weight)
intercept_decay = 1.0
return dataset, intercept_decay
def _prepare_fit_binary(est, y, i):
"""Initialization for fit_binary.
Returns y, coef, intercept.
"""
y_i = np.ones(y.shape, dtype=np.float64, order="C")
y_i[y != est.classes_[i]] = -1.0
average_intercept = 0
average_coef = None
if len(est.classes_) == 2:
if not est.average:
coef = est.coef_.ravel()
intercept = est.intercept_[0]
else:
coef = est.standard_coef_.ravel()
intercept = est.standard_intercept_[0]
average_coef = est.average_coef_.ravel()
average_intercept = est.average_intercept_[0]
else:
if not est.average:
coef = est.coef_[i]
intercept = est.intercept_[i]
else:
coef = est.standard_coef_[i]
intercept = est.standard_intercept_[i]
average_coef = est.average_coef_[i]
average_intercept = est.average_intercept_[i]
return y_i, coef, intercept, average_coef, average_intercept
def fit_binary(est, i, X, y, alpha, C, learning_rate, n_iter,
pos_weight, neg_weight, sample_weight):
"""Fit a single binary classifier.
The i'th class is considered the "positive" class.
"""
# if average is not true, average_coef, and average_intercept will be
# unused
y_i, coef, intercept, average_coef, average_intercept = \
_prepare_fit_binary(est, y, i)
assert y_i.shape[0] == y.shape[0] == sample_weight.shape[0]
dataset, intercept_decay = _make_dataset(X, y_i, sample_weight)
penalty_type = est._get_penalty_type(est.penalty)
learning_rate_type = est._get_learning_rate_type(learning_rate)
# XXX should have random_state_!
random_state = check_random_state(est.random_state)
# numpy mtrand expects a C long which is a signed 32 bit integer under
# Windows
seed = random_state.randint(0, np.iinfo(np.int32).max)
if not est.average:
return plain_sgd(coef, intercept, est.loss_function,
penalty_type, alpha, C, est.l1_ratio,
dataset, n_iter, int(est.fit_intercept),
int(est.verbose), int(est.shuffle), seed,
pos_weight, neg_weight,
learning_rate_type, est.eta0,
est.power_t, est.t_, intercept_decay)
else:
standard_coef, standard_intercept, average_coef, \
average_intercept = average_sgd(coef, intercept, average_coef,
average_intercept,
est.loss_function, penalty_type,
alpha, C, est.l1_ratio, dataset,
n_iter, int(est.fit_intercept),
int(est.verbose), int(est.shuffle),
seed, pos_weight, neg_weight,
learning_rate_type, est.eta0,
est.power_t, est.t_,
intercept_decay,
est.average)
if len(est.classes_) == 2:
est.average_intercept_[0] = average_intercept
else:
est.average_intercept_[i] = average_intercept
return standard_coef, standard_intercept
class BaseSGDClassifier(six.with_metaclass(ABCMeta, BaseSGD,
LinearClassifierMixin)):
loss_functions = {
"hinge": (Hinge, 1.0),
"squared_hinge": (SquaredHinge, 1.0),
"perceptron": (Hinge, 0.0),
"log": (Log, ),
"modified_huber": (ModifiedHuber, ),
"squared_loss": (SquaredLoss, ),
"huber": (Huber, DEFAULT_EPSILON),
"epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON),
"squared_epsilon_insensitive": (SquaredEpsilonInsensitive,
DEFAULT_EPSILON),
}
@abstractmethod
def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15,
fit_intercept=True, n_iter=5, shuffle=True, verbose=0,
epsilon=DEFAULT_EPSILON, n_jobs=1, random_state=None,
learning_rate="optimal", eta0=0.0, power_t=0.5,
class_weight=None, warm_start=False, average=False):
super(BaseSGDClassifier, self).__init__(loss=loss, penalty=penalty,
alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept,
n_iter=n_iter, shuffle=shuffle,
verbose=verbose,
epsilon=epsilon,
random_state=random_state,
learning_rate=learning_rate,
eta0=eta0, power_t=power_t,
warm_start=warm_start,
average=average)
self.class_weight = class_weight
self.classes_ = None
self.n_jobs = int(n_jobs)
def _partial_fit(self, X, y, alpha, C,
loss, learning_rate, n_iter,
classes, sample_weight,
coef_init, intercept_init):
X, y = check_X_y(X, y, 'csr', dtype=np.float64, order="C")
n_samples, n_features = X.shape
self._validate_params()
_check_partial_fit_first_call(self, classes)
n_classes = self.classes_.shape[0]
# Allocate datastructures from input arguments
self._expanded_class_weight = compute_class_weight(self.class_weight,
self.classes_, y)
sample_weight = self._validate_sample_weight(sample_weight, n_samples)
if self.coef_ is None or coef_init is not None:
self._allocate_parameter_mem(n_classes, n_features,
coef_init, intercept_init)
elif n_features != self.coef_.shape[-1]:
raise ValueError("Number of features %d does not match previous data %d."
% (n_features, self.coef_.shape[-1]))
self.loss_function = self._get_loss_function(loss)
if self.t_ is None:
self.t_ = 1.0
# delegate to concrete training procedure
if n_classes > 2:
self._fit_multiclass(X, y, alpha=alpha, C=C,
learning_rate=learning_rate,
sample_weight=sample_weight, n_iter=n_iter)
elif n_classes == 2:
self._fit_binary(X, y, alpha=alpha, C=C,
learning_rate=learning_rate,
sample_weight=sample_weight, n_iter=n_iter)
else:
raise ValueError("The number of class labels must be "
"greater than one.")
return self
def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None,
intercept_init=None, sample_weight=None):
if hasattr(self, "classes_"):
self.classes_ = None
X, y = check_X_y(X, y, 'csr', dtype=np.float64, order="C")
n_samples, n_features = X.shape
# labels can be encoded as float, int, or string literals
# np.unique sorts in asc order; largest class id is positive class
classes = np.unique(y)
if self.warm_start and self.coef_ is not None:
if coef_init is None:
coef_init = self.coef_
if intercept_init is None:
intercept_init = self.intercept_
else:
self.coef_ = None
self.intercept_ = None
if self.average > 0:
self.standard_coef_ = self.coef_
self.standard_intercept_ = self.intercept_
self.average_coef_ = None
self.average_intercept_ = None
# Clear iteration count for multiple call to fit.
self.t_ = None
self._partial_fit(X, y, alpha, C, loss, learning_rate, self.n_iter,
classes, sample_weight, coef_init, intercept_init)
return self
def _fit_binary(self, X, y, alpha, C, sample_weight,
learning_rate, n_iter):
"""Fit a binary classifier on X and y. """
coef, intercept = fit_binary(self, 1, X, y, alpha, C,
learning_rate, n_iter,
self._expanded_class_weight[1],
self._expanded_class_weight[0],
sample_weight)
self.t_ += n_iter * X.shape[0]
# need to be 2d
if self.average > 0:
if self.average <= self.t_ - 1:
self.coef_ = self.average_coef_.reshape(1, -1)
self.intercept_ = self.average_intercept_
else:
self.coef_ = self.standard_coef_.reshape(1, -1)
self.standard_intercept_ = np.atleast_1d(intercept)
self.intercept_ = self.standard_intercept_
else:
self.coef_ = coef.reshape(1, -1)
# intercept is a float, need to convert it to an array of length 1
self.intercept_ = np.atleast_1d(intercept)
def _fit_multiclass(self, X, y, alpha, C, learning_rate,
sample_weight, n_iter):
"""Fit a multi-class classifier by combining binary classifiers
Each binary classifier predicts one class versus all others. This
strategy is called OVA: One Versus All.
"""
# Use joblib to fit OvA in parallel.
result = Parallel(n_jobs=self.n_jobs, backend="threading",
verbose=self.verbose)(
delayed(fit_binary)(self, i, X, y, alpha, C, learning_rate,
n_iter, self._expanded_class_weight[i], 1.,
sample_weight)
for i in range(len(self.classes_)))
for i, (_, intercept) in enumerate(result):
self.intercept_[i] = intercept
self.t_ += n_iter * X.shape[0]
if self.average > 0:
if self.average <= self.t_ - 1.0:
self.coef_ = self.average_coef_
self.intercept_ = self.average_intercept_
else:
self.coef_ = self.standard_coef_
self.standard_intercept_ = np.atleast_1d(intercept)
self.intercept_ = self.standard_intercept_
def partial_fit(self, X, y, classes=None, sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Subset of the training data
y : numpy array, shape (n_samples,)
Subset of the target values
classes : array, shape (n_classes,)
Classes across all calls to partial_fit.
Can be obtained by via `np.unique(y_all)`, where y_all is the
target vector of the entire dataset.
This argument is required for the first call to partial_fit
and can be omitted in the subsequent calls.
Note that y doesn't need to contain all labels in `classes`.
sample_weight : array-like, shape (n_samples,), optional
Weights applied to individual samples.
If not provided, uniform weights are assumed.
Returns
-------
self : returns an instance of self.
"""
if self.class_weight in ['balanced', 'auto']:
raise ValueError("class_weight '{0}' is not supported for "
"partial_fit. In order to use 'balanced' weights, "
"use compute_class_weight('{0}', classes, y). "
"In place of y you can us a large enough sample "
"of the full training set target to properly "
"estimate the class frequency distributions. "
"Pass the resulting weights as the class_weight "
"parameter.".format(self.class_weight))
return self._partial_fit(X, y, alpha=self.alpha, C=1.0, loss=self.loss,
learning_rate=self.learning_rate, n_iter=1,
classes=classes, sample_weight=sample_weight,
coef_init=None, intercept_init=None)
def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : numpy array, shape (n_samples,)
Target values
coef_init : array, shape (n_classes, n_features)
The initial coefficients to warm-start the optimization.
intercept_init : array, shape (n_classes,)
The initial intercept to warm-start the optimization.
sample_weight : array-like, shape (n_samples,), optional
Weights applied to individual samples.
If not provided, uniform weights are assumed. These weights will
be multiplied with class_weight (passed through the
contructor) if class_weight is specified
Returns
-------
self : returns an instance of self.
"""
return self._fit(X, y, alpha=self.alpha, C=1.0,
loss=self.loss, learning_rate=self.learning_rate,
coef_init=coef_init, intercept_init=intercept_init,
sample_weight=sample_weight)
class SGDClassifier(BaseSGDClassifier, _LearntSelectorMixin):
"""Linear classifiers (SVM, logistic regression, a.o.) with SGD training.
This estimator implements regularized linear models with stochastic
gradient descent (SGD) learning: the gradient of the loss is estimated
each sample at a time and the model is updated along the way with a
decreasing strength schedule (aka learning rate). SGD allows minibatch
(online/out-of-core) learning, see the partial_fit method.
For best results using the default learning rate schedule, the data should
have zero mean and unit variance.
This implementation works with data represented as dense or sparse arrays
of floating point values for the features. The model it fits can be
controlled with the loss parameter; by default, it fits a linear support
vector machine (SVM).
The regularizer is a penalty added to the loss function that shrinks model
parameters towards the zero vector using either the squared euclidean norm
L2 or the absolute norm L1 or a combination of both (Elastic Net). If the
parameter update crosses the 0.0 value because of the regularizer, the
update is truncated to 0.0 to allow for learning sparse models and achieve
online feature selection.
Read more in the :ref:`User Guide <sgd>`.
Parameters
----------
loss : str, 'hinge', 'log', 'modified_huber', 'squared_hinge',\
'perceptron', or a regression loss: 'squared_loss', 'huber',\
'epsilon_insensitive', or 'squared_epsilon_insensitive'
The loss function to be used. Defaults to 'hinge', which gives a
linear SVM.
The 'log' loss gives logistic regression, a probabilistic classifier.
'modified_huber' is another smooth loss that brings tolerance to
outliers as well as probability estimates.
'squared_hinge' is like hinge but is quadratically penalized.
'perceptron' is the linear loss used by the perceptron algorithm.
The other losses are designed for regression but can be useful in
classification as well; see SGDRegressor for a description.
penalty : str, 'none', 'l2', 'l1', or 'elasticnet'
The penalty (aka regularization term) to be used. Defaults to 'l2'
which is the standard regularizer for linear SVM models. 'l1' and
'elasticnet' might bring sparsity to the model (feature selection)
not achievable with 'l2'.
alpha : float
Constant that multiplies the regularization term. Defaults to 0.0001
l1_ratio : float
The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.
l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.
Defaults to 0.15.
fit_intercept : bool
Whether the intercept should be estimated or not. If False, the
data is assumed to be already centered. Defaults to True.
n_iter : int, optional
The number of passes over the training data (aka epochs). The number
of iterations is set to 1 if using partial_fit.
Defaults to 5.
shuffle : bool, optional
Whether or not the training data should be shuffled after each epoch.
Defaults to True.
random_state : int seed, RandomState instance, or None (default)
The seed of the pseudo random number generator to use when
shuffling the data.
verbose : integer, optional
The verbosity level
epsilon : float
Epsilon in the epsilon-insensitive loss functions; only if `loss` is
'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'.
For 'huber', determines the threshold at which it becomes less
important to get the prediction exactly right.
For epsilon-insensitive, any differences between the current prediction
and the correct label are ignored if they are less than this threshold.
n_jobs : integer, optional
The number of CPUs to use to do the OVA (One Versus All, for
multi-class problems) computation. -1 means 'all CPUs'. Defaults
to 1.
learning_rate : string, optional
The learning rate schedule:
constant: eta = eta0
optimal: eta = 1.0 / (t + t0) [default]
invscaling: eta = eta0 / pow(t, power_t)
where t0 is chosen by a heuristic proposed by Leon Bottou.
eta0 : double
The initial learning rate for the 'constant' or 'invscaling'
schedules. The default value is 0.0 as eta0 is not used by the
default schedule 'optimal'.
power_t : double
The exponent for inverse scaling learning rate [default 0.5].
class_weight : dict, {class_label: weight} or "balanced" or None, optional
Preset for the class_weight fit parameter.
Weights associated with classes. If not given, all classes
are supposed to have weight one.
The "balanced" mode uses the values of y to automatically adjust
weights inversely proportional to class frequencies in the input data
as ``n_samples / (n_classes * np.bincount(y))``
warm_start : bool, optional
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
average : bool or int, optional
When set to True, computes the averaged SGD weights and stores the
result in the ``coef_`` attribute. If set to an int greater than 1,
averaging will begin once the total number of samples seen reaches
average. So average=10 will begin averaging after seeing 10 samples.
Attributes
----------
coef_ : array, shape (1, n_features) if n_classes == 2 else (n_classes,\
n_features)
Weights assigned to the features.
intercept_ : array, shape (1,) if n_classes == 2 else (n_classes,)
Constants in decision function.
Examples
--------
>>> import numpy as np
>>> from sklearn import linear_model
>>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]])
>>> Y = np.array([1, 1, 2, 2])
>>> clf = linear_model.SGDClassifier()
>>> clf.fit(X, Y)
... #doctest: +NORMALIZE_WHITESPACE
SGDClassifier(alpha=0.0001, average=False, class_weight=None, epsilon=0.1,
eta0=0.0, fit_intercept=True, l1_ratio=0.15,
learning_rate='optimal', loss='hinge', n_iter=5, n_jobs=1,
penalty='l2', power_t=0.5, random_state=None, shuffle=True,
verbose=0, warm_start=False)
>>> print(clf.predict([[-0.8, -1]]))
[1]
See also
--------
LinearSVC, LogisticRegression, Perceptron
"""
def __init__(self, loss="hinge", penalty='l2', alpha=0.0001, l1_ratio=0.15,
fit_intercept=True, n_iter=5, shuffle=True, verbose=0,
epsilon=DEFAULT_EPSILON, n_jobs=1, random_state=None,
learning_rate="optimal", eta0=0.0, power_t=0.5,
class_weight=None, warm_start=False, average=False):
super(SGDClassifier, self).__init__(
loss=loss, penalty=penalty, alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept, n_iter=n_iter, shuffle=shuffle,
verbose=verbose, epsilon=epsilon, n_jobs=n_jobs,
random_state=random_state, learning_rate=learning_rate, eta0=eta0,
power_t=power_t, class_weight=class_weight, warm_start=warm_start,
average=average)
def _check_proba(self):
check_is_fitted(self, "t_")
if self.loss not in ("log", "modified_huber"):
raise AttributeError("probability estimates are not available for"
" loss=%r" % self.loss)
@property
def predict_proba(self):
"""Probability estimates.
This method is only available for log loss and modified Huber loss.
Multiclass probability estimates are derived from binary (one-vs.-rest)
estimates by simple normalization, as recommended by Zadrozny and
Elkan.
Binary probability estimates for loss="modified_huber" are given by
(clip(decision_function(X), -1, 1) + 1) / 2.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
array, shape (n_samples, n_classes)
Returns the probability of the sample for each class in the model,
where classes are ordered as they are in `self.classes_`.
References
----------
Zadrozny and Elkan, "Transforming classifier scores into multiclass
probability estimates", SIGKDD'02,
http://www.research.ibm.com/people/z/zadrozny/kdd2002-Transf.pdf
The justification for the formula in the loss="modified_huber"
case is in the appendix B in:
http://jmlr.csail.mit.edu/papers/volume2/zhang02c/zhang02c.pdf
"""
self._check_proba()
return self._predict_proba
def _predict_proba(self, X):
if self.loss == "log":
return self._predict_proba_lr(X)
elif self.loss == "modified_huber":
binary = (len(self.classes_) == 2)
scores = self.decision_function(X)
if binary:
prob2 = np.ones((scores.shape[0], 2))
prob = prob2[:, 1]
else:
prob = scores
np.clip(scores, -1, 1, prob)
prob += 1.
prob /= 2.
if binary:
prob2[:, 0] -= prob
prob = prob2
else:
# the above might assign zero to all classes, which doesn't
# normalize neatly; work around this to produce uniform
# probabilities
prob_sum = prob.sum(axis=1)
all_zero = (prob_sum == 0)
if np.any(all_zero):
prob[all_zero, :] = 1
prob_sum[all_zero] = len(self.classes_)
# normalize
prob /= prob_sum.reshape((prob.shape[0], -1))
return prob
else:
raise NotImplementedError("predict_(log_)proba only supported when"
" loss='log' or loss='modified_huber' "
"(%r given)" % self.loss)
@property
def predict_log_proba(self):
"""Log of probability estimates.
This method is only available for log loss and modified Huber loss.
When loss="modified_huber", probability estimates may be hard zeros
and ones, so taking the logarithm is not possible.
See ``predict_proba`` for details.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Returns
-------
T : array-like, shape (n_samples, n_classes)
Returns the log-probability of the sample for each class in the
model, where classes are ordered as they are in
`self.classes_`.
"""
self._check_proba()
return self._predict_log_proba
def _predict_log_proba(self, X):
return np.log(self.predict_proba(X))
class BaseSGDRegressor(BaseSGD, RegressorMixin):
loss_functions = {
"squared_loss": (SquaredLoss, ),
"huber": (Huber, DEFAULT_EPSILON),
"epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON),
"squared_epsilon_insensitive": (SquaredEpsilonInsensitive,
DEFAULT_EPSILON),
}
@abstractmethod
def __init__(self, loss="squared_loss", penalty="l2", alpha=0.0001,
l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True,
verbose=0, epsilon=DEFAULT_EPSILON, random_state=None,
learning_rate="invscaling", eta0=0.01, power_t=0.25,
warm_start=False, average=False):
super(BaseSGDRegressor, self).__init__(loss=loss, penalty=penalty,
alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept,
n_iter=n_iter, shuffle=shuffle,
verbose=verbose,
epsilon=epsilon,
random_state=random_state,
learning_rate=learning_rate,
eta0=eta0, power_t=power_t,
warm_start=warm_start,
average=average)
def _partial_fit(self, X, y, alpha, C, loss, learning_rate,
n_iter, sample_weight,
coef_init, intercept_init):
X, y = check_X_y(X, y, "csr", copy=False, order='C', dtype=np.float64)
y = astype(y, np.float64, copy=False)
n_samples, n_features = X.shape
self._validate_params()
# Allocate datastructures from input arguments
sample_weight = self._validate_sample_weight(sample_weight, n_samples)
if self.coef_ is None:
self._allocate_parameter_mem(1, n_features,
coef_init, intercept_init)
elif n_features != self.coef_.shape[-1]:
raise ValueError("Number of features %d does not match previous data %d."
% (n_features, self.coef_.shape[-1]))
if self.average > 0 and self.average_coef_ is None:
self.average_coef_ = np.zeros(n_features,
dtype=np.float64,
order="C")
self.average_intercept_ = np.zeros(1,
dtype=np.float64,
order="C")
self._fit_regressor(X, y, alpha, C, loss, learning_rate,
sample_weight, n_iter)
return self
def partial_fit(self, X, y, sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Subset of training data
y : numpy array of shape (n_samples,)
Subset of target values
sample_weight : array-like, shape (n_samples,), optional
Weights applied to individual samples.
If not provided, uniform weights are assumed.
Returns
-------
self : returns an instance of self.
"""
return self._partial_fit(X, y, self.alpha, C=1.0,
loss=self.loss,
learning_rate=self.learning_rate, n_iter=1,
sample_weight=sample_weight,
coef_init=None, intercept_init=None)
def _fit(self, X, y, alpha, C, loss, learning_rate, coef_init=None,
intercept_init=None, sample_weight=None):
if self.warm_start and self.coef_ is not None:
if coef_init is None:
coef_init = self.coef_
if intercept_init is None:
intercept_init = self.intercept_
else:
self.coef_ = None
self.intercept_ = None
if self.average > 0:
self.standard_intercept_ = self.intercept_
self.standard_coef_ = self.coef_
self.average_coef_ = None
self.average_intercept_ = None
# Clear iteration count for multiple call to fit.
self.t_ = None
return self._partial_fit(X, y, alpha, C, loss, learning_rate,
self.n_iter, sample_weight,
coef_init, intercept_init)
def fit(self, X, y, coef_init=None, intercept_init=None,
sample_weight=None):
"""Fit linear model with Stochastic Gradient Descent.
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Training data
y : numpy array, shape (n_samples,)
Target values
coef_init : array, shape (n_features,)
The initial coefficients to warm-start the optimization.
intercept_init : array, shape (1,)
The initial intercept to warm-start the optimization.
sample_weight : array-like, shape (n_samples,), optional
Weights applied to individual samples (1. for unweighted).
Returns
-------
self : returns an instance of self.
"""
return self._fit(X, y, alpha=self.alpha, C=1.0,
loss=self.loss, learning_rate=self.learning_rate,
coef_init=coef_init,
intercept_init=intercept_init,
sample_weight=sample_weight)
@deprecated(" and will be removed in 0.19.")
def decision_function(self, X):
"""Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
array, shape (n_samples,)
Predicted target values per element in X.
"""
return self._decision_function(X)
def _decision_function(self, X):
"""Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
array, shape (n_samples,)
Predicted target values per element in X.
"""
check_is_fitted(self, ["t_", "coef_", "intercept_"], all_or_any=all)
X = check_array(X, accept_sparse='csr')
scores = safe_sparse_dot(X, self.coef_.T,
dense_output=True) + self.intercept_
return scores.ravel()
def predict(self, X):
"""Predict using the linear model
Parameters
----------
X : {array-like, sparse matrix}, shape (n_samples, n_features)
Returns
-------
array, shape (n_samples,)
Predicted target values per element in X.
"""
return self._decision_function(X)
def _fit_regressor(self, X, y, alpha, C, loss, learning_rate,
sample_weight, n_iter):
dataset, intercept_decay = _make_dataset(X, y, sample_weight)
loss_function = self._get_loss_function(loss)
penalty_type = self._get_penalty_type(self.penalty)
learning_rate_type = self._get_learning_rate_type(learning_rate)
if self.t_ is None:
self.t_ = 1.0
random_state = check_random_state(self.random_state)
# numpy mtrand expects a C long which is a signed 32 bit integer under
# Windows
seed = random_state.randint(0, np.iinfo(np.int32).max)
if self.average > 0:
self.standard_coef_, self.standard_intercept_, \
self.average_coef_, self.average_intercept_ =\
average_sgd(self.standard_coef_,
self.standard_intercept_[0],
self.average_coef_,
self.average_intercept_[0],
loss_function,
penalty_type,
alpha, C,
self.l1_ratio,
dataset,
n_iter,
int(self.fit_intercept),
int(self.verbose),
int(self.shuffle),
seed,
1.0, 1.0,
learning_rate_type,
self.eta0, self.power_t, self.t_,
intercept_decay, self.average)
self.average_intercept_ = np.atleast_1d(self.average_intercept_)
self.standard_intercept_ = np.atleast_1d(self.standard_intercept_)
self.t_ += n_iter * X.shape[0]
if self.average <= self.t_ - 1.0:
self.coef_ = self.average_coef_
self.intercept_ = self.average_intercept_
else:
self.coef_ = self.standard_coef_
self.intercept_ = self.standard_intercept_
else:
self.coef_, self.intercept_ = \
plain_sgd(self.coef_,
self.intercept_[0],
loss_function,
penalty_type,
alpha, C,
self.l1_ratio,
dataset,
n_iter,
int(self.fit_intercept),
int(self.verbose),
int(self.shuffle),
seed,
1.0, 1.0,
learning_rate_type,
self.eta0, self.power_t, self.t_,
intercept_decay)
self.t_ += n_iter * X.shape[0]
self.intercept_ = np.atleast_1d(self.intercept_)
class SGDRegressor(BaseSGDRegressor, _LearntSelectorMixin):
"""Linear model fitted by minimizing a regularized empirical loss with SGD
SGD stands for Stochastic Gradient Descent: the gradient of the loss is
estimated each sample at a time and the model is updated along the way with
a decreasing strength schedule (aka learning rate).
The regularizer is a penalty added to the loss function that shrinks model
parameters towards the zero vector using either the squared euclidean norm
L2 or the absolute norm L1 or a combination of both (Elastic Net). If the
parameter update crosses the 0.0 value because of the regularizer, the
update is truncated to 0.0 to allow for learning sparse models and achieve
online feature selection.
This implementation works with data represented as dense numpy arrays of
floating point values for the features.
Read more in the :ref:`User Guide <sgd>`.
Parameters
----------
loss : str, 'squared_loss', 'huber', 'epsilon_insensitive', \
or 'squared_epsilon_insensitive'
The loss function to be used. Defaults to 'squared_loss' which refers
to the ordinary least squares fit. 'huber' modifies 'squared_loss' to
focus less on getting outliers correct by switching from squared to
linear loss past a distance of epsilon. 'epsilon_insensitive' ignores
errors less than epsilon and is linear past that; this is the loss
function used in SVR. 'squared_epsilon_insensitive' is the same but
becomes squared loss past a tolerance of epsilon.
penalty : str, 'none', 'l2', 'l1', or 'elasticnet'
The penalty (aka regularization term) to be used. Defaults to 'l2'
which is the standard regularizer for linear SVM models. 'l1' and
'elasticnet' might bring sparsity to the model (feature selection)
not achievable with 'l2'.
alpha : float
Constant that multiplies the regularization term. Defaults to 0.0001
l1_ratio : float
The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1.
l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1.
Defaults to 0.15.
fit_intercept : bool
Whether the intercept should be estimated or not. If False, the
data is assumed to be already centered. Defaults to True.
n_iter : int, optional
The number of passes over the training data (aka epochs). The number
of iterations is set to 1 if using partial_fit.
Defaults to 5.
shuffle : bool, optional
Whether or not the training data should be shuffled after each epoch.
Defaults to True.
random_state : int seed, RandomState instance, or None (default)
The seed of the pseudo random number generator to use when
shuffling the data.
verbose : integer, optional
The verbosity level.
epsilon : float
Epsilon in the epsilon-insensitive loss functions; only if `loss` is
'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'.
For 'huber', determines the threshold at which it becomes less
important to get the prediction exactly right.
For epsilon-insensitive, any differences between the current prediction
and the correct label are ignored if they are less than this threshold.
learning_rate : string, optional
The learning rate:
constant: eta = eta0
optimal: eta = 1.0/(alpha * t)
invscaling: eta = eta0 / pow(t, power_t) [default]
eta0 : double, optional
The initial learning rate [default 0.01].
power_t : double, optional
The exponent for inverse scaling learning rate [default 0.25].
warm_start : bool, optional
When set to True, reuse the solution of the previous call to fit as
initialization, otherwise, just erase the previous solution.
average : bool or int, optional
When set to True, computes the averaged SGD weights and stores the
result in the ``coef_`` attribute. If set to an int greater than 1,
averaging will begin once the total number of samples seen reaches
average. So ``average=10 will`` begin averaging after seeing 10 samples.
Attributes
----------
coef_ : array, shape (n_features,)
Weights assigned to the features.
intercept_ : array, shape (1,)
The intercept term.
average_coef_ : array, shape (n_features,)
Averaged weights assigned to the features.
average_intercept_ : array, shape (1,)
The averaged intercept term.
Examples
--------
>>> import numpy as np
>>> from sklearn import linear_model
>>> n_samples, n_features = 10, 5
>>> np.random.seed(0)
>>> y = np.random.randn(n_samples)
>>> X = np.random.randn(n_samples, n_features)
>>> clf = linear_model.SGDRegressor()
>>> clf.fit(X, y)
... #doctest: +NORMALIZE_WHITESPACE
SGDRegressor(alpha=0.0001, average=False, epsilon=0.1, eta0=0.01,
fit_intercept=True, l1_ratio=0.15, learning_rate='invscaling',
loss='squared_loss', n_iter=5, penalty='l2', power_t=0.25,
random_state=None, shuffle=True, verbose=0, warm_start=False)
See also
--------
Ridge, ElasticNet, Lasso, SVR
"""
def __init__(self, loss="squared_loss", penalty="l2", alpha=0.0001,
l1_ratio=0.15, fit_intercept=True, n_iter=5, shuffle=True,
verbose=0, epsilon=DEFAULT_EPSILON, random_state=None,
learning_rate="invscaling", eta0=0.01, power_t=0.25,
warm_start=False, average=False):
super(SGDRegressor, self).__init__(loss=loss, penalty=penalty,
alpha=alpha, l1_ratio=l1_ratio,
fit_intercept=fit_intercept,
n_iter=n_iter, shuffle=shuffle,
verbose=verbose,
epsilon=epsilon,
random_state=random_state,
learning_rate=learning_rate,
eta0=eta0, power_t=power_t,
warm_start=warm_start,
average=average)
| bsd-3-clause |
krast/suse_xen | tools/xm-test/lib/XmTestLib/NetConfig.py | 31 | 8702 | #!/usr/bin/python
"""
Copyright (C) International Business Machines Corp., 2005, 2006
Authors: Dan Smith <danms@us.ibm.com>
Daniel Stekloff <dsteklof@us.ibm.com>
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; under version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
import sys
import commands
import os
import re
import time
import random
from xen.xend.sxp import Parser
from Xm import *
from Test import *
from config import *
class NetworkError(Exception):
def __init__(self, msg):
self.errMsg = msg
def __str__(self):
return str(self.errMsg)
def getXendNetConfig():
# Find out what environment we're in: bridge, nat, or route
xconfig = os.getenv("XEND_CONFIG")
if not xconfig:
xconfig = "/etc/xen/xend-config.sxp"
try:
configfile = open(xconfig, 'r')
except:
return "bridge"
S = configfile.read()
pin = Parser()
pin.input(S)
pin.input_eof()
val = pin.get_val()
while val[0] != 'network-script':
val = pin.get_val()
if val[0] != 'network-script' or len(val) < 2:
# entry network-script not found or no type specified
netenv = "bridge"
else:
# split network command into script name and its parameters
sub_val = val[1].split()
if sub_val[0] == "network-bridge":
netenv = "bridge"
elif sub_val[0] == "network-route":
netenv = "route"
elif sub_val[0] == "network-nat":
netenv = "nat"
else:
raise NetworkError("Failed to get network env from xend config")
configfile.close()
return netenv
class NetConfig:
def __init__(self):
self.netenv = getXendNetConfig()
self.used_ips = {}
self.free_oct_ips = [ 0, 0, 0, 0 ]
self.total_ips = 0
if NETWORK_IP_RANGE == 'dhcp':
self.netmask = NETWORK_IP_RANGE
self.network = NETWORK_IP_RANGE
self.max_ip = NETWORK_IP_RANGE
self.min_ip = NETWORK_IP_RANGE
else:
self.netmask = NETMASK
self.network = NETWORK
s_ip = ''
# Get starting ip and max ip from configured ip range
s_ip = NETWORK_IP_RANGE
ips = s_ip.split("-")
self.max_ip = ips[1]
self.min_ip = ips[0]
self.__setMaxNumberIPs()
# Clean out any aliases in the network range for dom0's interface.
# If an alias exists, a test xendevice add command could fail.
if NETWORK_IP_RANGE != "dhcp":
self.__cleanDom0Aliases()
def __setMaxNumberIPs(self):
# Count the number of IPs available, to help tests know whether they
# have enough to run or not
masko = self.netmask.split('.')
maxo = self.max_ip.split('.')
mino = self.min_ip.split('.')
ips = 0
# Last octet
self.free_oct_ips[3] = (int(maxo[3]) - int(mino[3])) + 1
# 3rd octet
self.free_oct_ips[2] = (int(maxo[2]) - int(mino[2])) + 1
# 2nd octet
self.free_oct_ips[1] = (int(maxo[1]) - int(mino[1])) + 1
# 1st octet
self.free_oct_ips[0] = (int(maxo[0]) - int(mino[0])) + 1
self.total_ips = self.free_oct_ips[3]
if self.free_oct_ips[2] > 1:
self.total_ips = (self.total_ips * self.free_oct_ips[2])
if self.free_oct_ips[1] > 1:
self.total_ips = (self.total_ips * self.free_oct_ips[1])
if self.free_oct_ips[0] > 1:
self.total_ips = (self.total_ips * self.free_oct_ips[0])
def __cleanDom0Aliases(self):
# Remove any aliases within the supplied network IP range on dom0
scmd = 'ip addr show dev %s' % (DOM0_INTF)
status, output = traceCommand(scmd)
if status:
raise NetworkError("Failed to show %s aliases: %d" %
(DOM0_INTF, status))
lines = output.split("\n")
for line in lines:
ip = re.search('(\d+\.\d+\.\d+\.\d+)', line)
if ip and self.isIPInRange(ip.group(1)) == True:
dcmd = 'ip addr del %s/32 dev %s' % (ip.group(1), DOM0_INTF)
dstatus, doutput = traceCommand(dcmd)
if dstatus:
raise NetworkError("Failed to remove %s aliases: %d" %
(DOM0_INTF, status))
def getNetEnv(self):
return self.netenv
def setUsedIP(self, domname, interface, ip):
self.used_ips['%s:%s' % (domname, interface)] = ip
def __findFirstOctetIP(self, prefix, min, max):
for i in range(min, max):
ip = '%s%s' % (prefix, str(i))
found = False
for k in self.used_ips.keys():
if self.used_ips[k] == ip:
found = True
if found == False:
return ip
if found == True:
return None
def getFreeIP(self, domname, interface):
# Get a free IP. It uses the starting ip octets and then the
# total number of allowed numbers for that octet. It only
# calculates ips for the last two octets, we shouldn't need more
start_octets = self.min_ip.split(".")
ip = None
# Only working with ips from last two octets, shouldn't need more
max = int(start_octets[2]) + self.free_oct_ips[2]
for i in range(int(start_octets[2]), max):
prefix = '%s.%s.%s.' % (start_octets[0], start_octets[1], str(i))
ip = self.__findFirstOctetIP(prefix, int(start_octets[3]), self.free_oct_ips[3])
if ip:
break
if not ip:
raise NetworkError("Ran out of configured addresses.")
self.setUsedIP(domname, interface, ip)
return ip
def getNetMask(self):
return self.netmask
def getNetwork(self):
return self.network
def getIP(self, domname, interface):
# Depending on environment, set an IP. Uses the configured range
# of IPs, network address, and netmask
if NETWORK_IP_RANGE == "dhcp":
return None
# Make sure domain and interface aren't already assigned an IP
if self.used_ips.has_key('%s:%s' % (domname, interface)):
raise NetworkError("Domain %s interface %s is already has IP"
% (domname, interface))
return self.getFreeIP(domname, interface)
def setIP(self, domname, interface, ip):
# Make sure domain and interface aren't already assigned an IP
if self.used_ips.has_key('%s:%s' % (domname, interface)):
raise NetworkError("Domain %s interface %s is already has IP"
% (domname, interface))
self.setUsedIP(domname, interface, ip)
def releaseIP(self, domname, interface, ip):
if self.used_ips.has_key('%s:%s' % (domname, interface)):
del self.used_ips['%s:%s' % (domname, interface)]
def getNumberAllowedIPs(self):
return self.total_ips
def canRunNetTest(self, ips):
# Check to see if a test can run, returns true or false. Input is
# number of ips needed.
if NETWORK_IP_RANGE == "dhcp":
return True
if self.total_ips >= ips:
return True
return False
def isIPInRange(self, ip):
# Checks to see if supplied ip is in the range of allowed ips
maxo = self.max_ip.split('.')
mino = self.min_ip.split('.')
ipo = ip.split('.')
if int(ipo[0]) < int(mino[0]):
return False
elif int(ipo[0]) > int(maxo[0]):
return False
if int(ipo[1]) < int(mino[1]):
return False
elif int(ipo[1]) > int(maxo[1]):
return False
if int(ipo[2]) < int(mino[2]):
return False
elif int(ipo[2]) > int(maxo[2]):
return False
if int(ipo[3]) < int(mino[3]):
return False
elif int(ipo[3]) > int(maxo[3]):
return False
return True
| gpl-2.0 |
dongjietan/BattleCity | cocos2d/download-deps.py | 67 | 12377 | #!/usr/bin/env python
#coding=utf-8
#
# ./download-deps.py
#
# Downloads Cocos2D-x 3rd party dependencies from github:
# https://github.com/cocos2d/cocos2d-x-3rd-party-libs-bin) and extracts the zip
# file
#
# Having the dependencies outside the official cocos2d-x repo helps prevent
# bloating the repo.
#
"""****************************************************************************
Copyright (c) 2014 cocos2d-x.org
Copyright (c) 2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************"""
import os.path
import zipfile
import shutil
import sys
import traceback
import distutils
import fileinput
import json
from optparse import OptionParser
from time import time
from sys import stdout
from distutils.errors import DistutilsError
from distutils.dir_util import copy_tree, remove_tree
class UnrecognizedFormat:
def __init__(self, prompt):
self._prompt = prompt
def __str__(self):
return self._prompt
class CocosZipInstaller(object):
def __init__(self, workpath, config_path, version_path, remote_version_key=None):
self._workpath = workpath
self._config_path = config_path
self._version_path = version_path
data = self.load_json_file(config_path)
self._current_version = data["version"]
self._repo_name = data["repo_name"]
try:
self._move_dirs = data["move_dirs"]
except:
self._move_dirs = None
self._filename = self._current_version + '.zip'
self._url = data["repo_parent"] + self._repo_name + '/archive/' + self._filename
self._zip_file_size = int(data["zip_file_size"])
# 'v' letter was swallowed by github, so we need to substring it from the 2nd letter
self._extracted_folder_name = os.path.join(self._workpath, self._repo_name + '-' + self._current_version[1:])
try:
data = self.load_json_file(version_path)
if remote_version_key is None:
self._remote_version = data["version"]
else:
self._remote_version = data[remote_version_key]
except:
print("==> version file doesn't exist")
def get_input_value(self, prompt):
ret = raw_input(prompt)
ret.rstrip(" \t")
return ret
def download_file(self):
print("==> Ready to download '%s' from '%s'" % (self._filename, self._url))
import urllib2
try:
u = urllib2.urlopen(self._url)
except urllib2.HTTPError as e:
if e.code == 404:
print("==> Error: Could not find the file from url: '%s'" % (self._url))
print("==> Http request failed, error code: " + str(e.code) + ", reason: " + e.read())
sys.exit(1)
f = open(self._filename, 'wb')
meta = u.info()
content_len = meta.getheaders("Content-Length")
file_size = 0
if content_len and len(content_len) > 0:
file_size = int(content_len[0])
else:
# github server may not reponse a header information which contains `Content-Length`,
# therefore, the size needs to be written hardcode here. While server doesn't return
# `Content-Length`, use it instead
print("==> WARNING: Couldn't grab the file size from remote, use 'zip_file_size' section in '%s'" % self._config_path)
file_size = self._zip_file_size
print("==> Start to download, please wait ...")
file_size_dl = 0
block_sz = 8192
block_size_per_second = 0
old_time = time()
status = ""
while True:
buffer = u.read(block_sz)
if not buffer:
print("%s%s" % (" " * len(status), "\r")),
break
file_size_dl += len(buffer)
block_size_per_second += len(buffer)
f.write(buffer)
new_time = time()
if (new_time - old_time) > 1:
speed = block_size_per_second / (new_time - old_time) / 1000.0
if file_size != 0:
percent = file_size_dl * 100. / file_size
status = r"Downloaded: %6dK / Total: %dK, Percent: %3.2f%%, Speed: %6.2f KB/S " % (file_size_dl / 1000, file_size / 1000, percent, speed)
else:
status = r"Downloaded: %6dK, Speed: %6.2f KB/S " % (file_size_dl / 1000, speed)
print(status),
sys.stdout.flush()
print("\r"),
block_size_per_second = 0
old_time = new_time
print("==> Downloading finished!")
f.close()
def ensure_directory(self, target):
if not os.path.exists(target):
os.mkdir(target)
def unpack_zipfile(self, extract_dir):
"""Unpack zip `filename` to `extract_dir`
Raises ``UnrecognizedFormat`` if `filename` is not a zipfile (as determined
by ``zipfile.is_zipfile()``).
"""
if not zipfile.is_zipfile(self._filename):
raise UnrecognizedFormat("%s is not a zip file" % (self._filename))
print("==> Extracting files, please wait ...")
z = zipfile.ZipFile(self._filename)
try:
for info in z.infolist():
name = info.filename
# don't extract absolute paths or ones with .. in them
if name.startswith('/') or '..' in name:
continue
target = os.path.join(extract_dir, *name.split('/'))
if not target:
continue
if name.endswith('/'):
# directory
self.ensure_directory(target)
else:
# file
data = z.read(info.filename)
f = open(target, 'wb')
try:
f.write(data)
finally:
f.close()
del data
unix_attributes = info.external_attr >> 16
if unix_attributes:
os.chmod(target, unix_attributes)
finally:
z.close()
print("==> Extraction done!")
def ask_to_delete_downloaded_zip_file(self):
ret = self.get_input_value("==> Would you like to save '%s'? So you don't have to download it later. [Yes/no]: " % self._filename)
ret = ret.strip()
if ret != 'yes' and ret != 'y' and ret != 'no' and ret != 'n':
print("==> Saving the dependency libraries by default")
return False
else:
return True if ret == 'no' or ret == 'n' else False
def download_zip_file(self):
if not os.path.isfile(self._filename):
self.download_file()
try:
if not zipfile.is_zipfile(self._filename):
raise UnrecognizedFormat("%s is not a zip file" % (self._filename))
except UnrecognizedFormat as e:
print("==> Unrecognized zip format from your local '%s' file!" % (self._filename))
if os.path.isfile(self._filename):
os.remove(self._filename)
print("==> Download it from internet again, please wait...")
self.download_zip_file()
def need_to_update(self):
if not os.path.isfile(self._version_path):
return True
with open(self._version_path) as data_file:
data = json.load(data_file)
if self._remote_version == self._current_version:
return False
return True
def load_json_file(self, file_path):
if not os.path.isfile(file_path):
raise Exception("Could not find (%s)" % (file_path))
with open(file_path) as data_file:
data = json.load(data_file)
return data
def run(self, workpath, folder_for_extracting, remove_downloaded, force_update, download_only):
if not force_update and not self.need_to_update():
print("==> Not need to update!")
return
if os.path.exists(self._extracted_folder_name):
shutil.rmtree(self._extracted_folder_name)
self.download_zip_file()
if not download_only:
self.unpack_zipfile(self._workpath)
print("==> Copying files...")
if not os.path.exists(folder_for_extracting):
os.mkdir(folder_for_extracting)
distutils.dir_util.copy_tree(self._extracted_folder_name, folder_for_extracting)
if self._move_dirs is not None:
for srcDir in self._move_dirs.keys():
distDir = os.path.join( os.path.join(workpath, self._move_dirs[srcDir]), srcDir)
if os.path.exists(distDir):
shutil.rmtree(distDir)
shutil.move( os.path.join(folder_for_extracting, srcDir), distDir)
print("==> Cleaning...")
if os.path.exists(self._extracted_folder_name):
shutil.rmtree(self._extracted_folder_name)
if os.path.isfile(self._filename):
if remove_downloaded is not None:
if remove_downloaded == 'yes':
os.remove(self._filename)
elif self.ask_to_delete_downloaded_zip_file():
os.remove(self._filename)
else:
print("==> Download (%s) finish!" % self._filename)
def _check_python_version():
major_ver = sys.version_info[0]
if major_ver > 2:
print ("The python version is %d.%d. But python 2.x is required. (Version 2.7 is well tested)\n"
"Download it here: https://www.python.org/" % (major_ver, sys.version_info[1]))
return False
return True
def main():
workpath = os.path.dirname(os.path.realpath(__file__))
if not _check_python_version():
exit()
parser = OptionParser()
parser.add_option('-r', '--remove-download',
action="store", type="string", dest='remove_downloaded', default=None,
help="Whether to remove downloaded zip file, 'yes' or 'no'")
parser.add_option("-f", "--force-update",
action="store_true", dest="force_update", default=False,
help="Whether to force update the third party libraries")
parser.add_option("-d", "--download-only",
action="store_true", dest="download_only", default=False,
help="Only download zip file of the third party libraries, will not extract it")
(opts, args) = parser.parse_args()
print("=======================================================")
print("==> Prepare to download external libraries!")
external_path = os.path.join(workpath, 'external')
installer = CocosZipInstaller(workpath, os.path.join(workpath, 'external', 'config.json'), os.path.join(workpath, 'external', 'version.json'), "prebuilt_libs_version")
installer.run(workpath, external_path, opts.remove_downloaded, opts.force_update, opts.download_only)
# -------------- main --------------
if __name__ == '__main__':
try:
main()
except Exception as e:
traceback.print_exc()
sys.exit(1)
| mit |
nils-van-zuijlen/arbre_competences | competences/admin.py | 1 | 1258 | # -*-coding:utf-8 -*-
"""
Classes de configuration de l'interface d'administration
Ce programme est sous licence GNU GPL
©2017 Nils et Samuel Van Zuijlen
"""
from django.contrib import admin
from django.utils.text import Truncator
from competences.models import Categorie, Detail
class CategorieAdmin(admin.ModelAdmin):
"""Classe d'administration du modèle des catégories de compétences"""
list_display = ('nom', 'description')
ordering = ('nom',)
search_fields = ('nom', 'description')
class DetailAdmin(admin.ModelAdmin):
"""Classe d'administration du modèle des détails de compétences"""
list_display = ('categorie', 'user', 'details_court')
list_filter = ('categorie', 'user')
ordering = ('categorie',)
search_fields = ('details',)
fields = ('user', 'categorie', 'details')
@staticmethod
def details_court(detail):
"""
Retourne les 40 premiers caractères du contenu de l'article, suivi de
points de suspension si le texte est plus long.
"""
return Truncator(detail.details).chars(40, truncate='...')
details_court.short_description = 'Aperçu du contenu'
admin.site.register(Categorie, CategorieAdmin)
admin.site.register(Detail, DetailAdmin)
| gpl-3.0 |
badlogicmanpreet/nupic | examples/opf/clients/hotgym/prediction/one_gym/nupic_output.py | 17 | 6193 | # ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
"""
Provides two classes with the same signature for writing data out of NuPIC
models.
(This is a component of the One Hot Gym Prediction Tutorial.)
"""
import csv
from collections import deque
from abc import ABCMeta, abstractmethod
# Try to import matplotlib, but we don't have to.
try:
import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.dates import date2num
except ImportError:
pass
WINDOW = 100
class NuPICOutput(object):
__metaclass__ = ABCMeta
def __init__(self, names, showAnomalyScore=False):
self.names = names
self.showAnomalyScore = showAnomalyScore
@abstractmethod
def write(self, timestamps, actualValues, predictedValues,
predictionStep=1):
pass
@abstractmethod
def close(self):
pass
class NuPICFileOutput(NuPICOutput):
def __init__(self, *args, **kwargs):
super(NuPICFileOutput, self).__init__(*args, **kwargs)
self.outputFiles = []
self.outputWriters = []
self.lineCounts = []
headerRow = ['timestamp', 'kw_energy_consumption', 'prediction']
for name in self.names:
self.lineCounts.append(0)
outputFileName = "%s_out.csv" % name
print "Preparing to output %s data to %s" % (name, outputFileName)
outputFile = open(outputFileName, "w")
self.outputFiles.append(outputFile)
outputWriter = csv.writer(outputFile)
self.outputWriters.append(outputWriter)
outputWriter.writerow(headerRow)
def write(self, timestamps, actualValues, predictedValues,
predictionStep=1):
assert len(timestamps) == len(actualValues) == len(predictedValues)
for index in range(len(self.names)):
timestamp = timestamps[index]
actual = actualValues[index]
prediction = predictedValues[index]
writer = self.outputWriters[index]
if timestamp is not None:
outputRow = [timestamp, actual, prediction]
writer.writerow(outputRow)
self.lineCounts[index] += 1
def close(self):
for index, name in enumerate(self.names):
self.outputFiles[index].close()
print "Done. Wrote %i data lines to %s." % (self.lineCounts[index], name)
class NuPICPlotOutput(NuPICOutput):
def __init__(self, *args, **kwargs):
super(NuPICPlotOutput, self).__init__(*args, **kwargs)
# Turn matplotlib interactive mode on.
plt.ion()
self.dates = []
self.convertedDates = []
self.actualValues = []
self.predictedValues = []
self.actualLines = []
self.predictedLines = []
self.linesInitialized = False
self.graphs = []
plotCount = len(self.names)
plotHeight = max(plotCount * 3, 6)
fig = plt.figure(figsize=(14, plotHeight))
gs = gridspec.GridSpec(plotCount, 1)
for index in range(len(self.names)):
self.graphs.append(fig.add_subplot(gs[index, 0]))
plt.title(self.names[index])
plt.ylabel('KW Energy Consumption')
plt.xlabel('Date')
plt.tight_layout()
def initializeLines(self, timestamps):
for index in range(len(self.names)):
print "initializing %s" % self.names[index]
# graph = self.graphs[index]
self.dates.append(deque([timestamps[index]] * WINDOW, maxlen=WINDOW))
self.convertedDates.append(deque(
[date2num(date) for date in self.dates[index]], maxlen=WINDOW
))
self.actualValues.append(deque([0.0] * WINDOW, maxlen=WINDOW))
self.predictedValues.append(deque([0.0] * WINDOW, maxlen=WINDOW))
actualPlot, = self.graphs[index].plot(
self.dates[index], self.actualValues[index]
)
self.actualLines.append(actualPlot)
predictedPlot, = self.graphs[index].plot(
self.dates[index], self.predictedValues[index]
)
self.predictedLines.append(predictedPlot)
self.linesInitialized = True
def write(self, timestamps, actualValues, predictedValues,
predictionStep=1):
assert len(timestamps) == len(actualValues) == len(predictedValues)
# We need the first timestamp to initialize the lines at the right X value,
# so do that check first.
if not self.linesInitialized:
self.initializeLines(timestamps)
for index in range(len(self.names)):
self.dates[index].append(timestamps[index])
self.convertedDates[index].append(date2num(timestamps[index]))
self.actualValues[index].append(actualValues[index])
self.predictedValues[index].append(predictedValues[index])
# Update data
self.actualLines[index].set_xdata(self.convertedDates[index])
self.actualLines[index].set_ydata(self.actualValues[index])
self.predictedLines[index].set_xdata(self.convertedDates[index])
self.predictedLines[index].set_ydata(self.predictedValues[index])
self.graphs[index].relim()
self.graphs[index].autoscale_view(True, True, True)
plt.draw()
plt.legend(('actual','predicted'), loc=3)
def refreshGUI(self):
"""Give plot a pause, so data is drawn and GUI's event loop can run.
"""
plt.pause(0.0001)
def close(self):
plt.ioff()
plt.show()
NuPICOutput.register(NuPICFileOutput)
NuPICOutput.register(NuPICPlotOutput)
| agpl-3.0 |
dawran6/zulip | zerver/tests/test_realm_filters.py | 17 | 3065 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from zerver.lib.actions import get_realm, do_add_realm_filter
from zerver.lib.test_classes import ZulipTestCase
from zerver.models import RealmFilter
import ujson
class RealmFilterTest(ZulipTestCase):
def test_list(self):
# type: () -> None
self.login("iago@zulip.com")
realm = get_realm('zulip')
do_add_realm_filter(
realm,
"#(?P<id>[123])",
"https://realm.com/my_realm_filter/%(id)s")
result = self.client_get("/json/realm/filters")
self.assert_json_success(result)
self.assertEqual(200, result.status_code)
content = ujson.loads(result.content)
self.assertEqual(len(content["filters"]), 1)
def test_create(self):
# type: () -> None
self.login("iago@zulip.com")
data = {"pattern": "", "url_format_string": "https://realm.com/my_realm_filter/%(id)s"}
result = self.client_post("/json/realm/filters", info=data)
self.assert_json_error(result, 'This field cannot be blank.')
data['pattern'] = '$a'
result = self.client_post("/json/realm/filters", info=data)
self.assert_json_error(result, 'Invalid filter pattern, you must use the following format OPTIONAL_PREFIX(?P<id>.+)')
data['pattern'] = 'ZUL-(?P<id>\d++)'
result = self.client_post("/json/realm/filters", info=data)
self.assert_json_error(result, 'Invalid filter pattern, you must use the following format OPTIONAL_PREFIX(?P<id>.+)')
data['pattern'] = 'ZUL-(?P<id>\d+)'
data['url_format_string'] = '$fgfg'
result = self.client_post("/json/realm/filters", info=data)
self.assert_json_error(result, 'URL format string must be in the following format: `https://example.com/%(\\w+)s`')
data['url_format_string'] = 'https://realm.com/my_realm_filter/%(id)s'
result = self.client_post("/json/realm/filters", info=data)
self.assert_json_success(result)
def test_not_realm_admin(self):
# type: () -> None
self.login("hamlet@zulip.com")
result = self.client_post("/json/realm/filters")
self.assert_json_error(result, 'Must be a realm administrator')
result = self.client_delete("/json/realm/filters/15")
self.assert_json_error(result, 'Must be a realm administrator')
def test_delete(self):
# type: () -> None
self.login("iago@zulip.com")
realm = get_realm('zulip')
filter_id = do_add_realm_filter(
realm,
"#(?P<id>[123])",
"https://realm.com/my_realm_filter/%(id)s")
filters_count = RealmFilter.objects.count()
result = self.client_delete("/json/realm/filters/{0}".format(filter_id + 1))
self.assert_json_error(result, 'Filter not found')
result = self.client_delete("/json/realm/filters/{0}".format(filter_id))
self.assert_json_success(result)
self.assertEqual(RealmFilter.objects.count(), filters_count - 1)
| apache-2.0 |
jeremiahmarks/sl4a | python-build/python-libs/gdata/src/gdata/tlslite/VerifierDB.py | 359 | 3104 | """Class for storing SRP password verifiers."""
from utils.cryptomath import *
from utils.compat import *
import mathtls
from BaseDB import BaseDB
class VerifierDB(BaseDB):
"""This class represent an in-memory or on-disk database of SRP
password verifiers.
A VerifierDB can be passed to a server handshake to authenticate
a client based on one of the verifiers.
This class is thread-safe.
"""
def __init__(self, filename=None):
"""Create a new VerifierDB instance.
@type filename: str
@param filename: Filename for an on-disk database, or None for
an in-memory database. If the filename already exists, follow
this with a call to open(). To create a new on-disk database,
follow this with a call to create().
"""
BaseDB.__init__(self, filename, "verifier")
def _getItem(self, username, valueStr):
(N, g, salt, verifier) = valueStr.split(" ")
N = base64ToNumber(N)
g = base64ToNumber(g)
salt = base64ToString(salt)
verifier = base64ToNumber(verifier)
return (N, g, salt, verifier)
def __setitem__(self, username, verifierEntry):
"""Add a verifier entry to the database.
@type username: str
@param username: The username to associate the verifier with.
Must be less than 256 characters in length. Must not already
be in the database.
@type verifierEntry: tuple
@param verifierEntry: The verifier entry to add. Use
L{tlslite.VerifierDB.VerifierDB.makeVerifier} to create a
verifier entry.
"""
BaseDB.__setitem__(self, username, verifierEntry)
def _setItem(self, username, value):
if len(username)>=256:
raise ValueError("username too long")
N, g, salt, verifier = value
N = numberToBase64(N)
g = numberToBase64(g)
salt = stringToBase64(salt)
verifier = numberToBase64(verifier)
valueStr = " ".join( (N, g, salt, verifier) )
return valueStr
def _checkItem(self, value, username, param):
(N, g, salt, verifier) = value
x = mathtls.makeX(salt, username, param)
v = powMod(g, x, N)
return (verifier == v)
def makeVerifier(username, password, bits):
"""Create a verifier entry which can be stored in a VerifierDB.
@type username: str
@param username: The username for this verifier. Must be less
than 256 characters in length.
@type password: str
@param password: The password for this verifier.
@type bits: int
@param bits: This values specifies which SRP group parameters
to use. It must be one of (1024, 1536, 2048, 3072, 4096, 6144,
8192). Larger values are more secure but slower. 2048 is a
good compromise between safety and speed.
@rtype: tuple
@return: A tuple which may be stored in a VerifierDB.
"""
return mathtls.makeVerifier(username, password, bits)
makeVerifier = staticmethod(makeVerifier) | apache-2.0 |
chipaca/snapcraft | snapcraft/storeapi/v2/_api_schema.py | 1 | 19445 | # -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*-
#
# Copyright 2020 Canonical Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Attributes that the jsonschema from the Snap Store originally require but
# Snapcraft does not have been commented out from this schema originally
# imported from
# https://dashboard.snapcraft.io/docs/v2/en/snaps.html#snap-channel-map
from typing import Any, Dict
# Version 14, found at: https://dashboard.snapcraft.io/docs/v2/en/snaps.html#snap-releases
RELEASES_JSONSCHEMA: Dict[str, Any] = {
"properties": {
"releases": {
"items": {
"properties": {
"architecture": {"introduced_at": 1, "type": "string"},
"branch": {"introduced_at": 1, "type": ["string", "null"]},
"channel": {
"description": "The channel name for this release.",
"introduced_at": 8,
"type": "string",
},
"expiration-date": {
"description": "The date when this release expires, in ISO 8601 format. If null, the release does not expire.",
"format": "date-time",
"introduced_at": 8,
"type": ["string", "null"],
},
"progressive": {
"introduced_at": 4,
"properties": {
"current-percentage": {
"introduced_at": 14,
"type": ["number", "null"],
},
"paused": {"type": ["boolean", "null"]},
"percentage": {"type": ["number", "null"]},
},
"required": ["paused", "percentage", "current-percentage"],
"type": "object",
},
"revision": {"introduced_at": 1, "type": ["integer", "null"]},
"risk": {"introduced_at": 1, "type": "string"},
"track": {"introduced_at": 1, "type": "string"},
"when": {
"format": "date-time",
"introduced_at": 1,
"type": "string",
},
},
"required": [
"architecture",
"branch",
"revision",
"risk",
"track",
"when",
],
"type": "object",
},
"minItems": 0,
"type": "array",
},
"revisions": {
"items": {
"properties": {
"architectures": {
"introduced_at": 1,
"items": {"type": "string"},
"minItems": 1,
"type": "array",
},
"attributes": {"introduced_at": 2, "type": "object"},
"base": {"introduced_at": 1, "type": ["string", "null"]},
"build_url": {"introduced_at": 1, "type": ["string", "null"]},
"confinement": {
"enum": ["strict", "classic", "devmode"],
"introduced_at": 1,
"type": "string",
},
"created_at": {
"format": "date-time",
"introduced_at": 1,
"type": "string",
},
"epoch": {"introduced_at": 1, "type": "object"},
"grade": {
"enum": ["stable", "devel"],
"introduced_at": 1,
"type": "string",
},
"revision": {"introduced_at": 1, "type": "integer"},
"sha3-384": {"introduced_at": 1, "type": "string"},
"size": {"introduced_at": 1, "type": "integer"},
"status": {
"enum": [
"Published",
"Unpublished",
"ManualReviewPending",
"NeedsInformation",
"AutomaticallyRejected",
"Rejected",
],
"introduced_at": 1,
"type": "string",
},
"version": {"introduced_at": 1, "type": "string"},
},
"required": [
"architectures",
"build_url",
"confinement",
"created_at",
"grade",
"revision",
"sha3-384",
"size",
"status",
"version",
],
"type": "object",
},
"minItems": 0,
"type": "array",
},
},
"required": ["releases", "revisions"],
"type": "object",
}
CHANNEL_MAP_JSONSCHEMA: Dict[str, Any] = {
"properties": {
"channel-map": {
"items": {
"properties": {
"architecture": {"type": "string"},
"channel": {
"description": 'The channel name, including "latest/" for the latest track.',
"type": "string",
},
"expiration-date": {
"description": "The date when this release expires, in RFC 3339 format. If null, the release does not expire.",
"format": "date-time",
"type": ["string", "null"],
},
"progressive": {
"properties": {
"paused": {"type": ["boolean", "null"]},
"percentage": {"type": ["number", "null"]},
"current-percentage": {"type": ["number", "null"]},
},
"required": ["paused", "percentage", "current-percentage"],
"type": "object",
},
"revision": {"type": "integer"},
"when": {
"description": "The date when this release was made, in RFC 3339 format.",
"format": "date-time",
"type": "string",
},
},
"required": [
"architecture",
"channel",
"expiration-date",
"progressive",
"revision",
# "when"
],
"type": "object",
},
"minItems": 0,
"type": "array",
},
"revisions": {
"items": {
"properties": {
"architectures": {
"items": {"type": "string"},
"minItems": 1,
"type": "array",
},
"attributes": {"type": "object"},
"base": {"type": ["string", "null"]},
"build-url": {"type": ["string", "null"]},
"confinement": {
"enum": ["strict", "classic", "devmode"],
"type": "string",
},
"created-at": {"format": "date-time", "type": "string"},
"epoch": {
"properties": {
"read": {
"items": {"type": "integer"},
"minItems": 1,
"type": ["array", "null"],
},
"write": {
"items": {"type": "integer"},
"minItems": 1,
"type": ["array", "null"],
},
},
"required": ["read", "write"],
"type": "object",
},
"grade": {"enum": ["stable", "devel"], "type": "string"},
"revision": {"type": "integer"},
"sha3-384": {"type": "string"},
"size": {"type": "integer"},
"version": {"type": "string"},
},
"required": [
"architectures",
# "attributes",
# "base",
# "build-url",
# "confinement",
# "created-at",
# "epoch",
# "grade",
"revision",
# "sha3-384",
# "size",
# "status",
"version",
],
"type": "object",
},
"minItems": 0,
"type": "array",
},
"snap": {
"description": "Metadata about the requested snap.",
"introduced_at": 6,
"properties": {
"channels": {
"description": "The list of most relevant channels for this snap. Branches are only included if there is a release for it.",
"introduced_at": 9,
"items": {
"description": "A list of channels and their metadata for the requested snap.",
"properties": {
"branch": {
"description": "The branch name for this channel, can be null.",
"type": ["string", "null"],
},
"fallback": {
"description": "The name of the channel that this channel would fall back to if there were no releases in it. If null, this channel has no fallback channel.",
"type": ["string", "null"],
},
"name": {
"description": 'The channel name, including "latest/" for the latest track.',
"type": "string",
},
"risk": {
"description": "The risk name for this channel.",
"type": "string",
},
"track": {
"description": "The track name for this channel.",
"type": "string",
},
},
"required": ["name", "track", "risk", "branch", "fallback"],
"type": "object",
},
"minItems": 1,
"type": "array",
},
"default-track": {
"description": "The default track name for this snap. If no default track is set, this value is null.",
"type": ["string", "null"],
},
"id": {
"description": "The snap ID for this snap package.",
"type": "string",
},
"name": {"description": "The snap package name.", "type": "string"},
"private": {
"description": "Whether this snap is private or not.",
"type": "boolean",
},
"tracks": {
"description": "An ordered list of most relevant tracks for this snap.",
"introduced_at": 9,
"items": {
"description": "An ordered list of tracks and their metadata for this snap.",
"properties": {
"creation-date": {
"description": "The track creation date, in ISO 8601 format.",
"format": "date-time",
"type": ["string", "null"],
},
"name": {
"description": "The track name.",
"type": "string",
},
"version-pattern": {
"description": "A Python regex to validate the versions being released to this track. If null, no validation is enforced.",
"type": ["string", "null"],
},
},
# pattern is documented as required but is not returned,
# version-pattern is returned instead.
"required": ["name", "creation-date", "version-pattern"],
"type": "object",
},
"minItems": 1,
"type": "array",
},
},
"required": [
# "id",
"channels",
# "default-track",
"name",
# "private",
# "tracks"
],
"type": "object",
},
},
"required": ["channel-map", "revisions", "snap"],
"type": "object",
}
# Version 27, found at https://dashboard.snapcraft.io/docs/v2/en/tokens.html#api-tokens-whoami
WHOAMI_JSONSCHEMA: Dict[str, Any] = {
"properties": {
"account": {
"properties": {
"email": {
"description": "The primary email for the user",
"type": "string",
},
"id": {
"description": "The store account ID for the user",
"type": "string",
},
"name": {
"description": "The display name for the user",
"type": "string",
},
"username": {
"description": "The store username for the user",
"type": "string",
},
},
"required": ["email", "id", "name", "username"],
"type": "object",
},
"channels": {
"oneOf": [
{
"description": "A list of channels to restrict the macaroon to, allows wildcards in the fnmatch format (https://docs.python.org/3/library/fnmatch.html)",
"items": {"description": "Valid channel name.", "type": "string"},
"minItems": 1,
"type": "array",
"uniqueItems": True,
},
{"type": "null"},
]
},
"errors": {
"items": {
"properties": {
"code": {"type": "string"},
"extra": {"additionalProperties": True, "type": "object"},
"message": {"type": "string"},
},
"required": ["code", "message", "extra"],
"type": "object",
},
"type": "array",
},
"expires": {
"oneOf": [
{
"description": "A timestamp (string formatted per ISO8601) after which the macaroon should not be valid",
"format": "date-time",
"type": "string",
},
{"type": "null"},
]
},
"packages": {
"oneOf": [
{
"description": 'A list of packages to restrict the macaroon to. Those can be defined in two ways: 1- by name: each item in the list should be a json dict like `{"name": "the-name"}`, or 2- by snap_id: each item in the list should be a json dict like `{"snap_id": "some-snap-id-1234"}`.',
"items": {
"anyOf": [{"required": ["snap_id"]}, {"required": ["name"]}],
"description": "Package identifier: a dict with at least name or snap_id keys.",
"properties": {
"name": {"type": "string"},
"snap_id": {"type": "string"},
},
"type": "object",
},
"minItems": 1,
"type": "array",
"uniqueItems": True,
},
{"type": "null"},
]
},
"permissions": {
"oneOf": [
{
"description": "A list of permissions to restrict the macaroon to",
"items": {
"description": "A valid token permission.",
"enum": [
"edit_account",
"modify_account_key",
"package_access",
"package_manage",
"package_metrics",
"package_purchase",
"package_push",
"package_register",
"package_release",
"package_update",
"package_upload",
"package_upload_request",
"store_admin",
"store_review",
],
"type": "string",
},
"minItems": 1,
"type": "array",
"uniqueItems": True,
},
{"type": "null"},
]
},
"store_ids": {
"oneOf": [
{
"description": "A list of store IDs to restrict the macaroon to",
"items": {"description": "A store ID.", "type": "string"},
"minItems": 1,
"type": "array",
"uniqueItems": True,
},
{"type": "null"},
]
},
},
"required": ["account", "channels", "packages", "permissions"],
"type": "object",
}
| gpl-3.0 |
bkloppenborg/liboi | lib/gtest-1.6.0/test/gtest_list_tests_unittest.py | 1068 | 5415 | #!/usr/bin/env python
#
# Copyright 2006, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Unit test for Google Test's --gtest_list_tests flag.
A user can ask Google Test to list all tests by specifying the
--gtest_list_tests flag. This script tests such functionality
by invoking gtest_list_tests_unittest_ (a program written with
Google Test) the command line flags.
"""
__author__ = 'phanna@google.com (Patrick Hanna)'
import gtest_test_utils
# Constants.
# The command line flag for enabling/disabling listing all tests.
LIST_TESTS_FLAG = 'gtest_list_tests'
# Path to the gtest_list_tests_unittest_ program.
EXE_PATH = gtest_test_utils.GetTestExecutablePath('gtest_list_tests_unittest_')
# The expected output when running gtest_list_tests_unittest_ with
# --gtest_list_tests
EXPECTED_OUTPUT_NO_FILTER = """FooDeathTest.
Test1
Foo.
Bar1
Bar2
DISABLED_Bar3
Abc.
Xyz
Def
FooBar.
Baz
FooTest.
Test1
DISABLED_Test2
Test3
"""
# The expected output when running gtest_list_tests_unittest_ with
# --gtest_list_tests and --gtest_filter=Foo*.
EXPECTED_OUTPUT_FILTER_FOO = """FooDeathTest.
Test1
Foo.
Bar1
Bar2
DISABLED_Bar3
FooBar.
Baz
FooTest.
Test1
DISABLED_Test2
Test3
"""
# Utilities.
def Run(args):
"""Runs gtest_list_tests_unittest_ and returns the list of tests printed."""
return gtest_test_utils.Subprocess([EXE_PATH] + args,
capture_stderr=False).output
# The unit test.
class GTestListTestsUnitTest(gtest_test_utils.TestCase):
"""Tests using the --gtest_list_tests flag to list all tests."""
def RunAndVerify(self, flag_value, expected_output, other_flag):
"""Runs gtest_list_tests_unittest_ and verifies that it prints
the correct tests.
Args:
flag_value: value of the --gtest_list_tests flag;
None if the flag should not be present.
expected_output: the expected output after running command;
other_flag: a different flag to be passed to command
along with gtest_list_tests;
None if the flag should not be present.
"""
if flag_value is None:
flag = ''
flag_expression = 'not set'
elif flag_value == '0':
flag = '--%s=0' % LIST_TESTS_FLAG
flag_expression = '0'
else:
flag = '--%s' % LIST_TESTS_FLAG
flag_expression = '1'
args = [flag]
if other_flag is not None:
args += [other_flag]
output = Run(args)
msg = ('when %s is %s, the output of "%s" is "%s".' %
(LIST_TESTS_FLAG, flag_expression, ' '.join(args), output))
if expected_output is not None:
self.assert_(output == expected_output, msg)
else:
self.assert_(output != EXPECTED_OUTPUT_NO_FILTER, msg)
def testDefaultBehavior(self):
"""Tests the behavior of the default mode."""
self.RunAndVerify(flag_value=None,
expected_output=None,
other_flag=None)
def testFlag(self):
"""Tests using the --gtest_list_tests flag."""
self.RunAndVerify(flag_value='0',
expected_output=None,
other_flag=None)
self.RunAndVerify(flag_value='1',
expected_output=EXPECTED_OUTPUT_NO_FILTER,
other_flag=None)
def testOverrideNonFilterFlags(self):
"""Tests that --gtest_list_tests overrides the non-filter flags."""
self.RunAndVerify(flag_value='1',
expected_output=EXPECTED_OUTPUT_NO_FILTER,
other_flag='--gtest_break_on_failure')
def testWithFilterFlags(self):
"""Tests that --gtest_list_tests takes into account the
--gtest_filter flag."""
self.RunAndVerify(flag_value='1',
expected_output=EXPECTED_OUTPUT_FILTER_FOO,
other_flag='--gtest_filter=Foo*')
if __name__ == '__main__':
gtest_test_utils.Main()
| lgpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.