code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
"""
Implementation of JSONEncoder
"""
# NOTE(kgibbs): This line must be added to make this file work under
# Python 2.2, which is commonly used at Google.
from __future__ import generators
# NOTE(kgibbs): End changes.
import re
# this should match any kind of infinity
INFCHARS = re.compile(r'[infINF]')
ESCAPE = re.compile(r'[\x00-\x19\\"\b\f\n\r\t]')
ESCAPE_ASCII = re.compile(r'([\\"]|[^\ -~])')
ESCAPE_DCT = {
'\\': '\\\\',
'"': '\\"',
'\b': '\\b',
'\f': '\\f',
'\n': '\\n',
'\r': '\\r',
'\t': '\\t',
}
for i in range(0x20):
ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
def floatstr(o, allow_nan=True):
s = str(o)
# If the first non-sign is a digit then it's not a special value
if (o < 0.0 and s[1].isdigit()) or s[0].isdigit():
return s
elif not allow_nan:
raise ValueError("Out of range float values are not JSON compliant: %r"
% (o,))
# These are the string representations on the platforms I've tried
if s == 'nan':
return 'NaN'
if s == 'inf':
return 'Infinity'
if s == '-inf':
return '-Infinity'
# NaN should either be inequal to itself, or equal to everything
if o != o or o == 0.0:
return 'NaN'
# Last ditch effort, assume inf
if o < 0:
return '-Infinity'
return 'Infinity'
def encode_basestring(s):
"""
Return a JSON representation of a Python string
"""
def replace(match):
return ESCAPE_DCT[match.group(0)]
return '"' + ESCAPE.sub(replace, s) + '"'
def encode_basestring_ascii(s):
def replace(match):
s = match.group(0)
try:
return ESCAPE_DCT[s]
except KeyError:
return '\\u%04x' % (ord(s),)
return '"' + str(ESCAPE_ASCII.sub(replace, s)) + '"'
class JSONEncoder(object):
"""
Extensible JSON <http://json.org> encoder for Python data structures.
Supports the following objects and types by default:
+-------------------+---------------+
| Python | JSON |
+===================+===============+
| dict | object |
+-------------------+---------------+
| list, tuple | array |
+-------------------+---------------+
| str, unicode | string |
+-------------------+---------------+
| int, long, float | number |
+-------------------+---------------+
| True | true |
+-------------------+---------------+
| False | false |
+-------------------+---------------+
| None | null |
+-------------------+---------------+
To extend this to recognize other objects, subclass and implement a
``.default()`` method with another method that returns a serializable
object for ``o`` if possible, otherwise it should call the superclass
implementation (to raise ``TypeError``).
"""
__all__ = ['__init__', 'default', 'encode', 'iterencode']
def __init__(self, skipkeys=False, ensure_ascii=True,
check_circular=True, allow_nan=True, sort_keys=False):
"""
Constructor for JSONEncoder, with sensible defaults.
If skipkeys is False, then it is a TypeError to attempt
encoding of keys that are not str, int, long, float or None. If
skipkeys is True, such items are simply skipped.
If ensure_ascii is True, the output is guaranteed to be str
objects with all incoming unicode characters escaped. If
ensure_ascii is false, the output will be unicode object.
If check_circular is True, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.
If allow_nan is True, then NaN, Infinity, and -Infinity will be
encoded as such. This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.
If sort_keys is True, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.
"""
self.skipkeys = skipkeys
self.ensure_ascii = ensure_ascii
self.check_circular = check_circular
self.allow_nan = allow_nan
self.sort_keys = sort_keys
def _iterencode_list(self, lst, markers=None):
if not lst:
yield '[]'
return
if markers is not None:
markerid = id(lst)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = lst
yield '['
first = True
for value in lst:
if first:
first = False
else:
yield ', '
for chunk in self._iterencode(value, markers):
yield chunk
yield ']'
if markers is not None:
del markers[markerid]
def _iterencode_dict(self, dct, markers=None):
if not dct:
yield '{}'
return
if markers is not None:
markerid = id(dct)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = dct
yield '{'
first = True
if self.ensure_ascii:
encoder = encode_basestring_ascii
else:
encoder = encode_basestring
allow_nan = self.allow_nan
if self.sort_keys:
keys = dct.keys()
keys.sort()
items = [(k,dct[k]) for k in keys]
else:
items = dct.iteritems()
for key, value in items:
# NOTE(kgibbs): This line was modified to replace the use of
# basestring, to make this file work under Python 2.2, which is
# commonly used at Google.
if isinstance(key, (str, unicode)):
# NOTE(kgibbs): End changes.
pass
# JavaScript is weakly typed for these, so it makes sense to
# also allow them. Many encoders seem to do something like this.
elif isinstance(key, float):
key = floatstr(key, allow_nan)
elif isinstance(key, (int, long)):
key = str(key)
elif key is True:
key = 'true'
elif key is False:
key = 'false'
elif key is None:
key = 'null'
elif self.skipkeys:
continue
else:
raise TypeError("key %r is not a string" % (key,))
if first:
first = False
else:
yield ', '
yield encoder(key)
yield ': '
for chunk in self._iterencode(value, markers):
yield chunk
yield '}'
if markers is not None:
del markers[markerid]
def _iterencode(self, o, markers=None):
# NOTE(kgibbs): This line was modified to replace the use of
# basestring, to make this file work under Python 2.2, which is
# commonly used at Google.
if isinstance(o, (str, unicode)):
# NOTE(kgibbs): End changes.
if self.ensure_ascii:
encoder = encode_basestring_ascii
else:
encoder = encode_basestring
yield encoder(o)
elif o is None:
yield 'null'
elif o is True:
yield 'true'
elif o is False:
yield 'false'
elif isinstance(o, (int, long)):
yield str(o)
elif isinstance(o, float):
yield floatstr(o, self.allow_nan)
elif isinstance(o, (list, tuple)):
for chunk in self._iterencode_list(o, markers):
yield chunk
elif isinstance(o, dict):
for chunk in self._iterencode_dict(o, markers):
yield chunk
else:
if markers is not None:
markerid = id(o)
if markerid in markers:
raise ValueError("Circular reference detected")
markers[markerid] = o
for chunk in self._iterencode_default(o, markers):
yield chunk
if markers is not None:
del markers[markerid]
def _iterencode_default(self, o, markers=None):
newobj = self.default(o)
return self._iterencode(newobj, markers)
def default(self, o):
"""
Implement this method in a subclass such that it returns
a serializable object for ``o``, or calls the base implementation
(to raise a ``TypeError``).
For example, to support arbitrary iterators, you could
implement default like this::
def default(self, o):
try:
iterable = iter(o)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, o)
"""
raise TypeError("%r is not JSON serializable" % (o,))
def encode(self, o):
"""
Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo":["bar", "baz"]}'
"""
# This doesn't pass the iterator directly to ''.join() because it
# sucks at reporting exceptions. It's going to do this internally
# anyway because it uses PySequence_Fast or similar.
chunks = list(self.iterencode(o))
return ''.join(chunks)
def iterencode(self, o):
"""
Encode the given object and yield each string
representation as available.
For example::
for chunk in JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)
"""
if self.check_circular:
markers = {}
else:
markers = None
return self._iterencode(o, markers)
__all__ = ['JSONEncoder']
| Python |
r"""
A simple, fast, extensible JSON encoder and decoder
JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
simplejson exposes an API familiar to uses of the standard library
marshal and pickle modules.
Encoding basic Python object hierarchies::
>>> import simplejson
>>> simplejson.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> print simplejson.dumps("\"foo\bar")
"\"foo\bar"
>>> print simplejson.dumps(u'\u1234')
"\u1234"
>>> print simplejson.dumps('\\')
"\\"
>>> print simplejson.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True)
{"a": 0, "b": 0, "c": 0}
>>> from StringIO import StringIO
>>> io = StringIO()
>>> simplejson.dump(['streaming API'], io)
>>> io.getvalue()
'["streaming API"]'
Decoding JSON::
>>> import simplejson
>>> simplejson.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]
>>> simplejson.loads('"\\"foo\\bar"')
u'"foo\x08ar'
>>> from StringIO import StringIO
>>> io = StringIO('["streaming API"]')
>>> simplejson.load(io)
[u'streaming API']
Specializing JSON object decoding::
>>> import simplejson
>>> def as_complex(dct):
... if '__complex__' in dct:
... return complex(dct['real'], dct['imag'])
... return dct
...
>>> simplejson.loads('{"__complex__": true, "real": 1, "imag": 2}',
... object_hook=as_complex)
(1+2j)
Extending JSONEncoder::
>>> import simplejson
>>> class ComplexEncoder(simplejson.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... return simplejson.JSONEncoder.default(self, obj)
...
>>> dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[', '2.0', ', ', '1.0', ']']
Note that the JSON produced by this module is a subset of YAML,
so it may be used as a serializer for that as well.
"""
__version__ = '1.3'
__all__ = [
'dump', 'dumps', 'load', 'loads',
'JSONDecoder', 'JSONEncoder',
]
from decoder import JSONDecoder
from encoder import JSONEncoder
def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, **kw):
"""
Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the some chunks written to ``fp``
may be ``unicode`` instances, subject to normal Python ``str`` to
``unicode`` coercion rules. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter()``) this is likely
to cause an error.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
if cls is None:
cls = JSONEncoder
iterable = cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan,
**kw).iterencode(obj)
# could accelerate with writelines in some versions of Python, at
# a debuggability cost
for chunk in iterable:
fp.write(chunk)
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, **kw):
"""
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the return value will be a
``unicode`` instance subject to normal Python ``str`` to ``unicode``
coercion rules instead of being escaped to an ASCII ``str``.
If ``check_circular`` is ``False``, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is ``False``, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg.
"""
if cls is None:
cls = JSONEncoder
return cls(skipkeys=skipkeys, ensure_ascii=ensure_ascii,
check_circular=check_circular, allow_nan=allow_nan, **kw).encode(obj)
def load(fp, encoding=None, cls=None, object_hook=None, **kw):
"""
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
be specified. Encodings that are not ASCII based (such as UCS-2) are
not allowed, and should be wrapped with
``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
object and passed to ``loads()``
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
return cls(encoding=encoding, **kw).decode(fp.read())
def loads(s, encoding=None, cls=None, object_hook=None, **kw):
"""
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg.
"""
if cls is None:
cls = JSONDecoder
if object_hook is not None:
kw['object_hook'] = object_hook
return cls(encoding=encoding, **kw).decode(s)
def read(s):
"""
json-py API compatibility hook. Use loads(s) instead.
"""
import warnings
warnings.warn("simplejson.loads(s) should be used instead of read(s)",
DeprecationWarning)
return loads(s)
def write(obj):
"""
json-py API compatibility hook. Use dumps(s) instead.
"""
import warnings
warnings.warn("simplejson.dumps(s) should be used instead of write(s)",
DeprecationWarning)
return dumps(obj)
| Python |
import web.home, web.game, web.gameroom
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
app = webapp.WSGIApplication([
('/', web.home.HomeAction)
,('/g', web.gameroom.GameroomAction)
,('/game', web.game.GameAction)
], debug=False)
def main():
run_wsgi_app(app)
if __name__ == "__main__":
main() | Python |
import os, domain.model
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template
class HomeAction(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if (user):
query = domain.model.Player.all()
query.filter("user =", user)
players = query.fetch(1)
if players:
player = players[0]
else:
player = domain.model.Player(user = user, alias = user.nickname())
player.put();
model = {'userName': user.nickname()
,'logoutURL': users.create_logout_url('/')
}
path = os.path.join(os.path.dirname(__file__), '../html/dashboard.html')
self.response.out.write(template.render(path, model))
else:
self.redirect(users.create_login_url(self.request.uri))
| Python |
import domain.model
import simplejson
from google.appengine.ext import webapp, db
from google.appengine.api import users
class GameAction(webapp.RequestHandler):
def post(self):
user = users.get_current_user()
if (user):
query = domain.model.Player.all()
query.filter("user =", user)
player = query.fetch(1)[0]
operation = self.request.get("op")
if operation == "delete":
games = domain.model.Game.all()
games.filter("creator =", player)
for game in games:
self.response.out.write("Deleted")
game.team1.delete()
game.team2.delete()
game.delete()
else:
self.redirect(users.create_login_url(self.request.uri))
def get(self):
user = users.get_current_user()
if (user):
query = domain.model.Game.all()
games = dict()
x = 0
for game in query:
x = x + 1
games[hash(x)] = {"name":game.name,
"creator":game.creator.alias,
"id" : str(game.key()),
"len" : game.playersConnected()
}
self.response.out.write(simplejson.dumps(games))
else:
self.redirect(users.create_login_url(self.request.uri))
| Python |
import os, domain.model
from google.appengine.ext import webapp, db
from google.appengine.api import users
from google.appengine.ext.webapp import template
import simplejson
class GameroomAction(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if (user):
query = domain.model.Player.all()
query.filter("user =", user)
players = query.fetch(1)
if len(players):
player = players[0]
else:
player = domain.model.Player(user = user, alias = user.nickname())
player.put()
op = self.request.get("op")
if op == "joinTeam":
self.joinTeam(player)
return
if op == "leaveTeam":
self.leaveTeam(player)
return
if op == "leave":
game = db.get(db.Key(self.request.get("id")))
if not game:
self.redirect("/")
return
else:
code = game.remove(player)
game.team1.removePlayer(player)
game.team2.removePlayer(player)
game.team1.put()
game.team2.put()
game.put()
return
if op == "check":
game = db.get(db.Key(self.request.get("id")))
if game:
players = []
for playerKey in game.players:
player = db.get(db.Key(playerKey))
players.append(player.alias)
teams = [game.team1.getPlayer1Alias(),
game.team1.getPlayer2Alias(),
game.team2.getPlayer1Alias(),
game.team2.getPlayer2Alias()]
self.response.out.write(simplejson.dumps({"players":players, "teams":teams}))
else:
self.response.out.write("Game ended")
return
if op == "join":
game = db.get(db.Key(self.request.get("id")))
if not game:
self.redirect(self.request.referer)
return
else:
game = domain.model.Game(name = self.request.get('gameName'), creator = player)
team1 = domain.model.Team(name="Team one")
team2 = domain.model.Team(name="Team two")
team1.put()
team2.put()
game.team1 = team1
game.team2 = team2
game.addPlayer(player)
game.put()
connectedPlayers = []
for key in game.players:
player = db.get(db.Key(key))
connectedPlayers.append(player)
model = {'user': user
,'logoutURL': users.create_logout_url('/')
,'game' : game
,'players' : connectedPlayers
,'isOwner' : game.creator.user == user
}
path = os.path.join(os.path.dirname(__file__), '../html/gameroom.html')
self.response.out.write(template.render(path, model))
else:
self.redirect(users.create_login_url(self.request.uri))
def post(self):
self.get()
def joinTeam(self, player):
game = db.get(db.Key(self.request.get("id")))
teamNumber = self.request.get("team")
team = game.team1
if teamNumber == "2":
team = game.team2
team.addPlayer(player)
team.put()
results = [game.team1.getPlayer1Alias(),
game.team1.getPlayer2Alias(),
game.team2.getPlayer1Alias(),
game.team2.getPlayer2Alias()]
self.response.out.write(simplejson.dumps(results))
return
def leaveTeam(self, player):
game = db.get(db.Key(self.request.get("id")))
teamNumber = self.request.get("team")
team = game.team1
if teamNumber == "2":
team = game.team2
team.removePlayer(player)
team.put()
results = [game.team1.getPlayer1Alias(),
game.team1.getPlayer2Alias(),
game.team2.getPlayer1Alias(),
game.team2.getPlayer2Alias()]
self.response.out.write(simplejson.dumps(results))
return
| Python |
from google.appengine.ext import db
from google.appengine.api import users
class Player(db.Model):
user = db.UserProperty()
alias = db.StringProperty()
class Team(db.Model):
name = db.StringProperty()
player1 = db.ReferenceProperty(Player, collection_name="teams1")
player2 = db.ReferenceProperty(Player, collection_name="teams2")
def addPlayer(self, player):
retValue = None
if not self.player1:
self.player1 = player
retValue = 1
elif not self.player2:
self.player2 = player
retValue = 2
return retValue
def removePlayer(self, player):
if self.player1 and self.player1.alias == player.alias:
self.player1 = None
elif self.player2 and self.player2.alias == player.alias:
self.player2 = None
def getPlayer1Alias(self):
if self.player1:
return self.player1.alias
else:
return None
def getPlayer2Alias(self):
if self.player2:
return self.player2.alias
else:
return None
class Game(db.Model):
name = db.StringProperty()
creator = db.ReferenceProperty(Player)
players = db.ListProperty(str)
team1 = db.ReferenceProperty(Team, collection_name="games1")
team2 = db.ReferenceProperty(Team, collection_name="games2")
def addPlayer(self, player):
if len(self.players) < 4:
self.players.append(str(player.key()))
def remove(self, player):
try:
i = self.players.index(str(player.key()))
del self.players[i]
except ValueError:
i = -1
return i
def playersConnected(self):
return len(self.players)
| Python |
import subprocess
import sys
import shlex
from optparse import OptionParser
import lib.common
import lib.constants
import lib.functions
APP_TITLE = "State Report"
parser = OptionParser()
parser.add_option("-n","--node", dest="node",help="Specify the Node to want to report state on")
parser.add_option("-g","--group", dest="group",help="Specify the Node to want to report state on")
parser.add_option("-e","--enforce",action="store_true", dest="enforce",help="Specify the Node to want to report state on")
(options, args) = parser.parse_args()
lib.functions.banner(lib.constants.TITLE + " v" + str(lib.constants.VERSION) + " -- " + APP_TITLE)
if not options.node and not options.group:
print "Nothing specified -- Exiting"
sys.exit(1)
if options.node and options.group:
print "Both node and group specified, only one at a time is support -- Exiting"
sys.exit(1)
if options.node and not lib.common.member_groups.has_key(options.node.lower()):
print "Node not set to be managed in your config -- Exiting"
sys.exit(1)
def process_state(node_name,enforce):
depends_already_passed = []
print "Node:", node_name
final_state_success = True
group_size = len(lib.common.member_groups[node_name.lower()])
for (group_count,group) in enumerate(lib.common.member_groups[node_name.lower()]):
print "Member of: '"+group+"' (" + str(group_count+1) + " of " + str(group_size) + ")"
final_state_size = len(lib.common.final_state[group.lower()])
for (final_state_count,state) in enumerate(lib.common.final_state[group.lower()]):
print "\n*** Requested Final State: '"+state+"' (" + str(final_state_count+1) + " of " + str(final_state_size) + ") ***"
depend_size = len(lib.common.full_depends[state])
for (depend_count,depend) in enumerate(lib.common.full_depends[state]):
if depend in depends_already_passed:
print " State:\t'"+state+"' has dependency: '" + depend + "'. That has already passed a dependency check... skipping. (" + str(depend_count+1) + " of " + str(depend_size) + ")"
continue
if state==depend:
print " State:\t'"+state+"' is the final state. (" + str(depend_count+1) + " of " + str(depend_size) + ")"
else:
print " State:\t'"+state+"' has dependency: '" + depend + "'. Checking to see if '"+depend+"' is in correct state. (" + str(depend_count+1) + " of " + str(depend_size) + ")"
retry_count = 0
retry_loop=True
depend_passed = 0
check_command_size = len(lib.common.checks[depend])
while retry_loop and retry_count <= 1:
retry_count += 1
for (check_command_count,check_command) in enumerate(lib.common.checks[depend]):
connect_string = shlex.split(lib.common.nodes[node_name.lower()] + ' "' + check_command +'"')
try:
subprocess.check_call(connect_string,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print "\tPASS\t--\t(" + str(check_command_count+1) + " of " + str(check_command_size) + ")\t" + check_command
retry_loop=False
depend_passed+=1
except subprocess.CalledProcessError:
print "\tFAIL\t--\t(" + str(check_command_count+1) + " of " + str(check_command_size) + ")\t" + check_command
if enforce:
retry_loop = True
print "Attempting Remedy:"
for remedy_command in lib.common.remedys[depend]:
connect_string = shlex.split(lib.common.nodes[node_name.lower()] + ' "' + remedy_command +'"')
print " cmd:\t",remedy_command
try:
subprocess.check_call(connect_string,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
except:
continue
else:
retry_loop = False
if depend_passed == check_command_size:
if depend not in depends_already_passed:
depends_already_passed.append(depend)
else:
final_state_success=False
return final_state_success
if options.node:
final_state_success = process_state(options.node.lower(),options.enforce)
print ""
if final_state_success:
print "PASS: " + options.node + " is in it's correct Final State"
sys.exit(0)
else:
print "FAIL: " + options.node + " is NOT in it's correct Final State"
sys.exit(1)
if options.group and lib.common.groups.has_key(options.group.lower()):
node_count = len(lib.common.groups[options.group.lower()])
group_state_success = []
for (index,node) in enumerate(lib.common.groups[options.group.lower()]):
print "**** Processing Group: " + options.group + " -- Current Node: " + node + " (" +str(index+1) + " of " + str(node_count) + ") ****\n"
group_state_success.append((node,process_state(node.lower(),options.enforce)))
print ""
lib.functions.banner("State Report for Group:" + options.group)
for (node,state) in group_state_success:
if state:
print " " + node + "\tPASS"
else:
print " " + node + "\tFAIL"
print ""
| Python |
# -*- coding: utf-8 -*-
#
# jQuery File Upload Plugin GAE Python Example 2.1.0
# https://github.com/blueimp/jQuery-File-Upload
#
# Copyright 2011, Sebastian Tschan
# https://blueimp.net
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
from __future__ import with_statement
from google.appengine.api import files, images
from google.appengine.ext import blobstore, deferred
from google.appengine.ext.webapp import blobstore_handlers
import json
import re
import urllib
import webapp2
WEBSITE = 'http://blueimp.github.io/jQuery-File-Upload/'
MIN_FILE_SIZE = 1 # bytes
MAX_FILE_SIZE = 5000000 # bytes
IMAGE_TYPES = re.compile('image/(gif|p?jpeg|(x-)?png)')
ACCEPT_FILE_TYPES = IMAGE_TYPES
THUMBNAIL_MODIFICATOR = '=s80' # max width / height
EXPIRATION_TIME = 300 # seconds
def cleanup(blob_keys):
blobstore.delete(blob_keys)
class UploadHandler(webapp2.RequestHandler):
def initialize(self, request, response):
super(UploadHandler, self).initialize(request, response)
self.response.headers['Access-Control-Allow-Origin'] = '*'
self.response.headers[
'Access-Control-Allow-Methods'
] = 'OPTIONS, HEAD, GET, POST, PUT, DELETE'
self.response.headers[
'Access-Control-Allow-Headers'
] = 'Content-Type, Content-Range, Content-Disposition'
def validate(self, file):
if file['size'] < MIN_FILE_SIZE:
file['error'] = 'File is too small'
elif file['size'] > MAX_FILE_SIZE:
file['error'] = 'File is too big'
elif not ACCEPT_FILE_TYPES.match(file['type']):
file['error'] = 'Filetype not allowed'
else:
return True
return False
def get_file_size(self, file):
file.seek(0, 2) # Seek to the end of the file
size = file.tell() # Get the position of EOF
file.seek(0) # Reset the file position to the beginning
return size
def write_blob(self, data, info):
blob = files.blobstore.create(
mime_type=info['type'],
_blobinfo_uploaded_filename=info['name']
)
with files.open(blob, 'a') as f:
f.write(data)
files.finalize(blob)
return files.blobstore.get_blob_key(blob)
def handle_upload(self):
results = []
blob_keys = []
for name, fieldStorage in self.request.POST.items():
if type(fieldStorage) is unicode:
continue
result = {}
result['name'] = re.sub(
r'^.*\\',
'',
fieldStorage.filename
)
result['type'] = fieldStorage.type
result['size'] = self.get_file_size(fieldStorage.file)
if self.validate(result):
blob_key = str(
self.write_blob(fieldStorage.value, result)
)
blob_keys.append(blob_key)
result['deleteType'] = 'DELETE'
result['deleteUrl'] = self.request.host_url +\
'/?key=' + urllib.quote(blob_key, '')
if (IMAGE_TYPES.match(result['type'])):
try:
result['url'] = images.get_serving_url(
blob_key,
secure_url=self.request.host_url.startswith(
'https'
)
)
result['thumbnailUrl'] = result['url'] +\
THUMBNAIL_MODIFICATOR
except: # Could not get an image serving url
pass
if not 'url' in result:
result['url'] = self.request.host_url +\
'/' + blob_key + '/' + urllib.quote(
result['name'].encode('utf-8'), '')
results.append(result)
deferred.defer(
cleanup,
blob_keys,
_countdown=EXPIRATION_TIME
)
return results
def options(self):
pass
def head(self):
pass
def get(self):
self.redirect(WEBSITE)
def post(self):
if (self.request.get('_method') == 'DELETE'):
return self.delete()
result = {'files': self.handle_upload()}
s = json.dumps(result, separators=(',', ':'))
redirect = self.request.get('redirect')
if redirect:
return self.redirect(str(
redirect.replace('%s', urllib.quote(s, ''), 1)
))
if 'application/json' in self.request.headers.get('Accept'):
self.response.headers['Content-Type'] = 'application/json'
self.response.write(s)
def delete(self):
blobstore.delete(self.request.get('key') or '')
class DownloadHandler(blobstore_handlers.BlobstoreDownloadHandler):
def get(self, key, filename):
if not blobstore.get(key):
self.error(404)
else:
# Prevent browsers from MIME-sniffing the content-type:
self.response.headers['X-Content-Type-Options'] = 'nosniff'
# Cache for the expiration time:
self.response.headers['Cache-Control'] = 'public,max-age=%d' % EXPIRATION_TIME
# Send the file forcing a download dialog:
self.send_blob(key, save_as=filename, content_type='application/octet-stream')
app = webapp2.WSGIApplication(
[
('/', UploadHandler),
('/([^/]+)/([^/]+)', DownloadHandler)
],
debug=True
)
| Python |
#!/usr/bin/env python
#********************************************************************
# Filename: FINally.py
# Authors: Daniel Sisco
# Date Created: 4-20-2007
#
# Abstract: This is the primary file for the FINally expense analysis tool. It is responsible for
# handling read/write access to the SQLite database as well as providing a GUI interface for the user.
#
# Copyright 2008-2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
# import wxPython libraries - including some simplifiers for grid and calendar
import wx
import wx.grid as gridlib
import wx.calendar as callib
import cfg
import os
from datetime import date, datetime
from database import *
from wx._core import WXK_F1, WXK_F2
from grid import GraphicsGrid
from statusBar import CustomStatusBar
from menuBar import CreateMenu
from prefs import EditPreferences, SaveWindowPreferences
from filterControl import CustomFilterPanel
from expenseDialogue import NewExpenseDialog
from expenseTypeDialog import expenseTypeDialog
from userDialog import userDialog
try:
from agw import flatmenu as FM
from agw.artmanager import ArtManager, RendererBase, DCSaver
from agw.fmresources import ControlFocus, ControlPressed
from agw.fmresources import FM_OPT_SHOW_CUSTOMIZE, FM_OPT_SHOW_TOOLBAR, FM_OPT_MINIBAR
except ImportError: # if it's not there locally, try the wxPython lib.
import wx.lib.agw.flatmenu as FM
from wx.lib.agw.artmanager import ArtManager, RendererBase, DCSaver
from wx.lib.agw.fmresources import ControlFocus, ControlPressed
from wx.lib.agw.fmresources import FM_OPT_SHOW_CUSTOMIZE, FM_OPT_SHOW_TOOLBAR, FM_OPT_MINIBAR
import wx.aui as AUI
AuiPaneInfo = AUI.AuiPaneInfo
AuiManager = AUI.AuiManager
#********************************************************************
# FINally class definitions
#********************************************************************
class GraphicsPage(wx.Panel):
"""
Class Name: GraphicsPage
Extends: wx.Panel
Description: The Graphics page contains two things - a grid or table of entries,
and a button panel to perform some operations on the grid.
"""
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.SetBackgroundColour("GREY")
# bind keyboard events
self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
# create wx.Grid object
self.grid = GraphicsGrid(self)
# create a userlist and type list for the menus
# NOTE: this must be done after the Database creation above
# define local Expense objects for population
self.database = Database()
self.userList = self.database.GetSimpleUserList()
self.typeList = self.database.GetExpenseTypeList()
# create a sizer for this Panel and add the buttons and the table
self.sizer = wx.BoxSizer(wx.VERTICAL) # define new box sizer
self.sizer.Add(self.grid, 1, wx.GROW) # add grid (resize vert and horz)
self.SetSizer(self.sizer)
def ShowNewExpenseDialogue(self, event):
dia = NewExpenseDialog(self, -1, 'New Expense Entry')
dia.ShowModal()
dia.Destroy()
def OnKeyDown(self, event):
# F1 = new expense
if (event.GetKeyCode() == WXK_F1):
dia = NewExpenseDialog(self, -1, 'New Expense Entry')
dia.ShowModal()
dia.Destroy()
event.Skip()
#***************************
# NOT REQUIRED AT THIS TIME
#***************************
def OnUserSelect(self, evt):
pass
def OnTypeSelect(self, evt):
pass
def OnCalSelChanged(self, evt):
print "DATE", self.cal.PyGetDate()
pass
def OnValueEntry(self, evt):
pass
def OnDescEntry(self, evt):
pass
#********************************************************************
class AppMainFrame(wx.Frame):
"""This class inherts wx.Frame methods, and is the top level window of our application."""
size = (900,400)
def __init__(self, title):
wx.Frame.__init__( self,
None,
id=-1,
title=title,
pos=wx.DefaultPosition,
size=AppMainFrame.size,
style=wx.DEFAULT_FRAME_STYLE)
# define AUI manager
self._mgr = AuiManager()
self._mgr.SetManagedWindow(self)
self.database = Database()
# add an icon!
self.icon = wx.Icon("img/FINally.png", wx.BITMAP_TYPE_PNG)
self.SetIcon(self.icon)
self.sb = CustomStatusBar(self)
self.SetStatusBar(self.sb)
self.panel = wx.Panel(self) # basically just a container for the notebook
self.notebook = wx.Notebook(self.panel, size=AppMainFrame.size)
self.gPage = GraphicsPage(self.notebook)
self.notebook.AddPage(self.gPage, "Grid")
# populate and connect the menuBar
CreateMenu(self)
# Create the filter panel
self.filterPanel = CustomFilterPanel(self.panel)
# arrange notebook windows in a simple box sizer
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sizer.Add(self.notebook, 1, wx.EXPAND)
self.sizer.Add(self.filterPanel, 0, wx.ALIGN_BOTTOM)
self.panel.SetSizer(self.sizer)
# support for AUI content
self._mgr.AddPane(self.panel, AuiPaneInfo().Name("main_panel").CenterPane())
self.menuBar.PositionAUI(self._mgr)
self._mgr.Update()
ArtManager.Get().SetMBVerticalGradient(True)
ArtManager.Get().SetRaiseToolbar(False)
self.menuBar.Refresh()
def SetBackgroundColor(self, colorString):
self.SetBackgroundColour(colorString)
def OnQuit(self, event):
localSize = self.GetSize()
SaveWindowPreferences(localSize[0], localSize[1])
self._mgr.UnInit()
self.Destroy()
def OnPrefs(self, event):
EditPreferences(self, event)
def OnAbout(self, event):
msg = "Welcome to FINally!\n\n" + \
"Author: Daniel LaBeau Sisco @ 10/10/2010\n\n" + \
"Please report any bug/requests or improvements\n" + \
"to Daniel Sisco at the following email address:\n\n" + \
"daniel.sisco@gmail.com\n\n" + \
"Please visit FINally at http://code.google.com/p/fin-ally/ for more information\n"
dlg = wx.MessageDialog(self, msg, "About FINally",
wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
def OnUnsupported(self, event):
msg = "...this feature is unsupported!\n You should complain to Daniel Sisco at the following email address:\n\n" + \
"daniel.sisco@gmail.com\n\n"
dlg = wx.MessageDialog(self, msg, "Sorry...",
wx.OK)
dlg.ShowModal()
dlg.Destroy()
def OnEditExpenseType(self, event):
dlg = expenseTypeDialog(self, -1, 'Edit Expense Types')
dlg.ShowModal()
dlg.Destroy()
def OnEditUser(self, event):
dlg = userDialog(self, -1, 'Edit Users')
dlg.ShowModal()
dlg.Destroy()
#********************************************************************
class AppLauncher(wx.App):
"""This class inherits wx.App methods, and should be the first object created during FINally
operation. This will be the only instance of an application class and will contain the primary
Frame (top level window)."""
# static variables go here
title = "FINally v%s.%s.%s" % (cfg.VERSION[0], cfg.VERSION[1], cfg.VERSION[2])
def OnInit(self):
"""Should be used instead of __init__ for Application objects"""
# create and make visible a "top level window" of type wxFrame
self.frame = AppMainFrame(AppLauncher.title)
self.frame.Show(True)
self.SetTopWindow(self.frame)
return True # required during OnInit
def Main(self):
"""kicks off the application heartbeat, which means that we let wxPython watch for user
input (mouse, keyboard, etc...) and respond"""
self.MainLoop()
def GetTitle(self):
"""returns the title of the application - as shown in the top level window"""
return AppLauncher.title
def GetVersion(self):
"""returns the version of this application"""
return AppLauncher.version
#*******************************************************************************************************
# MAIN
#*******************************************************************************************************
if __name__ == '__main__':
"""This is the starting point for the FIN-ally application. All functionality that must occur
pre-GUI-start must be placed here. The final action in this main fcn should be the launch of
the GUI Main."""
# perform database migrations if necessary - passing the version the application
# will be working with to the migration script (ie: schemaVersion)
schemaVersion = "%s_%s" % (dbVer[0], dbVer[1]) # reformatting needed for passing via CLI
string = "python migrate.py %s" % (schemaVersion)
print "executing command: \n>", string
os.system(string)
# create an instance of the Database class and then perform the initial database ID
db = Database();
db.Create() #TODO: move this into a database __init__ function?
# create highest level wx object (wxApp) instance
launcher = AppLauncher(redirect=False)
launcher.Main()
| Python |
#!/usr/bin/env python
#********************************************************************
# Filename: utils.py
# Authors: Daniel Sisco
# Date Created: 1-22-2008
#
# Abstract: A collection of utilities for the Fin-ally project. This
# file should include most generic utilities. Examples include debug print
# function, file locators, current directory locators, etc.
#
# Version History: See repository
#
# Copyright 2008 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fn-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
import glob, os, sys, re, cfg
from datetime import date, datetime
BLANK_TERM = "[BLANK]"
# global month dictionary
monthDict = {"January": 1,
"February": 2,
"March": 3,
"April": 4,
"May": 5,
"June": 6,
"July": 7,
"August": 8,
"September": 9,
"October": 10,
"November": 11,
"December": 12}
#********************************************************************
def GenFileList(searchString):
"""This generator function returns a list of all files matching the searchString in a directory"""
for match in glob.glob(os.path.join(GetCurrentDir(), searchString)):
yield match
#********************************************************************
def GetCurrentDir():
"""This function returns the absolute path to this Python script"""
pathname = os.path.dirname(sys.argv[0])
return(os.path.abspath(pathname))
#********************************************************************
def dPrint(string):
if cfg.DEBUG == 1:
print string
#********************************************************************
def dateMatch(dateString):
"""Parses the dateString looking for a pre-defined date/time format.
Returns a safe datetime object (Jan 1, 1A) if no match is found.
Returns the datetime object corresponding to the dateString if a match
is found."""
if(re.match('\d{1.2}-\d{1,2}-\d{4}', dateString)):
localDate = datetime.strptime(dateString, "%m-%d-%Y")
elif(re.match('\d{1,2}\/\d{1,2}\/\d{4}', dateString)):
localDate = datetime.strptime(dateString, "%m/%d/%Y")
elif(re.match('\d{1,2}\.\d{1,2}\.\d{4}', dateString)):
localDate = datetime.strptime(dateString, "%m.%d.%Y")
else:
dateString = '1/1/0001'
localDate = datetime.strptime(dateString, "%m/%d/%Y")
print "using default date - no match found"
# return just the date portion of the datetime object
return localDate.date()
# Test main functionality
if __name__ == '__main__':
print "Please run Fin-ally by launching FINally.py!" | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: schema_2_0.py
# Authors: Daniel Sisco
# Date Created: 9/19/2010
#
# Abstract: Version 1.0 of the FINally database schema
#
# Version History: See repository
#
# Copyright 2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
from sqlmigratelite.migrate import MigrateObject
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref, eagerload
from sqlalchemy.orm.exc import NoResultFound
Base = declarative_base()
version = "2.0"
dbVer = (2,0)
#********************************************************************
# Create SQLAlchemy tables in the form of python classes.
#********************************************************************
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
shortName = Column(String)
def __repr__(self):
return "<User('%s', '%s')>" % (self.name, self.shortName)
#********************************************************************
class ExpenseType(Base):
__tablename__ = 'expenseTypes'
id = Column(Integer, primary_key=True)
description = Column(String)
def __repr__(self):
return "<ExpenseType('%s')>" % (self.description)
#********************************************************************
class Expense(Base):
__tablename__ = 'expenses'
id = Column(Integer, primary_key=True)
amount = Column(Integer)
date = Column(String)
description = Column(String)
# define user_id to support database level link and user for class level link
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship(User, backref=backref('expenses', order_by=id))
expenseType_id = Column(Integer, ForeignKey('expenseTypes.id'))
expenseType = relationship(ExpenseType, backref=backref('expenses', order_by=id))
def __repr__(self):
return "<Expense('%s', '%s', '%s')>" % (self.amount, self.date, self.description)
#********************************************************************
class Preference(Base):
__tablename__ = 'preferences'
id = Column(Integer, primary_key=True)
defUser_id = Column(Integer, ForeignKey('users.id'))
defUser = relationship(User, backref=backref('preferences', order_by=id))
defExpenseType_id = Column(Integer, ForeignKey('expenseTypes.id'))
defExpenseType = relationship(ExpenseType, backref=backref('preferences', order_by=id))
defAmount = Column(Integer)
def __repr__(self):
return "<Preference('%s, %s, %s')>" % (self.defUser_id, self.defExpenseType_id, self.defAmount)
#********************************************************************
class Version(Base):
__tablename__ = 'versions'
id = Column(Integer, primary_key=True)
minor = Column(Integer)
major = Column(Integer)
def __repr__(self):
return "<Version('%s', '%s')>" % (self.minor, self.major)
#************************************
class SchemaObject(MigrateObject):
"""
version 2.0 schema object - defines custom dumpContent and loadContent methods
"""
def __init__(self, dbPath):
MigrateObject.__init__(self, dbPath, version)
def dumpContent(self):
"""dumps User and Version tables as-is"""
self.localDict['User'] = self.session.query(User).all()
self.localDict['ExpenseType'] = self.session.query(ExpenseType).all()
self.localDict['Expense'] = self.session.query(Expense).all()
self.localDict['Preference'] = self.session.query(Preference).all()
def loadContent(self):
Base.metadata.create_all(self.engine)
for i in self.localDict['User']:
u = User()
u.name = i.name
u.shortName = i.shortName
self.session.add(u)
self.session.commit()
for i in self.localDict['ExpenseType']:
t = ExpenseType()
t.description = i.description
self.session.add(t)
self.session.commit()
for i in self.localDict['Expense']:
e = Expense()
e.user_id = i.user_id
e.expenseType_id = i.expenseType_id
e.amount = i.amount
e.date = i.date
e.description = i.description
self.session.add(e)
self.session.commit()
# update the version number
# TODO: move this into sqlmigratelite core
v = Version(minor=dbVer[1], major=dbVer[0])
self.session.add(v)
self.session.commit() | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: expenseDialogue.py
# Authors: Daniel Sisco
# Date Created: 10/31/2010
#
# Abstract: This is the primary file for the FINally expense analysis tool. It is responsible for
# handling read/write access to the SQLite database as well as providing a GUI interface for the user.
#
# Copyright 2008-2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
# import wxPython libraries - including some simplifiers for grid and calendar
import wx
import wx.calendar as callib
import wx.grid as gridlib
import cfg
import os
from datetime import date, datetime
from database import *
#********************************************************************
class NewExpenseDialog(wx.Dialog):
def __init__(self, parent, *args, **kwds):
# begin wxGlade: NewExpenseDialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, parent, *args, **kwds)
#**** ADDED ****
self.database = Database()
self.userList = self.database.GetSimpleUserList()
self.typeList = self.database.GetExpenseTypeList()
self.prefs = self.database.GetPrefs()
self.parent = parent
#**** END ADD ****
self.CalSizer_staticbox = wx.StaticBox(self, -1, "Expense Date")
self.ExpenseStaticSizer_staticbox = wx.StaticBox(self, -1, "Expense Info")
self.UserSizer_staticbox = wx.StaticBox(self, -1, "User")
#**** MOD ****
self.userControl = wx.ComboBox(self, -1, value=str(self.prefs.defUser_id), choices=self.userList, style=wx.CB_DROPDOWN|wx.CB_DROPDOWN)
#**** MOD ****
self.calendarControl = callib.CalendarCtrl(self, -1, wx.DateTime_Now())
self.amountText = wx.StaticText(self, -1, "amount")
#**** MOD ****
self.amountControl = wx.TextCtrl(self, -1, str(self.prefs.defAmount))
self.expenseTypeText = wx.StaticText(self, -1, "expense type")
#**** MOD ****
self.expenseTypeControl = wx.ComboBox(self, -1, value=str(self.prefs.defExpenseType_id), choices=self.typeList, style=wx.CB_DROPDOWN|wx.CB_DROPDOWN)
self.descriptionText = wx.StaticText(self, -1, "description")
#**** MOD ****
self.descriptionControl = wx.TextCtrl(self, -1, "item description")
self.okButton = wx.Button(self, wx.ID_OK, "")
self.cancelButton = wx.Button(self, wx.ID_CANCEL, "")
self.__set_properties()
self.__do_layout()
self.Bind(wx.EVT_COMBOBOX, self.OnUserSelect, self.userControl)
self.Bind(wx.EVT_TEXT, self.OnValueEntry, self.amountControl)
self.Bind(wx.EVT_COMBOBOX, self.OnTypeSelect, self.expenseTypeControl)
self.Bind(wx.EVT_TEXT, self.OnDescEntry, self.descriptionControl)
self.Bind(wx.EVT_BUTTON, self.OnOkButton, self.okButton)
self.Bind(wx.EVT_BUTTON, self.onCancelButton, self.cancelButton)
# end wxGlade
def __set_properties(self):
# begin wxGlade: NewExpenseDialog.__set_properties
self.SetTitle("New Expense Dialog")
self.amountText.SetMinSize((80, 23))
self.expenseTypeText.SetMinSize((80, 23))
self.descriptionText.SetMinSize((80, 23))
self.amountControl.SetMinSize((150, -1))
self.expenseTypeControl.SetMinSize((150, -1))
self.descriptionControl.SetMinSize((150, -1))
self.okButton.SetDefault()
# end wxGlade
def __do_layout(self):
# begin wxGlade: NewExpenseDialog.__do_layout
VerticalSizer = wx.BoxSizer(wx.VERTICAL)
ButtonSizer = wx.BoxSizer(wx.HORIZONTAL)
sizer_1 = wx.BoxSizer(wx.HORIZONTAL)
ExpenseSizer = wx.BoxSizer(wx.HORIZONTAL)
ExpenseStaticSizer = wx.StaticBoxSizer(self.ExpenseStaticSizer_staticbox, wx.HORIZONTAL)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_3 = wx.BoxSizer(wx.VERTICAL)
CalSizer = wx.StaticBoxSizer(self.CalSizer_staticbox, wx.HORIZONTAL)
UserSizer = wx.StaticBoxSizer(self.UserSizer_staticbox, wx.HORIZONTAL)
UserSizer.Add(self.userControl, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
VerticalSizer.Add(UserSizer, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, 5)
CalSizer.Add(self.calendarControl, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
VerticalSizer.Add(CalSizer, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
sizer_3.Add(self.amountText, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_3.Add(self.expenseTypeText, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_3.Add(self.descriptionText, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
ExpenseStaticSizer.Add(sizer_3, 0, 0, 0)
sizer_2.Add(self.amountControl, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.expenseTypeControl, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_2.Add(self.descriptionControl, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
ExpenseStaticSizer.Add(sizer_2, 0, wx.EXPAND, 0)
ExpenseSizer.Add(ExpenseStaticSizer, 1, wx.LEFT|wx.RIGHT|wx.BOTTOM, 5)
VerticalSizer.Add(ExpenseSizer, 0, wx.TOP|wx.EXPAND, 5)
sizer_1.Add(self.okButton, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
sizer_1.Add(self.cancelButton, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
ButtonSizer.Add(sizer_1, 1, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
VerticalSizer.Add(ButtonSizer, 0, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
self.SetSizer(VerticalSizer)
VerticalSizer.Fit(self)
self.Layout()
# end wxGlade
def OnUserSelect(self, event): # wxGlade: NewExpenseDialog.<event_handler>
event.Skip()
def OnCalSelChanged(self, event): # wxGlade: NewExpenseDialog.<event_handler>
event.Skip()
def OnValueEntry(self, event): # wxGlade: NewExpenseDialog.<event_handler>
event.Skip()
def OnTypeSelect(self, event): # wxGlade: NewExpenseDialog.<event_handler>
event.Skip()
def OnDescEntry(self, event): # wxGlade: NewExpenseDialog.<event_handler>
event.Skip()
def OnOkButton(self, event): # wxGlade: NewExpenseDialog.<event_handler>
"""respond to the user clicking 'enter!' by pushing the local objects into the database
layer"""
# it's critical to create a new expense object here to avoid overwriting
# an existing expense object. However, we will *not* create user
# or expenseType because calls below create a new expense
localExpenseObject = Expense()
#
# NOTE: operator selects both User and ExpenseType by selecting a string.
# This string is used to look up the existing database objects, which are
# fed to the overall Expense object for creation. These calls also create
# new User and ExpenseType objects as well as populate them.
#
# TODO: this needs to be smarter: (A) what if the string doesn't match an existing
# object? (B) What if the user wants to enter a new object?
#
# configure amount, description, and date
amount = self.amountControl.GetValue()
# place something here to avoid math errors
if(amount == ""):
amount = 0.00
# consolidate objects into one expense type and push into database
self.database.CreateExpense(float(amount),
self.descriptionControl.GetValue(),
self.calendarControl.PyGetDate(),
self.userControl.GetValue(),
self.expenseTypeControl.GetValue())
# update grid with new row, format new row
self.parent.grid.tableBase.UpdateData()
self.Close()
def onCancelButton(self, event): # wxGlade: NewExpenseDialog.<event_handler>
#**** MOD ****
self.Destroy()
event.Skip() | Python |
import wx.grid as gridlib
#********************************************************************
class columnInfo:
"""This class defines the information required to create and modify columns in
a grid. This keeps all columns definition data together, but adding information here
does complete the addition of a new column."""
# TODO: consolidate these into a dict or some other structure
colLabels = ('user', 'type', 'amount', 'date', 'desc', 'id', 'del')
defColWidth = "100,50,50,200,300,50,50"
# col widths are now stored in the database - only defaults are stored here
#colWidth = [100, 50, 50, 200, 300, 50, 50]
colRO = [0,0,0,0,0,1,0] # 0 = R/W, 1 = R
colType = [gridlib.GRID_VALUE_CHOICE,
gridlib.GRID_VALUE_CHOICE,
gridlib.GRID_VALUE_NUMBER,
gridlib.GRID_VALUE_STRING, # should be GRID_VALUE_DATETIME
gridlib.GRID_VALUE_STRING,
gridlib.GRID_VALUE_NUMBER,
gridlib.GRID_VALUE_STRING]
rowHeight = 20
# create global instances of classes
colInfo = columnInfo() | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: userDialog.py
# Authors: Daniel Sisco
# Date Created: 11/5/2010
#
# Abstract: This files contains the user add/edit/delete dialog.
#
# Copyright 2008-2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
# import wxPython libraries - including some simplifiers for grid and calendar
import wx
import wx.calendar as callib
import wx.grid as gridlib
import cfg
import os
from datetime import date, datetime
from database import *
from grid import CustomDataTable
#********************************************************************
class UserColumnInfo:
"""This class defines the information required to create and modify columns in
a grid. This keeps all columns definition data together, but adding information here
does complete the addition of a new column."""
colLabels = ('user', 'short')
colWidth = [100, 50]
colRO = [0, 0] # 0 = R/W, 1 = R
colType = [gridlib.GRID_VALUE_STRING,
gridlib.GRID_VALUE_STRING]
rowHeight = 20
#********************************************************************
class SimpleUserGrid(gridlib.Grid):
"""This is a simple grid class - which means most of the methods are automatically
defined by the wx library"""
def __init__(self, parent):
gridlib.Grid.__init__(self, parent, -1, size=(250,300))
self.CreateGrid(25,2)
# apply column labels
for i in range(len(UserColumnInfo.colLabels)):
self.SetColLabelValue(i, UserColumnInfo.colLabels[i])
# apply columns width
for i in range(len(UserColumnInfo.colWidth)):
self.SetColSize(i, UserColumnInfo.colWidth[i])
# create a Database object and pull some data out of it
self.database = Database()
data = self.database.GetUserList()
# used for refreshing the grid if users are edited
self.dataTable = CustomDataTable(gridlib.Grid)
self.oldNameValue = ""
self.Bind(gridlib.EVT_GRID_CELL_CHANGE, self.OnCellChange)
self.Bind(gridlib.EVT_GRID_EDITOR_SHOWN, self.OnEditorShown)
self.rowAttr = gridlib.GridCellAttr()
self.CreateReadOnlyCols()
# push data into grid, line by line
for i in range(len(data)):
self.SetCellValue(i,0,str(data[i].name))
self.SetCellValue(i,1,str(data[i].shortName))
def OnCellChange(self, evt):
"""Using a class variable that stores the previous ExpenseType description,
this method edits the ExpenseType table in the database"""
# new value and ID are the same for both columns
newValue = self.GetCellValue(evt.GetRow(), evt.GetCol())
uId = self.database.GetUserId(self.oldNameValue)
if 0 == evt.GetCol():
self.database.EditUser(newValue, self.GetCellValue(evt.GetRow(), evt.GetCol()+1), uId)
else:
self.database.EditUser(self.GetCellValue(evt.GetRow(), evt.GetCol()-1), newValue, uId)
# refresh grid
self.dataTable.UpdateData()
evt.Skip()
def OnEditorShown(self, evt):
"""This method stores the current value into a class variable before
the user attempts to edit. This allows us to look-up ExpenseType id
by the 'old description' before the user changes it"""
if 0 == evt.GetCol():
self.oldNameValue = self.GetCellValue(evt.GetRow(), evt.GetCol())
else:
self.oldNameValue = self.GetCellValue(evt.GetRow(), evt.GetCol()-1)
evt.Skip()
def RefreshData(self, delete=0):
"""The delete argument removes one row from the top of the simple grid.
There is currently no way to delete more than one row at a time, so this
is safe."""
if(delete == 1):
# remove the last row
self.DeleteRows(0,1)
# push data into grid, line by line
data = self.database.GetUserList()
for i in range(len(data)):
self.SetCellValue(i,0,str(data[i].name))
self.SetCellValue(i,1,str(data[i].shortName))
def CreateReadOnlyCols(self):
"""creates read-only columns"""
self.rowAttr.SetReadOnly(1)
for i in range(len(UserColumnInfo.colRO)):
if UserColumnInfo.colRO[i] == 1:
self.SetColAttr(i,self.rowAttr)
self.rowAttr.IncRef()
#********************************************************************
class userDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: userDialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
#**** BEGIN ADD ****
self.database = Database()
self.dataTable = CustomDataTable(gridlib.Grid)
self.userChoices = self.database.GetSimpleUserList()
self.newUserFullName = "new user full name..."
self.newUserShortName = "new user short name..."
self.deleteSizer_staticbox = wx.StaticBox(self, -1, "Delete Existing Users")
self.newTypeSizer_staticbox = wx.StaticBox(self, -1, "Add New Users")
self.editSizer_staticbox = wx.StaticBox(self, -1, "Edit Existing Users")
#**** MOD ****
self.userGrid = SimpleUserGrid(self)
self.userEditToggle = wx.ToggleButton(self, -1, "edit users...")
#*** MOD ***
self.deleteComboBox = wx.ComboBox(self,
-1,
self.userChoices[0], #default
choices=self.userChoices,
style=wx.CB_DROPDOWN)
self.deleteButton = wx.Button(self, -1, "delete")
self.shortNameEntry = wx.TextCtrl(self, -1, "new user short name...")
self.addButton = wx.Button(self, -1, "add")
self.nameEntry = wx.TextCtrl(self, -1, "new user full name...")
self.__set_properties()
self.__do_layout()
#**** ADDED ****
self.Bind(wx.EVT_BUTTON, self.onDeleteButton, self.deleteButton)
self.Bind(wx.EVT_BUTTON, self.onAddButton, self.addButton)
#**** END ADD ****
# end wxGlade
def __set_properties(self):
# begin wxGlade: userDialog.__set_properties
self.SetTitle("User Dialog")
#**** MOD ****
# end wxGlade
def __do_layout(self):
# begin wxGlade: userDialog.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
newTypeSizer = wx.StaticBoxSizer(self.newTypeSizer_staticbox, wx.VERTICAL)
innerNameSizer = wx.BoxSizer(wx.HORIZONTAL)
innerShortNameSizer = wx.BoxSizer(wx.HORIZONTAL)
deleteSizer = wx.StaticBoxSizer(self.deleteSizer_staticbox, wx.VERTICAL)
innerDeleteSizer = wx.BoxSizer(wx.HORIZONTAL)
editSizer = wx.StaticBoxSizer(self.editSizer_staticbox, wx.VERTICAL)
sizer_8 = wx.BoxSizer(wx.VERTICAL)
sizer_8.Add(self.userGrid, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_8.Add(self.userEditToggle, 0, wx.RIGHT|wx.TOP|wx.BOTTOM|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
editSizer.Add(sizer_8, 1, wx.EXPAND, 0)
sizer_2.Add(editSizer, 1, wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 5)
innerDeleteSizer.Add(self.deleteComboBox, 1, wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
innerDeleteSizer.Add(self.deleteButton, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
deleteSizer.Add(innerDeleteSizer, 1, wx.EXPAND, 0)
sizer_2.Add(deleteSizer, 0, wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 5)
innerShortNameSizer.Add(self.shortNameEntry, 1, wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
innerShortNameSizer.Add(self.addButton, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
newTypeSizer.Add(innerShortNameSizer, 1, wx.EXPAND, 0)
innerNameSizer.Add(self.nameEntry, 1, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
newTypeSizer.Add(innerNameSizer, 1, wx.TOP|wx.EXPAND, 3)
sizer_2.Add(newTypeSizer, 0, wx.ALL|wx.EXPAND, 5)
sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
#**** ADDED ****
def onAddButton(self, event):
"""triggers when the add button is clicked in the user dialog. This function
determines if conditions are correct for a new user entry and creates that user"""
localName = self.nameEntry.GetValue()
localShortName = self.shortNameEntry.GetValue()
if( localName != self.newUserFullName
and localShortName != self.newUserShortName):
# create new entry
success = self.database.CreateUser(localName, localShortName)
# reset text in text entry box
self.nameEntry.SetValue(self.newUserFullName)
self.shortNameEntry.SetValue(self.newUserShortName)
# refresh Grid
self.userGrid.RefreshData()
self.dataTable.UpdateData()
if success:
# refresh comboBox choices and add new entry
self.userChoices = self.database.GetUserList()
self.deleteComboBox.Append(localName)
else:
print "please enter user information!"
event.Skip()
def onDeleteButton(self, event):
"""triggered when the delete button is clicked in the user dialog. This function
either processes the deletion of a particular user entry, or informs the user
that a deletion is not possible at this time.
TODO: trigger another dialog to allow the user to specify a 'transfer to' user
before deleting a user record that is in use."""
if(self.userEditToggle.GetValue()):
typeToDelete = self.deleteComboBox.GetValue()
IdxToDelete = self.deleteComboBox.GetSelection()
localId = self.database.GetUserId(typeToDelete)
if localId != -1:
if(self.database.UserInUse(localId)):
# TODO: prompt user for new expenseType to apply using MigrateExpenseType
print "there are %s expenses using this user!" % (self.database.UserInUse(localId))
else:
# look up type via description, get ID, delete from db
print "deleting %s at position %s" % (typeToDelete, IdxToDelete)
# remove from ComboBox
self.deleteComboBox.Delete(IdxToDelete)
localId = self.database.GetUserId(typeToDelete)
self.database.DeleteUser(localId)
# refresh Grid with delete option activated
self.userGrid.RefreshData(delete=1)
self.dataTable.UpdateData()
else:
print "user %s doesn't seem to exist anymore, close dialog and try again" % (typeToDelete)
else:
#TODO: open a dialoge to say this
print "you must unlock the grid before deleting"
event.Skip()
#**** END ADD ****
| Python |
#!/usr/bin/env python
#********************************************************************
# Filename: migrate.py
# Authors: Daniel Sisco
# Date Created: 9-19-010
#
# Abstract: This is the Model/Controller component of the FINally SQLite finance tool.
# This file provides driver level functions for data manipulation that can be called
# by the FINally View component (Model-functionality). This file is also responsible
# for post processing and manipulating data before passing it back to the View
# (Controller-functionality).
#
# Version History: See repository
#
# Copyright 2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
import sys, re, os
from utils import GenFileList
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
# globals
Base = declarative_base()
dict = {}
dbName = ""
storedVersion = [0,0]
schemaVersion = [0,0]
#*****************************************************
class Version(Base):
__tablename__ = 'versions'
id = Column(Integer, primary_key=True)
minor = Column(Integer)
major = Column(Integer)
def __repr__(self):
return "<Version('%s', '%s')>" % (self.minor, self.major)
#*****************************************************
def dumpFrom1_0():
from schema_1_0 import SchemaObject
global dict, dbName
object = SchemaObject(dbName)
dict = object.dump()
#*****************************************************
def loadTo2_0():
from schema_2_0 import SchemaObject
global dict, dbName
object = SchemaObject(dbName)
object.load(dict)
#*****************************************************
def dumpFrom2_0():
from schema_2_0 import SchemaObject
global dict, dbName
object = SchemaObject(dbName)
dict = object.dump()
#*****************************************************
def loadTo2_1():
from schema_2_1 import SchemaObject
global dict, dbName
object = SchemaObject(dbName)
object.load(dict)
#*****************************************************
def dumpFrom2_1():
from schema_2_1 import SchemaObject
global dict, dbName
object = SchemaObject(dbName)
dict = object.dump()
#*****************************************************
def loadTo2_2():
from schema_2_2 import SchemaObject
global dict, dbName
object = SchemaObject(dbName)
object.load(dict)
#*****************************************************
def IdentifyDatabase():
"""This method will locate a database (.db) file and then load specific pieces of information
into the appropriate variables for consumption by other modules"""
global dbName
dbFiles = list(GenFileList('*.db'))
# if any files were present...
if dbFiles:
#TODO: search for appropriate .db setup in each of these files
for tempFileName in dbFiles:
dbNameMatch = re.search('\w+\.db$', tempFileName)
if dbNameMatch:
# remove the database name from the regex match
databaseName = dbNameMatch.group(0)
# store name for global access
dbName = os.path.abspath(databaseName)
cont = True
break #ensures we load the first valid database
else: # if no database files present, prompt user to create a new database file...
cont = False
return cont
#*******************************************************************************************************
# MAIN
#*******************************************************************************************************
if __name__ == '__main__':
# identify database file
if(True == IdentifyDatabase()):
# pull argument from argv
tempArgs = sys.argv[1]
temp = re.split('_', tempArgs)
schemaVersion[0] = int(temp[0])
schemaVersion[1] = int(temp[1])
#print "schemaVersion: %s.%s" % (schemaVersion[0], schemaVersion[1])
# remove version from database
connString = 'sqlite:///' + dbName
engine = create_engine(connString, echo=False)
SessionObject = sessionmaker(bind=engine)
session = SessionObject()
v = session.query(Version).one()
storedVersion[0] = v.major
storedVersion[1] = v.minor
#print "storedVersion: %s.%s" % (storedVersion[0], storedVersion[1])
if(schemaVersion != storedVersion):
#tuple-ize
schemaVersionT = (schemaVersion[0], schemaVersion[1])
storedVersionT = (storedVersion[0], storedVersion[1])
# TODO: replace this with a 'chain' mechanism as per sqlmigratelite
if(schemaVersionT == (2,0)):
# we're moving to version 2.0
if(storedVersionT == (1,0)):
print "updating from %s to %s" % (storedVersionT, schemaVersionT)
dumpFrom1_0()
loadTo2_0()
elif(schemaVersionT == (2,1)):
# we've moving to version 2.1
if(storedVersionT == (2,0)):
print "updating from %s to %s" % (storedVersionT, schemaVersionT)
dumpFrom2_0()
loadTo2_1()
elif(storedVersionT == (1,0)):
print "updating from %s to %s" % (storedVersionT, schemaVersionT)
dumpFrom1_0()
loadTo2_0()
dumpFrom2_0()
loadTo2_1()
elif(schemaVersionT == (2,2)):
# we're moving to version 2.2
if(storedVersionT == (2,1)):
print "updating from %s to %s" % (storedVersionT, schemaVersionT)
dumpFrom2_1()
loadTo2_2()
elif(storedVersionT == (2,0)):
print "updating from %s to %s" % (storedVersionT, schemaVersionT)
dumpFrom2_0()
loadTo2_1()
dumpFrom2_1()
loadTo2_2()
elif(storedVersionT == (1,0)):
print "updating from %s to %s" % (storedVersionT, schemaVersionT)
dumpFrom1_0()
loadTo2_0()
dumpFrom2_0()
loadTo2_1()
dumpFrom2_1()
loadTo2_2()
else:
print "no migration required"
session.close()
else:
print "no migration required" | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: database.py
# Authors: Daniel Sisco, Matt Van Kirk
# Date Created: 4-20-2007
#
# Abstract: This is the Model/Controller component of the FINally SQLite finance tool.
# This file provides driver level functions for data manipulation that can be called
# by the FINally View component (Model-functionality). This file is also responsible
# for post processing and manipulating data before passing it back to the View
# (Controller-functionality).
#
# Version History: See repository
#
# Copyright 2008 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
import sys, re, os
from utils import GenFileList, dPrint, BLANK_TERM
from datetime import date, datetime
from schema_2_2 import *
from colInfo import colInfo
def IdentifyDatabase():
"""This method will locate a database (.db) file and then load specific pieces of information
into the appropriate variables for consumption by other modules"""
dbFiles = list(GenFileList('*.db'))
# if any files were present...
if dbFiles:
#TODO: search for appropriate .db setup in each of these files
for tempFileName in dbFiles:
dbNameMatch = re.search('\w+\.db$', tempFileName)
if dbNameMatch:
# remove the database name from the regex match
databaseName = dbNameMatch.group(0)
# store name for global access
fullName = os.path.abspath(databaseName)
Database().SetName(fullName)
dPrint(fullName)
break #ensures we load the first valid database
else: # if no database files present, prompt user to create a new database file...
print "Please enter a new database name ending in '.db'\n"
databaseName = raw_input('database name: ')
# Strip non alpha-numeric characters out of databaseName
databaseName = re.sub('[^a-zA-Z0-9_.]','',databaseName)
# store full name and flag as a new database
fullName = os.path.abspath(databaseName)
d = Database()
d.SetName(fullName)
d.FlagNewDb()
return fullName
#********************************************************************
# CLASSES
#********************************************************************
class FilterTerms():
"""Class containing filter terms for global use. Methods include
getters and setters for all filter methods. NOTE: this is not
stored in the database because it's not desired to store this
information across tool uses."""
startMonth = datetime.now().month
startYear = datetime.now().year
monthRange = 1
searchTerms = "[BLANK]"
typeTerms = "all"
def SetStartMonth(self, month):
self.__class__.startMonth = month
def GetStartMonth(self):
return self.__class__.startMonth
def SetStartYear(self, year):
self.__class__.startYear = year
def GetStartYear(self):
return self.__class__.startYear
def SetMonthRange(self, range):
self.__class__.monthRange = range
def GetMonthRange(self):
return self.__class__.monthRange
def SetSearchTerms(self, terms):
self.__class__.searchTerms = terms
def GetSearchTerms(self):
return self.__class__.searchTerms
def SetExpenseTypeTerms(self, type):
self.__class__.typeTerms = type
def GetExpenseTypeTerms(self):
return self.__class__.typeTerms
def RegexMatch():
""""""
searchString = FilterTerms().GetSearchTerms()
if(searchString != BLANK_TERM):
# replace + with literal version
pattern = re.compile('\+')
searchString = pattern.sub('\+', searchString)
pattern = re.compile('\(')
searchString = pattern.sub('\(', searchString)
pattern = re.compile('\)')
searchString = pattern.sub('\)', searchString)
pattern = re.compile('\/')
searchString = pattern.sub('\/', searchString)
pattern = re.compile('\!')
searchString = pattern.sub('\!', searchString)
pattern = re.compile('\?')
searchString = pattern.sub('\?', searchString)
pattern = re.compile('\.')
searchString = pattern.sub('\.', searchString)
else:
searchString = "."
return searchString
class Database():
"""The Database object contains database meta data such as name, size, and location,
as well as methods for locating a database, arbitrating between several databases,
and checking database validity."""
# static variables - will be populated by methods of this class
fullName = ""
newDb = False
def Create(self):
"""connects to a specific database"""
# create all tables
Base.metadata.create_all(engine)
if 1 == self.newDb:
print "creating blank database"
self.InitBlankDb()
self.__class__.newDb = False
def InitBlankDb(self):
"""This function is called during powerup to ensure that a database
of the appropriate name exists. The object defined here will be discarded,
but the database will remain."""
session = SessionObject()
print "Creating database: \n\t", Database().fullName, "\n\n"
# create User table
rhs = User(name='Rachel Sisco', shortName='Rachel')
dls = User(name='Daniel Sisco', shortName='Dan')
session.add_all([rhs, dls])
session.commit()
# create expenseType table
clothing = ExpenseType(description='clothing!')
makeup = ExpenseType(description='makeup!')
session.add_all([clothing, makeup])
session.commit()
# create demo expense table
e1 = Expense(user=rhs, expenseType=makeup, amount='15.01', date=date.today(), description='makeup for mah FACE!')
e2 = Expense(user=dls, expenseType=clothing, amount='50.25', date=date.today(), description='clothing for mah parts.')
session.add_all([e1,e2])
session.commit()
# create dataSort table
ds = DataSort(sortTerm1='date')
session.add(ds)
session.commit()
# create version table
v = Version(minor=dbVer[1], major=dbVer[0])
session.add(v)
session.commit()
# create preference table
colString = colInfo.defColWidth # pull default from grid.py
p = Preference(frameHeight=300, frameWidth=900, colWidths=colString)
session.add(p)
session.commit()
session.close()
def CreateExpense(self, amount, desc, date, userName, typeDesc):
"""Creates a new expense"""
session = SessionObject()
e = Expense()
e.amount = amount
e.description = desc
e.date = date
e.user = session.query(User).filter(User.name==userName).one()
e.expenseType = session.query(ExpenseType).filter(ExpenseType.description==typeDesc).one()
session.add(e)
session.commit()
session.close()
def EditExpense(self, amount, desc, date, userId, typeId, inputId):
"""Edits an existing object - expects to get arguments corresponding
to Expense object members:
amount
description
date
user_id
expenseType_id
id
"""
#TODO: can we just pass an ExpenseObject?
session = SessionObject()
try:
e = session.query(Expense).filter(Expense.id==inputId).one()
e.amount = amount
e.description = desc
e.date = date
e.user_id = userId
e.expenseType_id = typeId
except NoResultFound:
print "edit error"
e = -1
session.commit()
session.close()
def DeleteExpense(self, deleteId):
"""Removes an expense with the appropriate ID from the database"""
session = SessionObject()
e = session.query(Expense).filter(Expense.id==deleteId).one()
session.delete(e)
session.commit()
session.close()
def GetExpense(self, reqId):
"""returns the Expense object matching the reqId input"""
#TODO: add fault handling here
session = SessionObject()
e = session.query(Expense).filter(Expense.id==reqId).one()
session.close()
return e
def GetAllExpenses(self):
"""returns all data in the database in a 2D list in the following format:
[ 0 ][ 1 ][ 2 ][ 3 ][ 4 ][5 ][6 ]
[0][user][expenseType][amount][date][description][id][del]
[1][user][expenseType][amount][date][description][id][del]
user and expenseType are dereferenced down to the underlying string,
and amount and date are cast to string types to appease the grid."""
minorList=[]
majorList=[]
session = SessionObject()
localSortTerm = self.GetSortTerm(1)
filters = FilterTerms()
# generate date objects for start and end dates
startDate = date(filters.GetStartYear(), filters.GetStartMonth(), 1)
tempEndMonth = filters.GetStartMonth() + filters.GetMonthRange()
tempEndYear = filters.GetStartYear()
# TODO: update this to work correctly past two years
if (tempEndMonth <= 12):
endDate = date(tempEndYear, tempEndMonth, 1)
elif (tempEndMonth <= 24):
endDate = date(tempEndYear+1, tempEndMonth-12, 1)
# grab all expenses
expenseList = session.query(Expense).filter(Expense.date >= startDate). \
filter(Expense.date < endDate). \
order_by(localSortTerm).all()
# compile regex match terms
matchString = RegexMatch()
typeString = filters.GetExpenseTypeTerms()
# iterate through expenses - packing into listxlist
for i in expenseList:
if(re.search(matchString, i.description) and (i.expenseType.description == typeString or typeString == "all")):
minorList = [i.user.name,
i.expenseType.description,
str(i.amount),
str(i.date),
i.description,
i.id,
"delete"]
majorList.append(minorList)
session.close()
return majorList
def GetUserList(self):
"""Returns a list of the entire User object (name and shortName)"""
list = []
session = SessionObject()
userList = session.query(User).order_by(User.name).all()
for i in userList:
list.append(i)
session.close()
return list
def GetSimpleUserList(self):
"""Returns a list of just the user name - like the name implies"""
list = []
session = SessionObject()
userList = session.query(User).order_by(User.name).all()
for i in userList:
list.append(i.name)
session.close()
return list
def GetUser(self, userName):
"""returns the User object matching the input name"""
#TODO: add fault handling here
session = SessionObject()
u = session.query(User).filter(User.name==userName).one()
session.close()
return u
def GetUserId(self, userName):
"""reurns the User object id matching the input name"""
#TODO: add fault handling here
session = SessionObject()
try:
uId = session.query(User).filter(User.name==userName).one().id
except NoResultFound:
uId = -1
session.close()
return uId
def CreateUser(self, name, shortName):
"""Creates a new user"""
session = SessionObject()
success = 0
# ensure that type with this description does not already exist
try:
session.query(User).filter(User.name== name).one()
except NoResultFound:
u = User()
u.name = name
u.shortName = shortName
session.add(u)
session.commit()
success = 1
session.close()
return success
def EditUser(self, name, shortName, inputId):
session = SessionObject()
u = session.query(User).filter(User.id == inputId).one()
u.name = name
u.shortName = shortName
session.commit()
session.close()
def DeleteUser(self, inputId):
session = SessionObject()
try:
u = session.query(User).filter(User.id == inputId).one()
session.delete(u)
session.commit()
except NoResultFound:
print "record with id %s does not exist!" % inputId
session.close
def UserInUse(self, typeId):
"""returns the number of expenses using the user with the input ID"""
session = SessionObject()
cnt = len(session.query(Expense).filter(Expense.user_id == typeId).all())
session.close
return cnt
def GetExpenseTypeList(self):
"""Returns a list of expense types - nothing else."""
list = []
session = SessionObject()
typeList = session.query(ExpenseType).order_by(ExpenseType.description).all()
for i in typeList:
list.append(str(i.description))
session.close()
return list
def GetExpenseType(self, desc):
"""returns an ExpenseType object matching the typeName argument"""
#TODO add fault handling here
session = SessionObject()
t = session.query(ExpenseType).filter(ExpenseType.description == desc).one()
session.close()
return t
def GetExpenseTypeId(self, desc):
"""returns an ExpenseType id matching the typeName argument"""
#TODO add fault handling here
session = SessionObject()
try:
tId = session.query(ExpenseType).filter(ExpenseType.description==desc).one().id
except NoResultFound:
tId = -1
session.close()
return tId
def CreateExpenseType(self, desc):
"""Creates a new expense"""
session = SessionObject()
success = 0
# ensure that type with this description does not already exist
try:
session.query(ExpenseType).filter(ExpenseType.description == desc).one()
except NoResultFound:
t = ExpenseType()
t.description = desc
session.add(t)
session.commit()
success = 1
session.close()
return success
def EditExpenseType(self, desc, inputId):
session = SessionObject()
et = session.query(ExpenseType).filter(ExpenseType.id == inputId).one()
et.description = desc
session.commit()
session.close()
def DeleteExpenseType(self, inputId):
session = SessionObject()
try:
et = session.query(ExpenseType).filter(ExpenseType.id == inputId).one()
session.delete(et)
session.commit()
except NoResultFound:
print "record with id %s does not exist!" % inputId
session.close
def MigrateExpenseType(self, fromId, toId):
"""migrates any expenses using expense type with ID 'fromId' to expense type
with ID 'toId'. Does nothing if no expenses are using expense type with Id
'fromId'."""
def ExpenseTypeInUse(self, typeId):
"""returns the number of expenses using the expense type with the input ID"""
session = SessionObject()
try:
et = session.query(Expense).filter(Expense.expenseType_id == typeId).all()
cnt = len(et)
except NoResultFound:
cnt = 0
session.close
return cnt
def SetName(self, name):
self.__class__.fullName = name
def FlagNewDb(self):
self.__class__.newDb = True
def EditPrefs(self, inputDefUserId, inputDefExpTypeId, inputDefAmount):
session = SessionObject()
# there should only be one preference entry in the table
# otherwise the table is blank - create it
try:
p = session.query(Preference).one()
except NoResultFound:
p = Preference()
session.add(p)
session.commit()
p.defUser_id = inputDefUserId
p.defExpenseType_id = inputDefExpTypeId
p.defAmount = inputDefAmount
session.commit()
session.close()
def SetDefUserPref(self, inputId=-1):
"""input should be the id of a user."""
session = SessionObject()
try:
p = session.query(Preference).one()
p.defUser_id = inputId
session.commit()
except NoResultFound:
print "failure"
session.close()
def SetDefExpTypePref(self, inputId=-1):
"""input should be the id of an expenseType."""
session = SessionObject()
try:
p = session.query(Preference).one()
p.defExpenseType_id = inputId
session.commit()
except NoResultFound:
print "failure"
session.close()
def SetDefAmountPref(self, inputAmount):
session = SessionObject()
try:
p = session.query(Preference).one()
p.defAmount = inputAmount
session.commit()
except NoResultFound:
print "failure"
def GetPrefs(self):
session = SessionObject()
# there should only be one preference entry in the table
# otherwise the table is blank - create it
try:
p = session.query(Preference).options(eagerload('defUser'), eagerload('defExpenseType')).one()
except NoResultFound:
p = Preference()
session.add(p)
session.commit()
p = session.query(Preference).options(eagerload('defUser'), eagerload('defExpenseType')).one()
session.close()
return p
def SetColWidthPref(self, locColWidths):
session = SessionObject()
try:
p = session.query(Preference).one()
p.colWidths = locColWidths
session.commit()
except NoResultFound:
print "failure"
session.close()
def SetSortTerm(self, term, value):
session = SessionObject()
try:
st = session.query(DataSort).one()
except NoResultFound:
st = DataSort()
session.add(st)
session.commit()
st = session.query(DataSort).one()
#TODO: support the other sort terms later
if(term == 1):
st.sortTerm1 = value
session.commit()
session.close()
def GetSortTerm(self, term):
session = SessionObject()
try:
localTerm = session.query(DataSort).one().sortTerm1
except NoResultFound:
localTerm = "date"
session.close()
return localTerm
def GetVersion(self):
session = SessionObject()
v = session.query(Version).one()
session.close()
return (v.major, v.minor)
#********************************************************************
# DATABASE.PY CONTENT
#********************************************************************
connString = 'sqlite:///' + IdentifyDatabase()
engine = create_engine(connString, echo=False)
SessionObject = sessionmaker(bind=engine)
#********************************************************************
# MAIN
#********************************************************************
# Test main functionality
if __name__ == '__main__':
print "Please run Fin-ally by launching FINally.py!" | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: menuBar.py
# Authors: Daniel Sisco
# Date Created: 10-3-2010
#
# Abstract: This is the primary file for the FINally expense analysis tool. It is responsible for
# handling read/write access to the SQLite database as well as providing a GUI interface for the user.
#
# Copyright 2008-2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
import wx
import math
import random
import os
import sys
try:
from agw import flatmenu as FM
from agw.artmanager import ArtManager, RendererBase, DCSaver
from agw.fmresources import ControlFocus, ControlPressed
from agw.fmresources import FM_OPT_SHOW_CUSTOMIZE, FM_OPT_SHOW_TOOLBAR, FM_OPT_MINIBAR
except ImportError: # if it's not there locally, try the wxPython lib.
import wx.lib.agw.flatmenu as FM
from wx.lib.agw.artmanager import ArtManager, RendererBase, DCSaver
from wx.lib.agw.fmresources import ControlFocus, ControlPressed
from wx.lib.agw.fmresources import FM_OPT_SHOW_CUSTOMIZE, FM_OPT_SHOW_TOOLBAR, FM_OPT_MINIBAR
bitmapDir = 'img/'
#********************************************************************
# menu IDs
#********************************************************************
MENU_HELP = wx.NewId()
MENU_PREFS = wx.NewId()
MENU_NEW_DB = wx.NewId()
MENU_OPEN_DB = wx.NewId()
MENU_QUIT = wx.NewId()
MENU_NEW_EXPENSE = wx.NewId()
MENU_EDIT_EXPENSE_TYPE = wx.NewId()
MENU_NEW_USER = wx.NewId()
#********************************************************************
def switchRGBtoBGR(colour):
return wx.Colour(colour.Blue(), colour.Green(), colour.Red())
#********************************************************************
class FM_MyRenderer(RendererBase):
""" My custom style. """
def __init__(self):
RendererBase.__init__(self)
def DrawButton(self, dc, rect, state, useLightColours=True):
if state == ControlFocus:
penColour = switchRGBtoBGR(ArtManager.Get().FrameColour())
brushColour = switchRGBtoBGR(ArtManager.Get().BackgroundColour())
elif state == ControlPressed:
penColour = switchRGBtoBGR(ArtManager.Get().FrameColour())
brushColour = switchRGBtoBGR(ArtManager.Get().HighlightBackgroundColour())
else: # ControlNormal, ControlDisabled, default
penColour = switchRGBtoBGR(ArtManager.Get().FrameColour())
brushColour = switchRGBtoBGR(ArtManager.Get().BackgroundColour())
# Draw the button borders
dc.SetPen(wx.Pen(penColour))
dc.SetBrush(wx.Brush(brushColour))
dc.DrawRoundedRectangle(rect.x, rect.y, rect.width, rect.height,4)
def DrawMenuBarBg(self, dc, rect):
# For office style, we simple draw a rectangle with a gradient colouring
vertical = ArtManager.Get().GetMBVerticalGradient()
dcsaver = DCSaver(dc)
# fill with gradient
startColour = ArtManager.Get().GetMenuBarFaceColour()
endColour = ArtManager.Get().LightColour(startColour, 90)
dc.SetPen(wx.Pen(endColour))
dc.SetBrush(wx.Brush(endColour))
dc.DrawRectangleRect(rect)
def DrawToolBarBg(self, dc, rect):
if not ArtManager.Get().GetRaiseToolbar():
return
# fill with gradient
startColour = ArtManager.Get().GetMenuBarFaceColour()
dc.SetPen(wx.Pen(startColour))
dc.SetBrush(wx.Brush(startColour))
dc.DrawRectangle(0, 0, rect.GetWidth(), rect.GetHeight())
def CreateMenu(self):
# define the menuBar object
self.menuBar = FM.FlatMenuBar(self,
wx.ID_ANY,
32,
5,
options = FM_OPT_SHOW_TOOLBAR | FM_OPT_SHOW_CUSTOMIZE)
fileMenu = FM.FlatMenu()
optionMenu = FM.FlatMenu()
helpMenu = FM.FlatMenu()
self.newMyTheme = ArtManager.Get().AddMenuTheme(FM_MyRenderer())
# Set the menubar theme - refer to the wxPython demo for more options
ArtManager.Get().SetMenuTheme(FM.Style2007)
# Load toolbar icons (32x32)
new_expense = wx.Bitmap(os.path.join(bitmapDir, "new_expense.png"), wx.BITMAP_TYPE_PNG)
help_blue = wx.Bitmap(os.path.join(bitmapDir, "blueHelp_16.png"), wx.BITMAP_TYPE_PNG)
exit_red = wx.Bitmap(os.path.join(bitmapDir, "exit.png"), wx.BITMAP_TYPE_PNG)
# Create toolbar icons
# ID Help Text image object
self.menuBar.AddTool(MENU_NEW_EXPENSE, "New Expense", new_expense)
self.menuBar.AddSeparator()
self.menuBar.AddTool(MENU_QUIT, "Quit", exit_red)
#
# Create File Menu
#
item = FM.FlatMenuItem(fileMenu, MENU_NEW_DB, "&New Database\tCtrl+N", "New Database", wx.ITEM_NORMAL)
fileMenu.AppendItem(item)
item = FM.FlatMenuItem(fileMenu, MENU_OPEN_DB, "&Open Database\tCtrl+O", "Open Database", wx.ITEM_NORMAL)
fileMenu.AppendItem(item)
item = FM.FlatMenuItem(fileMenu, MENU_QUIT, "Quit\tCtrl+Q", "Quit", wx.ITEM_NORMAL)
fileMenu.AppendItem(item)
#
# Create Options Menu
#
item = FM.FlatMenuItem(optionMenu, MENU_PREFS, "&Preferences\tCtrl+P", "Preferences", wx.ITEM_NORMAL)
optionMenu.AppendItem(item)
item = FM.FlatMenuItem(optionMenu, MENU_EDIT_EXPENSE_TYPE, "Edit Expense &Type\tCtrl+T",
"Edit Expense Type", wx.ITEM_NORMAL)
optionMenu.AppendItem(item)
item = FM.FlatMenuItem(optionMenu, MENU_NEW_USER, "Edit &User\tCtrl+U",
"Edit User", wx.ITEM_NORMAL)
optionMenu.AppendItem(item)
#
# Create Help Menu
#
item = FM.FlatMenuItem(helpMenu, MENU_HELP, "&About\tCtrl+A", "About...", wx.ITEM_NORMAL, None, help_blue)
helpMenu.AppendItem(item)
# Add menu to the menu bar
self.menuBar.Append(fileMenu, "&File")
self.menuBar.Append(optionMenu, "&Options")
self.menuBar.Append(helpMenu, "&Help")
ConnectMenuBar(self)
def ConnectMenuBar(self):
# Attach menu events to some handlers
# event function menu item ID
self.Bind(FM.EVT_FLAT_MENU_SELECTED, self.OnAbout, id=MENU_HELP)
self.Bind(FM.EVT_FLAT_MENU_SELECTED, self.gPage.ShowNewExpenseDialogue, id=MENU_NEW_EXPENSE)
self.Bind(FM.EVT_FLAT_MENU_SELECTED, self.OnQuit, id=MENU_QUIT)
self.Bind(FM.EVT_FLAT_MENU_SELECTED, self.OnPrefs, id=MENU_PREFS)
self.Bind(FM.EVT_FLAT_MENU_SELECTED, self.OnEditExpenseType,id=MENU_EDIT_EXPENSE_TYPE)
self.Bind(FM.EVT_FLAT_MENU_SELECTED, self.OnEditUser, id=MENU_NEW_USER)
# unsupported as of right now
self.Bind(FM.EVT_FLAT_MENU_SELECTED, self.OnUnsupported, id=MENU_NEW_DB) # TODO
self.Bind(FM.EVT_FLAT_MENU_SELECTED, self.OnUnsupported, id=MENU_OPEN_DB) # TODO
| Python |
#!/usr/bin/env python
#********************************************************************
# Filename: cfg.py
# Authors: Daniel Sisco
# Date Created: 7-20-2010
#
# Abstract: Global variables for the Fin-ally project, hopefully just configuration variables
#
# Copyright 2008 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
# activates certain debug messages, especially in dPrint()
# 0 = no print
# 1 = print
DEBUG = 1
# activates either a pop-up dialogue for new expenses, or uses a static button panel
# 1 = static button panel
# 0 = pop-up dialogue
NEW_EXPENSE_PANEL = 0
# activates a grid-based context menu in which a user can delete a row
# 1 = grid-based context menu active
# 0 = menu inactive
GRID_CONTEXT_MENU = 0
# FINally version - used for database migration and version checking
VERSION = (1,6,0)
| Python |
#!/usr/bin/env python
#********************************************************************
# Filename: schema_2_2.py
# Authors: Daniel Sisco
# Date Created: 11/27/2010
#
# Abstract: Version 2.2 of the FINally database schema
#
# Version History: See repository
#
# Copyright 2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
from sqlmigratelite.migrate import MigrateObject
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref, eagerload
from sqlalchemy.orm.exc import NoResultFound
from colInfo import colInfo
Base = declarative_base()
version = "2.2"
dbVer = (2,2)
#********************************************************************
# Create SQLAlchemy tables in the form of python classes.
#********************************************************************
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
shortName = Column(String)
def __repr__(self):
return "<User('%s', '%s')>" % (self.name, self.shortName)
#********************************************************************
class ExpenseType(Base):
__tablename__ = 'expenseTypes'
id = Column(Integer, primary_key=True)
description = Column(String)
def __repr__(self):
return "<ExpenseType('%s')>" % (self.description)
#********************************************************************
class Expense(Base):
__tablename__ = 'expenses'
id = Column(Integer, primary_key=True)
amount = Column(Integer)
date = Column(String)
description = Column(String)
# define user_id to support database level link and user for class level link
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship(User, backref=backref('expenses', order_by=id))
expenseType_id = Column(Integer, ForeignKey('expenseTypes.id'))
expenseType = relationship(ExpenseType, backref=backref('expenses', order_by=id))
def __repr__(self):
return "<Expense('%s', '%s', '%s')>" % (self.amount, self.date, self.description)
#********************************************************************
class Preference(Base):
__tablename__ = 'preferences'
id = Column(Integer, primary_key=True)
defUser_id = Column(Integer, ForeignKey('users.id'))
defUser = relationship(User, backref=backref('preferences', order_by=id))
defExpenseType_id = Column(Integer, ForeignKey('expenseTypes.id'))
defExpenseType = relationship(ExpenseType, backref=backref('preferences', order_by=id))
defAmount = Column(Integer)
# application frame default sizes
frameWidth = Column(Integer)
frameHeight= Column(Integer)
# grid column widths
colWidths = Column(String)
def __repr__(self):
return "<Preference('%s, %s, %s')>" % (self.defUser_id, self.defExpenseType_id, self.defAmount)
#********************************************************************
class DataSort(Base):
__tablename__ = 'dataSort'
id = Column(Integer, primary_key=True)
sortTerm1 = Column(String)
sortTerm2 = Column(String)
sortTerm3 = Column(String)
sortTerm4 = Column(String)
sortTerm5 = Column(String)
def __repr__(self):
return "<DataSort('%s, %s, %s, %s, %s')>" % (self.sortTerm1,
self.sortTerm2,
self.sortTerm3,
self.sortTerm4,
self.sortTerm5)
#********************************************************************
class Version(Base):
__tablename__ = 'versions'
id = Column(Integer, primary_key=True)
minor = Column(Integer)
major = Column(Integer)
def __repr__(self):
return "<Version('%s', '%s')>" % (self.minor, self.major)
#************************************
class SchemaObject(MigrateObject):
"""
version 2.2 schema object - defines custom dumpContent and loadContent methods
"""
def __init__(self, dbPath):
MigrateObject.__init__(self, dbPath, version)
def dumpContent(self):
"""dumps User and Version tables as-is"""
self.localDict['User'] = self.session.query(User).all()
self.localDict['ExpenseType'] = self.session.query(ExpenseType).all()
self.localDict['Expense'] = self.session.query(Expense).all()
self.localDict['Preference'] = self.session.query(Preference).all()
self.localDict['DataSort'] = self.session.query(DataSort).all()
def loadContent(self):
Base.metadata.create_all(self.engine)
for i in self.localDict['User']:
u = User()
u.name = i.name
u.shortName = i.shortName
self.session.add(u)
self.session.commit()
for i in self.localDict['ExpenseType']:
t = ExpenseType()
t.description = i.description
self.session.add(t)
self.session.commit()
for i in self.localDict['Expense']:
e = Expense()
e.user_id = i.user_id
e.expenseType_id = i.expenseType_id
e.amount = i.amount
e.date = i.date
e.description = i.description
self.session.add(e)
self.session.commit()
for i in self.localDict['Preference']:
p = Preference()
p.defUser_id = i.defUser_id
p.defExpenseType_id = i.defExpenseType_id
p.defAmount = i.defAmount
p.colWidths = colInfo.defColWidth
self.session.add(p)
self.session.commit()
# update the version number
# TODO: move this into sqlmigratelite core
v = Version(minor=dbVer[1], major=dbVer[0])
self.session.add(v)
self.session.commit() | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: SQLiteCommands.py
# Authors: Daniel Sisco
# Date Created: 1-23-2008
#
# Abstract: The actual SQLite commands in string format. These can be
# quite lengthy and there are many of them, so we have pulled them into
# their own file.
#
# Version History: See repository
#
# Copyright 2008 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
#********************************************************************
# EXPENSE TABLE
#********************************************************************
# Used for creation of the base 'expenses' table
SQLDEF_EXPENSES = """
CREATE TABLE IF NOT EXISTS exp (
id INTEGER PRIMARY KEY,
who TEXT,
amount NUMBER,
date DATE,
desc TEXT
)
"""
# Used for deleting a specific record with matching id from table
# 'expenses'
SQLDEF_DELETE = """
DELETE FROM exp
WHERE %s = id
"""
# Used for inserting a complete record into 'expenses'
SQLDEF_INSERT_EXPENSES = """
INSERT INTO exp (who, amount, date, desc)
VALUES ('%s', '%f', '%s', '%s')
"""
# Used for returning all records from 'expenses'
SQLDEF_GET_ALL = """
SELECT * from exp
"""
# Used for returning some records with certain criteria from 'expenses'
SQLDEF_GET_RANGE = """
SELECT * FROM exp
WHERE %s
"""
# Used for returning some values with certain criteria from 'expenses'
SQLDEF_GET_SOME = """
SELECT (%s) from exp
WHERE (%s)
"""
# Used for changing the value of some record from 'expenses'
SQLDEF_UPDATE = """
UPDATE exp
SET %s = '%s'
WHERE id = %s
"""
#********************************************************************
# USER INFO TABLE
#********************************************************************
# Used for creating the userInfo table in the database
SQLDEF_USER_INFO = """
CREATE TABLE IF NOT EXISTS userInfo (
id INTEGER PRIMARY KEY,
dbName TEXT,
creationDate DATE,
purpose TEXT,
version NUMBER
"""
# Used for inserting a complete record into 'userInfo'
SQLDEF_INSERT_USER_INFO = """
INSERT INTO userInfo (dbName, creationDate, purpose, version)
VALUES ('%s', '%s', '%s', '%f')
"""
| Python |
#!/usr/bin/env python
#********************************************************************
# Filename: schema_2_1.py
# Authors: Daniel Sisco
# Date Created: 10/10/2010
#
# Abstract: Version 1.0 of the FINally database schema
#
# Version History: See repository
#
# Copyright 2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
from sqlmigratelite.migrate import MigrateObject
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref, eagerload
from sqlalchemy.orm.exc import NoResultFound
Base = declarative_base()
version = "2.1"
dbVer = (2,1)
#********************************************************************
# Create SQLAlchemy tables in the form of python classes.
#********************************************************************
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
shortName = Column(String)
def __repr__(self):
return "<User('%s', '%s')>" % (self.name, self.shortName)
#********************************************************************
class ExpenseType(Base):
__tablename__ = 'expenseTypes'
id = Column(Integer, primary_key=True)
description = Column(String)
def __repr__(self):
return "<ExpenseType('%s')>" % (self.description)
#********************************************************************
class Expense(Base):
__tablename__ = 'expenses'
id = Column(Integer, primary_key=True)
amount = Column(Integer)
date = Column(String)
description = Column(String)
# define user_id to support database level link and user for class level link
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship(User, backref=backref('expenses', order_by=id))
expenseType_id = Column(Integer, ForeignKey('expenseTypes.id'))
expenseType = relationship(ExpenseType, backref=backref('expenses', order_by=id))
def __repr__(self):
return "<Expense('%s', '%s', '%s')>" % (self.amount, self.date, self.description)
#********************************************************************
class Preference(Base):
__tablename__ = 'preferences'
id = Column(Integer, primary_key=True)
defUser_id = Column(Integer, ForeignKey('users.id'))
defUser = relationship(User, backref=backref('preferences', order_by=id))
defExpenseType_id = Column(Integer, ForeignKey('expenseTypes.id'))
defExpenseType = relationship(ExpenseType, backref=backref('preferences', order_by=id))
defAmount = Column(Integer)
def __repr__(self):
return "<Preference('%s, %s, %s')>" % (self.defUser_id, self.defExpenseType_id, self.defAmount)
#********************************************************************
class DataSort(Base):
__tablename__ = 'dataSort'
id = Column(Integer, primary_key=True)
sortTerm1 = Column(String)
sortTerm2 = Column(String)
sortTerm3 = Column(String)
sortTerm4 = Column(String)
sortTerm5 = Column(String)
def __repr__(self):
return "<DataSort('%s, %s, %s, %s, %s')>" % (self.sortTerm1,
self.sortTerm2,
self.sortTerm3,
self.sortTerm4,
self.sortTerm5)
#********************************************************************
class Version(Base):
__tablename__ = 'versions'
id = Column(Integer, primary_key=True)
minor = Column(Integer)
major = Column(Integer)
def __repr__(self):
return "<Version('%s', '%s')>" % (self.minor, self.major)
#************************************
class SchemaObject(MigrateObject):
"""
version 2.1 schema object - defines custom dumpContent and loadContent methods
"""
def __init__(self, dbPath):
MigrateObject.__init__(self, dbPath, version)
def dumpContent(self):
"""dumps User and Version tables as-is"""
self.localDict['User'] = self.session.query(User).all()
self.localDict['ExpenseType'] = self.session.query(ExpenseType).all()
self.localDict['Expense'] = self.session.query(Expense).all()
self.localDict['Preference'] = self.session.query(Preference).all()
self.localDict['DataSort'] = self.session.query(DataSort).all()
def loadContent(self):
Base.metadata.create_all(self.engine)
for i in self.localDict['User']:
u = User()
u.name = i.name
u.shortName = i.shortName
self.session.add(u)
self.session.commit()
for i in self.localDict['ExpenseType']:
t = ExpenseType()
t.description = i.description
self.session.add(t)
self.session.commit()
for i in self.localDict['Expense']:
e = Expense()
e.user_id = i.user_id
e.expenseType_id = i.expenseType_id
e.amount = i.amount
e.date = i.date
e.description = i.description
self.session.add(e)
self.session.commit()
for i in self.localDict['Preference']:
p = Preference()
p.defUser_id = i.defUser_id
p.defExpenseType_id = i.defExpenseType_id
p.defAmount = i.defAmount
self.sesion.add(p)
self.session.commit()
# update the version number
# TODO: move this into sqlmigratelite core
v = Version(minor=dbVer[1], major=dbVer[0])
self.session.add(v)
self.session.commit() | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: FINally.py
# Authors: Daniel Sisco
# Date Created: 4-20-2007
#
# Abstract: This is the primary file for the FINally expense analysis tool. It is responsible for
# handling read/write access to the SQLite database as well as providing a GUI interface for the user.
#
# Copyright 2008-2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
# import wxPython libraries - including some simplifiers for grid and calendar
import wx
import wx.grid as gridlib
import cfg
from datetime import date, datetime
from database import Database
from utils import dateMatch
from prefs import SaveColumnPreferences
from colInfo import colInfo
#********************************************************************
class GraphicsGrid(gridlib.Grid):
"""
Class Name: GraphicsGrid
Extends: wx.grid.Grid (gridlib.Grid)
Description: This class is responsible for grid format and operator event binding
such as right-clicking the grid or creating an editor while changing a cell. This
class does not manage data directly, and instead uses a table base member for data
management.
"""
#TODO: determine how much control to give this over the data we want to see. Consider adding
#another class for the data itself, a class that would be passed to everything and modified
#in many places. This would allow a future calculation object to make changes and force them
#to show up in the graphics page.
def __init__(self, parent):
gridlib.Grid.__init__(self, parent)
# pull some data out of the database and push it into the tableBase
self.database = Database()
self.tableBase = CustomDataTable(self,1) # define the base
self.SetTable(self.tableBase) # set the grid table
self.SetColFormatFloat(2,-1,2) # formats the monetary entries correctly
self.AutoSize() # auto-sizing here ensures that scrollbars will always be present
# during window resizing
self.rowAttr = gridlib.GridCellAttr()
self.FormatTableRows()
self.FormatTableCols()
# bind editor creation to an event so we can 'catch' unique editors
self.Bind(gridlib.EVT_GRID_EDITOR_CREATED,
self.OnGrid1GridEditorCreated)
self.Bind(gridlib.EVT_GRID_COL_SIZE, self.OnGridColSize)
# bind grid-based context menu if active
if cfg.GRID_CONTEXT_MENU == 1:
self.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.onGridRightClick)
self.Bind(gridlib.EVT_GRID_CELL_LEFT_CLICK, self.onGridClick)
self.Bind(gridlib.EVT_GRID_CMD_LABEL_LEFT_CLICK, self.onColClick)
def onColClick(self, event):
if event.GetRow() == -1 and event.GetCol() != -1:
localSortBy = colInfo.colLabels[event.GetCol()]
# some col names match the database sort term, but some do not
if localSortBy == 'user':
self.database.SetSortTerm(1, 'user_id')
elif(localSortBy == 'type'):
self.database.SetSortTerm(1, 'expenseType_id')
elif(localSortBy == 'amount'):
self.database.SetSortTerm(1, 'amount')
elif(localSortBy == 'date'):
self.database.SetSortTerm(1, 'date')
elif(localSortBy == 'desc'):
self.database.SetSortTerm(1, 'description')
elif(localSortBy == 'id'):
self.database.SetSortTerm(1, 'id')
else:
print "you did not click a column"
self.tableBase.UpdateData()
self.ForceRefresh()
event.Skip()
def onGridClick(self, event):
if(event.GetCol() == 6):
self.tableBase.DeleteRow(event.GetRow())
event.Skip()
def onGridRightClick(self, event):
if cfg.GRID_CONTEXT_MENU == 1:
# highlight the grid row in red
row = event.GetRow()
attr = gridlib.GridCellAttr()
attr.SetBackgroundColour(wx.RED)
self.SetRowAttr(row, attr)
self.ForceRefresh()
# only do this part the first time so the events are only bound once
#
# Yet another alternate way to do IDs. Some prefer them up top to
# avoid clutter, some prefer them close to the object of interest
# for clarity.
if not hasattr(self, "popupDeleteId"):
self.popupDeleteId = wx.NewId()
# use of lambda functions prevent two new methods
self.Bind(wx.EVT_MENU, lambda evt, temp=row: self.OnPopupDelete(evt, temp), id=self.popupDeleteId)
# create a menu and pack it some some options
menu = wx.Menu()
menu.Append(self.popupDeleteId, "Delete")
self.PopupMenu(menu)
menu.Destroy()
else:
event.Skip
def OnPopupDelete(self, event, row):
if cfg.GRID_CONTEXT_MENU == 1:
# delete the current row
# TODO: add a #define here or something
self.tableBase.DeleteRow(row)
else:
event.Skip()
def OnGridColSize(self, event):
"""called when a column is resized in the grid"""
SaveColumnPreferences(event.GetRowOrCol(), self.GetColSize(event.GetRowOrCol()))
event.Skip()
def OnGrid1GridEditorCreated(self, event):
"""This function will fire when a cell editor is created, which seems to be
the first time that cell is edited (duh). Standard columns will be left alone
in this method, but unique columns (ie: comboBoxes) will be set explicitly."""
Row = event.GetRow()
Col = event.GetCol()
# Col 0 is the User object column
if Col == 0:
#Get a reference to the underlying ComboBox control.
self.comboBox = event.GetControl()
#Bind the ComboBox events.
self.comboBox.Bind(wx.EVT_COMBOBOX, self.ComboBoxSelection)
# load combo box with all user types
for i in self.database.GetSimpleUserList():
self.comboBox.Append(i)
# Col 1 is the Expense Type object column
elif Col == 1:
self.comboBox = event.GetControl()
self.comboBox.Bind(wx.EVT_COMBOBOX, self.ComboBoxSelection)
for i in self.database.GetExpenseTypeList():
self.comboBox.Append(i)
def ComboBoxSelection(self, event):
"""This method fires when the underlying ComboBox object is done with
it's selection"""
event.Skip()
def FormatTableCols(self):
if self.tableBase.GetNumberRows():
# create read-only columns
self.rowAttr.SetReadOnly(1)
for i in range(len(colInfo.colRO)):
if colInfo.colRO[i] == 1:
self.SetColAttr(i,self.rowAttr)
self.rowAttr.IncRef()
# format column width
tmp = 0
localWidths = self.database.GetPrefs().colWidths.split(',')
for i in localWidths:
self.SetColSize(tmp,int(i))
tmp += 1
def FormatTableRows(self, skipEditorRefresh=0):
for i in range(self.tableBase.GetNumberRows()):
self._FormatTableRow(i, skipEditorRefresh)
def _FormatTableRow(self, row, skipEditorRefresh):
"""Formats a single row entry - editor types, height, color, etc..."""
if skipEditorRefresh == 0:
# create 'drop down' style choice editors for two columns
userChoiceEditor = gridlib.GridCellChoiceEditor([], allowOthers = False)
typeChoiceEditor = gridlib.GridCellChoiceEditor([], allowOthers = False)
self.SetCellEditor(row,0,userChoiceEditor)
self.SetCellEditor(row,1,typeChoiceEditor)
self.SetCellEditor(row,2,gridlib.GridCellFloatEditor(-1,2))
self.SetRowSize(row, colInfo.rowHeight)
self.SetCellBackgroundColour(row,6,"GREEN")
#********************************************************************
class CustomDataTable(gridlib.PyGridTableBase):
"""
Class Name: CustomDataTable
Extends: wx.grid.PyGridTableBase (gridlib.PyGridTableBase)
Description: An instance of the uninstantiated base class PyGridTableBase. This instance
must contain several methods (listed below) for modifying/viewing/querying data in the grid.
As well as an init method that populates the grid with data.
Required members are: GetNumber[Rows|Cols], GetValue, SetValue, and IsEmptyCell.
"""
dataTypes = colInfo.colType # used for custom renderers
previousRowCnt = 0
previousColCnt = 0
localData = []
parent = 0
# used to turn this class into a Borg class
__shared_state = {}
def __init__(self, parent, first=0):
# bind the underlyng Python dictionary to a class variable
self.__dict__ = self.__shared_state
gridlib.PyGridTableBase.__init__(self)
# TODO: This needs to be cleaned up so that CustomDataTable does not have to
# deal with so much data specification. This should be a single fcn call for
# data
self.__class__.previousRowCnt = 0
self.__class__.previousColCnt = 0
self.database = Database()
self.__class__.localData = self.database.GetAllExpenses()
if(first):
self.__class__.parent = parent
#***************************
# REQUIRED METHODS
#***************************
def GetNumberRows(self):
return len(self.__class__.localData)
def GetNumberCols(self):
if self.GetNumberRows():
return len(self.__class__.localData[0])
else:
return 0
def GetValue(self, row, col):
return self.__class__.localData[row][col]
def IsEmptyCell(self, row, col):
try:
if self.__class__.localData[row][col] != "":
return True
else:
return False
except:
return False
def SetValue(self, row, col, value):
comboBoxEdit = 0
# determine the record being modified using the primary key (located in col 5)
e = self.database.GetExpense(self.__class__.localData[row][5])
# determine which value is being set
if(0 == col):
e.user_id = self.database.GetUserId(value)
comboBoxEdit = 1
if(1 == col):
e.expenseType_id = self.database.GetExpenseTypeId(value)
comboBoxEdit = 1
if(2 == col):
e.amount = float(value)
if(3 == col):
# strptime will pull a datetime object out of an explicitly formatting string
localDate = dateMatch(value)
e.date = localDate
if(4 == col):
e.description = value
self.database.EditExpense(e.amount,
e.description,
e.date,
e.user_id,
e.expenseType_id,
self.__class__.localData[row][5])
# we want to avoid trying to modify the editor property if we've
# just finished working with an editor.
self.UpdateData(comboBoxEdit)
#***************************
# OPTIONAL METHODS
#***************************
def UpdateData(self, skipEditorRefresh=0):
"""This function performs the following actions: (1) pulls data from the
database in the specified order and lying within the specific window criteria.
(2) checks to see if a resize attempt is necessary. (3) updates old col/row counts
(4) refreshes grid. This function is intended to be the single point of contact
for performing a data refresh."""
self.__class__.previousColCnt = self.GetNumberCols()
self.__class__.previousRowCnt = self.GetNumberRows()
self.__class__.localData = self.database.GetAllExpenses()
self.__ResetView(skipEditorRefresh)
def GetPrevNumberRows(self):
return self.__class__.previousRowCnt
def GetPrevNumberCols(self):
return self.__class__.previousColCnt
def DeleteRow(self, row):
"""This function determines the ID of the element being deleted, removed it from the
database, informs the grid that a specific row is being removed, and then removes it from the
localData data collection. This is faster than re-loading all the expenses."""
# remove from the database
id = self.__class__.localData[row][5]
self.database.DeleteExpense(id)
self.UpdateData()
def __ResetView(self, skipEditorRefresh):
"""This function can be found at: http://wiki.wxpython.org/wxGrid
It implements a generic resize mechanism that uses the previous and current
row and col count to determine if the grid should be trimmed or extended. It
refreshes grid data and resizes the scroll bars using a 'jiggle trick'"""
self.GetView().BeginBatch()
for current, new, delmsg, addmsg in [(self.__class__.previousRowCnt, self.GetNumberRows(), gridlib.GRIDTABLE_NOTIFY_ROWS_DELETED, gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED),
(self.__class__.previousColCnt, self.GetNumberCols(), gridlib.GRIDTABLE_NOTIFY_COLS_DELETED, gridlib.GRIDTABLE_NOTIFY_COLS_APPENDED)]:
# determine if we've added or removed a row or col...
if new < current:
msg = gridlib.GridTableMessage(self,
delmsg,
new, # position
current-new)
self.GetView().ProcessTableMessage(msg)
elif new > current:
msg = gridlib.GridTableMessage(self,
addmsg,
new-current)
self.GetView().ProcessTableMessage(msg)
# refresh all data
msg = gridlib.GridTableMessage(self, gridlib.GRIDTABLE_REQUEST_VIEW_GET_VALUES)
self.GetView().ProcessTableMessage(msg)
self.GetView().EndBatch()
# apply correct formatting to each row after update
self.__class__.parent.FormatTableRows(skipEditorRefresh)
self.__class__.parent.FormatTableCols()
# The scroll bars aren't resized (at least on windows)
# Jiggling the size of the window rescales the scrollbars
h,w = self.__class__.parent.GetSize()
self.__class__.parent.SetSize((h+1, w))
self.__class__.parent.SetSize((h, w))
self.__class__.parent.ForceRefresh()
def GetColLabelValue(self, col):
return colInfo.colLabels[col]
| Python |
#!/usr/bin/env python
#********************************************************************
# Filename: threads.py
# Authors: Daniel Sisco
# Date Created: 12-22-2010
#
# Abstract: provides common 'thread' classes for various FINally objects.
#
# Copyright 2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
class ExpenseTypeThread():
"""This class supports global ExpenseType updates. It will execute every function
present in the class variable refreshFuncList when the method RunRefreshFuncs is
called. This class is intended to provide unified updates for all expenseType
components when any modification to the underlying expenseType objects are made."""
refreshFuncList = []
def StoreRefreshFunc(self, func):
self.__class__.refreshFuncList.append(func)
def ClearRefreshFuncList(self):
self.__class__.refreshFuncList = []
def RunRefreshFuncs(self):
for i in self.__class__.refreshFuncList:
i() # actually execute the function | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: filterControl.py
# Authors: Daniel Sisco
# Date Created: 10-3-2010
#
# Abstract: This is the primary file for the FINally expense analysis tool. It is responsible for
# handling read/write access to the SQLite database as well as providing a GUI interface for the user.
#
# Copyright 2008-2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
import wx
import wx.calendar as callib
import wx.grid as gridlib
from utils import monthDict, BLANK_TERM
from grid import CustomDataTable
from database import FilterTerms, Database
from datetime import datetime
from threads import ExpenseTypeThread
#*****************************************
# NOTE: this class was generated by wxGlade
# and hand-modified to work for FINally.
#*****************************************
class CustomFilterPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, -1)
self.database = Database()
self.bufferSize = (15,15)
self.dataTable = CustomDataTable(gridlib.Grid)
# values populated by controls in this panel - consumed by the application
self.startMonth = "January"
self.monthRange = 1
self.searchTerm = ""
self.filterTerms = FilterTerms()
# create the overarcing date filter box
self.filterSizer_staticbox = wx.StaticBox(self, -1, "date filter")
# create and bind the month range control
self.dateRangeText = wx.StaticText(self, -1, "month range", style=wx.ALIGN_CENTRE)
self.slider = wx.Slider(self,
100, # id
1, # default
1, # min
12, # max
(-1, -1), # pos
(250, -1),# size
wx.SL_HORIZONTAL | wx.SL_AUTOTICKS | wx.SL_LABELS )
self.slider.SetTickFreq(1, 1)
self.Bind(wx.EVT_SLIDER, self.OnMonthRange, self.slider)
# this comboBox is based on monthDict, so find the current month key
# in monthDict and use as default
now = datetime.now()
for key in monthDict:
if(now.month == monthDict[key]):
defaultMonth = key
# create and bind the start month combo box
self.startMonthText = wx.StaticText(self, -1, "start month")
self.startDateCombo = wx.ComboBox(self, -1, value=defaultMonth, choices=list(monthDict.keys()), style=wx.CB_DROPDOWN|wx.CB_DROPDOWN)
self.Bind(wx.EVT_COMBOBOX, self.OnMonthStart, self.startDateCombo)
# create and bind the start year combo box
self.startYearText = wx.StaticText(self, -1, "start year")
self.startYearCombo = wx.ComboBox(self, -1, value="2010", choices=["2010", "2011"], style=wx.CB_DROPDOWN|wx.CB_DROPDOWN)
self.Bind(wx.EVT_COMBOBOX, self.OnYearStart, self.startYearCombo)
# create the overarcing search box
self.searchSizer_staticbox = wx.StaticBox(self, -1, "search")
# create and bind the expense search widget
self.searchText = wx.StaticText(self, -1, "search expenses", style=wx.ALIGN_CENTRE)
# NOTE: for some reason the search control doesn't take a panel as the parent, just 'self'
self.search = wx.SearchCtrl(self, size=(200,-1), style=wx.TE_PROCESS_ENTER)
self.search.ShowCancelButton(1)
self.search.ShowSearchButton(1)
self.Bind(wx.EVT_SEARCHCTRL_SEARCH_BTN, self.OnSearch, self.search)
self.Bind(wx.EVT_SEARCHCTRL_CANCEL_BTN, self.OnCancel, self.search)
self.Bind(wx.EVT_TEXT_ENTER, self.OnSearch, self.search)
# create and bind the expenseType search widget
self.searchTypeText = wx.StaticText(self, -1, "search type", style=wx.ALIGN_CENTRE)
self.searchTypeCombo = wx.ComboBox(self, -1, style=wx.CB_DROPDOWN|wx.CB_DROPDOWN)
self.Bind(wx.EVT_COMBOBOX, self.OnTypeSearch, self.searchTypeCombo)
self.ExpTypeComboUpdate()
# declare local expenseType thread class and push the update function into it
self.etThread = ExpenseTypeThread()
self.etThread.StoreRefreshFunc(self.ExpTypeComboUpdate)
self.reservedSizer_staticbox = wx.StaticBox(self, -1, " reserved")
self.__do_layout()
def __do_layout(self):
sizer_1 = wx.BoxSizer(wx.VERTICAL)
filterPanelSizer = wx.BoxSizer(wx.HORIZONTAL)
reservedSizer = wx.StaticBoxSizer(self.reservedSizer_staticbox, wx.HORIZONTAL)
searchSizer = wx.StaticBoxSizer(self.searchSizer_staticbox, wx.HORIZONTAL)
searchSizerRight = wx.BoxSizer(wx.VERTICAL)
searchSizerLeft = wx.BoxSizer(wx.VERTICAL)
filterSizer = wx.StaticBoxSizer(self.filterSizer_staticbox, wx.HORIZONTAL)
filterSizerLeft = wx.BoxSizer(wx.VERTICAL)
filterSizerLeft.Add(self.startMonthText, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)
filterSizerLeft.Add(self.startDateCombo, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 15)
filterSizer.Add(filterSizerLeft, 0, wx.ALL|wx.EXPAND, 5)
filterSizerMid = wx.BoxSizer(wx.VERTICAL)
filterSizerMid.Add(self.startYearText, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)
filterSizerMid.Add(self.startYearCombo, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 15)
filterSizer.Add(filterSizerMid, 0, wx.ALL|wx.EXPAND, 5)
filterSizerRight = wx.BoxSizer(wx.VERTICAL)
filterSizerRight.Add(self.dateRangeText, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)
filterSizerRight.Add(self.slider, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)
filterSizer.Add(filterSizerRight, 1, wx.ALL|wx.EXPAND, 5)
filterPanelSizer.Add(filterSizer, 1, wx.RIGHT|wx.EXPAND, 5)
searchSizerLeft.Add(self.searchText, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)
searchSizerLeft.Add(self.search, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 20)
searchSizer.Add(searchSizerLeft, 0, wx.ALL|wx.EXPAND, 5)
searchSizerRight.Add(self.searchTypeText, 0, wx.ALIGN_CENTER_HORIZONTAL, 5)
searchSizerRight.Add(self.searchTypeCombo, 0, wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 20)
searchSizer.Add(searchSizerRight, 0, wx.ALL|wx.EXPAND, 5)
filterPanelSizer.Add(searchSizer, 0, wx.EXPAND, 0)
filterPanelSizer.Add(reservedSizer, 1, wx.LEFT|wx.EXPAND, 5)
sizer_1.Add(filterPanelSizer, 1, wx.ALL|wx.EXPAND, 5)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
def OnSearch(self, event):
localSearch = self.search.GetValue()
# replace null match with "match anything"
if(localSearch == ""):
localSearch = BLANK_TERM
self.filterTerms.SetSearchTerms(localSearch)
self.dataTable.UpdateData()
event.Skip()
def OnCancel(self, event):
self.search.SetValue("")
self.filterTerms.SetSearchTerms(BLANK_TERM)
self.dataTable.UpdateData()
event.Skip()
def OnMonthStart(self, event):
self.filterTerms.SetStartMonth(monthDict[self.startDateCombo.GetValue()])
self.dataTable.UpdateData()
event.Skip()
def OnMonthRange(self, event):
self.filterTerms.SetMonthRange(self.slider.GetValue())
self.dataTable.UpdateData()
event.Skip()
def OnYearStart(self, event):
self.filterTerms.SetStartYear(int(self.startYearCombo.GetValue()))
self.dataTable.UpdateData()
event.Skip()
def OnTypeSearch(self, event):
self.filterTerms.SetExpenseTypeTerms(self.searchTypeCombo.GetValue())
self.dataTable.UpdateData()
event.Skip()
def ExpTypeComboUpdate(self):
"""This function is responsible for re-loading all ComboBox values, and
setting the default value appropriately."""
# refresh the choices
self.expenseTypeChoices = self.database.GetExpenseTypeList()
self.expenseTypeChoices.insert(0, "all")
# remove all values from the ComboBox
self.searchTypeCombo.Clear()
# load new values into ComboBox
for i in self.expenseTypeChoices:
self.searchTypeCombo.Append(i)
# set ComboBox default value
self.searchTypeCombo.SetValue("all") | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: FINally.py
# Authors: Daniel Sisco
# Date Created: 4-20-2007
#
# Abstract: This is the primary file for the FINally expense analysis tool. It is responsible for
# handling read/write access to the SQLite database as well as providing a GUI interface for the user.
#
# Copyright 2008-2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
# import wxPython libraries - including some simplifiers for grid and calendar
import wx
import cfg
from datetime import date, datetime
from database import *
class CustomStatusBar(wx.StatusBar):
def __init__(self, parent):
wx.StatusBar.__init__(self, parent, -1)
self.database = Database()
# This status bar has three fields
self.SetFieldsCount(3)
# Sets the three fields to be relative widths to each other.
self.SetStatusWidths([-2, -2, -1])
self.SetStatusText("", 0)
self.SetStatusText("", 1)
self.versionString = "FINally v%s.%s.%s | database v%s.%s" % (cfg.VERSION[0],
cfg.VERSION[1],
cfg.VERSION[2],
self.database.GetVersion()[0],
self.database.GetVersion()[1])
self.SetStatusText(self.versionString, 2) | Python |
#!/usr/bin/env python
#********************************************************************
# Filename: schema_1_0.py
# Authors: Daniel Sisco
# Date Created: 9/19/2010
#
# Abstract: Version 1.0 of the FINally database schema
#
# Version History: See repository
#
# Copyright 2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
from sqlmigratelite.migrate import MigrateObject
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship, backref
Base = declarative_base()
version = "1.0"
dbVer = (1,0)
#********************************************************************
# Create SQLAlchemy tables in the form of python classes.
#********************************************************************
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
shortName = Column(String)
def __repr__(self):
return "<User('%s', '%s')>" % (self.name, self.shortName)
#********************************************************************
class ExpenseType(Base):
__tablename__ = 'expenseTypes'
id = Column(Integer, primary_key=True)
description = Column(String)
def __repr__(self):
return "<ExpenseType('%s')>" % (self.description)
#********************************************************************
class Expense(Base):
__tablename__ = 'expenses'
id = Column(Integer, primary_key=True)
amount = Column(Integer)
date = Column(String)
description = Column(String)
# define user_id to support database level link and user for class level link
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship(User, backref=backref('expenses', order_by=id))
expenseType_id = Column(Integer, ForeignKey('expenseTypes.id'))
expenseType = relationship(ExpenseType, backref=backref('expenseTypes', order_by=id))
def __repr__(self):
return "<Expense('%s', '%s', '%s')>" % (self.amount, self.date, self.description)
#********************************************************************
class Version(Base):
__tablename__ = 'versions'
id = Column(Integer, primary_key=True)
minor = Column(Integer)
major = Column(Integer)
def __repr__(self):
return "<Version('%s', '%s')>" % (self.minor, self.major)
#************************************
class SchemaObject(MigrateObject):
"""
version 1.0 schema object - defines custom dumpContent and loadContent methods
"""
def __init__(self, dbPath):
MigrateObject.__init__(self, dbPath, version)
def dumpContent(self):
"""dumps User and Version tables as-is"""
self.localDict['User'] = self.session.query(User).all()
self.localDict['ExpenseType'] = self.session.query(ExpenseType).all()
self.localDict['Expense'] = self.session.query(Expense).all()
def loadContent(self):
"""no support for v1.0 load at this time"""
pass | Python |
import wx
from database import Database
def EditPreferences(self, event):
"""fires when the new user button is clicked, this method creates a new user object"""
dia = PreferenceDialog(self, -1, 'Edit Preferences')
dia.ShowModal()
dia.Destroy()
event.Skip()
#********************************************************************
def SaveWindowPreferences(frameWidth, frameHeight):
"""called when we want to write window-based preferences into the database"""
#print "size of the main frame is: %s by %s" % (frameWidth, frameHeight)
#********************************************************************
def SaveColumnPreferences(colId, colWidth):
"""called when we want to write column preferences into the database"""
print "size of column %s changed to %s" % (colId, colWidth)
# pull current column widths out of database - split into array
database = Database()
locColWidths = database.GetPrefs().colWidths.split(',')
locColWidths[colId] = str(colWidth)
# re-load string with desired col width
locString = ""
for i in locColWidths:
locString += i
locString +=","
locString = locString.rstrip(",")
# push back into database
database.SetColWidthPref(locString)
#********************************************************************
class PreferenceDialog(wx.Dialog):
def __init__(self, parent, id, title):
wx.Dialog.__init__(self, parent, id, title, size=(350,300))
self.database = Database()
self.userList = self.database.GetSimpleUserList()
self.typeList = self.database.GetExpenseTypeList()
self.prefs = self.database.GetPrefs()
self.parent = parent
self.sizer = wx.BoxSizer(wx.VERTICAL) # define new box sizer
self.buttonPanel = wx.Panel(self) # create a panel for the buttons
# SAVE BUTTON
self.saveButton = wx.Button(self.buttonPanel,
id = -1,
label = "Save",
pos = (0,0))
self.Bind(wx.EVT_BUTTON, self.OnSaveClick, self.saveButton)
# DEFAULT USER
self.userSelect = wx.ComboBox(self.buttonPanel,
id=-1,
value=str(self.prefs.defUser_id),
choices=self.userList,
pos=(100,0),
style=wx.CB_DROPDOWN)
self.Bind(wx.EVT_COMBOBOX, self.OnUserSelect, self.userSelect)
# DEFAULT EXPENSE TYPE
self.expenseTypeSelect = wx.ComboBox(self.buttonPanel,
id=-1,
value=str(self.prefs.defExpenseType_id),
choices=self.typeList,
pos=(100,100),
style=wx.CB_DROPDOWN)
self.Bind(wx.EVT_COMBOBOX, self.OnExpenseTypeSelect, self.expenseTypeSelect)
# create and bind a value entry box
self.valueEntry = wx.TextCtrl(self.buttonPanel,
-1,
str(self.prefs.defAmount),
pos = (0,25),
size = (90, 21))
self.Bind(wx.EVT_TEXT, self.OnValueEntry, self.valueEntry)
self.sizer.Add(self.buttonPanel, 0, wx.ALIGN_LEFT) # add panel (no resize vert and aligned left horz)
self.SetSizer(self.sizer)
def OnSaveClick(self, evt):
"""respond to the user clicking 'save' by pushing the local objects into the database
layer"""
self.database.EditPrefs(self.userSelect.GetValue(),
self.expenseTypeSelect.GetValue(),
self.valueEntry.GetValue())
self.Close()
#***************************
# NOT REQUIRED AT THIS TIME
#***************************
def OnUserSelect(self, evt):
evt.Skip()
def OnExpenseTypeSelect(self, evt):
evt.Skip()
def OnValueEntry(self, evt):
evt.Skip()
| Python |
#!/usr/bin/env python
#********************************************************************
# Filename: expenseTypeDialog.py
# Authors: Daniel Sisco
# Date Created: 11/5/2010
#
# Abstract: This files contains the user add/edit/delete dialog.
#
# Copyright 2008-2010 Daniel Sisco
# This file is part of Fin-ally.
#
# Fin-ally 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.
#
# Fin-ally 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 Fin-ally. If not, see <http://www.gnu.org/licenses/>.
#********************************************************************
# import wxPython libraries - including some simplifiers for grid and calendar
import wx
import wx.calendar as callib
import wx.grid as gridlib
import cfg
import os
from datetime import date, datetime
from database import *
from grid import CustomDataTable
from threads import ExpenseTypeThread
#********************************************************************
class TypeColumnInfo:
"""This class defines the information required to create and modify columns in
a grid. This keeps all columns definition data together, but adding information here
does complete the addition of a new column."""
colLabels = ('Expense Type')
colWidth = [100]
colRO = [0] # 0 = R/W, 1 = R
colType = [gridlib.GRID_VALUE_STRING]
rowHeight = 20
#********************************************************************
class SimpleTypeGrid(gridlib.Grid):
"""This is a simple grid class - which means most of the methods are automatically
defined by the wx library"""
def __init__(self, parent):
gridlib.Grid.__init__(self, parent, -1, size=(200,300))
self.CreateGrid(100,1)
self.SetColLabelValue(0,"expense type")
# create a Database object and pull some data out of it
self.database = Database()
data = self.database.GetExpenseTypeList()
# used for refreshing the grid if an expenseType is edited
self.dataTable = CustomDataTable(gridlib.Grid)
self.currentValue = ""
self.Bind(gridlib.EVT_GRID_CELL_CHANGE, self.OnCellChange)
self.Bind(gridlib.EVT_GRID_EDITOR_SHOWN, self.OnEditorShown)
self.rowAttr = gridlib.GridCellAttr()
self.CreateReadOnlyCols()
# push data into grid, line by line
for i in range(len(data)):
self.SetCellValue(i,0,str(data[i]))
self.SetColSize(0,100)
# create unifying expenseType thread
self.etThread = ExpenseTypeThread()
def OnCellChange(self, evt):
"""Using a class variable that stores the previous ExpenseType description,
this method edits the ExpenseType table in the database"""
value = self.GetCellValue(evt.GetRow(), evt.GetCol())
# pull ID of the ExpenseType of interest and then edit the ExpenseType of that ID
etId = self.database.GetExpenseTypeId(self.currentValue)
self.database.EditExpenseType(value, etId)
self.dataTable.UpdateData()
self.etThread.RunRefreshFuncs()
evt.Skip()
def OnEditorShown(self, evt):
"""This method stores the current value into a class variable before
the user attempts to edit. This allows us to look-up ExpenseType id
by the 'old description' before the user changes it"""
self.currentValue = self.GetCellValue(evt.GetRow(), evt.GetCol())
evt.Skip()
def RefreshData(self, delete=0):
"""The delete argument removes one row from the top of the simple grid.
There is currently no way to delete more than one row at a time, so this
is safe."""
if(delete == 1):
# remove the last row
self.DeleteRows(0,1)
# push data into grid, line by line
data = self.database.GetExpenseTypeList()
for i in range(len(data)):
self.SetCellValue(i,0,str(data[i]))
def CreateReadOnlyCols(self):
"""creates read-only columns"""
self.rowAttr.SetReadOnly(1)
for i in range(len(TypeColumnInfo.colRO)):
if TypeColumnInfo.colRO[i] == 1:
self.SetColAttr(i,self.rowAttr)
self.rowAttr.IncRef()
#********************************************************************
class expenseTypeDialog(wx.Dialog):
def __init__(self, *args, **kwds):
# begin wxGlade: expenseTypeDialog.__init__
kwds["style"] = wx.DEFAULT_DIALOG_STYLE
wx.Dialog.__init__(self, *args, **kwds)
#**** BEGIN ADD ****
self.database = Database()
self.dataTable = CustomDataTable(gridlib.Grid)
self.expenseTypeChoices = self.database.GetExpenseTypeList()
self.newTypeText = "new type description..."
self.deleteSizer_staticbox = wx.StaticBox(self, -1, "Delete Existing Types")
self.newTypeSizer_staticbox = wx.StaticBox(self, -1, "Add New Types")
self.editSizer_staticbox = wx.StaticBox(self, -1, "Edit Existing Types")
#**** MOD ****
self.expenseTypeGrid = SimpleTypeGrid(self)
self.expenseTypeEditToggle = wx.ToggleButton(self, -1, "edit expense types...")
#*** MOD ***
self.deleteComboBox = wx.ComboBox(self,
-1,
self.expenseTypeChoices[0], #default
choices=self.expenseTypeChoices,
style=wx.CB_DROPDOWN)
self.deleteButton = wx.Button(self, -1, "delete")
self.newExpenseTypeEntry = wx.TextCtrl(self, -1, self.newTypeText)
self.addButton = wx.Button(self, -1, "add")
self.__set_properties()
self.__do_layout()
#**** ADDED ****
self.Bind(wx.EVT_BUTTON, self.onDeleteButton, self.deleteButton)
self.Bind(wx.EVT_BUTTON, self.onAddButton, self.addButton)
#**** END ADD ****
# end wxGlade
# create unifying expenseType thread
self.etThread = ExpenseTypeThread()
self.etThread.StoreRefreshFunc(self.ExpTypeDiaDelComboUpdate)
def __set_properties(self):
# begin wxGlade: expenseTypeDialog.__set_properties
self.SetTitle("Expense Type Dialog")
#**** MOD ****
# end wxGlade
def __do_layout(self):
# begin wxGlade: expenseTypeDialog.__do_layout
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
newTypeSizer = wx.StaticBoxSizer(self.newTypeSizer_staticbox, wx.VERTICAL)
innerNewTypeSizer = wx.BoxSizer(wx.HORIZONTAL)
deleteSizer = wx.StaticBoxSizer(self.deleteSizer_staticbox, wx.VERTICAL)
innerDeleteSizer = wx.BoxSizer(wx.HORIZONTAL)
editSizer = wx.StaticBoxSizer(self.editSizer_staticbox, wx.VERTICAL)
sizer_8 = wx.BoxSizer(wx.VERTICAL)
sizer_8.Add(self.expenseTypeGrid, 1, wx.ALL|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
sizer_8.Add(self.expenseTypeEditToggle, 0, wx.RIGHT|wx.TOP|wx.BOTTOM|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
editSizer.Add(sizer_8, 1, wx.EXPAND, 0)
sizer_2.Add(editSizer, 1, wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 5)
innerDeleteSizer.Add(self.deleteComboBox, 1, wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
innerDeleteSizer.Add(self.deleteButton, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
deleteSizer.Add(innerDeleteSizer, 1, wx.EXPAND, 0)
sizer_2.Add(deleteSizer, 0, wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 5)
innerNewTypeSizer.Add(self.newExpenseTypeEntry, 1, wx.RIGHT|wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 5)
innerNewTypeSizer.Add(self.addButton, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
newTypeSizer.Add(innerNewTypeSizer, 1, wx.EXPAND, 0)
sizer_2.Add(newTypeSizer, 0, wx.ALL|wx.EXPAND, 5)
sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
self.SetSizer(sizer_1)
sizer_1.Fit(self)
self.Layout()
# end wxGlade
#**** ADDED ****
def ExpTypeDiaDelComboUpdate(self):
self.deleteComboBox.Clear()
for i in self.database.GetExpenseTypeList():
self.deleteComboBox.Append(i)
def onAddButton(self, event):
"""triggers when the add button is clicked in the expense type dialog. This function
determines if conditions are correct for a new expense type entry and creates that type"""
localText = self.newExpenseTypeEntry.GetValue()
if(localText != self.newTypeText):
# if we successfully create a new expenseType...
if self.database.CreateExpenseType(localText):
# refresh Grid
self.expenseTypeGrid.RefreshData()
self.dataTable.UpdateData()
# refresh all expenseType dependents
self.etThread.RunRefreshFuncs()
# reset text in text entry box
self.newExpenseTypeEntry.SetValue(self.newTypeText)
else:
print "please enter a new expense type description!"
event.Skip()
def onDeleteButton(self, event):
"""triggered when the delete button is clicked in the expense type dialog. This function
either processes the deletion of a particular type entry, or informs the user
that a deletion is not possible at this time.
TODO: trigger another dialog to allow the user to specify a 'transfer to' type
before deleting an expense type record that is in use."""
if(self.expenseTypeEditToggle.GetValue()):
typeToDelete = self.deleteComboBox.GetValue()
IdxToDelete = self.deleteComboBox.GetSelection()
localId = self.database.GetExpenseTypeId(typeToDelete)
# verify that the expense actually exists
if localId != -1:
if(self.database.ExpenseTypeInUse(localId)):
# TODO: prompt user for new expenseType to apply using MigrateExpenseType
print "there are %s expenses using this type!" % (self.database.ExpenseTypeInUse(localId))
else:
# look up type via description, get ID, delete from db
print "deleting %s at position %s" % (typeToDelete, IdxToDelete)
print "default is %s" % (self.database.GetPrefs().defExpenseType_id)
# remove from Preferences
if(self.database.GetPrefs().defExpenseType_id == typeToDelete):
self.database.SetDefExpTypePref("")
localId = self.database.GetExpenseTypeId(typeToDelete)
self.database.DeleteExpenseType(localId)
# refresh Grid with delete option activated
self.expenseTypeGrid.RefreshData(delete=1)
self.dataTable.UpdateData()
self.etThread.RunRefreshFuncs()
else:
print "expense %s doesn't seem to exist anymore, close dialog and try again" % (typeToDelete)
else:
#TODO: open a dialoge to say this
print "you must unlock the grid before deleting"
event.Skip()
#**** END ADD ****
| Python |
import os
# This imports the global environment -- such as environment
# variables. Without this, the PATH to javac (/s/std/bin) would
# not be available.
env = Environment(ENV = os.environ)
# Abbreviate these so you can change them easier
source_dir = 'src'
build_dir = 'bin'
env['GEN_DIR'] = 'gen'
env['ANTLR_JAR'] = '/u/c/s/cs536-1/public/programs/antlr-3.4-complete.jar'
if 'CLASSPATH' not in os.environ:
classpath = build_dir + ':' + env['ANTLR_JAR']
else:
classpath = os.environ['CLASSPATH'] + ':' + build_dir + ':' + env['ANTLR_JAR']
env['JAVACLASSPATH'] = classpath
print env['JAVACLASSPATH']
##
## Generating the ANTLR grammar
##
env.Command('$GEN_DIR/src/cs536/syntax/MinC.java', 'src/cs536/syntax/MinC.g',
'java -cp $ANTLR_JAR org.antlr.Tool -o $GEN_DIR $SOURCE')
env.Clean('$GEN_DIR/src/cs536/syntax/MinC.java', '$GEN_DIR')
##
## Building the .class files
##
# Compile all the .java files in src/ to bin/ (the SCons target
# specifications work like assignment in languages: the target is the first
# parameter)
classes = env.Java(build_dir, [source_dir, '$GEN_DIR/src/cs536/syntax/MinC.java'])
# If we run 'scons' with no arguments, we just want to build the result
Default(classes)
# Make "scons compile" do the right thing
env.Alias('compile', classes)
| Python |
# these are from MARS, and in fact taken almost verbitim
instructions = [
("nop", "No operation"),
("add $dest,$left,$right", "Addition with overflow : set $dest to ($left plus $right)"),
("sub $dest,$left,$right", "Subtraction with overflow : set $dest to ($left minus $right)"),
("addi $dest,$left,<signed>", "Addition immediate with overflow : set $dest to ($left plus signed 16-bit immediate)"),
("addu $dest,$left,$right", "Addition unsigned without overflow : set $dest to ($left plus $right), no overflow"),
("subu $dest,$left,$right", "Subtraction unsigned without overflow : set $dest to ($left minus $right), no overflow"),
("addiu $dest,$left,<signed>", "Addition immediate unsigned without overflow : set $dest to ($left plus signed 16-bit immediate), no overflow"),
("mult $dest,$left", "Multiplication : Set hi to high-order 32 bits, lo to low-order 32 bits of the product of $dest and $left (use mfhi to access hi, mflo to access lo)"),
("multu $dest,$left", "Multiplication unsigned : Set HI to high-order 32 bits, LO to low-order 32 bits of the product of unsigned $dest and $left (use mfhi to access HI, mflo to access LO)"),
("mul $dest,$left,$right", "Multiplication without overflow : Set HI to high-order 32 bits, LO and $dest to low-order 32 bits of the product of $dest and $left (use mfhi to access HI, mflo to access LO)"),
("madd $dest,$left", "Multiply add : Multiply $dest by $left then increment HI by high-order 32 bits of product, increment LO by low-order 32 bits of product (use mfhi to access HI, mflo to access LO)"),
("maddu $dest,$left", "Multiply add unsigned : Multiply $dest by $left then increment HI by high-order 32 bits of product, increment LO by low-order 32 bits of product, unsigned (use mfhi to access HI, mflo to access LO)"),
("msub $dest,$left", "Multiply subtract : Multiply $dest by $left then decrement HI by high-order 32 bits of product, decrement LO by low-order 32 bits of product (use mfhi to access HI, mflo to access LO)"),
("msubu $dest,$left", "Multiply subtract unsigned : Multiply $dest by $left then decrement HI by high-order 32 bits of product, decement LO by low-order 32 bits of product, unsigned (use mfhi to access HI, mflo to access LO)"),
("div $dest,$left", "Division with overflow : Divide $dest by $left then set LO to quotient and HI to remainder (use mfhi to access HI, mflo to access LO)"),
("divu $dest,$left", "Division unsigned without overflow : Divide unsigned $dest by $left then set LO to quotient and HI to remainder (use mfhi to access HI, mflo to access LO)"),
("mfhi $dest", "Move from HI register : Set $dest to contents of HI (see multiply and divide operations)"),
("mflo $dest", "Move from LO register : Set $dest to contents of LO (see multiply and divide operations)"),
("mthi $dest", "Move to HI registerr : Set HI to contents of $dest (see multiply and divide operations)"),
("mtlo $dest", "Move to LO register : Set LO to contents of $dest (see multiply and divide operations)"),
("and $dest,$left,$right", "Bitwise AND : Set $dest to bitwise AND of $left and $right"),
("or $dest,$left,$right", "Bitwise OR : Set $dest to bitwise OR of $left and $right"),
("andi $dest,$left,<unsigned>", "Bitwise AND immediate : Set $dest to bitwise AND of $left and zero-extended 16-bit immediate"),
("ori $dest,$left,<unsigned>", "Bitwise OR immediate : Set $dest to bitwise OR of $left and zero-extended 16-bit immediate"),
("nor $dest,$left,$right", "Bitwise NOR : Set $dest to bitwise NOR of $left and $right"),
("xor $dest,$left,$right", "Bitwise XOR (exclusive OR) : Set $dest to bitwise XOR of $left and $right"),
("xori $dest,$left,<unsigned>", "Bitwise XOR immediate : Set $dest to bitwise XOR of $left and zero-extended 16-bit immediate"),
("sll $dest,$left,<numbits>", "Shift left logical : Set $dest to result of shifting $left left by number of bits specified by immediate"),
("sllv $dest,$left,$right", "Shift left logical variable : Set $dest to result of shifting $left left by number of bits specified by value in low-order 5 bits of $right"),
("srl $dest,$left,<numbits>", "Shift right logical : Set $dest to result of shifting $left right by number of bits specified by immediate"),
("sra $dest,$left,<numbits>", "Shift right arithmetic : Set $dest to result of sign-extended shifting $left right by number of bits specified by immediate"),
("srav $dest,$left,$right", "Shift right arithmetic variable : Set $dest to result of sign-extended shifting $left right by number of bits specified by value in low-order 5 bits of $right"),
("srlv $dest,$left,$right", "Shift right logical variable : Set $dest to result of shifting $left right by number of bits specified by value in low-order 5 bits of $right"),
("lui $dest,<unsigned>", "Load upper immediate : Set high-order 16 bits of $dest to 16-bit immediate and low-order 16 bits to 0"),
("lw $dest,<offset>,($base)", "Load word : Set $dest to contents of effective memory word address"),
("ll $dest,<offset>,($base)", "Load linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
("lwl $dest,<offset>,($base)", "Load word left : Load from 1 to 4 bytes left-justified into $dest, starting with effective memory byte address and continuing through the low-order byte of its word"),
("lwr $dest,<offset>,($base)", "Load word right : Load from 1 to 4 bytes right-justified into $dest, starting with effective memory byte address and continuing through the high-order byte of its word"),
("sw $src,<offset>,($base)", "Store word : Store contents of $src into effective memory word address"),
("sc $src,<offset>,($base)", "Store conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Stores $src value into effective address, then sets $src to 1 for success. Always succeeds because MARS does not simulate multiple processors."),
("swl $src,<offset>,($base)", "Store word left : Store high-order 1 to 4 bytes of $src into memory, starting with effective byte address and continuing through the low-order byte of its word"),
("swr $src,<offset>,($base)", "Store word right : Store low-order 1 to 4 bytes of $src into memory, starting with high-order byte of word containing effective byte address and continuing through that byte address"),
("lb $dest,<offset>,($base)", "Load byte : Set $dest to sign-extended 8-bit value from effective memory byte address"),
("lh $dest,<offset>,($base)", "Load halfword : Set $dest to sign-extended 16-bit value from effective memory halfword address"),
("lhu $dest,<offset>,($base)", "Load halfword unsigned : Set $dest to zero-extended 16-bit value from effective memory halfword address"),
("lbu $dest,<offset>,($base)", "Load byte unsigned : Set $dest to zero-extended 8-bit value from effective memory byte address"),
("sb $src,<offset>,($base)", "Store byte : Store the low-order 8 bits of $src into the effective memory byte address"),
("sh $src,<offset>,($base)", "Store halfword : Store the low-order 16 bits of $src into the effective memory halfword address"),
("beq $left,$t2,<label>", "Branch if equal : Branch to statement at <label>'s address if $left and $t2 are equal"),
("bne $left,$t2,<label>", "Branch if not equal : Branch to statement at <label>'s address if $left and $t2 are not equal"),
("bgez $src,<label>", "Branch if greater than or equal to zero : Branch to statement at <label>'s address if $src is greater than or equal to zero"),
("bgezal $src,<label>", "Branch if greater then or equal to zero and link : If $src is greater than or equal to zero, then set $ra to the Program Counter and branch to statement at <label>'s address"),
("bgtz $src,<label>", "Branch if greater than zero : Branch to statement at <label>'s address if $src is greater than zero"),
("blez $src,<label>", "Branch if less than or equal to zero : Branch to statement at <label>'s address if $src is less than or equal to zero"),
("bltz $src,<label>", "Branch if less than zero : Branch to statement at <label>'s address if $src is less than zero"),
("bltzal $src,<label>", "Branch if less than zero and link : If $src is less than or equal to zero, then set $ra to the Program Counter and branch to statement at <label>'s address"),
("slt $dest,$t2,$t3", "Set less than : If $t2 is less than $t3, then set $dest to 1 else set $dest to 0"),
("sltu $dest,$t2,$t3", "Set less than unsigned : If $t2 is less than $t3 using unsigned comparision, then set $dest to 1 else set $dest to 0"),
("slti $dest,$t2,<signed>", "Set less than immediate : If $t2 is less than sign-extended 16-bit immediate, then set $dest to 1 else set $dest to 0"),
("sltiu $dest,$t2,<signed>", "Set less than immediate unsigned : If $t2 is less than sign-extended 16-bit immediate using unsigned comparison, then set $dest to 1 else set $dest to 0"),
("movn $dest,$t2,$t3", "Move conditional not zero : Set $dest to $t2 if $t3 is not zero"),
("movz $dest,$t2,$t3", "Move conditional zero : Set $dest to $t2 if $t3 is zero"),
("movf $dest,$t2", "Move if FP condition flag 0 false : Set $dest to $t2 if FPU (Coprocessor 1) condition flag 0 is false (zero)"),
#("movf $dest,$t2,1", "Move if specified FP condition flag false : Set $dest to $t2 if FPU (Coprocessor 1) condition flag specified by the immediate is false (zero)"),
("movt $dest,$t2", "Move if FP condition flag 0 true : Set $dest to $t2 if FPU (Coprocessor 1) condition flag 0 is true (one)"),
#("movt $dest,$t2,1", "Move if specfied FP condition flag true : Set $dest to $t2 if FPU (Coprocessor 1) condition flag specified by the immediate is true (one)"),
#("break <unsigned>", "Break execution with code : Terminate program execution with specified exception code"),
#("break", "Break execution : Terminate program execution with exception"),
("syscall", "Issue a system call : Execute the system call specified by value in $v0"),
("j <label>", "Jump unconditionally : Jump to statement at <label> address"),
("jr $src", "Jump register unconditionally : Jump to statement whose address is in $src"),
("jal <label>", "Jump and link : Set $ra to Program Counter (return address) then jump to statement at <label> address"),
("jalr $dest,$src", "Jump and link register : Set $dest to Program Counter (return address) then jump to statement whose address is in $src"),
("jalr $src", "Jump and link register : Set $ra to Program Counter (return address) then jump to statement whose address is in $src"),
("clo $dest,$src", "Count number of leading ones : Set $dest to the count of leading one bits in $src starting at most significant bit position"),
("clz $dest,$src", "Count number of leading zeroes : Set $dest to the count of leading zero bits in $src starting at most significant bit positio"),
("add.s $fpdest,$fpleft,$fpright", "Floating point addition single precision : Set $fpdest to single-precision floating point value of $fpleft plus $fpright",),
("sub.s $fpdest,$fpleft,$fpright", "Floating point subtraction single precision : Set $fpdest to single-precision floating point value of $fpleft minus $fpright"),
("mul.s $fpdest,$fpleft,$fpright", "Floating point multiplication single precision : Set $fpdest to single-precision floating point value of $fpleft times $fpright"),
("div.s $fpdest,$fpleft,$fpright", "Floating point division single precision : Set $fpdest to single-precision floating point value of $fpleft divided by $fpright"),
("sqrt.s $fpdest,$fpsrc", "Square root single precision : Set $fpdest to single-precision floating point square root of $fpsrc"),
("floor.w.s $fpdest,$fpsrc", "Floor single precision to word : Set $fpdest to 32-bit integer floor of single-precision float in $fpsrc"),
("ceil.w.s $fpdest,$fpsrc", "Ceiling single precision to word : Set $fpdest to 32-bit integer ceiling of single-precision float in $fpsrc"),
("round.w.s $fpdest,$fpsrc", "Round single precision to word : Set $fpdest to 32-bit integer round of single-precision float in $fpsrc"),
("trunc.w.s $fpdest,$fpsrc", "Truncate single precision to word : Set $fpdest to 32-bit integer truncation of single-precision float in $fpsrc"),
("add.d $fpdest,$fpleft,$fpright", "Floating point addition double precision : Set $fpdest to double-precision floating point value of $fpleft plus $fpright"),
("sub.d $fpdest,$fpleft,$fpright", "Floating point subtraction double precision : Set $fpdest to double-precision floating point value of $fpleft minus $fpright"),
("mul.d $fpdest,$fpleft,$fpright", "Floating point multiplication double precision : Set $fpdest to double-precision floating point value of $fpleft times $fpright"),
("div.d $fpdest,$fpleft,$fpright", "Floating point division double precision : Set $fpdest to double-precision floating point value of $fpleft divided by $fpright"),
("sqrt.d $fpdest,$fpsrc", "Square root double precision : Set $fpdest to double-precision floating point square root of $fpsrc"),
("ceil.w.d $fpdest,$fpsrc", "Ceiling double precision to word : Set $fpdest to 32-bit integer ceiling of double-precision float in $fpsrc"),
("round.w.d $fpdest,$fpsrc", "Round double precision to word : Set $fpdest to 32-bit integer round of double-precision float in $fpsrc"),
("trunc.w.d $fpdest,$fpsrc", "Truncate double precision to word : Set $fpdest to 32-bit integer truncation of double-precision float in $fpsrc"),
("bc1t <label>", "Branch if FP condition flag 0 true (BC1T, not BCLT) : If Coprocessor 1 condition flag 0 is true (one) then branch to statement at <label>'s address"),
("bc1f <label>", "Branch if FP condition flag 0 false (BC1F, not BCLF) : If Coprocessor 1 condition flag 0 is false (zero) then branch to statement at <label>'s address"),
("c.eq.s $fpleft,$fpright", "Compare equal single precision : If $fpleft is equal to $fpright, set Coprocessor 1 condition flag 0 true else set it false"),
("c.le.s $fpleft,$fpright", "Compare less or equal single precision : If $fpleft is less than or equal to $fpright, set Coprocessor 1 condition flag 0 true else set it false"),
("c.lt.s $fpleft,$fpright", "Compare less than single precision : If $fpleft is less than $fpright, set Coprocessor 1 condition flag 0 true else set it false"),
("c.eq.d $fpleft,$fpright", "Compare equal double precision : If $fpleft is equal to $fpright (double-precision), set Coprocessor 1 condition flag 0 true else set it false"),
("c.le.d $fpleft,$fpright", "Compare less or equal double precision : If $fpleft is less than or equal to $fpright (double-precision), set Coprocessor 1 condition flag 0 true else set it false"),
("c.lt.d $fpleft,$fpright", "Compare less than double precision : If $fpleft is less than $fpright (double-precision), set Coprocessor 1 condition flag 0 true else set it false"),
("abs.s $fpdest,$fpsrc", "Floating point absolute value single precision : Set $fpdest to absolute value of $fpsrc, single precision"),
("abs.d $fpdest,$fpsrc", "Floating point absolute value double precision : Set $fpdest to absolute value of $fpsrc, double precision"),
("cvt.d.s $fpdest,$fpsrc", "Convert from single precision to double precision : Set $fpdest to double precision equivalent of single precision value in $fpsrc"),
("cvt.d.w $fpdest,$fpsrc", "Convert from word to double precision : Set $fpdest to double precision equivalent of 32-bit integer value in $fpsrc"),
("cvt.s.d $fpdest,$fpsrc", "Convert from double precision to single precision : Set $fpdest to single precision equivalent of double precision value in $fpsrc"),
("cvt.s.w $fpdest,$fpsrc", "Convert from word to single precision : Set $fpdest to single precision equivalent of 32-bit integer value in $fpsrc"),
("cvt.w.d $fpdest,$fpsrc", "Convert from double precision to word : Set $fpdest to 32-bit integer equivalent of double precision value in $fpsrc"),
("cvt.w.s $fpdest,$fpsrc", "Convert from single precision to word : Set $fpdest to 32-bit integer equivalent of single precision value in $fpsrc"),
("mov.d $fpdest,$fpsrc", "Move floating point double precision : Set double precision $fpdest to double precision value in $fpsrc"),
("movf.d $fpdest,$fpsrc", "Move floating point double precision : If condition flag 0 false, set double precision $fpdest to double precision value in $fpsrc"),
#("movf.d $fpdest,$fpsrc,1", "Move floating point double precision : If condition flag specified by immediate is false, set double precision $fpdest to double precision value in $fpsrc"),
("movt.d $fpdest,$fpsrc", "Move floating point double precision : If condition flag 0 true, set double precision $fpdest to double precision value in $fpsrc"),
#("movt.d $fpdest,$fpsrc,1", "Move floating point double precision : If condition flag specified by immediate is true, set double precision $fpdest to double precision value in $fpsrce"),
("movn.d $fpdest,$fpsrc,$intreg", "Move floating point double precision : If $intreg is not zero, set double precision $fpdest to double precision value in $fpsrc"),
("movz.d $fpdest,$fpsrc,$intreg", "Move floating point double precision : If $intreg is zero, set double precision $fpdest to double precision value in $fpsrc"),
("mov.s $fpdest,$fpsrc", "Move floating point single precision : Set single precision $fpdest to single precision value in $fpsrc"),
("movf.s $fpdest,$fpsrc", "Move floating point single precision : If condition flag 0 is false, set single precision $fpdest to single precision value in $fpsrc"),
#("movf.s $fpdest,$fpsrc,1", "Move floating point single precision : If condition flag specified by immediate is false, set single precision $fpdest to single precision value in $fpsrce"),
("movt.s $fpdest,$fpsrc", "Move floating point single precision : If condition flag 0 is true, set single precision $fpdest to single precision value in $fpsrce"),
#("movt.s $fpdest,$fpsrc,1", "Move floating point single precision : If condition flag specified by immediate is true, set single precision $fpdest to single precision value in $fpsrce"),
("movn.s $fpdest,$fpsrc,$intreg", "Move floating point single precision : If $intreg is not zero, set single precision $fpdest to single precision value in $fpsrc"),
("movz.s $fpdest,$fpsrc,$intreg", "Move floating point single precision : If $intreg is zero, set single precision $fpdest to single precision value in $fpsrc"),
("mfc1 $intdest,$fpsrc", "Move from Coprocessor 1 (FPU) : Set $intdest to value in Coprocessor 1 register $fpsrc"),
("mtc1 $intsrc,$fpdest", "Move to Coprocessor 1 (FPU) : Set Coprocessor 1 register $fpdest to value in $intsrc"),
("neg.d $fpdest,$fpsrc", "Floating point negate double precision : Set double precision $fpdest to negation of double precision value in $fpsrc"),
("neg.s $fpdest,$fpsrc", "Floating point negate single precision : Set single precision $fpdest to negation of single precision value in $fpsrc"),
("lwc1 $fpdest,<offset>,($base)", "Load word into Coprocessor 1 (FPU) : Set $fpdest to 32-bit value from effective memory word address"),
("ldc1 $fpdest,<offset>,($base)", "Load double word Coprocessor 1 (FPU)) : Set $fpdest to 64-bit value from effective memory doubleword address"),
("swc1 $fpsrc,<offset>,($base)", "Store word from Coprocesor 1 (FPU) : Store 32 bit value in $fpsrc to effective memory word address"),
("sdc1 $fpsrc,<offset>,($base)", "Store double word from Coprocessor 1 (FPU)) : Store 64 bit value in $fpsrc to effective memory doubleword address"),
("teq $left,$right", "Trap if equal : Trap if $left is equal to $right"),
("teqi $src,<signed>", "Trap if equal to immediate : Trap if $src is equal to sign-extended 16 bit immediate"),
("tne $left,$right", "Trap if not equal : Trap if $left is not equal to $right"),
("tnei $src,<signed>", "Trap if not equal to immediate : Trap if $src is not equal to sign-extended 16 bit immediate"),
("tge $left,$right", "Trap if greater or equal : Trap if $left is greater than or equal to $right"),
("tgeu $left,$right", "Trap if greater or equal unsigned : Trap if $left is greater than or equal to $right using unsigned comparision"),
("tgei $src,<signed>", "Trap if greater than or equal to immediate : Trap if $src greater than or equal to sign-extended 16 bit immediate"),
("tgeiu $src,<signed>", "Trap if greater or equal to immediate unsigned : Trap if $src greater than or equal to sign-extended 16 bit immediate, unsigned comparison"),
("tlt $left,$right", "Trap if less than: Trap if $left less than $right"),
("tltu $left,$right", "Trap if less than unsigned : Trap if $left less than $right, unsigned comparison"),
("tlti $src,<signed>", "Trap if less than immediate : Trap if $src less than sign-extended 16-bit immediate"),
("tltiu $src,<signed>", "Trap if less than immediate unsigned : Trap if $src less than sign-extended 16-bit immediate, unsigned comparison"),
("eret", "Exception return : Set Program Counter to Coprocessor 0 EPC register value, set Coprocessor Status register bit 1 (exception level) to zero"),
]
# these are from MARS, and in fact taken almost verbitim
pseudo_instructions = [
("not $t1,$t2", "Bitwise NOT (bit inversion)"),
("add $t1,$t2,<signed>", "ADDition : set $t1 to ($t2 plus 16-bit immediate)"),
#("add $t1,$t2,<large_unsigned>", "ADDition : set $t1 to ($t2 plus 32-bit immediate)"),
("addu $t1,$t2,<large_unsigned>", "ADDition Unsigned : set $t1 to ($t2 plus 32-bit immediate), no overflow"),
("addi $t1,$t2,<large_unsigned>", "ADDition Immediate : set $t1 to ($t2 plus 32-bit immediate)"),
("addiu $t1,$t2,<large_unsigned>", "ADDition Immediate Unsigned: set $t1 to ($t2 plus 32-bit immediate), no overflow"),
("sub $t1,$t2,<signed>", "SUBtraction : set $t1 to ($t2 minus 16-bit immediate)"),
#("sub $t1,$t2,<large_unsigned>", "SUBtraction : set $t1 to ($t2 minus 32-bit immediate)"),
("subu $t1,$t2,<large_unsigned>", "SUBtraction Unsigned : set $t1 to ($t2 minus 32-bit immediate), no overflow"),
("subi $t1,$t2,<signed>", "SUBtraction Immediate : set $t1 to ($t2 minus 16-bit immediate)"),
#("subi $t1,$t2,<large_unsigned>", "SUBtraction Immediate : set $t1 to ($t2 minus 32-bit immediate)"),
("subiu $t1,$t2,<large_unsigned>", "SUBtraction Immediate Unsigned : set $t1 to ($t2 minus 32-bit immediate), no overflow"),
#("andi $t1,$t2,<large_unsigned>", "AND Immediate : set $t1 to ($t2 bitwise-AND 32-bit immediate)"),
#("ori $t1,$t2,<large_unsigned>", "OR Immediate : set $t1 to ($t2 bitwise-OR 32-bit immediate)"),
#("xori $t1,$t2,<large_unsigned>", "XOR Immediate : set $t1 to ($t2 bitwise-exclusive-OR 32-bit immediate)"),
("and $t1,$t2,<unsigned>", "AND : set $t1 to ($t2 bitwise-AND 16-bit unsigned immediate)"),
("or $t1,$t2,<unsigned>", "OR : set $t1 to ($t2 bitwise-OR 16-bit unsigned immediate)"),
("xor $t1,$t2,<unsigned>", "XOR : set $t1 to ($t2 bitwise-exclusive-OR 16-bit unsigned immediate)"),
("and $t1,<unsigned>", "AND : set $t1 to ($t1 bitwise-AND 16-bit unsigned immediate)"),
("or $t1,<unsigned>", "OR : set $t1 to ($t1 bitwise-OR 16-bit unsigned immediate)"),
("xor $t1,<unsigned>", "XOR : set $t1 to ($t1 bitwise-exclusive-OR 16-bit unsigned immediate)"),
("andi $t1,<unsigned>", "AND Immediate : set $t1 to ($t1 bitwise-AND 16-bit unsigned immediate)"),
("ori $t1,<unsigned>", "OR Immediate : set $t1 to ($t1 bitwise-OR 16-bit unsigned immediate)"),
("xori $t1,<unsigned>", "XOR Immediate : set $t1 to ($t1 bitwise-exclusive-OR 16-bit unsigned immediate)"),
#("andi $t1,<large_unsigned>", "AND Immediate : set $t1 to ($t1 bitwise-AND 32-bit immediate)"),
#("ori $t1,<large_unsigned>", "OR Immediate : set $t1 to ($t1 bitwise-OR 32-bit immediate)"),
#("xori $t1,<large_unsigned>", "XOR Immediate : set $t1 to ($t1 bitwise-exclusive-OR 32-bit immediate)"),
("seq $t1,$t2,$t3", "Set EQual : if $t2 equal to $t3 then set $t1 to 1 else 0"),
("seq $t1,$t2,<signed>", "Set EQual : if $t2 equal to 16-bit immediate then set $t1 to 1 else 0"),
#("seq $t1,$t2,<large_unsigned>", "Set EQual : if $t2 equal to 32-bit immediate then set $t1 to 1 else 0"),
("sne $t1,$t2,$t3", "Set Not Equal : if $t2 not equal to $t3 then set $t1 to 1 else 0"),
("sne $t1,$t2,<signed>", "Set Not Equal : if $t2 not equal to 16-bit immediate then set $t1 to 1 else 0"),
#("sne $t1,$t2,<large_unsigned>", "Set Not Equal : if $t2 not equal to 32-bit immediate then set $t1 to 1 else 0"),
("sge $t1,$t2,$t3", "Set Greater or Equal : if $t2 greater or equal to $t3 then set $t1 to 1 else 0"),
("sge $t1,$t2,<signed>", "Set Greater or Equal : if $t2 greater or equal to 16-bit immediate then set $t1 to 1 else 0"),
#("sge $t1,$t2,<large_unsigned>", "Set Greater or Equal : if $t2 greater or equal to 32-bit immediate then set $t1 to 1 else 0"),
("sgeu $t1,$t2,$t3", "Set Greater or Equal Unsigned : if $t2 greater or equal to $t3 (unsigned compare) then set $t1 to 1 else 0"),
("sgeu $t1,$t2,<signed>", "Set Greater or Equal Unsigned : if $t2 greater or equal to 16-bit immediate (unsigned compare) then set $t1 to 1 else 0"),
#("sgeu $t1,$t2,<large_unsigned>", "Set Greater or Equal Unsigned : if $t2 greater or equal to 32-bit immediate (unsigned compare) then set $t1 to 1 else 0"),
("sgt $t1,$t2,$t3", "Set Greater Than : if $t2 greater than $t3 then set $t1 to 1 else 0"),
("sgt $t1,$t2,<signed>", "Set Greater Than : if $t2 greater than 16-bit immediate then set $t1 to 1 else 0"),
#("sgt $t1,$t2,<large_unsigned>", "Set Greater Than : if $t2 greater than 32-bit immediate then set $t1 to 1 else 0"),
("sgtu $t1,$t2,$t3", "Set Greater Than Unsigned : if $t2 greater than $t3 (unsigned compare) then set $t1 to 1 else 0"),
("sgtu $t1,$t2,<signed>", "Set Greater Than Unsigned : if $t2 greater than 16-bit immediate (unsigned compare) then set $t1 to 1 else 0"),
#("sgtu $t1,$t2,<large_unsigned>", "Set Greater Than Unsigned : if $t2 greater than 32-bit immediate (unsigned compare) then set $t1 to 1 else 0"),
("sle $t1,$t2,$t3", "Set Less or Equal : if $t2 less or equal to $t3 then set $t1 to 1 else 0"),
("sle $t1,$t2,<signed>", "Set Less or Equal : if $t2 less or equal to 16-bit immediate then set $t1 to 1 else 0"),
#("sle $t1,$t2,<large_unsigned>", "Set Less or Equal : if $t2 less or equal to 32-bit immediate then set $t1 to 1 else 0"),
("sleu $t1,$t2,$t3", "Set Less or Equal Unsigned: if $t2 less or equal to $t3 (unsigned compare) then set $t1 to 1 else 0"),
("sleu $t1,$t2,<signed>", "Set Less or Equal Unsigned: if $t2 less or equal to 16-bit immediate (unsigned compare) then set $t1 to 1 else 0"),
#("sleu $t1,$t2,<large_unsigned>", "Set Less or Equal Unsigned: if $t2 less or equal to 32-bit immediate (unsigned compare) then set $t1 to 1 else 0"),
("move $t1,$t2", "MOVE : Set $t1 to contents of $t2"),
("abs $t1,$t2", "ABSolute value : Set $t1 to absolute value of $t2 (algorithm from Hacker's Delight) "),
("neg $t1,$t2", "NEGate : Set $t1 to negation of $t2"),
("negu $t1,$t2", "NEGate Unsigned : Set $t1 to negation of $t2, no overflow"),
("b <label>", "Branch : Branch to statement at label unconditionally"),
("beqz $t1,<label>", "Branch if EQual Zero : Branch to statement at label if $t1 is equal to zero"),
("bnez $t1,<label>", "Branch if Not Equal Zero : Branch to statement at label if $t1 is not equal to zero"),
("beq $t1,<signed>,<label>", "Branch if EQual : Branch to statement at label if $t1 is equal to 16-bit immediate"),
#("beq $t1,<large_unsigned>,<label>", "Branch if EQual : Branch to statement at label if $t1 is equal to 32-bit immediate "),
("bne $t1,<signed>,<label>", "Branch if Not Equal : Branch to statement at label if $t1 is not equal to 16-bit immediate"),
#("bne $t1,<large_unsigned>,<label>", "Branch if Not Equal : Branch to statement at label if $t1 is not equal to 32-bit immediate "),
("bge $t1,$t2,<label>", "Branch if Greater or Equal : Branch to statement at label if $t1 is greater or equal to $t2"),
("bge $t1,<signed>,<label>", "Branch if Greater or Equal : Branch to statement at label if $t1 is greater or equal to 16-bit immediate "),
#("bge $t1,<large_unsigned>,<label>", "Branch if Greater or Equal : Branch to statement at label if $t1 is greater or equal to 32-bit immediate "),
("bgeu $t1,$t2,<label>", "Branch if Greater or Equal Unsigned : Branch to statement at label if $t1 is greater or equal to $t2 (unsigned compare)"),
("bgeu $t1,<signed>,<label>", "Branch if Greater or Equal Unsigned : Branch to statement at label if $t1 is greater or equal to 16-bit immediate (unsigned compare)"),
#("bgeu $t1,<large_unsigned>,<label>", "Branch if Greater or Equal Unsigned : Branch to statement at label if $t1 is greater or equal to 32-bit immediate (unsigned compare)"),
("bgt $t1,$t2,<label>", "Branch if Greater Than : Branch to statement at label if $t1 is greater than $t2"),
("bgt $t1,<signed>,<label>", "Branch if Greater Than : Branch to statement at label if $t1 is greater than 16-bit immediate "),
#("bgt $t1,<large_unsigned>,<label>", "Branch if Greater Than : Branch to statement at label if $t1 is greater than 32-bit immediate"),
("bgtu $t1,$t2,<label>", "Branch if Greater Than Unsigned: Branch to statement at label if $t1 is greater than $t2 (unsigned compare)"),
("bgtu $t1,<signed>,<label>", "Branch if Greater Than Unsigned: Branch to statement at label if $t1 is greater than 16-bit immediate (unsigned compare)"),
#("bgtu $t1,<large_unsigned>,<label>", "Branch if Greater Than Unsigned: Branch to statement at label if $t1 is greater than 16-bit immediate (unsigned compare)"),
("ble $t1,$t2,<label>", "Branch if Less or Equal : Branch to statement at label if $t1 is less than or equal to $t2"),
("ble $t1,<signed>,<label>", "Branch if Less or Equal : Branch to statement at label if $t1 is less than or equal to 16-bit immediate"),
#("ble $t1,<large_unsigned>,<label>", "Branch if Less or Equal : Branch to statement at label if $t1 is less than or equal to 32-bit immediate "),
("bleu $t1,$t2,<label>", "Branch if Less or Equal Unsigned : Branch to statement at label if $t1 is less than or equal to $t2 (unsigned compare)"),
("bleu $t1,<signed>,<label>", "Branch if Less or Equal Unsigned : Branch to statement at label if $t1 is less than or equal to 16-bit immediate (unsigned compare)"),
#("bleu $t1,<large_unsigned>,<label>", "Branch if Less or Equal Unsigned : Branch to statement at label if $t1 is less than or equal to 32-bit immediate (unsigned compare)"),
("blt $t1,$t2,<label>", "Branch if Less Than : Branch to statement at label if $t1 is less than $t2"),
("blt $t1,<signed>,<label>", "Branch if Less Than : Branch to statement at label if $t1 is less than 16-bit immediate"),
#("blt $t1,<large_unsigned>,<label>", "Branch if Less Than : Branch to statement at label if $t1 is less than 32-bit immediate"),
("bltu $t1,$t2,<label>", "Branch if Less Than Unsigned : Branch to statement at label if $t1 is less than $t2"),
("bltu $t1,<signed>,<label>", "Branch if Less Than Unsigned : Branch to statement at label if $t1 is less than 16-bit immediate "),
#("bltu $t1,<large_unsigned>,<label>", "Branch if Less Than Unsigned : Branch to statement at label if $t1 is less than 32-bit immediate"),
("rol $t1,$t2,$t3", "ROtate Left : Set $t1 to ($t2 rotated left by number of bit positions specified in $t3)"),
("rol $t1,$t2,<numbits>", "ROtate Left : Set $t1 to ($t2 rotated left by number of bit positions specified in 5-bit immediate)"),
("ror $t1,$t2,$t3", "ROtate Right : Set $t1 to ($t2 rotated right by number of bit positions specified in $t3)"),
("ror $t1,$t2,<numbits>", "ROtate Right : Set $t1 to ($t2 rotated right by number of bit positions specified in 5-bit immediate)"),
("mfc1.d $t1,$fpf2", "Move From Coprocessor 1 Double : Set $t1 to contents of $fpf2, set next higher register from $t1 to contents of next higher register from $fpf2"),
("mtc1.d $t1,$fpf2", "Move To Coprocessor 1 Double : Set $fpf2 to contents of $t1, set next higher register from $fpf2 to contents of next higher register from $t1"),
("mul $t1,$t2,<signed>", "MULtiplication : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of the product of $t2 and 16-bit signed immediate (use mfhi to access HI, mflo to access LO)"),
#("mul $t1,$t2,<large_unsigned>", "MULtiplication : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of the product of $t2 and 32-bit immediate (use mfhi to access HI, mflo to access LO)"),
("mulu $t1,$t2,$t3", "MULtiplication Unsigned : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of ($t2 multiplied by $t3, unsigned multiplication)"),
("mulu $t1,$t2,<signed>", "MULtiplication Unsigned : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of ($t2 multiplied by 16-bit immediate, unsigned multiplication)"),
#("mulu $t1,$t2,<large_unsigned>", "MULtiplication Unsigned : Set HI to high-order 32 bits, LO and $t1 to low-order 32 bits of ($t2 multiplied by 32-bit immediate, unsigned multiplication)"),
("mulo $t1,$t2,$t3", "MULtiplication with Overflow : Set $t1 to low-order 32 bits of the product of $t2 and $t3"),
("mulo $t1,$t2,<signed>", "MULtiplication with Overflow : Set $t1 to low-order 32 bits of the product of $t2 and signed 16-bit immediate"),
#("mulo $t1,$t2,<large_unsigned>", "MULtiplication with Overflow : Set $t1 to low-order 32 bits of the product of $t2 and 32-bit immediate"),
("mulou $t1,$t2,$t3", "MULtiplication with Overflow Unsigned : Set $t1 to low-order 32 bits of the product of $t2 and $t3"),
("mulou $t1,$t2,<signed>", "MULtiplication with Overflow Unsigned : Set $t1 to low-order 32 bits of the product of $t2 and signed 16-bit immediate"),
#("mulou $t1,$t2,<large_unsigned>", "MULtiplication with Overflow Unsigned : Set $t1 to low-order 32 bits of the product of $t2 and 32-bit immediate"),
("div $t1,$t2,$t3", "DIVision : Set $t1 to ($t2 divided by $t3, integer division)"),
("div $t1,$t2,<signed>", "DIVision : Set $t1 to ($t2 divided by 16-bit immediate, integer division)"),
#("div $t1,$t2,<large_unsigned>", "DIVision : Set $t1 to ($t2 divided by 32-bit immediate, integer division)"),
("divu $t1,$t2,$t3", "DIVision Unsigned : Set $t1 to ($t2 divided by $t3, unsigned integer division)"),
("divu $t1,$t2,<signed>", "DIVision Unsigned : Set $t1 to ($t2 divided by 16-bit immediate, unsigned integer division)"),
#("divu $t1,$t2,<large_unsigned>", "DIVision Unsigned : Set $t1 to ($t2 divided by 32-bit immediate, unsigned integer division)"),
("rem $t1,$t2,$t3", "REMainder : Set $t1 to (remainder of $t2 divided by $t3)"),
("rem $t1,$t2,<signed>", "REMainder : Set $t1 to (remainder of $t2 divided by 16-bit immediate)"),
#("rem $t1,$t2,<large_unsigned>", "REMainder : Set $t1 to (remainder of $t2 divided by 32-bit immediate)"),
("remu $t1,$t2,$t3", "REMainder : Set $t1 to (remainder of $t2 divided by $t3, unsigned division)"),
("remu $t1,$t2,<signed>", "REMainder : Set $t1 to (remainder of $t2 divided by 16-bit immediate, unsigned division)"),
#("remu $t1,$t2,<large_unsigned>", "REMainder : Set $t1 to (remainder of $t2 divided by 32-bit immediate, unsigned division)"),
######################### load/store pseudo-ops start here ##########################,
#,
# Most of these simply provide a variety of convenient memory addressing modes for ),
# specifying load/store address.
#
("li $t1,<signed>", "Load Immediate : Set $t1 to 16-bit immediate (sign-extended)"),
#("li $t1,<unsigned>", "Load Immediate : Set $t1 to unsigned 16-bit immediate (zero-extended)"),
#("li $t1,<large_unsigned>", "Load Immediate : Set $t1 to 32-bit immediate"),
("la $t1,($t2)", "Load Address : Set $t1 to contents of $t2"),
("la $t1,<signed>", "Load Address : Set $t1 to 16-bit immediate (sign-extended) "),
#("la $t1,<unsigned>", "Load Address : Set $t1 to 16-bit immediate (zero-extended) "),
#("la $t1,<large_unsigned>", "Load Address : Set $t1 to 32-bit immediate"),
("la $t1,<unsigned>,($t2)", "Load Address : Set $t1 to sum (of $t2 and 16-bit immediate)"),
#("la $t1,<large_unsigned>,($t2)", "Load Address : Set $t1 to sum (of $t2 and 32-bit immediate)"),
("la $t1,<label>", "Load Address : Set $t1 to label's address"),
("la $t1,<label>,($t2)", "Load Address : Set $t1 to sum (of $t2 and label's address)"),
("la $t1,<label>,<large_unsigned>", "Load Address : Set $t1 to sum (of label's address and 32-bit immediate)"),
("la $t1,<label>,<large_unsigned>,($t2)", "Load Address : Set $t1 to sum (of label's address, 32-bit immediate, and $t2)"),
("lw $t1,($t2)", "Load Word : Set $t1 to contents of effective memory word address"),
("lw $t1,<signed>", "Load Word : Set $t1 to contents of effective memory word address"),
#("lw $t1,<unsigned>", "Load Word : Set $t1 to contents of effective memory word address"),
#("lw $t1,<large_unsigned>", "Load Word : Set $t1 to contents of effective memory word address"),
("lw $t1,<unsigned>,($t2)", "Load Word : Set $t1 to contents of effective memory word address"),
#("lw $t1,<large_unsigned>,($t2)", "Load Word : Set $t1 to contents of effective memory word address"),
("lw $t1,<label>", "Load Word : Set $t1 to contents of memory word at label's address"),
("lw $t1,<label>,($t2)", "Load Word : Set $t1 to contents of effective memory word address"),
("lw $t1,<label>,<large_unsigned>", "Load Word : Set $t1 to contents of effective memory word address "),
("lw $t1,<label>,<large_unsigned>,($t2)", "Load Word : Set $t1 to contents of effective memory word address"),
("sw $t1,($t2)", "Store Word : Store $t1 contents into effective memory word address"),
("sw $t1,<signed>", "Store Word : Store $t1 contents into effective memory word address"),
#("sw $t1,<unsigned>", "Store Word : Store $t1 contents into effective memory word address"),
#("sw $t1,<large_unsigned>", "Store Word : Store $t1 contents into effective memory word address"),
("sw $t1,<unsigned>,($t2)", "Store Word : Store $t1 contents into effective memory word address"),
#("sw $t1,<large_unsigned>,($t2)", "Store Word : Store $t1 contents into effective memory word address"),
("sw $t1,<label>", "Store Word : Store $t1 contents into memory word at label's address"),
("sw $t1,<label>,($t2)", "Store Word : Store $t1 contents into effective memory word address"),
("sw $t1,<label>,<large_unsigned>", "Store Word : Store $t1 contents into effective memory word address"),
("sw $t1,<label>,<large_unsigned>,($t2)", "Store Word : Store $t1 contents into effective memory word address"),
("lh $t1,($t2)", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
("lh $t1,<signed>", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
#("lh $t1,<unsigned>", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
#("lh $t1,<large_unsigned>", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
("lh $t1,<unsigned>,($t2)", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
#("lh $t1,<large_unsigned>,($t2)", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
("lh $t1,<label>", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
("lh $t1,<label>,($t2)", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
("lh $t1,<label>,<large_unsigned>", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
("lh $t1,<label>,<large_unsigned>,($t2)", "Load Halfword : Set $t1 to sign-extended 16-bit value from effective memory halfword address"),
("sh $t1,($t2)", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
("sh $t1,<signed>", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
#("sh $t1,<unsigned>", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
#("sh $t1,<large_unsigned>", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
("sh $t1,<unsigned>,($t2)", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
#("sh $t1,<large_unsigned>,($t2)", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
("sh $t1,<label>", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
("sh $t1,<label>,($t2)", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
("sh $t1,<label>,<large_unsigned>", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
("sh $t1,<label>,<large_unsigned>,($t2)", "Store Halfword : Store the low-order 16 bits of $t1 into the effective memory halfword address"),
("lb $t1,($t2)", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
("lb $t1,<signed>", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
#("lb $t1,<unsigned>", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
#("lb $t1,<large_unsigned>", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
("lb $t1,<unsigned>,($t2)", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
#("lb $t1,<large_unsigned>,($t2)", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
("lb $t1,<label>", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
("lb $t1,<label>,($t2)", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
("lb $t1,<label>,<large_unsigned>", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
("lb $t1,<label>,<large_unsigned>,($t2)", "Load Byte : Set $t1 to sign-extended 8-bit value from effective memory byte address"),
("sb $t1,($t2)", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
("sb $t1,<signed>", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
#("sb $t1,<unsigned>", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
#("sb $t1,<large_unsigned>", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
("sb $t1,<unsigned>,($t2)", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
#("sb $t1,<large_unsigned>,($t2)", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
("sb $t1,<label>", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
("sb $t1,<label>,($t2)", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
("sb $t1,<label>,<large_unsigned>", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
("sb $t1,<label>,<large_unsigned>,($t2)", "Store Byte : Store the low-order 8 bits of $t1 into the effective memory byte address"),
("lhu $t1,($t2)", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
("lhu $t1,<signed>", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
#("lhu $t1,<unsigned>", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
#("lhu $t1,<large_unsigned>", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
("lhu $t1,<unsigned>,($t2)", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
#("lhu $t1,<large_unsigned>,($t2)", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
("lhu $t1,<label>", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
("lhu $t1,<label>,($t2)", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
("lhu $t1,<label>,<large_unsigned>", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
("lhu $t1,<label>,<large_unsigned>,($t2)", "Load Halfword Unsigned : Set $t1 to zero-extended 16-bit value from effective memory halfword address"),
("lbu $t1,($t2)", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
("lbu $t1,<signed>", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
#("lbu $t1,<unsigned>", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
#("lbu $t1,<large_unsigned>", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
("lbu $t1,<unsigned>,($t2)", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
#("lbu $t1,<large_unsigned>,($t2)", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
("lbu $t1,<label>", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
("lbu $t1,<label>,($t2)", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
("lbu $t1,<label>,<large_unsigned>", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
("lbu $t1,<label>,<large_unsigned>,($t2)", "Load Byte Unsigned : Set $t1 to zero-extended 8-bit value from effective memory byte address"),
("lwl $t1,($t2)", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
("lwl $t1,<signed>", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
#("lwl $t1,<unsigned>", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
#("lwl $t1,<large_unsigned>", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
("lwl $t1,<unsigned>,($t2)", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
#("lwl $t1,<large_unsigned>,($t2)", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
("lwl $t1,<label>", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
("lwl $t1,<label>,($t2)", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
("lwl $t1,<label>,<large_unsigned>", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
("lwl $t1,<label>,<large_unsigned>,($t2)", "Load Word Left : Load from 1 to 4 bytes left-justified into $t1, starting with effective memory byte address and continuing through the low-order byte of its word"),
("swl $t1,($t2)", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
("swl $t1,<signed>", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
#("swl $t1,<unsigned>", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
#("swl $t1,<large_unsigned>", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
("swl $t1,<unsigned>,($t2)", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
#("swl $t1,<large_unsigned>,($t2)", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
("swl $t1,<label>", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
("swl $t1,<label>,($t2)", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
("swl $t1,<label>,<large_unsigned>", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
("swl $t1,<label>,<large_unsigned>,($t2)", "Store Word Left : Store high-order 1 to 4 bytes of $t1 into memory, starting with effective memory byte address and continuing through the low-order byte of its word"),
("lwr $t1,($t2)", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
("lwr $t1,<signed>", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
#("lwr $t1,<unsigned>", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
#("lwr $t1,<large_unsigned>", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
("lwr $t1,<unsigned>,($t2)", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
#("lwr $t1,<large_unsigned>,($t2)", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
("lwr $t1,<label>", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
("lwr $t1,<label>,($t2)", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
("lwr $t1,<label>,<large_unsigned>", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
("lwr $t1,<label>,<large_unsigned>,($t2)", "Load Word Right : Load from 1 to 4 bytes right-justified into $t1, starting with effective memory byte address and continuing through the high-order byte of its word"),
("swr $t1,($t2)", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
("swr $t1,<signed>", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
#("swr $t1,<unsigned>", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
#("swr $t1,<large_unsigned>", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
("swr $t1,<unsigned>,($t2)", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
#("swr $t1,<large_unsigned>,($t2)", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
("swr $t1,<label>", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
("swr $t1,<label>,($t2)", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
("swr $t1,<label>,<large_unsigned>", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
("swr $t1,<label>,<large_unsigned>,($t2)", "Store Word Right : Store low-order 1 to 4 bytes of $t1 into memory, starting with high-order byte of word containing effective memory byte address and continuing through that byte address"),
("ll $t1,($t2)", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
("ll $t1,<signed>", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
#("ll $t1,<unsigned>", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
#("ll $t1,<large_unsigned>", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
("ll $t1,<unsigned>,($t2)", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
#("ll $t1,<large_unsigned>,($t2)", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
("ll $t1,<label>", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
("ll $t1,<label>,($t2)", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
("ll $t1,<label>,<large_unsigned>", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
("ll $t1,<label>,<large_unsigned>,($t2)", "Load Linked : Paired with Store Conditional (sc) to perform atomic read-modify-write. Treated as equivalent to Load Word (lw) because MARS does not simulate multiple processors."),
("sc $t1,($t2)", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
("sc $t1,<signed>", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
#("sc $t1,<unsigned>", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
#("sc $t1,<large_unsigned>", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
("sc $t1,<unsigned>,($t2)", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
#("sc $t1,<large_unsigned>,($t2)", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
("sc $t1,<label>", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
("sc $t1,<label>,($t2)", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
("sc $t1,<label>,<large_unsigned>", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
("sc $t1,<label>,<large_unsigned>,($t2)", "Store Conditional : Paired with Load Linked (ll) to perform atomic read-modify-write. Treated as equivalent to Store Word (sw) because MARS does not simulate multiple processors."),
("ulw $t1,<signed>,($t2)", "Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address"),
("ulh $t1,<signed>,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address"),
("ulhu $t1,<signed>,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address"),
("ld $t1,<signed>,($t2)", "Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory byte address"),
("usw $t1,<signed>,($t2)", "Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address"),
("ush $t1,<signed>,($t2)", "Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address"),
("sd $t1,<signed>,($t2)", "Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory byte address"),
#("ulw $t1,<large_unsigned>", "Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address"),
("ulw $t1,<label>", "Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address"),
("ulw $t1,<label>,<large_unsigned>", "Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address"),
("ulw $t1,($t2)", "Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address"),
#("ulw $t1,<large_unsigned>,($t2)", "Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address"),
("ulw $t1,<label>,($t2)", "Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address"),
("ulw $t1,<label>,<large_unsigned>,($t2)", "Unaligned Load Word : Set $t1 to the 32 bits starting at effective memory byte address"),
#("ulh $t1,<large_unsigned>", "Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address"),
("ulh $t1,<label>", "Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address"),
("ulh $t1,<label>,<large_unsigned>", "Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address"),
("ulh $t1,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address"),
#("ulh $t1,<large_unsigned>,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address"),
("ulh $t1,<label>,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address"),
("ulh $t1,<label>,<large_unsigned>,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, sign-extended, starting at effective memory byte address"),
#("ulhu $t1,<large_unsigned>", "Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address"),
("ulhu $t1,<label>", "Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address"),
("ulhu $t1,<label>,<large_unsigned>", "Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address"),
("ulhu $t1,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address"),
#("ulhu $t1,<large_unsigned>,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address"),
("ulhu $t1,<label>,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address"),
("ulhu $t1,<label>,<large_unsigned>,($t2)", "Unaligned Load Halfword : Set $t1 to the 16 bits, zero-extended, starting at effective memory byte address"),
("ld $t1,<large_unsigned>", "Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address"),
("ld $t1,<label>", "Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address"),
("ld $t1,<label>,<large_unsigned>", "Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address"),
("ld $t1,($t2)", "Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address"),
#("ld $t1,<large_unsigned>,($t2)", "Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address"),
("ld $t1,<label>,($t2)", "Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address"),
("ld $t1,<label>,<large_unsigned>,($t2)", "Load Doubleword : Set $t1 and the next register to the 64 bits starting at effective memory word address"),
("usw $t1,<large_unsigned>", "Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address"),
("usw $t1,<label>", "Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address"),
("usw $t1,<label>,<large_unsigned>", "Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address"),
("usw $t1,($t2)", "Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address"),
#("usw $t1,<large_unsigned>,($t2)", "Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address"),
("usw $t1,<label>,($t2)", "Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address"),
("usw $t1,<label>,<large_unsigned>,($t2)", "Unaligned Store Word : Store $t1 contents into the 32 bits starting at effective memory byte address"),
("ush $t1,<large_unsigned>", "Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address"),
("ush $t1,<label>", "Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address"),
("ush $t1,<label>,<large_unsigned>", "Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address"),
("ush $t1,($t2)", "Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address"),
#("ush $t1,<large_unsigned>,($t2)", "Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address"),
("ush $t1,<label>,($t2)", "Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address"),
("ush $t1,<label>,<large_unsigned>,($t2)", "Unaligned Store Halfword: Store low-order halfword $t1 contents into the 16 bits starting at effective memory byte address"),
("sd $t1,<large_unsigned>", "Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address"),
("sd $t1,<label>", "Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address"),
("sd $t1,<label>,<large_unsigned>", "Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address"),
("sd $t1,($t2)", "Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address"),
#("sd $t1,<large_unsigned>,($t2)", "Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address"),
("sd $t1,<label>,($t2)", "Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address"),
("sd $t1,<label>,<large_unsigned>,($t2)", "Store Doubleword : Store contents of $t1 and the next register to the 64 bits starting at effective memory word address"),
("lwc1 $fpf1,($t2)", "Load Word Coprocessor 1 : Set $fpf1 to 32-bit value from effective memory word address"),
("lwc1 $fpf1,<signed>", "Load Word Coprocessor 1 : Set $fpf1 to 32-bit value from effective memory word address"),
#("lwc1 $fpf1,<large_unsigned>", "Load Word Coprocessor 1 : Set $fpf1 to 32-bit value from effective memory word address"),
("lwc1 $fpf1,<large_unsigned>,($t2)", "Load Word Coprocessor 1 : Set $fpf1 to 32-bit value from effective memory word address"),
("lwc1 $fpf1,<label>", "Load Word Coprocessor 1 : Set $fpf1 to 32-bit value from effective memory word address"),
("lwc1 $fpf1,<label>,($t2)", "Load Word Coprocessor 1 : Set $fpf1 to 32-bit value from effective memory word address"),
("lwc1 $fpf1,<label>,<large_unsigned>", "Load Word Coprocessor 1 : Set $fpf1 to 32-bit value from effective memory word address"),
("lwc1 $fpf1,<label>,<large_unsigned>,($t2)", "Load Word Coprocessor 1 : Set $fpf1 to 32-bit value from effective memory word address"),
("ldc1 $fpf2,($t2)", "Load Doubleword Coprocessor 1 : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("ldc1 $fpf2,<signed>", "Load Doubleword Coprocessor 1 : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
#("ldc1 $fpf2,<large_unsigned>", "Load Doubleword Coprocessor 1 : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("ldc1 $fpf2,<large_unsigned>,($t2)", "Load Doubleword Coprocessor 1 : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("ldc1 $fpf2,<label>", "Load Doubleword Coprocessor 1 : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("ldc1 $fpf2,<label>,($t2)", "Load Doubleword Coprocessor 1 : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("ldc1 $fpf2,<label>,<large_unsigned>", "Load Doubleword Coprocessor 1 : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("ldc1 $fpf2,<label>,<large_unsigned>,($t2)", "Load Doubleword Coprocessor 1 : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("swc1 $fpf1,($t2)", "Store Word Coprocessor 1 : Store 32-bit value from $fpf1 to effective memory word address"),
("swc1 $fpf1,<signed>", "Store Word Coprocessor 1 : Store 32-bit value from $fpf1 to effective memory word address"),
#("swc1 $fpf1,<large_unsigned>", "Store Word Coprocessor 1 : Store 32-bit value from $fpf1 to effective memory word address"),
("swc1 $fpf1,<large_unsigned>,($t2)", "Store Word Coprocessor 1 : Store 32-bit value from $fpf1 to effective memory word address"),
("swc1 $fpf1,<label>", "Store Word Coprocessor 1 : Store 32-bit value from $fpf1 to effective memory word address"),
("swc1 $fpf1,<label>,($t2)", "Store Word Coprocessor 1 : Store 32-bit value from $fpf1 to effective memory word address"),
("swc1 $fpf1,<label>,<large_unsigned>", "Store Word Coprocessor 1 : Store 32-bit value from $fpf1 to effective memory word address"),
("swc1 $fpf1,<label>,<large_unsigned>,($t2)", "Store Word Coprocessor 1 : Store 32-bit value from $fpf1 to effective memory word address"),
("sdc1 $fpf2,($t2)", "Store Doubleword Coprocessor 1 : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("sdc1 $fpf2,<signed>", "Store Doubleword Coprocessor 1 : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
#("sdc1 $fpf2,<large_unsigned>", "Store Doubleword Coprocessor 1 : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("sdc1 $fpf2,<large_unsigned>,($t2)", "Store Doubleword Coprocessor 1 : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("sdc1 $fpf2,<label>", "Store Doubleword Coprocessor 1 : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("sdc1 $fpf2,<label>,($t2)", "Store Doubleword Coprocessor 1 : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("sdc1 $fpf2,<label>,<large_unsigned>", "Store Doubleword Coprocessor 1 : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("sdc1 $fpf2,<label>,<large_unsigned>,($t2)", "Store Doubleword Coprocessor 1 : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("l.s $fpf1,($t2)", "Load floating point Single precision : Set $fpf1 to 32-bit value at effective memory word address"),
("l.s $fpf1,<signed>", "Load floating point Single precision : Set $fpf1 to 32-bit value at effective memory word address"),
#("l.s $fpf1,<large_unsigned>", "Load floating point Single precision : Set $fpf1 to 32-bit value at effective memory word address"),
("l.s $fpf1,<large_unsigned>,($t2)", "Load floating point Single precision : Set $fpf1 to 32-bit value at effective memory word address"),
("l.s $fpf1,<label>", "Load floating point Single precision : Set $fpf1 to 32-bit value at effective memory word address"),
("l.s $fpf1,<label>,($t2)", "Load floating point Single precision : Set $fpf1 to 32-bit value at effective memory word address"),
("l.s $fpf1,<label>,<large_unsigned>", "Load floating point Single precision : Set $fpf1 to 32-bit value at effective memory word address"),
("l.s $fpf1,<label>,<large_unsigned>,($t2)", "Load floating point Single precision : Set $fpf1 to 32-bit value at effective memory word address"),
("s.s $fpf1,($t2)", "Store floating point Single precision : Store 32-bit value from $fpf1 to effective memory word address"),
("s.s $fpf1,<signed>", "Store floating point Single precision : Store 32-bit value from $fpf1 to effective memory word address"),
#("s.s $fpf1,<large_unsigned>", "Store floating point Single precision : Store 32-bit value from $fpf1 to effective memory word address"),
("s.s $fpf1,<large_unsigned>,($t2)", "Store floating point Single precision : Store 32-bit value from $fpf1 to effective memory word address"),
("s.s $fpf1,<label>", "Store floating point Single precision : Store 32-bit value from $fpf1 to effective memory word address"),
("s.s $fpf1,<label>,($t2)", "Store floating point Single precision : Store 32-bit value from $fpf1 to effective memory word address"),
("s.s $fpf1,<label>,<large_unsigned>", "Store floating point Single precision : Store 32-bit value from $fpf1 to effective memory word address"),
("s.s $fpf1,<label>,<large_unsigned>,($t2)", "Store floating point Single precision : Store 32-bit value from $fpf1 to effective memory word address"),
("l.d $fpf2,($t2)", "Load floating point Double precision : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("l.d $fpf2,<signed>", "Load floating point Double precision : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
#("l.d $fpf2,<large_unsigned>", "Load floating point Double precision : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("l.d $fpf2,<large_unsigned>,($t2)", "Load floating point Double precision : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("l.d $fpf2,<label>", "Load floating point Double precision : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("l.d $fpf2,<label>,($t2)", "Load floating point Double precision : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("l.d $fpf2,<label>,<large_unsigned>", "Load floating point Double precision : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("l.d $fpf2,<label>,<large_unsigned>,($t2)", "Load floating point Double precision : Set $fpf2 and $fpf3 register pair to 64-bit value at effective memory doubleword address"),
("s.d $fpf2,($t2)", "Store floating point Double precision : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("s.d $fpf2,<signed>", "Store floating point Double precision : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
#("s.d $fpf2,<large_unsigned>", "Store floating point Double precision : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("s.d $fpf2,<large_unsigned>,($t2)", "Store floating point Double precision : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("s.d $fpf2,<label>", "Store floating point Double precision : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("s.d $fpf2,<label>,($t2)", "Store floating point Double precision : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("s.d $fpf2,<label>,<large_unsigned>", "Store floating point Double precision : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address"),
("s.d $fpf2,<label>,<large_unsigned>,($t2)", "Store floating point Double precision : Store 64 bits from $fpf2 and $fpf3 register pair to effective memory doubleword address")
]
def parse_syntax(syntax):
try:
opcode, args = syntax.split()
except ValueError:
# something like "syscall" with no args
return (syntax, [])
args = args.split(",")
return (opcode, args)
def friendly_arg(arg):
# 4 possibilities. It can be an integer register, a floating point
# register, an immediate, or a label.
if arg.startswith("$fp"):
return ("FpRegs", arg[3:])
if arg.startswith("$"):
return ("Regs", arg[1:])
if arg.startswith("($"):
assert arg.endswith(")")
return ("Regs", arg[2:-1])
if arg == "<signed>" or arg == "<unsigned>" or arg == "<offset>" or arg == "<numbits>" or arg == "<large_unsigned>":
return ("int", arg[1:-1])
if arg == "<label>":
return ("String", arg[1:-1])
print arg
assert False
def java_fn_signature(syntax):
(opcode, args) = syntax
opcode = opcode.replace(".", "_")
argstr = ", ".join( (type + " " + name) for (type, name) in map(friendly_arg, args))
return "public Instruction %s (%s)" % (opcode, argstr)
def java_fn_body(syntax):
(opcode, args) = syntax
found_index = False
for arg in args:
if arg.startswith("($"):
assert arg.endswith(")")
found_index = True
def make_arg(arg):
(type, name) = arg
if type == "FpRegs" or type == "Regs":
return '"$"+%s' % name
elif found_index:
# then we don't want to stringize it
return name
else:
return '""+%s' % name
args_to_instruction_constructor = ", ".join(['"%s"' % opcode] + list(make_arg(arg) for arg in map(friendly_arg, args)))
instruction_type = "NonMemoryInstruction"
if found_index:
instruction_type = "MemoryAccessInstruction"
return "return new %s(%s);" % (instruction_type, args_to_instruction_constructor)
def java_fn_def(instruction, help):
signature = java_fn_signature(instruction)
body = java_fn_body(instruction)
return " /** %s */ \n %s { %s }\n" % (help, signature, body)
with open("AutogenMips.java", "w") as f:
f.write("""package cs536.codegen.mips;
import cs536.codegen.Instruction;
import cs536.codegen.mips.NonMemoryInstruction;
public class AutogenMips
{
""")
for (syntax, help) in instructions:
f.write(java_fn_def(parse_syntax(syntax), help))
f.write("}\n")
with open("AutogenMipsWithPseudo.java", "w") as f:
f.write("""package cs536.codegen.mips;
import cs536.codegen.Instruction;
import cs536.codegen.mips.NonMemoryInstruction;
public class AutogenMipsWithPseudo extends AutogenMips
{
""")
for (syntax, help) in pseudo_instructions:
f.write(java_fn_def(parse_syntax(syntax), help))
f.write("}\n")
#"mfc0 $dest,$8", "Move from Coprocessor 0 : Set $dest to the value stored in Coprocessor 0 register $8"
#"mtc0 $t1,$8", "Move to Coprocessor 0 : Set Coprocessor 0 register $8 to value stored in $t1"
#"bc1t 1,<label>", "Branch if specified FP condition flag true (BC1T, not BCLT) : If Coprocessor 1 condition flag specified by immediate is true (one) then branch to statement at <label>'s address"
#"bc1f 1,<label>", "Branch if specified FP condition flag false (BC1F, not BCLF) : If Coprocessor 1 condition flag specified by immediate is false (zero) then branch to statement at <label>'s address"
#"c.eq.s 1,$fpleft,$fpright", "Compare equal single precision : If $fpleft is equal to $fpright, set Coprocessor 1 condition flag specied by immediate to true else set it to false"
#"c.le.s 1,$fpleft,$fpright", "Compare less or equal single precision : If $fpleft is less than or equal to $fpright, set Coprocessor 1 condition flag specified by immediate to true else set it to false"
#"c.lt.s 1,$fpleft,$fpright", "Compare less than single precision : If $fpleft is less than $fpright, set Coprocessor 1 condition flag specified by immediate to true else set it to false"
#"c.eq.d 1,$fpleft,$fpright", "Compare equal double precision : If $fpleft is equal to $fpright (double-precision), set Coprocessor 1 condition flag specified by immediate to true else set it to false"
#"c.le.d 1,$fpleft,$fpright", "Compare less or equal double precision : If $fpleft is less than or equal to $fpright (double-precision), set Coprocessor 1 condition flag specfied by immediate true else set it false"
#"c.lt.d 1,$fpleft,$fpright", "Compare less than double precision : If $fpleft is less than $fpright (double-precision), set Coprocessor 1 condition flag specified by immediate to true else set it to false"
| Python |
import logging, sys
LOCALPATH = sys.path[0]+"/../"
####################################
# Log configuration
LOG_LEVEL = logging.INFO
LOG_ID = "bloomberg-{istance}"
LOG_DIR = LOCALPATH+"log"
####################################
####################################
# Lock coonfiguration
LOCK_FILE_NAME = LOCALPATH+"bloomberg-{istance}"
####################################
####################################
# WS configuration
WS_BLOOMBERG_USER = "larepublic"
WS_BLOOMBERG_PASSWORD = "L143Pub1Ic"
WS_URL= "http://data.bloomberg.com/apps/wds/IntradayData"
WS_REALTIME_URL = "http://data.bloomberg.com/apps/wds/SecurityData"
#outfields
WS_OUTFIELDS = list()
WS_OUTFIELDS.append("WBTKR")
WS_OUTFIELDS.append("DS192")
WS_OUTFIELDS.append("PR005")
WS_OUTFIELDS.append("PR051")
WS_OUTFIELDS.append("PR052")
WS_OUTFIELDS.append("UTIME")
#securities
WS_SECURITIES = list()
WS_SECURITIES.append("FTSEMIB:IND")
WS_SECURITIES.append("ITLMS:IND")
WS_SECURITIES.append("ITMC:IND")
WS_SECURITIES.append("ITSTAR:IND")
WS_SECURITIES.append("UKX:IND")
WS_SECURITIES.append("DAX:IND")
WS_SECURITIES.append("IBEX:IND")
WS_SECURITIES.append("INDU:IND")
WS_SECURITIES.append("CCMP:IND")
WS_SECURITIES.append("SPX:IND")
WS_SECURITIES.append("AEX:IND")
###################################
####################################
# Graph figures configuration
FIGURES = list()
FIGURES.append({'inch_width': 2.8, 'inch_height': 1.5, 'dpi': 100, 'tick_label_size': 6})
FIGURES.append({'inch_width': 2.2, 'inch_height': 1.115, 'tick_label_size': 5})
FIGURES_IMAGE_NAME = "indice{index}.png"
###################################
####################################
# Output configuration
TMP_DIR = LOCALPATH+"output/{istance}"
OUTPUT_DIR = "/localmountpoints/storage/economia/indici/{istance}"
###################################
####################################
# Nagios config
NAGIOS_COMMAND= "/usr/local/bin/kw_alert"
NAGIOS_HOST="back131.mi.kataweb.it"
NAGIOS_SERVICE="BLOOMBERG"
###################################
| Python |
from subprocess import call
class Nagios:
nagios_command = None
nagios_host = None
nagios_service = None
log = None
OK = 0
WARN = 1
CRITICAL = 2
def __init__(self, nagios_command, nagios_host, nagios_service, log):
if nagios_command!=None and nagios_host!=None and nagios_service!=None:
self.nagios_command = nagios_command
self.nagios_host = nagios_host
self.nagios_service = nagios_service
self.log=log
def existBaseConfig(self):
return self.nagios_command!=None and self.nagios_host!=None and self.nagios_service!=None
def executeCommand(self, message, level):
if self.existBaseConfig():
command = ("%s %s %s" + " " + str(level) +" \"%s\"")% (self.nagios_command, self.nagios_host, self.nagios_host, message)
self.log.debug("Comando: " + command)
response = call(command, shell=True)
if response==0:
self.log.debug("Comando nagios inviato correttamente")
else:
self.log.error("Errore nell'invio del comando nagios ")
else:
self.log.error("Impossibile inviare il messaggio.Lo script non dispone delle variabili necessarie ")
def warn(self, message):
self.executeCommand(message, self.WARN)
def ok(self, message):
self.executeCommand(message, self.OK)
def critical(self, message):
self.executeCommand(message, self.CRITICAL)
| Python |
import commands
import sys
import codecs,os, os.path
# LOCK AND UNLOCK #
class Lock:
log=None
NAME_FILE_LOCK = None
MAX_TRY = None
MAX_TRY = 3
def __init__(self, argv, log, namefilelock=".lock"):
if log!=None:
self.log=log
self.init(argv, namefilelock);
def init(self, argv, namefilelock=".lock"):
self.MAX_TRY = 3
self.setNameFileLock(namefilelock)
for arg in argv:
if (arg == "--unlock"):
if _debug: sys.stderr.write("Forzato l'unlock\n")
self.destroy()
def setNameFileLock(self, namefilelock):
if namefilelock.endswith(".lock")!=True:
namefilelock = namefilelock+".lock"
self.NAME_FILE_LOCK = namefilelock
def tryLock(self):
if self.isLocked():
self.log.info('LOCKED!! Il processo in esecuzione...')
self.incTry()
if( self.isMaxTry()):
self.destroy()
self.log.info('UNLOCKED!! forzo lo sblocco....')
else:
raise Exception("Lock presente")
else:
self.create()
def create(self):
self.printMessage("Creo lock "+self.NAME_FILE_LOCK)
output = open(self.NAME_FILE_LOCK, "w")
output.write ("%d\n0" % (os.getpid()) )
output.close()
def printMessage(self,message):
if message!=None:
print message
if self.log!=None:
self.log.info(message);
def destroy(self,force=1):
try:
self.printMessage("Destroy lock " + self.NAME_FILE_LOCK)
lf = open (self.NAME_FILE_LOCK,"r")
pids = lf.readline()
lf.close()
os.remove(self.NAME_FILE_LOCK)
pid = int (pids)
if( force ):
os.kill (pid,9)
self.printMessage('killed process with pid=%s' %pid )
except OSError:
self.printMessage('Error: destroy() - Lock file o processo non presente')
def isLocked(self):
isLocked = os.path.isfile(self.NAME_FILE_LOCK)
self.printMessage("isLocked: " + str(isLocked))
return isLocked
def incTry(self):
try:
lf = open (self.NAME_FILE_LOCK,"r")
pids = lf.readline()
counts = lf.readline()
lf.close()
pid = int (pids)
count = int (counts) + 1
output = open(self.NAME_FILE_LOCK, "w")
output.write ("%d\n%d" % (pid,count) )
output.close()
except OSError:
self.printMessage('Error: incTry() - Lock file non presente')
def isMaxTry(self):
try:
lf = open (self.NAME_FILE_LOCK,"r")
pids = lf.readline()
counts = lf.readline()
self.printMessage('tentativi: %s' %counts)
count = int(counts)
lf.close()
if (count >= self.MAX_TRY ):
return 1
return 0
except OSError:
self.printMessage('Error: isMaxTry() - Lock file non presente')
return None
| Python |
#!/usr/bin/python
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
# print grid of all colors and brightnesses
# uses stdout.write to write chars with no newline nor spaces between them
# This should run more-or-less identically on Windows and Unix.
from __future__ import print_function
import sys
# Add parent dir to sys path, so the following 'import colorama' always finds
# the local source in preference to any installed version of colorama.
import fixpath
from colorama import init, Fore, Back, Style
init()
# Fore, Back and Style are convenience classes for the constant ANSI strings that set
# the foreground, background and style. The don't have any magic of their own.
FORES = [ Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN, Fore.WHITE ]
BACKS = [ Back.BLACK, Back.RED, Back.GREEN, Back.YELLOW, Back.BLUE, Back.MAGENTA, Back.CYAN, Back.WHITE ]
STYLES = [ Style.DIM, Style.NORMAL, Style.BRIGHT ]
NAMES = {
Fore.BLACK: 'black', Fore.RED: 'red', Fore.GREEN: 'green', Fore.YELLOW: 'yellow', Fore.BLUE: 'blue', Fore.MAGENTA: 'magenta', Fore.CYAN: 'cyan', Fore.WHITE: 'white'
, Fore.RESET: 'reset',
Back.BLACK: 'black', Back.RED: 'red', Back.GREEN: 'green', Back.YELLOW: 'yellow', Back.BLUE: 'blue', Back.MAGENTA: 'magenta', Back.CYAN: 'cyan', Back.WHITE: 'white',
Back.RESET: 'reset'
}
# show the color names
sys.stdout.write(' ')
for foreground in FORES:
sys.stdout.write('%s%-7s' % (foreground, NAMES[foreground]))
print()
# make a row for each background color
for background in BACKS:
sys.stdout.write('%s%-7s%s %s' % (background, NAMES[background], Back.RESET, background))
# make a column for each foreground color
for foreground in FORES:
sys.stdout.write(foreground)
# show dim, normal bright
for brightness in STYLES:
sys.stdout.write('%sX ' % brightness)
sys.stdout.write(Style.RESET_ALL + ' ' + background)
print(Style.RESET_ALL)
print()
| Python |
#!/usr/bin/python
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
# Simple demo of changing foreground, background and brightness.
from __future__ import print_function
import fixpath
from colorama import init, Fore, Back, Style
init()
print(Fore.GREEN + 'green, '
+ Fore.RED + 'red, '
+ Fore.RESET + 'normal, '
, end='')
print(Back.GREEN + 'green, '
+ Back.RED + 'red, '
+ Back.RESET + 'normal, '
, end='')
print(Style.DIM + 'dim, '
+ Style.BRIGHT + 'bright, '
+ Style.NORMAL + 'normal'
, end=' ')
print()
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from __future__ import print_function
import fixpath
import colorama
from colorama import Fore, Back, Style
from random import randint, choice
from string import printable
# Fore, Back and Style are convenience classes for the constant ANSI strings that set
# the foreground, background and style. The don't have any magic of their own.
FORES = [ Fore.BLACK, Fore.RED, Fore.GREEN, Fore.YELLOW, Fore.BLUE, Fore.MAGENTA, Fore.CYAN, Fore.WHITE ]
BACKS = [ Back.BLACK, Back.RED, Back.GREEN, Back.YELLOW, Back.BLUE, Back.MAGENTA, Back.CYAN, Back.WHITE ]
STYLES = [ Style.DIM, Style.NORMAL, Style.BRIGHT ]
# This assumes your terminal is 80x24. Ansi minimum coordinate is (1,1).
MINY, MAXY = 1, 24
MINX, MAXX = 1, 80
# set of printable ASCII characters, including a space.
CHARS = ' ' + printable.strip()
PASSES = 1000
def main():
colorama.init()
# gratuitous use of lambda.
pos = lambda y, x: '\x1b[%d;%dH' % (y, x)
# draw a white border.
print(Back.WHITE, end='')
print('%s%s' % (pos(MINY, MINX), ' '*MAXX), end='')
for y in range(MINY, 1+MAXY):
print('%s %s ' % (pos(y, MINX), pos(y, MAXX)), end='')
print('%s%s' % (pos(MAXY, MINX), ' '*MAXX), end='')
# draw some blinky lights for a while.
for i in range(PASSES):
print('%s%s%s%s%s' % (pos(randint(1+MINY,MAXY-1), randint(1+MINX,MAXX-1)), choice(FORES), choice(BACKS), choice(STYLES), choice(CHARS)), end='')
# put cursor to top, left, and set color to white-on-black with normal brightness.
print('%s%s%s%s' % (pos(MINY, MINX), Fore.WHITE, Back.BLACK, Style.NORMAL), end='')
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/python
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
# check that stripped ANSI in redirected stderr does not affect stdout
from __future__ import print_function
import sys
import fixpath
from colorama import init, Fore
init()
print(Fore.GREEN + 'GREEN set on stdout. ', end='')
print(Fore.RED + 'RED redirected stderr', file=sys.stderr)
print('Further stdout should be GREEN, i.e., the stderr redirection should not affect stdout.')
| Python |
#!/usr/bin/python
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
# Demonstrate the difference between colorama intialized with wrapping on and off.
# The point of the demonstration is to show how the ANSI wrapping on Windows can be disabled.
# The unwrapped cases will be interpreted with ANSI on Unix, but not on Windows.
from __future__ import print_function
import sys
import fixpath
from colorama import AnsiToWin32, init, Fore
init()
print('%sWrapped yellow going to stdout, via the default print function.' % Fore.YELLOW)
init(wrap=False)
print('%sUnwrapped CYAN going to stdout, via the default print function.' % Fore.CYAN)
print('%sUnwrapped CYAN, using the file parameter to write via colorama the AnsiToWin32 function.' % Fore.CYAN, file=AnsiToWin32(sys.stdout))
print('%sUnwrapped RED going to stdout, via the default print function.' % Fore.RED)
init()
print('%sWrapped RED going to stdout, via the default print function.' % Fore.RED)
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
# Add demo dir's parent to sys path, so that 'import colorama' always finds
# the local source in preference to any installed version of colorama.
import sys
from os.path import normpath, dirname, join
local_colorama_module = normpath(join(dirname(__file__), '..'))
sys.path.insert(0, local_colorama_module)
| Python |
#!/usr/bin/python
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
# Demonstrate the different behavior when autoreset is True and False.
from __future__ import print_function
import fixpath
from colorama import init, Fore, Back, Style
init(autoreset=True)
print(Fore.CYAN + Back.MAGENTA + Style.BRIGHT + 'Line 1: colored, with autoreset=True')
print('Line 2: When auto reset is True, the color settings need to be set with every print.')
init(autoreset=False)
print(Fore.YELLOW + Back.BLUE + Style.BRIGHT + 'Line 3: colored, with autoreset=False')
print('Line 4: When autoreset=False, the prior color settings linger (this is the default behavior).')
| Python |
#!/usr/bin/env python
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from os.path import dirname, join
from distutils.core import setup
from colorama import VERSION
NAME = 'colorama'
def get_long_description(filename):
readme = join(dirname(__file__), filename)
return open(readme).read()
setup(
name=NAME,
version=VERSION,
description='Cross-platform colored terminal text.',
long_description=get_long_description('README.txt'),
keywords='color colour terminal text ansi windows crossplatform xplatform',
author='Jonathan Hartley',
author_email='tartley@tartley.com',
url='http://code.google.com/p/colorama/',
license='BSD',
packages=[NAME],
# see classifiers http://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Topic :: Terminals',
]
)
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from . import win32
# from wincon.h
class WinColor(object):
BLACK = 0
BLUE = 1
GREEN = 2
CYAN = 3
RED = 4
MAGENTA = 5
YELLOW = 6
GREY = 7
# from wincon.h
class WinStyle(object):
NORMAL = 0x00 # dim text, dim background
BRIGHT = 0x08 # bright text, dim background
class WinTerm(object):
def __init__(self):
self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
self.set_attrs(self._default)
self._default_fore = self._fore
self._default_back = self._back
self._default_style = self._style
def get_attrs(self):
return self._fore + self._back * 16 + self._style
def set_attrs(self, value):
self._fore = value & 7
self._back = (value >> 4) & 7
self._style = value & WinStyle.BRIGHT
def reset_all(self, on_stderr=None):
self.set_attrs(self._default)
self.set_console(attrs=self._default)
def fore(self, fore=None, on_stderr=False):
if fore is None:
fore = self._default_fore
self._fore = fore
self.set_console(on_stderr=on_stderr)
def back(self, back=None, on_stderr=False):
if back is None:
back = self._default_back
self._back = back
self.set_console(on_stderr=on_stderr)
def style(self, style=None, on_stderr=False):
if style is None:
style = self._default_style
self._style = style
self.set_console(on_stderr=on_stderr)
def set_console(self, attrs=None, on_stderr=False):
if attrs is None:
attrs = self.get_attrs()
handle = win32.STDOUT
if on_stderr:
handle = win32.STDERR
win32.SetConsoleTextAttribute(handle, attrs)
def get_position(self, handle):
position = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition
# Because Windows coordinates are 0-based,
# and win32.SetConsoleCursorPosition expects 1-based.
position.X += 1
position.Y += 1
return position
def set_cursor_position(self, position=None, on_stderr=False):
if position is None:
#I'm not currently tracking the position, so there is no default.
#position = self.get_position()
return
handle = win32.STDOUT
if on_stderr:
handle = win32.STDERR
win32.SetConsoleCursorPosition(handle, position)
def cursor_up(self, num_rows=0, on_stderr=False):
if num_rows == 0:
return
handle = win32.STDOUT
if on_stderr:
handle = win32.STDERR
position = self.get_position(handle)
adjusted_position = (position.Y - num_rows, position.X)
self.set_cursor_position(adjusted_position, on_stderr)
def erase_data(self, mode=0, on_stderr=False):
# 0 (or None) should clear from the cursor to the end of the screen.
# 1 should clear from the cursor to the beginning of the screen.
# 2 should clear the entire screen. (And maybe move cursor to (1,1)?)
#
# At the moment, I only support mode 2. From looking at the API, it
# should be possible to calculate a different number of bytes to clear,
# and to do so relative to the cursor position.
if mode[0] not in (2,):
return
handle = win32.STDOUT
if on_stderr:
handle = win32.STDERR
# here's where we'll home the cursor
coord_screen = win32.COORD(0,0)
csbi = win32.GetConsoleScreenBufferInfo(handle)
# get the number of character cells in the current buffer
dw_con_size = csbi.dwSize.X * csbi.dwSize.Y
# fill the entire screen with blanks
win32.FillConsoleOutputCharacter(handle, ' ', dw_con_size, coord_screen)
# now set the buffer's attributes accordingly
win32.FillConsoleOutputAttribute(handle, self.get_attrs(), dw_con_size, coord_screen );
# put the cursor at (0, 0)
win32.SetConsoleCursorPosition(handle, (coord_screen.X, coord_screen.Y))
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
'''
This module generates ANSI character codes to printing colors to terminals.
See: http://en.wikipedia.org/wiki/ANSI_escape_code
'''
CSI = '\033['
def code_to_chars(code):
return CSI + str(code) + 'm'
class AnsiCodes(object):
def __init__(self, codes):
for name in dir(codes):
if not name.startswith('_'):
value = getattr(codes, name)
setattr(self, name, code_to_chars(value))
class AnsiFore:
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
RESET = 39
class AnsiBack:
BLACK = 40
RED = 41
GREEN = 42
YELLOW = 43
BLUE = 44
MAGENTA = 45
CYAN = 46
WHITE = 47
RESET = 49
class AnsiStyle:
BRIGHT = 1
DIM = 2
NORMAL = 22
RESET_ALL = 0
Fore = AnsiCodes( AnsiFore )
Back = AnsiCodes( AnsiBack )
Style = AnsiCodes( AnsiStyle )
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import atexit
import sys
from .ansitowin32 import AnsiToWin32
orig_stdout = sys.stdout
orig_stderr = sys.stderr
wrapped_stdout = sys.stdout
wrapped_stderr = sys.stderr
atexit_done = False
def reset_all():
AnsiToWin32(orig_stdout).reset_all()
def init(autoreset=False, convert=None, strip=None, wrap=True):
if not wrap and any([autoreset, convert, strip]):
raise ValueError('wrap=False conflicts with any other arg=True')
global wrapped_stdout, wrapped_stderr
sys.stdout = wrapped_stdout = \
wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
sys.stderr = wrapped_stderr = \
wrap_stream(orig_stderr, convert, strip, autoreset, wrap)
global atexit_done
if not atexit_done:
atexit.register(reset_all)
atexit_done = True
def deinit():
sys.stdout = orig_stdout
sys.stderr = orig_stderr
def reinit():
sys.stdout = wrapped_stdout
sys.stderr = wrapped_stdout
def wrap_stream(stream, convert, strip, autoreset, wrap):
if wrap:
wrapper = AnsiToWin32(stream,
convert=convert, strip=strip, autoreset=autoreset)
if wrapper.should_wrap():
stream = wrapper.stream
return stream
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
# from winbase.h
STDOUT = -11
STDERR = -12
try:
from ctypes import windll
from ctypes import wintypes
except ImportError:
windll = None
SetConsoleTextAttribute = lambda *_: None
else:
from ctypes import (
byref, Structure, c_char, c_short, c_uint32, c_ushort, POINTER
)
class CONSOLE_SCREEN_BUFFER_INFO(Structure):
"""struct in wincon.h."""
_fields_ = [
("dwSize", wintypes._COORD),
("dwCursorPosition", wintypes._COORD),
("wAttributes", wintypes.WORD),
("srWindow", wintypes.SMALL_RECT),
("dwMaximumWindowSize", wintypes._COORD),
]
def __str__(self):
return '(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)' % (
self.dwSize.Y, self.dwSize.X
, self.dwCursorPosition.Y, self.dwCursorPosition.X
, self.wAttributes
, self.srWindow.Top, self.srWindow.Left, self.srWindow.Bottom, self.srWindow.Right
, self.dwMaximumWindowSize.Y, self.dwMaximumWindowSize.X
)
_GetStdHandle = windll.kernel32.GetStdHandle
_GetStdHandle.argtypes = [
wintypes.DWORD,
]
_GetStdHandle.restype = wintypes.HANDLE
_GetConsoleScreenBufferInfo = windll.kernel32.GetConsoleScreenBufferInfo
_GetConsoleScreenBufferInfo.argtypes = [
wintypes.HANDLE,
POINTER(CONSOLE_SCREEN_BUFFER_INFO),
]
_GetConsoleScreenBufferInfo.restype = wintypes.BOOL
_SetConsoleTextAttribute = windll.kernel32.SetConsoleTextAttribute
_SetConsoleTextAttribute.argtypes = [
wintypes.HANDLE,
wintypes.WORD,
]
_SetConsoleTextAttribute.restype = wintypes.BOOL
_SetConsoleCursorPosition = windll.kernel32.SetConsoleCursorPosition
_SetConsoleCursorPosition.argtypes = [
wintypes.HANDLE,
wintypes._COORD,
]
_SetConsoleCursorPosition.restype = wintypes.BOOL
_FillConsoleOutputCharacterA = windll.kernel32.FillConsoleOutputCharacterA
_FillConsoleOutputCharacterA.argtypes = [
wintypes.HANDLE,
c_char,
wintypes.DWORD,
wintypes._COORD,
POINTER(wintypes.DWORD),
]
_FillConsoleOutputCharacterA.restype = wintypes.BOOL
_FillConsoleOutputAttribute = windll.kernel32.FillConsoleOutputAttribute
_FillConsoleOutputAttribute.argtypes = [
wintypes.HANDLE,
wintypes.WORD,
wintypes.DWORD,
wintypes._COORD,
POINTER(wintypes.DWORD),
]
_FillConsoleOutputAttribute.restype = wintypes.BOOL
handles = {
STDOUT: _GetStdHandle(STDOUT),
STDERR: _GetStdHandle(STDERR),
}
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
handle = handles[stream_id]
csbi = CONSOLE_SCREEN_BUFFER_INFO()
success = _GetConsoleScreenBufferInfo(
handle, byref(csbi))
return csbi
def SetConsoleTextAttribute(stream_id, attrs):
handle = handles[stream_id]
return _SetConsoleTextAttribute(handle, attrs)
def SetConsoleCursorPosition(stream_id, position):
position = wintypes._COORD(*position)
# If the position is out of range, do nothing.
if position.Y <= 0 or position.X <= 0:
return
# Adjust for Windows' SetConsoleCursorPosition:
# 1. being 0-based, while ANSI is 1-based.
# 2. expecting (x,y), while ANSI uses (y,x).
adjusted_position = wintypes._COORD(position.Y - 1, position.X - 1)
# Adjust for viewport's scroll position
sr = GetConsoleScreenBufferInfo(STDOUT).srWindow
adjusted_position.Y += sr.Top
adjusted_position.X += sr.Left
# Resume normal processing
handle = handles[stream_id]
return _SetConsoleCursorPosition(handle, adjusted_position)
def FillConsoleOutputCharacter(stream_id, char, length, start):
handle = handles[stream_id]
char = c_char(char)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
success = _FillConsoleOutputCharacterA(
handle, char, length, start, byref(num_written))
return num_written.value
def FillConsoleOutputAttribute(stream_id, attr, length, start):
''' FillConsoleOutputAttribute( hConsole, csbi.wAttributes, dwConSize, coordScreen, &cCharsWritten )'''
handle = handles[stream_id]
attribute = wintypes.WORD(attr)
length = wintypes.DWORD(length)
num_written = wintypes.DWORD(0)
# Note that this is hard-coded for ANSI (vs wide) bytes.
return _FillConsoleOutputAttribute(
handle, attribute, length, start, byref(num_written))
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from mock import Mock, patch
try:
from unittest2 import TestCase, main
except ImportError:
from unittest import TestCase, main
from ..winterm import WinColor, WinStyle, WinTerm
class WinTermTest(TestCase):
@patch('colorama.winterm.win32')
def testInit(self, mockWin32):
mockAttr = Mock()
mockAttr.wAttributes = 7 + 6 * 16 + 8
mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
term = WinTerm()
self.assertEquals(term._fore, 7)
self.assertEquals(term._back, 6)
self.assertEquals(term._style, 8)
def testGetAttrs(self):
term = WinTerm()
term._fore = 0
term._back = 0
term._style = 0
self.assertEquals(term.get_attrs(), 0)
term._fore = WinColor.YELLOW
self.assertEquals(term.get_attrs(), WinColor.YELLOW)
term._back = WinColor.MAGENTA
self.assertEquals(
term.get_attrs(),
WinColor.YELLOW + WinColor.MAGENTA * 16)
term._style = WinStyle.BRIGHT
self.assertEquals(
term.get_attrs(),
WinColor.YELLOW + WinColor.MAGENTA * 16 + WinStyle.BRIGHT)
@patch('colorama.winterm.win32')
def testResetAll(self, mockWin32):
mockAttr = Mock()
mockAttr.wAttributes = 1 + 2 * 16 + 8
mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
term = WinTerm()
term.set_console = Mock()
term._fore = -1
term._back = -1
term._style = -1
term.reset_all()
self.assertEquals(term._fore, 1)
self.assertEquals(term._back, 2)
self.assertEquals(term._style, 8)
self.assertEquals(term.set_console.called, True)
def testFore(self):
term = WinTerm()
term.set_console = Mock()
term._fore = 0
term.fore(5)
self.assertEquals(term._fore, 5)
self.assertEquals(term.set_console.called, True)
def testBack(self):
term = WinTerm()
term.set_console = Mock()
term._back = 0
term.back(5)
self.assertEquals(term._back, 5)
self.assertEquals(term.set_console.called, True)
def testStyle(self):
term = WinTerm()
term.set_console = Mock()
term._style = 0
term.style(22)
self.assertEquals(term._style, 22)
self.assertEquals(term.set_console.called, True)
@patch('colorama.winterm.win32')
def testSetConsole(self, mockWin32):
mockAttr = Mock()
mockAttr.wAttributes = 0
mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
term = WinTerm()
term.windll = Mock()
term.set_console()
self.assertEquals(
mockWin32.SetConsoleTextAttribute.call_args,
((mockWin32.STDOUT, term.get_attrs()), {})
)
@patch('colorama.winterm.win32')
def testSetConsoleOnStderr(self, mockWin32):
mockAttr = Mock()
mockAttr.wAttributes = 0
mockWin32.GetConsoleScreenBufferInfo.return_value = mockAttr
term = WinTerm()
term.windll = Mock()
term.set_console(on_stderr=True)
self.assertEquals(
mockWin32.SetConsoleTextAttribute.call_args,
((mockWin32.STDERR, term.get_attrs()), {})
)
if __name__ == '__main__':
main()
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import sys
try:
from unittest2 import TestCase, main
except ImportError:
from unittest import TestCase, main
from mock import patch
from .utils import platform, redirected_output
from ..initialise import init
from ..ansitowin32 import StreamWrapper
orig_stdout = sys.stdout
orig_stderr = sys.stderr
class InitTest(TestCase):
def setUp(self):
# sanity check
self.assertNotWrapped()
def tearDown(self):
sys.stdout = orig_stdout
sys.stderr = orig_stderr
def assertWrapped(self):
self.assertIsNot(sys.stdout, orig_stdout, 'stdout should be wrapped')
self.assertIsNot(sys.stderr, orig_stderr, 'stderr should be wrapped')
self.assertTrue(isinstance(sys.stdout, StreamWrapper),
'bad stdout wrapper')
self.assertTrue(isinstance(sys.stderr, StreamWrapper),
'bad stderr wrapper')
def assertNotWrapped(self):
self.assertIs(sys.stdout, orig_stdout, 'stdout should not be wrapped')
self.assertIs(sys.stderr, orig_stderr, 'stderr should not be wrapped')
@patch('colorama.initialise.reset_all')
def testInitWrapsOnWindows(self, _):
with platform('windows'):
init()
self.assertWrapped()
def testInitDoesntWrapOnNonWindows(self):
with platform('darwin'):
init()
self.assertNotWrapped()
def testInitAutoresetOnWrapsOnAllPlatforms(self):
with platform('darwin'):
init(autoreset=True)
self.assertWrapped()
def testInitWrapOffDoesntWrapOnWindows(self):
with platform('windows'):
init(wrap=False)
self.assertNotWrapped()
def testInitWrapOffWillUnwrapIfRequired(self):
with platform('windows'):
init()
init(wrap=False)
self.assertNotWrapped()
def testInitWrapOffIncompatibleWithAutoresetOn(self):
self.assertRaises(ValueError, lambda: init(autoreset=True, wrap=False))
@patch('colorama.ansitowin32.winterm', None)
def testInitOnlyWrapsOnce(self):
with platform('windows'):
init()
init()
self.assertWrapped()
@patch('colorama.win32.SetConsoleTextAttribute')
@patch('colorama.initialise.AnsiToWin32')
def testAutoResetPassedOn(self, mockATW32, _):
with platform('windows'):
init(autoreset=True)
self.assertEquals(len(mockATW32.call_args_list), 2)
self.assertEquals(mockATW32.call_args_list[1][1]['autoreset'], True)
self.assertEquals(mockATW32.call_args_list[0][1]['autoreset'], True)
@patch('colorama.initialise.AnsiToWin32')
def testAutoResetChangeable(self, mockATW32):
with platform('windows'):
init()
init(autoreset=True)
self.assertEquals(len(mockATW32.call_args_list), 4)
self.assertEquals(mockATW32.call_args_list[2][1]['autoreset'], True)
self.assertEquals(mockATW32.call_args_list[3][1]['autoreset'], True)
init()
self.assertEquals(len(mockATW32.call_args_list), 6)
self.assertEquals(
mockATW32.call_args_list[4][1]['autoreset'], False)
self.assertEquals(
mockATW32.call_args_list[5][1]['autoreset'], False)
@patch('colorama.initialise.atexit.register')
def testAtexitRegisteredOnlyOnce(self, mockRegister):
init()
self.assertTrue(mockRegister.called)
mockRegister.reset_mock()
init()
self.assertFalse(mockRegister.called)
if __name__ == '__main__':
main()
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from contextlib import contextmanager
import sys
from mock import Mock
@contextmanager
def platform(name):
orig = sys.platform
sys.platform = name
yield
sys.platform = orig
@contextmanager
def redirected_output():
orig = sys.stdout
sys.stdout = Mock()
sys.stdout.isatty = lambda: False
yield
sys.stdout = orig
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import sys
try:
from unittest2 import TestCase, main
except ImportError:
from unittest import TestCase, main
from ..ansi import Fore, Back, Style
from ..ansitowin32 import AnsiToWin32
stdout_orig = sys.stdout
stderr_orig = sys.stderr
class AnsiTest(TestCase):
def setUp(self):
# sanity check: stdout should be a file or StringIO object.
# It will only be AnsiToWin32 if init() has previously wrapped it
self.assertNotEqual(type(sys.stdout), AnsiToWin32)
self.assertNotEqual(type(sys.stderr), AnsiToWin32)
def tearDown(self):
sys.stdout = stdout_orig
sys.stderr = stderr_orig
def testForeAttributes(self):
self.assertEquals(Fore.BLACK, '\033[30m')
self.assertEquals(Fore.RED, '\033[31m')
self.assertEquals(Fore.GREEN, '\033[32m')
self.assertEquals(Fore.YELLOW, '\033[33m')
self.assertEquals(Fore.BLUE, '\033[34m')
self.assertEquals(Fore.MAGENTA, '\033[35m')
self.assertEquals(Fore.CYAN, '\033[36m')
self.assertEquals(Fore.WHITE, '\033[37m')
self.assertEquals(Fore.RESET, '\033[39m')
def testBackAttributes(self):
self.assertEquals(Back.BLACK, '\033[40m')
self.assertEquals(Back.RED, '\033[41m')
self.assertEquals(Back.GREEN, '\033[42m')
self.assertEquals(Back.YELLOW, '\033[43m')
self.assertEquals(Back.BLUE, '\033[44m')
self.assertEquals(Back.MAGENTA, '\033[45m')
self.assertEquals(Back.CYAN, '\033[46m')
self.assertEquals(Back.WHITE, '\033[47m')
self.assertEquals(Back.RESET, '\033[49m')
def testStyleAttributes(self):
self.assertEquals(Style.DIM, '\033[2m')
self.assertEquals(Style.NORMAL, '\033[22m')
self.assertEquals(Style.BRIGHT, '\033[1m')
if __name__ == '__main__':
main()
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from mock import Mock, patch
try:
from unittest2 import TestCase, main
except ImportError:
from unittest import TestCase, main
from .utils import platform
from ..ansi import Style
from ..ansitowin32 import AnsiToWin32, StreamWrapper
class StreamWrapperTest(TestCase):
def testIsAProxy(self):
mockStream = Mock()
wrapper = StreamWrapper(mockStream, None)
self.assertTrue( wrapper.random_attr is mockStream.random_attr )
def testDelegatesWrite(self):
mockStream = Mock()
mockConverter = Mock()
wrapper = StreamWrapper(mockStream, mockConverter)
wrapper.write('hello')
self.assertTrue(mockConverter.write.call_args, (('hello',), {}))
class AnsiToWin32Test(TestCase):
def testInit(self):
mockStdout = object()
auto = object()
stream = AnsiToWin32(mockStdout, autoreset=auto)
self.assertEquals(stream.wrapped, mockStdout)
self.assertEquals(stream.autoreset, auto)
@patch('colorama.ansitowin32.winterm', None)
def testStripIsTrueOnWindows(self):
with platform('windows'):
stream = AnsiToWin32(None)
self.assertTrue(stream.strip)
def testStripIsFalseOffWindows(self):
with platform('darwin'):
stream = AnsiToWin32(None)
self.assertFalse(stream.strip)
def testWriteStripsAnsi(self):
mockStdout = Mock()
stream = AnsiToWin32(mockStdout)
stream.wrapped = Mock()
stream.write_and_convert = Mock()
stream.strip = True
stream.write('abc')
self.assertFalse(stream.wrapped.write.called)
self.assertEquals(stream.write_and_convert.call_args, (('abc',), {}))
def testWriteDoesNotStripAnsi(self):
mockStdout = Mock()
stream = AnsiToWin32(mockStdout)
stream.wrapped = Mock()
stream.write_and_convert = Mock()
stream.strip = False
stream.convert = False
stream.write('abc')
self.assertFalse(stream.write_and_convert.called)
self.assertEquals(stream.wrapped.write.call_args, (('abc',), {}))
def assert_autoresets(self, convert, autoreset=True):
stream = AnsiToWin32(Mock())
stream.convert = convert
stream.reset_all = Mock()
stream.autoreset = autoreset
stream.winterm = Mock()
stream.write('abc')
self.assertEquals(stream.reset_all.called, autoreset)
def testWriteAutoresets(self):
self.assert_autoresets(convert=True)
self.assert_autoresets(convert=False)
self.assert_autoresets(convert=True, autoreset=False)
self.assert_autoresets(convert=False, autoreset=False)
def testWriteAndConvertWritesPlainText(self):
stream = AnsiToWin32(Mock())
stream.write_and_convert( 'abc' )
self.assertEquals( stream.wrapped.write.call_args, (('abc',), {}) )
def testWriteAndConvertStripsAllValidAnsi(self):
stream = AnsiToWin32(Mock())
stream.call_win32 = Mock()
data = [
'abc\033[mdef',
'abc\033[0mdef',
'abc\033[2mdef',
'abc\033[02mdef',
'abc\033[002mdef',
'abc\033[40mdef',
'abc\033[040mdef',
'abc\033[0;1mdef',
'abc\033[40;50mdef',
'abc\033[50;30;40mdef',
'abc\033[Adef',
'abc\033[0Gdef',
'abc\033[1;20;128Hdef',
]
for datum in data:
stream.wrapped.write.reset_mock()
stream.write_and_convert( datum )
self.assertEquals(
[args[0] for args in stream.wrapped.write.call_args_list],
[ ('abc',), ('def',) ]
)
def testWriteAndConvertSkipsEmptySnippets(self):
stream = AnsiToWin32(Mock())
stream.call_win32 = Mock()
stream.write_and_convert( '\033[40m\033[41m' )
self.assertFalse( stream.wrapped.write.called )
def testWriteAndConvertCallsWin32WithParamsAndCommand(self):
stream = AnsiToWin32(Mock())
stream.convert = True
stream.call_win32 = Mock()
stream.extract_params = Mock(return_value='params')
data = {
'abc\033[adef': ('a', 'params'),
'abc\033[;;bdef': ('b', 'params'),
'abc\033[0cdef': ('c', 'params'),
'abc\033[;;0;;Gdef': ('G', 'params'),
'abc\033[1;20;128Hdef': ('H', 'params'),
}
for datum, expected in data.items():
stream.call_win32.reset_mock()
stream.write_and_convert( datum )
self.assertEquals( stream.call_win32.call_args[0], expected )
def testExtractParams(self):
stream = AnsiToWin32(Mock())
data = {
'': (),
';;': (),
'2': (2,),
';;002;;': (2,),
'0;1': (0, 1),
';;003;;456;;': (3, 456),
'11;22;33;44;55': (11, 22, 33, 44, 55),
}
for datum, expected in data.items():
self.assertEquals(stream.extract_params(datum), expected)
def testCallWin32UsesLookup(self):
listener = Mock()
stream = AnsiToWin32(listener)
stream.win32_calls = {
1: (lambda *_, **__: listener(11),),
2: (lambda *_, **__: listener(22),),
3: (lambda *_, **__: listener(33),),
}
stream.call_win32('m', (3, 1, 99, 2))
self.assertEquals(
[a[0][0] for a in listener.call_args_list],
[33, 11, 22] )
def testCallWin32DefaultsToParams0(self):
mockStdout = Mock()
stream = AnsiToWin32(mockStdout)
stream.win32_calls = {0: (mockStdout.reset,)}
stream.call_win32('m', [])
self.assertTrue(mockStdout.reset.called)
if __name__ == '__main__':
main()
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
from .initialise import init, deinit, reinit
from .ansi import Fore, Back, Style
from .ansitowin32 import AnsiToWin32
VERSION = '0.2.7'
| Python |
# Copyright Jonathan Hartley 2013. BSD 3-Clause license, see LICENSE file.
import re
import sys
from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
from .winterm import WinTerm, WinColor, WinStyle
from .win32 import windll
if windll is not None:
winterm = WinTerm()
def is_a_tty(stream):
return hasattr(stream, 'isatty') and stream.isatty()
class StreamWrapper(object):
'''
Wraps a stream (such as stdout), acting as a transparent proxy for all
attribute access apart from method 'write()', which is delegated to our
Converter instance.
'''
def __init__(self, wrapped, converter):
# double-underscore everything to prevent clashes with names of
# attributes on the wrapped stream object.
self.__wrapped = wrapped
self.__convertor = converter
def __getattr__(self, name):
return getattr(self.__wrapped, name)
def write(self, text):
self.__convertor.write(text)
class AnsiToWin32(object):
'''
Implements a 'write()' method which, on Windows, will strip ANSI character
sequences from the text, and if outputting to a tty, will convert them into
win32 function calls.
'''
ANSI_RE = re.compile('\033\[((?:\d|;)*)([a-zA-Z])')
def __init__(self, wrapped, convert=None, strip=None, autoreset=False):
# The wrapped stream (normally sys.stdout or sys.stderr)
self.wrapped = wrapped
# should we reset colors to defaults after every .write()
self.autoreset = autoreset
# create the proxy wrapping our output stream
self.stream = StreamWrapper(wrapped, self)
on_windows = sys.platform.startswith('win')
# should we strip ANSI sequences from our output?
if strip is None:
strip = on_windows
self.strip = strip
# should we should convert ANSI sequences into win32 calls?
if convert is None:
convert = on_windows and is_a_tty(wrapped)
self.convert = convert
# dict of ansi codes to win32 functions and parameters
self.win32_calls = self.get_win32_calls()
# are we wrapping stderr?
self.on_stderr = self.wrapped is sys.stderr
def should_wrap(self):
'''
True if this class is actually needed. If false, then the output
stream will not be affected, nor will win32 calls be issued, so
wrapping stdout is not actually required. This will generally be
False on non-Windows platforms, unless optional functionality like
autoreset has been requested using kwargs to init()
'''
return self.convert or self.strip or self.autoreset
def get_win32_calls(self):
if self.convert and winterm:
return {
AnsiStyle.RESET_ALL: (winterm.reset_all, ),
AnsiStyle.BRIGHT: (winterm.style, WinStyle.BRIGHT),
AnsiStyle.DIM: (winterm.style, WinStyle.NORMAL),
AnsiStyle.NORMAL: (winterm.style, WinStyle.NORMAL),
AnsiFore.BLACK: (winterm.fore, WinColor.BLACK),
AnsiFore.RED: (winterm.fore, WinColor.RED),
AnsiFore.GREEN: (winterm.fore, WinColor.GREEN),
AnsiFore.YELLOW: (winterm.fore, WinColor.YELLOW),
AnsiFore.BLUE: (winterm.fore, WinColor.BLUE),
AnsiFore.MAGENTA: (winterm.fore, WinColor.MAGENTA),
AnsiFore.CYAN: (winterm.fore, WinColor.CYAN),
AnsiFore.WHITE: (winterm.fore, WinColor.GREY),
AnsiFore.RESET: (winterm.fore, ),
AnsiBack.BLACK: (winterm.back, WinColor.BLACK),
AnsiBack.RED: (winterm.back, WinColor.RED),
AnsiBack.GREEN: (winterm.back, WinColor.GREEN),
AnsiBack.YELLOW: (winterm.back, WinColor.YELLOW),
AnsiBack.BLUE: (winterm.back, WinColor.BLUE),
AnsiBack.MAGENTA: (winterm.back, WinColor.MAGENTA),
AnsiBack.CYAN: (winterm.back, WinColor.CYAN),
AnsiBack.WHITE: (winterm.back, WinColor.GREY),
AnsiBack.RESET: (winterm.back, ),
}
def write(self, text):
if self.strip or self.convert:
self.write_and_convert(text)
else:
self.wrapped.write(text)
self.wrapped.flush()
if self.autoreset:
self.reset_all()
def reset_all(self):
if self.convert:
self.call_win32('m', (0,))
elif is_a_tty(self.wrapped):
self.wrapped.write(Style.RESET_ALL)
def write_and_convert(self, text):
'''
Write the given text to our wrapped stream, stripping any ANSI
sequences from the text, and optionally converting them into win32
calls.
'''
cursor = 0
for match in self.ANSI_RE.finditer(text):
start, end = match.span()
self.write_plain_text(text, cursor, start)
self.convert_ansi(*match.groups())
cursor = end
self.write_plain_text(text, cursor, len(text))
def write_plain_text(self, text, start, end):
if start < end:
self.wrapped.write(text[start:end])
self.wrapped.flush()
def convert_ansi(self, paramstring, command):
if self.convert:
params = self.extract_params(paramstring)
self.call_win32(command, params)
def extract_params(self, paramstring):
def split(paramstring):
for p in paramstring.split(';'):
if p != '':
yield int(p)
return tuple(split(paramstring))
def call_win32(self, command, params):
if params == []:
params = [0]
if command == 'm':
for param in params:
if param in self.win32_calls:
func_args = self.win32_calls[param]
func = func_args[0]
args = func_args[1:]
kwargs = dict(on_stderr=self.on_stderr)
func(*args, **kwargs)
elif command in ('H', 'f'): # set cursor position
func = winterm.set_cursor_position
func(params, on_stderr=self.on_stderr)
elif command in ('J'):
func = winterm.erase_data
func(params, on_stderr=self.on_stderr)
elif command == 'A':
if params == () or params == None:
num_rows = 1
else:
num_rows = params[0]
func = winterm.cursor_up
func(num_rows, on_stderr=self.on_stderr)
| Python |
#! /usr/bin/env python3.1
#-*- coding: utf-8 -*-
# Find a Bike
# Copyright (C) 2013 Cédric Bonhomme - http://cedricbonhomme.org/
#
# For more information : https://bitbucket.org/cedricbonhomme/find-a-bike
#
# 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/>.
__author__ = "Cedric Bonhomme"
__version__ = "$Revision: 0.3 $"
__date__ = "$Date: 2012/06/04 $"
__revision__ = "$Date: 2013/06/10 $"
__copyright__ = "Copyright (c) Cedric Bonhomme"
__license__ = "AGPLv3"
import cgi
import json
import datetime
import urllib.request, urllib.parse, urllib.error
from xml.dom.minidom import parseString
import configparser
config = configparser.SafeConfigParser()
config.read("./conf.cfg")
API_KEY = config.get('globals', 'api_key')
form = cgi.FieldStorage()
city = form.getvalue("city", "")
parking = form.getvalue("parking", "1")
latitude = form.getvalue("latitude", "")
longitude = form.getvalue("longitude", "")
zoom = form.getvalue("zoom", "10")
stations = []
cities = []
errors = []
html = '<!DOCTYPE html>\n<html>\n' + \
'<head>\n\t<meta charset="utf-8" />\n\t<title>Find a Bike</title>\n\t' + \
'<style>html, head, body { width: 100%; height: 100% }</style>\n\t' + \
'<link rel="stylesheet" href="./style.css" />\n'
try:
url = "https://api.jcdecaux.com/vls/v1/stations?apiKey="+API_KEY
if city == "":
try:
request = urllib.request.urlopen(url)
text = request.read().decode("utf-8")
stations = json.loads(text)
except Exception as e:
print(e)
else:
cities = city.split(',')
for current_city in cities:
try:
request = urllib.request.urlopen(url + "&contract=" + current_city)
text = request.read()
stations.extend(json.loads(text.decode()))
except:
errors.append(current_city)
for error in errors:
cities.remove(error)
except:
html += '</head>\n'
html += '<body>\n'
html += '<p>Unable to contact JCDecaux Web service or API key disabled.</p>\n'
html += '</body>\n'
html += '</html>\n'
parkings = None
if parking == "1":
request = urllib.request.urlopen("http://service.vdl.lu/rss/circulation_guidageparking.php")
text = request.read()
parkings = parseString(text)
if len(stations) == 0:
html += '</head>\n'
html += '<body>\n'
html += '<p>No stations.</p>\n'
html += '</body>\n'
html += '</html>\n'
else:
html += '<script src="http://openlayers.org/api/OpenLayers.js"></script>\n' + \
'<script src="./scripts.js"></script>\n'
html += """<script>
var stations_location;
function init(position) {
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var popupClass, popupContentHTML;
var zoom=%s;
AutoSizeAnchoredMinSize = OpenLayers.Class(OpenLayers.Popup.Anchored, {
'autoSize': true,
'minSize': new OpenLayers.Size(10,10)
});
map = new OpenLayers.Map("mapdiv" , {
controls:[
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.Attribution()]});
stations_location = new OpenLayers.Layer.Markers("Bikes");
map.addLayer(stations_location);
map.addLayer(new OpenLayers.Layer.OSM());\n""" % (zoom,)
if "" in (latitude, longitude):
html += """var lonLatCenter = new OpenLayers.LonLat(position.coords.longitude, position.coords.latitude).transform(
new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject() )
map.setCenter (lonLatCenter, %s);\n""" % (zoom,)
else:
html += """var lonLatCenter = new OpenLayers.LonLat(%s, %s).transform(
new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject() )
map.setCenter (lonLatCenter, %s);\n""" % (longitude, latitude, zoom)
for idx, station in enumerate(stations):
try:
# just to test the number
float(station["position"]["lng"])
except:
continue
html += """
var station%s = new OpenLayers.LonLat(%s, %s).transform(
new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
popupClass = AutoSizeAnchoredMinSize;""" % \
(idx, station["position"]["lng"], station["position"]["lat"])
if station["available_bikes"] == 0:
html += """
popupContentHTML = "<p><b>%s</b><hr />No bikes available.<br />Payment terminal: %s<br />Last update: %s</p>";""" % \
(station["name"], [station["banking"]==True and "yes" or "no"][0], \
datetime.datetime.fromtimestamp(station['last_update']/1000).strftime('%Y-%m-%d %H:%M:%S'))
html += """
addMarker(station%s, popupClass, popupContentHTML, true, true, "./marker-red.png", stations_location);""" % \
(idx,)
else:
html += """
popupContentHTML = "<p><b>%s</b><hr />Available bikes: %s<br />Payment terminal: %s<br />Last update: %s</p>";""" % \
(station["name"], station["available_bikes"], [station["banking"]==True and "yes" or "no"][0], \
datetime.datetime.fromtimestamp(station['last_update']/1000).strftime('%Y-%m-%d %H:%M:%S'))
html += """
addMarker(station%s, popupClass, popupContentHTML, true, true, "./marker-green.png", stations_location);""" % \
(idx,)
if parkings != None:
html += """
parking_lots = new OpenLayers.Layer.Markers("Parking lots");
map.addLayer(parking_lots);\n"""
for parking in parkings.getElementsByTagName('item'):
title = parking.getElementsByTagName('title')[0].childNodes[0].nodeValue
link = parking.getElementsByTagName('guid')[0].childNodes[0].nodeValue
try:
total_places = parking.getElementsByTagName('vdlxml:total')[0].childNodes[0].nodeValue
except:
total_places = "no data"
try:
available_places = parking.getElementsByTagName('vdlxml:actuel')[0].childNodes[0].nodeValue
except:
available_places = "no data"
latitude = parking.getElementsByTagName('vdlxml:localisation')[0]. \
getElementsByTagName('vdlxml:localisationLatitude')[0].childNodes[0].nodeValue
longitude = parking.getElementsByTagName('vdlxml:localisation')[0]. \
getElementsByTagName('vdlxml:localisationLongitude')[0].childNodes[0].nodeValue
picture = parking.getElementsByTagName('vdlxml:divers')[0]. \
getElementsByTagName('vdlxml:pictureUrl')[0].childNodes[0].nodeValue
html += """
var parking%s = new OpenLayers.LonLat(%s, %s).transform(
new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
popupClass = AutoSizeAnchoredMinSize;""" % \
(idx, longitude, latitude)
html += """
popupContentHTML = "<p><b>%s</b><hr />Total places: %s<br />Available places: %s<br /><a href='%s'>More information</a></p><img src='%s' width='250px' height='188px' />";""" % \
(title, total_places, available_places, link, picture)
html += """
addMarker(parking%s, popupClass, popupContentHTML, true, false, "./parking.png", parking_lots);""" % \
(idx,)
html += "}\n</script>\n</head>\n"
html += '<body onload="getLocation();">\n'
if city != "":
html += """<h1>Bikes available in %s</h1>\n""" % ", ".join(cities)
if errors != []:
html += """<p>No results found for %s.</p>\n""" % ", ".join(errors)
else:
html += """<h1>Bikes available in the world</h1>\n"""
html += '<div id="mapdiv" style="width:100%;height:100%;"></div>\n'
html += '<p>This software is under Affero GPL license. You are welcome to copy, modify or ' + \
'redistribute the <a href="https://bitbucket.org/cedricbonhomme/find-a-bike/">source code</a> ' + \
'according to the <a href="https://www.gnu.org/licenses/agpl-3.0.txt">AGPLv3</a> license.\n'
html += "</body>\n</html>"
# Finally print the web page.
print("Content-type:text/html; Accept-Charset: utf-8")
print("")
print(html.encode("ascii", "xmlcharrefreplace").decode())
| Python |
'''This will take in a CSV list of ticker symbols, and should create a correctly
formatted table of information about each one.'''
import csv
import os
import sys
from bs4 import BeautifulSoup
from selenium import webdriver
from datetime import date
class ImproperSymbolException(Exception):
'''Exception class which should occur if one of the symbols in the list is
not of the expected format (right now, 5 characters only).'''
pass
def main():
tickers_uri = './test_files/combined_sec_list_jan_2014.csv'
ticker_symbols_mf, ticker_symbols_etf = read_csv_list(tickers_uri)
print(ticker_symbols_etf)
print(len(ticker_symbols_etf))
perf_url_mf = 'http://performance.morningstar.com/fund/performance-return.action?ops=p&p=total_returns_page&t='
risk_url_mf = 'http://performance.morningstar.com/fund/ratings-risk.action?t='
perf_url_etf = 'http://performance.morningstar.com/funds/etf/total-returns.action?t='
risk_url_etf = 'http://performance.morningstar.com/funds/etf/ratings-risk.action?t='
quote_url_etf = 'http://etfs.morningstar.com/quote?t='
mf_dict = scrape_mf_pages(perf_url_mf, risk_url_mf, ticker_symbols_mf)
etf_dict = scrape_etf_pages(quote_url_etf, perf_url_etf, risk_url_etf, ticker_symbols_etf)
print(mf_dict)
out_uri = './output_chart_combined.csv'
print_to_csv(mf_dict, etf_dict, out_uri)
def scrape_etf_pages(quote_url_start, perf_url_start, risk_url_start, ticker_symbols):
info_dict = {}
driver = webdriver.PhantomJS()
for symbol in ticker_symbols:
print("Currently on: " + str(symbol))
info_dict[symbol] = {}
quote_url = quote_url_start + str(symbol)
driver.get(quote_url)
html = driver.page_source
soup = BeautifulSoup(html)
#Type
etf_type = soup.find("span", {"id":"MorningstarCategory"}).text
info_dict[symbol]['type'] = etf_type.strip()
perf_url = perf_url_start + symbol
driver.get(perf_url)
html = driver.page_source
soup = BeautifulSoup(html)
#Full name
name = soup.find("div", {"class": "r_title"}).find("h1").text
info_dict[symbol]['name'] = name
#Number of stars is the morningstar rating. Always in a span labeled the same way.
star_label = soup.find("span", {"id": "star_span"})['class'][0]
rating = star_label[len(star_label)-1]
info_dict[symbol]['rating'] = rating
#Get the price ranking
info_dict[symbol]['decile_rank'] = {}
table = soup.find("tbody").find_all("tr")
row_data = map(lambda l: l.text, table[len(table)-2].find_all("td"))
rel_rank_data = row_data[len(row_data)-5::]
curr_year = date.today().year
for i, year in enumerate(range(curr_year-5, curr_year)):
try:
info_dict[symbol]['decile_rank'][year] = float(rel_rank_data[i])
except ValueError:
info_dict[symbol]['decile_rank'][year] = '-'
#Get the 1, 3, 5, 10 year performances
perf_ele = soup.find_all("table")[1].find_all("tr")[1].find_all("td")
year_perfs_any = map(lambda l: l.text, perf_ele)[len(perf_ele)-5:len(perf_ele)-1]
year_perfs = []
for perf in year_perfs_any:
try:
year_perfs.append(float(perf))
except ValueError:
year_perfs.append('-')
perf_years = [1, 3, 5, 10]
info_dict[symbol]['performances'] = dict(zip(perf_years, year_perfs))
#Now, need the risk data.
risk_url = risk_url_start + symbol
print("Currently looking at: " + risk_url)
driver.get(risk_url)
html = driver.page_source
soup = BeautifulSoup(html)
#Getting beta. But I'm getting lazy so it's now all in 1 line.
while True:
try:
beta_ele = soup.find("div", {"id":"div_mpt_stats"}).find_all("tr")[5].find_all("td")[2]
except IndexError:
print "Trapped in loop ETF."
driver.refresh()
html = driver.page_source
soup = BeautifulSoup(html)
continue
else:
break
beta = beta_ele.string
#Getting sharpe ratio
sharpe_ele = soup.find("div", {"id":"div_volatility"}).find_all("tr")[3].find_all("td")[2]
sharpe = sharpe_ele.text
info_dict[symbol]['sharpe_ratio'] = sharpe
for name, ele in [('beta', beta), ('sharpe_ratio', sharpe)]:
try:
info_dict[symbol][name] = float(ele)
except ValueError:
info_dict[symbol][name] = '-'
return info_dict
def scrape_mf_pages(perf_url_start, risk_url_start, ticker_symbols):
'''Main fuction which will get all relevant info, and dump it to a 2D
dictionary- key is the symbol, maps to a dictionary where keys are info
needed for output CSV.'''
info_dict = {}
driver = webdriver.PhantomJS()
for symbol in ticker_symbols:
print("Currently on: " + str(symbol))
info_dict[symbol] = {}
perf_url = perf_url_start + symbol
print("Looking at URL: " + perf_url)
driver.get(perf_url)
html = driver.page_source
soup = BeautifulSoup(html)
''' There's really only the one major table that we care about.
soup.find("table").find_all("tr") <- This will give us a list of
table rows. These can then be searched through in more dept depending
on what you're looking for.'''
#Full name
name = soup.find("div", {"class": "r_title"}).find("h1").text
info_dict[symbol]['name'] = name
#Type
mf_type = soup.find("span", {"class":"databox"})['name']
info_dict[symbol]['type'] = mf_type
#Number of stars is the morningstar rating. Always in a span labeled the same way.
star_label = soup.find("span", {"id": "star_span"})['class'][0]
rating = star_label[len(star_label)-1]
info_dict[symbol]['rating'] = rating
#Get the decile rank in category of the last 5 years.
#Know that we want the second to last row, and don't want the newlines
info_dict[symbol]['decile_rank'] = {}
first_table_rows = soup.find("table").find_all("tr")
decile_row = first_table_rows[len(first_table_rows)-2].find_all("td")
decile_row = list(decile_row)
ranks = map(lambda ele: ele.string, decile_row)
ranks = ranks[len(ranks)-5::]
curr_year = date.today().year
for i, year in enumerate(range(curr_year-5, curr_year)):
try:
info_dict[symbol]['decile_rank'][year] = float(ranks[i])
except ValueError:
info_dict[symbol]['decile_rank'][year] = '-'
#Want the performances for 1 year, 3 year, 5 year, and 10 year.
perf_row = soup.find_all("table")[1].find_all("tr")[1].find_all("td")
year_perfs_any = map(lambda l: l.string, perf_row[len(perf_row)-5:len(perf_row)-1])
year_perfs = []
for perf in year_perfs_any:
try:
year_perfs.append(float(perf))
except ValueError:
year_perfs.append('-')
perf_years = [1, 3, 5, 10]
print(year_perfs)
info_dict[symbol]['performances'] = dict(zip(perf_years, year_perfs))
#Now, need the risk data.
risk_url = risk_url_start + symbol
driver.get(risk_url)
html = driver.page_source
soup = BeautifulSoup(html)
#Getting beta. But I'm getting lazy so it's now all in 1 line.
#For some reason, this page doesn't always load correctly.
while True:
try:
beta_ele = soup.find("div", {"id":"div_mpt_stats"}).find_all("tr")[5].find_all("td")[2]
except IndexError:
print("Trapped in loop MF!")
driver.refresh()
html = driver.page_source
soup = BeautifulSoup(html)
continue
else:
break
beta = beta_ele.string
#Getting sharpe ratio
sharpe_ele = soup.find("div", {"id":"div_volatility"}).find_all("tr")[3].find_all("td")[2]
sharpe = sharpe_ele.text
for name, ele in [('beta', beta), ('sharpe_ratio', sharpe)]:
try:
info_dict[symbol][name] = float(ele)
except ValueError:
info_dict[symbol][name] = '-'
return info_dict
def read_csv_list(uri):
'''Function that should take in a CSV containing a list of 5-digit ticker
symbols, and return a python list.'''
symbol_list_mf = []
symbol_list_etf = []
count = 0
with open(uri, 'rU') as symbol_file:
csv_reader = csv.reader(symbol_file)
while True:
try:
line = csv_reader.next()
if line == []:
print(line)
continue
count += 1
#Want to remove any whitespace that might have gotten in before
#or after the symbol
symbol = line[0].strip()
#Want to make sure we have a symbol for which I know the page
#structure.
if len(symbol) not in range(3, 6):
raise ImproperSymbolException("At this time, the scraper can only \
deal with Mutual Funds and ETF's. As such, the ticker \
symbols passed in must all be 3-5 characters. The \
symbol %s on line %s does not qualify." % (symbol, count))
elif len(symbol) == 5:
symbol_list_mf.append(symbol)
#Note: this could be 3 or 4 characters.
else:
symbol_list_etf.append(symbol)
except StopIteration:
break
return symbol_list_mf, symbol_list_etf
def print_to_csv(mf_dict, etf_dict, out_uri):
#Want to make sure that all of the same type are grouped together.
#The outer key will be the type. The inner will be a list of the lines.
grouped_lines = {}
with open(out_uri, 'wb') as x_file:
x_writer = csv.writer(x_file)
x_writer.writerow(['Symbol', 'Name', 'Class', 'MStar Rating', '1 Year', '3 Year', '5 Year', '10 Year', '2009', '2010', '2011', '2012', '2013', 'Beta', 'Sharpe Ratio'])
for cat_dict in [mf_dict, etf_dict]:
for symbol in cat_dict:
curr = cat_dict[symbol]
line = []
line.append(symbol)
line.append(curr['name'])
line.append(curr['type'])
line.append(curr['rating'])
#The performances
line.append(curr['performances'][1])
line.append(curr['performances'][3])
line.append(curr['performances'][5])
line.append(curr['performances'][10])
#Decile rankings
curr_year = date.today().year
past_5_yrs = range(curr_year-5, curr_year)
for year in past_5_yrs:
line.append(curr['decile_rank'][year])
line.append(curr['beta'])
line.append(curr['sharpe_ratio'])
if curr['type'] in grouped_lines.keys():
grouped_lines[curr['type']].append(line)
else:
grouped_lines[curr['type']] = [line]
#Now we have groups of lines by type.
#Want to print them into the CSV
for group_list in grouped_lines.values():
#Now that we have a grouping, print all in there.
for line in group_list:
x_writer.writerow(line)
x_writer.writerow([])
main()
| Python |
""" Copyright (C) 2014 T.Hofkamp
This file is part of FilofaxDIY.
FilofaxDIY 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.
FilofaxDIY 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 FilofaxDIY. If not, see <http://www.gnu.org/licenses/>.
"""
class xfig():
"""
Create xfig files with coordinates in millimeters
@ivar orientation: Orientation of the paper ("Landscape" or "Portrait")
@type orientation: C{str}
@ivar justification: ("Center" or "Flush Left")
@type justification:
@ivar units: "Metric" or "Inches"
@type units: C{str}
@ivar papersize: "Letter", "Legal", "Ledger", "Tabloid",
"A", "B", "C", "D", "E",
"A4", "A3", "A2", "A1", "A0" and "B5"
@type papersize: C{str}
@ivar magnification: export and print magnification, %
@type magnification: C{float}
@ivar multiplepage: Printing on single or multiple pages ("Single" or "Multiple")
@type multiplepage: C{str}
@ivar transparentcolor: color number for transparent color for GIF
export. -3=background, -2=None, -1=Default,
0-31 for standard colors or 32- for user colors)
@type transparentcolor: C{int}
@ivar resolution: Fig units/inch and coordinate system
@type resolution: C{int}
@ivar coord_system: The place of origin 1=lower left (NOT USED), 2=upper left
@type coord_system: C{int}
@ivar drawing: Buffer for holding the drawing on the paper
@type drawing: C{str}
@ivar depth: Layer on which to draw
@type depth: C{int}
@ivar xorigin: X-offset to draw functions
@type xorigin: C{int}
@ivar yorigin: Y-offset to draw functions
@type yorigin: C{int}
@ivar originstack: The stack holding the origins
@type originstack: C{[(int, int)]}
"""
"""
-1 Default font
0 Times Roman
1 Times Italic
2 Times Bold
3 Times Bold Italic
4 AvantGarde Book
5 AvantGarde Book Oblique
6 AvantGarde Demi
7 AvantGarde Demi Oblique
8 Bookman Light
9 Bookman Light Italic
10 Bookman Demi
11 Bookman Demi Italic
12 Courier
13 Courier Oblique
14 Courier Bold
15 Courier Bold Oblique
16 Helvetica
17 Helvetica Oblique
18 Helvetica Bold
19 Helvetica Bold Oblique
20 Helvetica Narrow
21 Helvetica Narrow Oblique
22 Helvetica Narrow Bold
23 Helvetica Narrow Bold Oblique
24 New Century Schoolbook Roman
25 New Century Schoolbook Italic
26 New Century Schoolbook Bold
27 New Century Schoolbook Bold Italic
28 Palatino Roman
29 Palatino Italic
30 Palatino Bold
31 Palatino Bold Italic
32 Symbol
33 Zapf Chancery Medium Italic
34 Zapf Dingbats
"""
def __init__(self,paper = "Letter", orient = "Portrait"):
self.orientation = orient #"Landscape" or "Portrait"
self.justification = "Center" #"Center" or "Flush Left"
self.units = "Metric" #"Metric" or "Inches"
self.papersize = paper #"Letter", "Legal", "Ledger", "Tabloid",
# "A", "B", "C", "D", "E",
# "A4", "A3", "A2", "A1", "A0" and "B5"
self.magnification = 100.0 #export and print magnification, %
self.multiplepage = "Single" #"Single" or "Multiple" pages
self.transparentcolor = -2 #color number for transparent color for GIF
# export. -3=background, -2=None, -1=Default,
# 0-31 for standard colors or 32- for user colors)
# which are associated with the whole figure)
self.resolution = 1200 #Fig units/inch and coordinate system:
self.coord_system=2 # 1: origin at lower left corner (NOT USED)
# 2: upper left)
self.drawing = ""
self.depth = 50 # the depth/layer to draw on
self.xorigin = 0
self.yorigin = 0
self.originstack = []
def pushorigin(self,dx,dy):
"""
Push the current origin to the stack, and move it relative to (dx,dy)
@param dx: Delta x to move the origin to
@type dx: C{int}
@param dy: Delta y to move the origin to
@type dy: C{int}
"""
self.originstack.append((self.xorigin,self.yorigin))
self.xorigin += dx
self.yorigin += dy
def poporigin(self):
"""
Return to the previous origin
"""
(self.xorigin,self.yorigin) = self.originstack.pop()
def setorigin(self,x,y):
"""
Set the current origin, clearing the stack
@param x: x to move the origin to
@type x: C{int}
@param y: y to move the origin to
@type y: C{int}
"""
self.originstack = []
self.xorigin = x
self.yorigin = y
def setdepth(self,newdepth):
"""
Set the layer to draw to
@param newdepth: The layer number (0...999)
@type newdepth: C{int}
"""
self.depth = newdepth
def getpaperwidth(self):
"""
Return the width of the paper
@return: The width in mm
@rtype: C{int}
"""
paper={
"4A0":( 1682 , 2378),
"2A0":( 1189 , 1682),
"A0":( 841 , 1189),
"A1":( 594 , 841),
"A2":( 420 , 594),
"A3":( 297 , 420),
"A4":(210,297),
"A5":( 148 , 210),
"A6":( 105 , 148),
"A7":(74 , 105),
"A8":( 52 , 74),
"A9":( 37 , 52),
"A10":( 26 , 37),
"Letter":( 216 , 279),
"Legal":( 216 , 356),
"Junior Legal":( 127 , 203),
"Ledger/Tabloid":( 279 , 432),
"A":( 216 , 279),
"B":( 279 , 432),
"C":( 432 , 559),
"D":( 559 , 864),
"E":( 864 , 1118) }
if self.orientation == "Portrait":
return paper[self.papersize][0]
return paper[self.papersize][1]
def getpaperheight(self):
"""
Return the height of the paper
@return: The height in mm
@rtype: C{int}
"""
# should be based on some kind of table, and orientation
paper={
"4A0":( 1682 , 2378),
"2A0":( 1189 , 1682),
"A0":( 841 , 1189),
"A1":( 594 , 841),
"A2":( 420 , 594),
"A3":( 297 , 420),
"A4":(210,297),
"A5":( 148 , 210),
"A6":( 105 , 148),
"A7":(74 , 105),
"A8":( 52 , 74),
"A9":( 37 , 52),
"A10":( 26 , 37),
"Letter":( 216 , 279),
"Legal":( 216 , 356),
"Junior Legal":( 127 , 203),
"Ledger/Tabloid":( 279 , 432),
"A":( 216 , 279),
"B":( 279 , 432),
"C":( 432 , 559),
"D":( 559 , 864),
"E":( 864 , 1118) }
if self.orientation == "Portrait":
return paper[self.papersize][1]
return paper[self.papersize][0]
def line(self,fx,fy,dx,dy,style=0,dikte=1):
"""
Draw a line from (fx,fy) to (fx+dx,fy+dy) with the style an thickness (1/80")
Coordinates are relative to self.origin
@param fx: fx From this X point
@type fx: C{int}
@param fy: fy From this Y point
@type fy: C{int}
@param dx: dx Draw relative to X point
@type dx: C{int}
@param dy: dy Draw relative to Y point
@type dy: C{int}
@param style: The style of the line 0=SOLID
@type style: C{int}
@param dikte: Thickness of the line in 1/80"
@type dikte: C{int}
"""
self.writeline("2 1 "+str(style)+" "+str(dikte)+" 0 7 "+str(self.depth)+" -1 -1 0.000 0 0 -1 0 0 2")
self.writeline("\t"+str(self.mm2pos(self.xorigin+fx))+" "+str(self.mm2pos(self.yorigin+fy))+" "+str(self.mm2pos(self.xorigin+fx+dx))+" "+str(self.mm2pos(self.yorigin+fy+dy)))
def tekst(self,x,y,text,font=0,fsize=12,align=0):
"""
Write some tekst to the canvas
Coordinates are relative to origin
@param x: X point to start (depending on align)
@type x: C{int}
@param y: Y of lower point of tekst
@type y: C{int}
@param text: The actual text to show
@type text: C{str}
@param font: Font number to draw (LaTeX ??)
@type font: C{int}
@param fsize: The size of the font in 1/80"
@type fsize: C{int}
@param align: Align the tekst left(0),centre(1) or right(2)
@type align: C{int}
"""
#self.writeline("4 "+str(align)+" 0 "+str(self.depth)+" -1 "+str(font)+" "+str(fsize)+" 0.0000 6 135 480 "+str(self.mm2pos(x))+" "+str(self.mm2pos(y))+" "+text+"\\001")
line = "4 {align} 0 {depth} -1 {font} {fsize} 0.0000 6 135 480 {x} {y} {text}\\001"
line = line.format(align = align, depth = self.depth, font = font, fsize = fsize,
x = self.mm2pos(self.xorigin+x), y = self.mm2pos(self.yorigin+y), text = text)
self.writeline(line)
def circle(self,x,y,rad,style=0,dikte=1):
"""
Draw a circle on centre (x,y) with the given radius, relative to origin
@param x: x Centre of circle
@type x: C{int}
@param y: y Centre of circle
@type y: C{int}
@param rad: Radius circle
@type rad: C{int}
@param style: The style of the circle 0=SOLID
@type style: C{int}
@param dikte: Thickness of the circle in 1/80"
@type dikte: C{int}
"""
# also something with fillig, future
self.ellipse(x,y,rad,rad,style,dikte) # ellipse is also a circle
# self.writeline("1 3 "+str(style)+" "+str(dikte)+" 0 7 "+str(self.depth)+" -1 -1 0.000 1 0.0000 "+str(self.mm2pos(x))+" "+str(self.mm2pos(y))+" "+str(self.mm2pos(rad))+" "+str(self.mm2pos(rad))+" "+str(self.mm2pos(x))+" "+str(self.mm2pos(y))+" "+str(self.mm2pos(x+rad))+" "+str(self.mm2pos(y)))
#line = "1 3 {style} {dikte} 0 7 {depth} -1 -1 0.000 1 0.0000 {x} {y} {radius} {radius} {x} {y} {xi} {y}"
#line = line.format(style = style, dikte = dikte, depth = self.depth, x = self.mm2pos(self.xorigin+x), y = self.mm2pos(self.yorigin+y),
# radius = self.mm2pos(rad), xi = self.mm2pos(self.xorigin+x+rad))
#self.writeline(line)
def ellipse(self,x,y,xrad,yrad,style=0,dikte=1):
"""
Draw a circle on centre (x,y) with the given radius, relative to origin
@param x: x Centre of circle
@type x: C{int}
@param y: y Centre of circle
@type y: C{int}
@param xrad: Radius circle horizontal
@type xrad: C{int}
@param yrad: Radius circle vertical
@type yrad: C{int}
@param style: The style of the circle 0=SOLID
@type style: C{int}
@param dikte: Thickness of the circle in 1/80"
@type dikte: C{int}
"""
line = "1 3 {style} {dikte} 0 7 {depth} -1 -1 0.000 1 0.0000 {x} {y} {radiusx} {radiusy} {x} {y} {xi} {y}"
line = line.format(style = style, dikte = dikte, depth = self.depth, x = self.mm2pos(self.xorigin+x), y = self.mm2pos(self.yorigin+y),
radiusx = self.mm2pos(xrad), radiusy = self.mm2pos(yrad), xi = self.mm2pos(self.xorigin+x+xrad))
self.writeline(line)
def box(self,fx,fy,w,h,style=0,dikte=1):
"""
Draw a box from (fx,fy) to (fx+w,fy+h) with the style an thickness (1/80")
Coordinates are relative to self.origin
@param fx: From this X point
@type fx: C{int}
@param fy: From this Y point
@type fy: C{int}
@param w: The width of the box
@type w: C{int}
@param h: h The height of the box
@type h: C{int}
@param style: The style of the line 0=SOLID
@type style: C{int}
@param dikte: Thickness of the line in 1/80"
@type dikte: C{int}
"""
self.writeline("2 2 "+str(style)+" "+str(dikte)+" 0 7 "+str(self.depth)+" -1 -1 0.000 0 0 -1 0 0 5")
line = "\t{x1} {y1} {x2} {y1} {x2} {y2} {x1} {y2} {x1} {y1}"
line = line.format(x1 = self.mm2pos(self.xorigin+fx), y1 = self.mm2pos(self.yorigin+fy),
x2 = self.mm2pos(self.xorigin+fx+w), y2 = self.mm2pos(self.yorigin+fy+h))
self.writeline(line)
def mm2pos(self,mm):
"""
Calculate mm to xfig units
self.resolution is expressed in units/xfig-inch. This xfig-inch is 2.667 cm (1.050") on paper
@param mm: distance in mm
@type mm: C{float}
@return: The number of fig units for the given distance
@rtype: C{int}
"""
figunitspermm=140*self.resolution/6300.0
return int(round(mm*self.resolution/figunitspermm))
# return int(round(mm*resolution/25.4))
def comment(self,comment):
"""
Add some comment in the file
@param comment: The line of comment
@type comment: C{str}
"""
self.drawing += '#' + comment + "\n"
def writeline(self,line):
"""
Add a line of output to the drawing
@param line: The line of output for xfig
@type line: C{str}
"""
self.drawing += line + "\n"
def save(self,filename):
"""
Write the drawing to a file
@param filename: The complete filename to which the drawing has to be written
@type filename: C{str}
"""
# write out some header
f = open(filename,mode='w')
f.write('#FIG 3.2\n')
f.write('# Created by FiloFax version 1.0\n')
f.write(self.orientation + '\n')
f.write(self.justification + '\n')
f.write(self.units + '\n')
f.write(self.papersize + '\n')
f.write(str(self.magnification) + '\n')
f.write(self.multiplepage + '\n')
f.write(str(self.transparentcolor) + '\n')
f.write(str(self.resolution) + ' ' + str(self.coord_system) + '\n')
f.write(self.drawing)
f.close()
| Python |
""" Copyright (C) 2014 T.Hofkamp
This file is part of FilofaxDIY.
FilofaxDIY 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.
FilofaxDIY 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 FilofaxDIY. If not, see <http://www.gnu.org/licenses/>.
"""
class pdfout():
"""
Create xfig files with coordinates in millimeters
@ivar orientation: Orientation of the paper ("Landscape" or "Portrait")
@type orientation: C{str}
@ivar paperheight: Height of the paper
@type paperheight: C{float}
@ivar magnification: export and print magnification, %
@type magnification: C{float}
@ivar resolution: Fig units/inch and coordinate system
@type resolution: C{int}
@ivar drawing: Buffer for holding the drawing on the paper
@type drawing: C{str}
@ivar xorigin: X-offset to draw functions
@type xorigin: C{int}
@ivar yorigin: Y-offset to draw functions
@type yorigin: C{int}
@ivar originstack: The stack holding the origins
@type originstack: C{[(int, int)]}
"""
# ['Courier', 'Courier-Bold', 'Courier-BoldOblique', 'Courier-Oblique', 'Helvetica', 'Helvetica-Bold', 'Helvetica-BoldOblique', 'Helvetica-Oblique', 'Symbol', 'Times-Bold', 'Times-BoldItalic', 'Times-Italic', 'Times-Roman', 'ZapfDingbats']
def __init__(self,width,height):
#self.paperwidth = width
self.paperheight = height
self.resolution = 72 #Fig units/inch and coordinate system:
self.drawings = []
self.xorigin = 0
self.yorigin = 0
self.originstack = []
def pushorigin(self,dx,dy):
"""
Push the current origin to the stack, and move it relative to (dx,dy)
@param dx: Delta x to move the origin to
@type dx: C{int}
@param dy: Delta y to move the origin to
@type dy: C{int}
"""
self.originstack.append((self.xorigin,self.yorigin))
self.xorigin += dx
self.yorigin += dy
def poporigin(self):
"""
Return to the previous origin
"""
(self.xorigin,self.yorigin) = self.originstack.pop()
def setorigin(self,x,y):
"""
Set the current origin, clearing the stack
@param x: x to move the origin to
@type x: C{int}
@param y: y to move the origin to
@type y: C{int}
"""
self.originstack = []
self.xorigin = x
self.yorigin = y
def line(self,fx,fy,dx,dy,style=0,dikte=1,gray=0):
"""
Draw a line from (fx,fy) to (fx+dx,fy+dy) with the style an thickness (1/80")
Coordinates are relative to self.origin
@param fx: fx From this X point
@type fx: C{int}
@param fy: fy From this Y point
@type fy: C{int}
@param dx: dx Draw relative to X point
@type dx: C{int}
@param dy: dy Draw relative to Y point
@type dy: C{int}
@param style: The style of the line 0=SOLID
@type style: C{int}
@param dikte: Thickness of the line in 1/80"
@type dikte: C{int}
"""
self.drawings.append(('L',self.mm2pos(self.xorigin+fx),self.mm2pos(self.paperheight-(self.yorigin+fy)),
self.mm2pos(self.xorigin+fx+dx),self.mm2pos(self.paperheight-(self.yorigin+fy+dy)),
style,dikte,gray))
# add gray color default to 0
# for gray in (0.0, 0.25, 0.50, 0.75, 1.0): canvas.setFillGray(gray)
def image(self,filename,x,y,w = None,h = None):
"""
Draw a image on (x,y) with the size (w,h)
Coordinates are relative to self.origin
@param x: x From this X point
@type x: C{int}
@param y: y From this Y point
@type y: C{int}
@param w: Set de image to this width
@type w: C{int}
@param h: Make te image this height
@type h: C{int}
@param filename: The name of the file to load
@type filename: C{str}
"""
if w != None:
w = self.mm2pos(w)
if h != None:
h = self.mm2pos(h)
self.drawings.append(('I',self.mm2pos(self.xorigin+x),self.mm2pos(self.paperheight-(self.yorigin+y)),
w,h,filename))
def tekst(self,x,y,text,font='Helvetica',fsize=12,align=0,gray=0):
"""
Write some tekst to the canvas
Coordinates are relative to origin
@param x: X point to start (depending on align)
@type x: C{int}
@param y: Y of lower point of tekst
@type y: C{int}
@param text: The actual text to show
@type text: C{str}
@param font: Font number to draw (LaTeX ??)
@type font: C{int}
@param fsize: The size of the font in 1/72"
@type fsize: C{int}
@param align: Align the tekst left(0),centre(1) or right(2)
@type align: C{int}
"""
self.drawings.append(('T',self.mm2pos(self.xorigin+x), self.mm2pos(self.paperheight-(self.yorigin+y)), text,font,fsize,align,gray))
def circle(self,x,y,rad,style=0,dikte=1,gray=0):
"""
Draw a circle on centre (x,y) with the given radius, relative to origin
@param x: x Centre of circle
@type x: C{int}
@param y: y Centre of circle
@type y: C{int}
@param rad: Radius circle
@type rad: C{int}
@param style: The style of the circle 0=SOLID
@type style: C{int}
@param dikte: Thickness of the circle in 1/72"
@type dikte: C{int}
"""
self.drawings.append(('C',self.mm2pos(self.xorigin+x), self.mm2pos(self.paperheight-(self.yorigin+y)),self.mm2pos(rad),style,dikte,gray))
def mm2pos(self,mm):
"""
Calculate mm to xfig units
self.resolution is expressed in units/xfig-inch.
@param mm: distance in mm
@type mm: C{float}
@return: The number of fig units for the given distance
@rtype: C{int}
"""
return mm*self.resolution/25.4
def save(self,pdf):
"""
Write the drawing to a file
@param filename: The complete filename to which the drawing has to be written
@type filename: C{str}
"""
for cmd in self.drawings:
if cmd[0] == 'L':
# line x,y,x2,y2,style,dikte,gray=0
pdf.setLineWidth(cmd[6])
pdf.setStrokeGray(cmd[7])
if cmd[5] == 0: # solid
pdf.setDash()
else: # 2 == dashed
pdf.setDash(1,2)
#canvas.setDash(self, array=[], phase=0)
pdf.line(cmd[1],cmd[2],cmd[3],cmd[4])
elif cmd[0] == 'C': # circle(self,x,y,rad,style=0,dikte=1,gray=0):
pdf.setLineWidth(cmd[5])
pdf.setStrokeGray(cmd[6])
if cmd[4] == 0: # solid
pdf.setDash()
else: # 2 == dashed
pdf.setDash(1,2)
pdf.circle(cmd[1],cmd[2],cmd[3])
elif cmd[0] == 'T': # tekst(self,x,y,text,font=0,fsize=12,align=0,gray=0):
#print(cmd[4],cmd[5])
pdf.setFont(cmd[4],cmd[5])
pdf.setStrokeGray(cmd[7])
if cmd[6] == 0: # left align
pdf.drawString(cmd[1],cmd[2], cmd[3])
elif cmd[6] == 1: # centre
pdf.drawCentredString(cmd[1],cmd[2], cmd[3])
else: #cmd[6] == 2:
pdf.drawRightString( cmd[1],cmd[2], cmd[3])
elif cmd[0] == 'I': # image(self,filename,x,y,w = None,h = None)
pdf.drawImage(cmd[5],cmd[1],cmd[2],cmd[3],cmd[4])
else:
error("unknown command")
self.drawings=[]
pdf.showPage()
| Python |
""" Copyright (C) 2014 T.Hofkamp
This file is part of FilofaxDIY.
FilofaxDIY 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.
FilofaxDIY 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 FilofaxDIY. If not, see <http://www.gnu.org/licenses/>.
"""
import locale
import datetime
from xfiglib import pdfout # name is not logical
import argparse
from reportlab.pdfgen import canvas
import reportlab.lib.pagesizes
from reportlab.lib.units import cm
FILOFAXDIYVERSION="https://code.google.com/p/filofax-diy/" # should be from versioning system, but how can I do this ????
class filofax:
def __init__(self,language,font,lineheight,paper,orient,filename,filofax):
if language != None:
locale.setlocale(locale.LC_TIME,language)
#statics
self.font= font # which font to use
self.headerfont=self.font # header font will be the same
self.headerfsize=10 # fontsize in 1/72" for header on top of page
self.headerheight=11 # height in mm for header on top of page
self.mdayfont=self.font # monthday font (1..31)
self.mdayfsize=19
self.dayofweekfont=self.font # name of the weekday font (eg monday)
self.dayofweekfsize=9
#self.agendawidth=95.0
#self.agendaheight=171.0
self.agendawidth=filofax[0] # how large is one agenda page
self.agendaheight=filofax[1]
self.nrholes = filofax[2] # nr of holes / 2, rounded up
self.holesoffset = filofax[3] # offset from middle
self.holesstep = filofax[4] # space between holes
self.lineheight = lineheight # space between lines in one agenda day
# create the reportlab pdf stream
self.canvas = canvas.Canvas(filename,pageCompression=1,verbosity=0) #,pagesize=A4,bottumup = 0,pageCompression=0,
if orient == 'Portrait':
self.canvas.setPageSize(reportlab.lib.pagesizes.portrait(paper))
else:
self.canvas.setPageSize(reportlab.lib.pagesizes.landscape(paper))
self.canvas.setAuthor('T.Hofkamp')
self.canvas.setCreator(FILOFAXDIYVERSION)
self.canvas.setTitle('Agenda')
self.canvas.setSubject('FilofaxDIY printable agenda')
"""
personal 95x171 holes 5.5mm at 5mm from edge at 26,45,64mm from midle
A5 148x210
pocket 81x120
a4 210x297
mini 67x105
"""
self.cutlinelength = 10 # the length of the cutlines between the agenda pages
self.outermargin = 5 # margin at the edge
self.innermargin = 10 # margin at the holes
""" is now filled with the program, depending on the size of the paper
Try to fit as many agenda-pages as you can, on one paper page.
# the next 5 vars can be derived from papersize and agendapagesize
self.agendapagesperpage = 3 # xcount =3,ycount=1 count=xcount*ycount
self.evenpageorigins = [(6.0, 19.5), (101.0, 19.5), (196.0, 19.5)]
self.oddpageorigins = [(196.0, 19.5), (101.0, 19.5), (6.0, 19.5)]
self.cutlinesx = (6,101,196,291)
self.cutlinesy = (19.5,190.5)
"""
self.paperwidth = self.canvas._pagesize[0] * 10 / cm # calculate the width in mm from the choosen paper parameter
self.paperheight = self.canvas._pagesize[1] * 10 / cm # calculate the height in mm from the choosen paper parameter
xcount = int(self.paperwidth / self.agendawidth)
ycount = int(self.paperheight / self.agendaheight)
self.agendapagesperpage = xcount * ycount
# assert(self.agendapagesperpage > 0)
startx = (self.paperwidth - xcount * self.agendawidth) / 2.0 # where does the first agendapage start
starty = (self.paperheight - ycount * self.agendaheight) / 2.0
self.cutlinesx = []
for x in range(xcount + 1):
self.cutlinesx.append(startx + x * self.agendawidth)
self.cutlinesy = []
for y in range(ycount + 1):
self.cutlinesy.append(starty + y * self.agendaheight)
self.evenpageorigins = [] # the origins of the agenda pages on the page (mm) left to right, and down
self.oddpageorigins = [] # almost equal to the evenpageorigins, only from right to left, and then down
for y in range(ycount):
for x in range(xcount):
self.evenpageorigins.append((self.cutlinesx[x],self.cutlinesy[y]))
for x in range(xcount-1,-1,-1):
self.oddpageorigins.append((self.cutlinesx[x],self.cutlinesy[y]))
#dynamic vars
self.currentonevenpage = False # true or false,depending on which side of paper
self.currentagendapage = self.agendapagesperpage - 1 # point to last agenda page
# because reportlab pdf, cannot write to two pages at the same time, all draw actions are bufferd
# with pdfout object, evenpage and oddpage contains the buffered draw action
self.evenpage = None # the buffers
self.oddpage = None
self.currentpage = self.oddpage # point to the current object for buffering
def titlepage(self,year):
"""
Make the title page
Maybe add GLPv3 logo in the future
@param year: The year for which the agenda is created
@type year: C(int)
"""
self.formfeed() # start on a new agenda page
self.assertevenpage()
# Show the year at 1/3 of page
self.currentpage.tekst(self.outermargin+(self.agendawidth-self.innermargin-self.outermargin)/2,self.agendaheight/3,year,self.font,48,1)
# show the program name and version at 7/8 of the page
self.currentpage.tekst(self.outermargin+(self.agendawidth-self.innermargin-self.outermargin)/2,self.agendaheight*7/8,FILOFAXDIYVERSION,self.font,8,1)
self.currentpage.image('gplv3.jpg',self.innermargin+5,self.agendaheight-10,7.38,3.77)
def calender(self,year):
pass
def monthplanner(self):
pass
def drawday(self,day,height,width):
"""
Draw just one day, Linespacing is determined by self.lineheight, except when it is 0, no lines are drawn
On the bottom a thick line is draw as seperation to the next day or end of agenda paper
@param day: The day for which to draw the agenda
@type day: C(datetime.date)
@param height: The height to draw the day in (mm)
@param height: C(float)
@param width: The height to draw the day in (mm)
@param width: C(float)
"""
leftindent = 0
rightindent = 0
if self.currentonevenpage:
# evenpage,when holes are on left
self.currentpage.tekst(width,5,str(int(day.strftime("%d"))),self.mdayfont,self.mdayfsize,2) #day of the month
self.currentpage.tekst(width - 10,3,day.strftime("%A"),self.dayofweekfont,self.dayofweekfsize,2) # day of the week
self.currentpage.tekst(0,3,day.strftime("%j"),self.dayofweekfont,self.dayofweekfsize,0)
rightindent = 10
else:
# oddpage,when holes are on right
self.currentpage.tekst(0,5,str(int(day.strftime("%d"))),self.mdayfont,self.mdayfsize,0)
self.currentpage.tekst(10,3,day.strftime("%A"),self.dayofweekfont,self.dayofweekfsize,0)
self.currentpage.tekst(width,3,day.strftime("%j"),self.dayofweekfont,self.dayofweekfsize,2)
leftindent = 10
if self.lineheight > 0:
i = 6
while i + self.lineheight < height - 2:
self.currentpage.line(leftindent,i,width-leftindent-rightindent,0,2,0.5)
i = i + self.lineheight
if i > 10:
leftindent = 0
rightindent = 0
self.currentpage.line(0,height - 2,width,0,0,2)
def weekon2pages(self,day):
"""
@param day: C(datetime.date)
Draw the week from "day", to the agenda pages. 3 times a workday, and 2 workdays, and 2 weekend days
In the future, check the height for using it with other formats
Collect month names in order to fill header
"""
wdayheight = 52.0
wendheight = wdayheight / 2
width = self.agendawidth - self.innermargin - self.outermargin
self.formfeed()
self.assertoddpage()
self.currentpage.pushorigin(self.outermargin,0)
# header
self.currentpage.line(0,self.headerheight - 2,width,0,0,2)
self.currentpage.tekst(0,7,day.strftime("%Y"),self.headerfont,self.headerfsize,0) #year
self.currentpage.tekst(10,7,day.strftime("%B"),self.headerfont,self.headerfsize,0) # month
self.currentpage.tekst(width,7,day.strftime("WEEK %W"),self.headerfont,self.headerfsize,2) # weeknr
self.currentpage.pushorigin(0,self.headerheight)
# monday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.pushorigin(0,wdayheight)
# tuesday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.pushorigin(0,wdayheight)
# wednesday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.poporigin()
self.currentpage.poporigin()
self.currentpage.poporigin()
self.currentpage.poporigin()
self.formfeed()
self.currentpage.pushorigin(self.innermargin,0)
# header
self.currentpage.line(0,self.headerheight - 2,width,0,0,2)
self.currentpage.tekst(width,7,day.strftime("%Y"),self.headerfont,self.headerfsize,2) #year
self.currentpage.tekst(width - 10,7,day.strftime("%B"),self.headerfont,self.headerfsize,2) # month
self.currentpage.tekst(0,7,day.strftime("WEEK %W"),self.headerfont,self.headerfsize,0) # weeknr
self.currentpage.pushorigin(0,self.headerheight)
# thursday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.pushorigin(0,wdayheight)
# friday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.pushorigin(0,wdayheight)
# saturday
self.drawday(day,wendheight,width)
day += datetime.date.resolution
self.currentpage.pushorigin(0,wendheight)
# sunday
self.drawday(day,wendheight,width)
#day += datetime.date.resolution
self.currentpage.poporigin()
self.currentpage.poporigin()
self.currentpage.poporigin()
self.currentpage.poporigin()
self.currentpage.poporigin()
# header doen
def weekon6pages(self,day):
"""
@param day: C(datetime.date)
Draw the week from "day", to the agenda pages. 5 times a workday, and 1x 2 days for the weekend
In the future, check the height for using it with other formats
It would be better to use more functions, eg header()
"""
# assert(dayofweek(day) == monday)
# future collect month names in order to fill header
wdayheight = 52.0 * 3
wendheight = wdayheight / 2
width = self.agendawidth - self.innermargin - self.outermargin
self.formfeed()
self.assertoddpage()
self.currentpage.pushorigin(self.outermargin,0)
# header
self.currentpage.line(0,self.headerheight - 2,width,0,0,2)
self.currentpage.tekst(0,7,day.strftime("%Y"),self.headerfont,self.headerfsize,0) #year
self.currentpage.tekst(10,7,day.strftime("%B"),self.headerfont,self.headerfsize,0) # month
self.currentpage.tekst(width,7,day.strftime("WEEK %W"),self.headerfont,self.headerfsize,2) # weeknr
self.currentpage.pushorigin(0,self.headerheight)
# monday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.poporigin()
self.formfeed()
self.currentpage.pushorigin(self.innermargin,0)
# header
self.currentpage.line(0,self.headerheight - 2,width,0,0,2)
self.currentpage.tekst(width,7,day.strftime("%Y"),self.headerfont,self.headerfsize,2) #year
self.currentpage.tekst(width - 10,7,day.strftime("%B"),self.headerfont,self.headerfsize,2) # month
self.currentpage.tekst(0,7,day.strftime("WEEK %W"),self.headerfont,self.headerfsize,0) # weeknr
self.currentpage.pushorigin(0,self.headerheight)
# tuesday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.pushorigin(0,wdayheight)
self.currentpage.poporigin()
self.formfeed()
self.currentpage.pushorigin(self.outermargin,0)
# header
self.currentpage.line(0,self.headerheight - 2,width,0,0,2)
self.currentpage.tekst(0,7,day.strftime("%Y"),self.headerfont,self.headerfsize,0) #year
self.currentpage.tekst(10,7,day.strftime("%B"),self.headerfont,self.headerfsize,0) # month
self.currentpage.tekst(width,7,day.strftime("WEEK %W"),self.headerfont,self.headerfsize,2) # weeknr
self.currentpage.pushorigin(0,self.headerheight)
# wednesday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.poporigin()
self.formfeed()
self.currentpage.pushorigin(self.innermargin,0)
# header
self.currentpage.line(0,self.headerheight - 2,width,0,0,2)
self.currentpage.tekst(width,7,day.strftime("%Y"),self.headerfont,self.headerfsize,2) #year
self.currentpage.tekst(width - 10,7,day.strftime("%B"),self.headerfont,self.headerfsize,2) # month
self.currentpage.tekst(0,7,day.strftime("WEEK %W"),self.headerfont,self.headerfsize,0) # weeknr
self.currentpage.pushorigin(0,self.headerheight)
# thurseday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.pushorigin(0,wdayheight)
self.currentpage.poporigin()
self.formfeed()
self.currentpage.pushorigin(self.outermargin,0)
# header
self.currentpage.line(0,self.headerheight - 2,width,0,0,2)
self.currentpage.tekst(0,7,day.strftime("%Y"),self.headerfont,self.headerfsize,0) #year
self.currentpage.tekst(10,7,day.strftime("%B"),self.headerfont,self.headerfsize,0) # month
self.currentpage.tekst(width,7,day.strftime("WEEK %W"),self.headerfont,self.headerfsize,2) # weeknr
self.currentpage.pushorigin(0,self.headerheight)
# friday
self.drawday(day,wdayheight,width)
day += datetime.date.resolution
self.currentpage.poporigin()
self.formfeed()
self.currentpage.pushorigin(self.innermargin,0)
# header
self.currentpage.line(0,self.headerheight - 2,width,0,0,2)
self.currentpage.tekst(width,7,day.strftime("%Y"),self.headerfont,self.headerfsize,2) #year
self.currentpage.tekst(width - 10,7,day.strftime("%B"),self.headerfont,self.headerfsize,2) # month
self.currentpage.tekst(0,7,day.strftime("WEEK %W"),self.headerfont,self.headerfsize,0) # weeknr
self.currentpage.pushorigin(0,self.headerheight)
# saturday
self.drawday(day,wendheight,width)
day += datetime.date.resolution
self.currentpage.pushorigin(0,wendheight)
# sunday
self.drawday(day,wendheight,width)
#day += datetime.date.resolution
self.currentpage.poporigin()
self.currentpage.poporigin()
def punchholes(self):
""" Draw the punch hole on one agenda page
Using parameter self.nrholes,holestep and holeoffset. This defines just the half of the holes, from the middle.
Because holes are mirrored to the center. nrholes is the half of the total number of holes, rounded UP
If holeoffset = 0, just one hole is draw
"""
# origin is top left of page
# maybe a parameter which kind of holes 1,2,3,4
middle = self.agendaheight/2
if self.currentonevenpage:
self.currentpage.line(10,middle,5,0,2)
else:
self.currentpage.line(self.agendawidth-10,middle,-5,0,2)
for i in range(self.nrholes):
hole = i*self.holesstep+self.holesoffset
if self.currentonevenpage:
self.currentpage.circle(5,middle+hole,2.75,1,2) # hole 5.5mm on the left side
if hole > 0:
self.currentpage.circle(5,middle-hole,2.75,1,2)
else:
self.currentpage.circle(self.agendawidth-5,middle+hole,2.75,1,2) # holes on the right side
if hole > 0:
self.currentpage.circle(self.agendawidth-5,middle-hole,2.75,1,2)
def drawcutlines(self,paper):
"""
Draw the line between the agenda pages. The length of the line is from self.cutlinelength.
The positions are calculated at __init__() from the give papersize. Only the lines at the edge are drawn.
@param paper: Object pdfout, representing one side of a paper
@type paper: L(pdfout.pdfout)
"""
for x in self.cutlinesx:
paper.line(x,self.cutlinesy[0]-self.cutlinelength/2,0,self.cutlinelength)
paper.line(x,self.cutlinesy[-1]-self.cutlinelength/2,0,self.cutlinelength)
for y in self.cutlinesy:
paper.line(self.cutlinesx[0]-self.cutlinelength/2,y,self.cutlinelength,0)
paper.line(self.cutlinesx[-1]-self.cutlinelength/2,y,self.cutlinelength,0)
def formfeed(self):
"""
Make sure the agenda page is free to be filled, Feed to the next free page. When the physical printer
paper is full, flush out to file-pdf, and open two empty ones.
evenpage (page 0) comes before oddpage (page 1), usual people do this the other way round
"""
# make sure there is a empty page
if self.currentonevenpage: # if we are on even page, just change to other side
self.currentonevenpage = False
self.currentpage = self.oddpage
self.oddpage.setorigin(self.oddpageorigins[self.currentagendapage][0],self.oddpageorigins[self.currentagendapage][1])
else: # we need a new page
self.currentonevenpage = True
self.currentagendapage += 1
if self.currentagendapage == self.agendapagesperpage: # check if paper is full
if self.evenpage != None:
self.evenpage.save(self.canvas)
if self.oddpage != None:
self.oddpage.save(self.canvas)
self.evenpage = pdfout.pdfout(self.paperwidth,self.paperheight)
self.drawcutlines(self.evenpage)
self.oddpage = pdfout.pdfout(self.paperwidth,self.paperheight)
self.drawcutlines(self.oddpage)
self.currentagendapage = 0
self.currentpage = self.evenpage # start on
self.evenpage.setorigin(self.evenpageorigins[self.currentagendapage][0],self.evenpageorigins[self.currentagendapage][1])
self.punchholes() # should be different, multiple holes are punched..... on same paper, not good
def assertoddpage(self):
""" make sure we are on an odd page (left side of agenda)
Good for starting out with an agenda (eg monday)
"""
if self.currentonevenpage:
self.formfeed()
def assertevenpage(self):
""" make sure we are on an even page
Used for the title page
"""
if not self.currentonevenpage:
self.formfeed()
def close(self):
""" write out any object to the pdf-file, and close the pdf stream
"""
if self.evenpage != None:
self.evenpage.save(self.canvas)
self.evenpage = None
if self.oddpage != None:
self.oddpage.save(self.canvas)
self.oddpage = None
self.canvas.save()
allowedpapers = {
"A4":reportlab.lib.pagesizes.A4,
"A3":reportlab.lib.pagesizes.A3,
"A2":reportlab.lib.pagesizes.A2,
"A1":reportlab.lib.pagesizes.A1,
"A0":reportlab.lib.pagesizes.A0,
"letter":reportlab.lib.pagesizes.letter,
"legal":reportlab.lib.pagesizes.legal,
"elevenSeventeen":reportlab.lib.pagesizes.elevenSeventeen,
"B5":reportlab.lib.pagesizes.B5,
"B4":reportlab.lib.pagesizes.B4,
"B3":reportlab.lib.pagesizes.B3,
"B2":reportlab.lib.pagesizes.B2,
"B1":reportlab.lib.pagesizes.B1,
"B0":reportlab.lib.pagesizes.B0}
# width,height,nrholes,offset,distancebetweenholes
agendasizes = {
'A4':(210,297,2,0,50), # holes are not good
'A5':(148,210,3,19,19), # holes not sure
'Personal':(95,171,3,23,19),
'Compact':(95,171,3,0,19), # holes not sure
'Pocket':(81,120,3,0,19), # holes not sure
'Mini':(67,105,3,0,40)} # center hole is twice,holes not sure
fonts = (
"Courier",
"Courier-Bold"
"Courier-BoldOblique",
"Courier-Oblique",
"Helvetica",
"Helvetica-Bold",
"Helvetica-BoldOblique",
"Helvetica-Oblique",
"Symbol",
"Times-Bold",
"Times-BoldItalic",
"Times-Italic",
"Times-Roman",
"ZapfDingbats" )
parser = argparse.ArgumentParser(description='Create a FilofaxDIY printable agenda')
parser.add_argument('--landscape',dest='orient',action='store_const',const='Landscape')
parser.add_argument('--portrait',dest='orient',action='store_const',const='Portrait')
parser.add_argument('--paper',default='letter',choices=allowedpapers)
parser.add_argument('--font',default='Helvetica',choices=fonts)
#parser.add_argument('--filofax',default='Personal',choices=agendasizes)
parser.add_argument('--filofax',default='Personal',choices=('Personal'))
parser.add_argument('--format',default='weekon2pages',choices=('weekon2pages','weekon6pages'))
parser.add_argument('--lineheight',default=4,type=int,choices=range(11))
parser.add_argument('--year',type=int,default=datetime.date.today().year + 1,choices=range(2014,2025))
#parser.add_argument('--language',choices=('en_US.UTF8','nl_NL.UTF8','fy_NL.UTF8'))
parser.add_argument('--language',type=str)
args = parser.parse_args()
if args.orient == None:
args.orient = 'Portrait'
#print(args)
#-language nl_NL
#of en_US of fy_NL
"""
-Landscape
-Portrait
-paper A4
-font Timesnewroman
&-format weekon2pages | weekon6pages
-lineheight 4
-filofax personal
&-year 2015
"""
#nextyear = datetime.date.today().year + 1
nextnewyearsday = datetime.date(args.year,1,1)
lastmondayofyear = nextnewyearsday - nextnewyearsday.weekday() * datetime.date.resolution
day = lastmondayofyear
outputfilename = "{size}_{year}_{locale}_{format}.pdf".format(size = args.filofax,year = args.year,locale = args.language,format = args.format)
#print(outputfilename)
agenda = filofax(args.language,args.font,args.lineheight,allowedpapers[args.paper],args.orient,outputfilename,agendasizes[args.filofax])
agenda.titlepage(str(args.year))
while day.year <= args.year:
if args.format == 'weekon2pages':
agenda.weekon2pages(day)
else:
agenda.weekon6pages(day)
day += datetime.date.resolution * 7
agenda.close()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtGui
from mainwindow import *
import urllib
import urllib2
import csv
import datetime
print "Welcome to the FINRA Regulation SHO Data Harvester"
#TODO LIST
#Error handling for http
#Options for updated vs not
class Harvester(QtGui.QWidget, Ui_MainWindow):
baseurl = "http://regsho.finra.org/"
def __init__(self, ui):
super(Harvester, self).__init__()
self.ui = ui
self.setConnect()
def setConnect(self):
self.ui.cbAllMkts.stateChanged.connect(self.allMkts)
self.ui.harvestButton.clicked[bool].connect(self.harvest)
def allMkts(self, state):
if state == QtCore.Qt.Checked:
self.ui.cbNasdaq.setChecked(True)
self.ui.cbNYSE.setChecked(True)
self.ui.cbADF.setChecked(True)
self.ui.cbORF.setChecked(True)
def harvest(self, pressed):
includeNasdaq = False
includeNYSE = False
includeADF = False
includeORF = False
includeAll = False
if self.ui.cbAllMkts.isChecked() or self.ui.cbEverything.isChecked():
includeAll = True
if includeAll or self.ui.cbNasdaq.isChecked():
includeNasdaq = True
if includeAll or self.ui.cbNYSE.isChecked():
includeNYSE = True
if includeAll or self.ui.cbADF.isChecked():
includeADF = True
if includeAll or self.ui.cbORF.isChecked():
includeORF = True
if self.ui.cbEverything.isChecked():
self.startdatestring = "20110601"
self.enddatestring = datetime.date.today().strftime("%Y%m%d")
else:
self.startdatestring = self.ui.startDate.date().toString("yyyyMMdd")
self.enddatestring = self.ui.endDate.date().toString("yyyyMMdd")
self.startdate = datetime.date(int(self.startdatestring[0:4]), int(self.startdatestring[4:6]), int(self.startdatestring[6:8]))
self.enddate = datetime.date(int(self.enddatestring[0:4]), int(self.enddatestring[4:6]), int(self.enddatestring[6:8]))
#Swap dates if startdate is after enddate
if self.startdate > self.enddate:
self.temp = self.startdate
self.startdate = self.enddate
self.enddate = self.temp
self.maxdate = datetime.date.today()
if self.startdate > self.maxdate:
self.startdate = self.maxdate
if self.enddate > self.maxdate:
self.enddate = self.maxdate
self.dateCounter = self.startdate
while self.dateCounter <= self.enddate:
if self.dateCounter.weekday() == 5 or self.dateCounter.weekday() == 6:
self.dateCounter = self.dateCounter + datetime.timedelta(days=1)
continue
if includeNasdaq:
data = None
if self.ui.cbUseUpdated.isChecked():
self.fullurl = self.baseurl + "FNSQshvol" + self.dateCounter.strftime("%Y%m%d") + "X.txt"
data = self.openPage(self.fullurl)
if data == None:
self.fullurl = self.baseurl + "FNSQshvol" + self.dateCounter.strftime("%Y%m%d") + ".txt"
data = self.openPage(self.fullurl)
if data != None:
self.convertToCSV(data)
if includeNYSE:
data = None
if self.ui.cbUseUpdated.isChecked():
self.fullurl = self.baseurl + "FNYXshvol" + self.dateCounter.strftime("%Y%m%d") + "X.txt"
data = self.openPage(self.fullurl)
if data == None:
self.fullurl = self.baseurl + "FNYXshvol" + self.dateCounter.strftime("%Y%m%d") + ".txt"
data = self.openPage(self.fullurl)
if data != None:
self.convertToCSV(data)
if includeADF:
data = None
if self.ui.cbUseUpdated.isChecked():
self.fullurl = self.baseurl + "FNRAshvol" + self.dateCounter.strftime("%Y%m%d") + "X.txt"
data = self.openPage(self.fullurl)
if data == None:
self.fullurl = self.baseurl + "FNRAshvol" + self.dateCounter.strftime("%Y%m%d") + ".txt"
data = self.openPage(self.fullurl)
if data != None:
self.convertToCSV(data)
if includeORF:
data = None
if self.ui.cbUseUpdated.isChecked():
self.fullurl = self.baseurl + "FORFshvol" + self.dateCounter.strftime("%Y%m%d") + "X.txt"
data = self.openPage(self.fullurl)
if data == None:
self.fullurl = self.baseurl + "FORFshvol" + self.dateCounter.strftime("%Y%m%d") + ".txt"
data = self.openPage(self.fullurl)
if data != None:
self.convertToCSV(data)
self.dateCounter = self.dateCounter + datetime.timedelta(days=1)
def openPage(self, url):
#make the request using the request object as an argument, store response in a variable
try:
response = urllib2.urlopen(url)
#store request response in a string
html_string = response.read()
return html_string
except urllib2.HTTPError, exception_variable:
#prints the HTTP error code that was given
outFile = open("ErrorDates.txt", 'ab')
outFile.write(url + " " + str(exception_variable.code) + "\n")
return None
except urllib2.URLError, exception_variable:
#prints the reason for failure out to help debugging
outFile = open("ErrorDates.txt", 'ab')
outFile.write(url + " " + str(exception_variable.code) + "\n")
return None
def convertToCSV(self, datastring):
csv_string = datastring.replace('|', ',')
dataList = csv_string.split("\n")
#Clear header
dataList.pop(0)
if dataList:
if dataList[0].count(",") == 0:
return
#Clear item count
dataList.pop()
dataList.pop()
csvFilename = "Data.csv"
outFile = open(csvFilename, 'ab')
for item in dataList:
outFile.write(item)
def main():
#Set up GUI
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
hv = Harvester(ui)
sys.exit(app.exec_())
if __name__ == '__main__':
main()
| Python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Fri May 25 17:25:34 2012
# by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(398, 281)
self.centralWidget = QtGui.QWidget(MainWindow)
self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
self.cbNasdaq = QtGui.QCheckBox(self.centralWidget)
self.cbNasdaq.setGeometry(QtCore.QRect(220, 80, 87, 20))
self.cbNasdaq.setTristate(False)
self.cbNasdaq.setObjectName(_fromUtf8("cbNasdaq"))
self.cbNYSE = QtGui.QCheckBox(self.centralWidget)
self.cbNYSE.setGeometry(QtCore.QRect(220, 110, 87, 20))
self.cbNYSE.setObjectName(_fromUtf8("cbNYSE"))
self.cbADF = QtGui.QCheckBox(self.centralWidget)
self.cbADF.setGeometry(QtCore.QRect(220, 140, 87, 20))
self.cbADF.setObjectName(_fromUtf8("cbADF"))
self.cbORF = QtGui.QCheckBox(self.centralWidget)
self.cbORF.setGeometry(QtCore.QRect(220, 170, 87, 20))
self.cbORF.setObjectName(_fromUtf8("cbORF"))
self.cbAllMkts = QtGui.QCheckBox(self.centralWidget)
self.cbAllMkts.setGeometry(QtCore.QRect(220, 50, 101, 20))
self.cbAllMkts.setObjectName(_fromUtf8("cbAllMkts"))
self.startDate = QtGui.QDateEdit(self.centralWidget)
self.startDate.setGeometry(QtCore.QRect(90, 20, 110, 25))
self.startDate.setDate(QtCore.QDate(2012, 5, 20))
self.startDate.setMaximumDate(QtCore.QDate(7999, 12, 31))
self.startDate.setMinimumDate(QtCore.QDate(2011, 6, 1))
self.startDate.setCurrentSection(QtGui.QDateTimeEdit.MonthSection)
self.startDate.setObjectName(_fromUtf8("startDate"))
self.endDate = QtGui.QDateEdit(self.centralWidget)
self.endDate.setGeometry(QtCore.QRect(90, 70, 110, 25))
self.endDate.setDate(QtCore.QDate(2012, 5, 21))
self.endDate.setMaximumDate(QtCore.QDate(7999, 12, 31))
self.endDate.setMinimumDate(QtCore.QDate(2011, 6, 1))
self.endDate.setObjectName(_fromUtf8("endDate"))
self.label = QtGui.QLabel(self.centralWidget)
self.label.setGeometry(QtCore.QRect(20, 20, 71, 16))
self.label.setObjectName(_fromUtf8("label"))
self.label_2 = QtGui.QLabel(self.centralWidget)
self.label_2.setGeometry(QtCore.QRect(20, 70, 71, 16))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.cbEverything = QtGui.QCheckBox(self.centralWidget)
self.cbEverything.setGeometry(QtCore.QRect(220, 20, 161, 20))
self.cbEverything.setObjectName(_fromUtf8("cbEverything"))
self.harvestButton = QtGui.QPushButton(self.centralWidget)
self.harvestButton.setGeometry(QtCore.QRect(50, 130, 114, 32))
self.harvestButton.setObjectName(_fromUtf8("harvestButton"))
self.cbUseUpdated = QtGui.QCheckBox(self.centralWidget)
self.cbUseUpdated.setGeometry(QtCore.QRect(220, 200, 141, 20))
self.cbUseUpdated.setObjectName(_fromUtf8("cbUseUpdated"))
self.label_3 = QtGui.QLabel(self.centralWidget)
self.label_3.setGeometry(QtCore.QRect(20, 170, 191, 31))
self.label_3.setObjectName(_fromUtf8("label_3"))
MainWindow.setCentralWidget(self.centralWidget)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 398, 22))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.mainToolBar = QtGui.QToolBar(MainWindow)
self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
self.statusBar = QtGui.QStatusBar(MainWindow)
self.statusBar.setObjectName(_fromUtf8("statusBar"))
MainWindow.setStatusBar(self.statusBar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "FINRA Regulation SHO Data Harvester", None, QtGui.QApplication.UnicodeUTF8))
self.cbNasdaq.setText(QtGui.QApplication.translate("MainWindow", "NASDAQ", None, QtGui.QApplication.UnicodeUTF8))
self.cbNYSE.setText(QtGui.QApplication.translate("MainWindow", "NYSE", None, QtGui.QApplication.UnicodeUTF8))
self.cbADF.setText(QtGui.QApplication.translate("MainWindow", "ADF", None, QtGui.QApplication.UnicodeUTF8))
self.cbORF.setText(QtGui.QApplication.translate("MainWindow", "ORF", None, QtGui.QApplication.UnicodeUTF8))
self.cbAllMkts.setText(QtGui.QApplication.translate("MainWindow", "All Markets", None, QtGui.QApplication.UnicodeUTF8))
self.startDate.setDisplayFormat(QtGui.QApplication.translate("MainWindow", "MM/dd/yyyy", None, QtGui.QApplication.UnicodeUTF8))
self.endDate.setDisplayFormat(QtGui.QApplication.translate("MainWindow", "MM/dd/yyyy", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("MainWindow", "Start Date:", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("MainWindow", "End Date:", None, QtGui.QApplication.UnicodeUTF8))
self.cbEverything.setText(QtGui.QApplication.translate("MainWindow", "Just grab everything", None, QtGui.QApplication.UnicodeUTF8))
self.harvestButton.setText(QtGui.QApplication.translate("MainWindow", "Harvest Data", None, QtGui.QApplication.UnicodeUTF8))
self.cbUseUpdated.setText(QtGui.QApplication.translate("MainWindow", "Use updated file", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("MainWindow", "*Earliest date is 06/01/2011", None, QtGui.QApplication.UnicodeUTF8))
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = getCurrentFolder(self.request.get("CurrentFolder",""))
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
"Minified version of the document.domain automatic fix script (#1919)."
"The original script can be found at _dev/domain_fix_template.js"
return """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? * " < > and control characters
return re.sub( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder or '\\' in currentFolder:
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = getCurrentFolder(self.request.get("CurrentFolder",""))
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? * " < > and control characters
return re.sub( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder or '\\' in currentFolder:
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
files += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(someObject),
os.path.getsize(someObjectPath)
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
try:
permissions = Config.ChmodOnFolderCreate
if not permissions:
os.makedirs(folderPath)
except AttributeError: #ChmodOnFolderCreate undefined
permissions = 0755
if permissions:
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%04d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
doChmod = False
try:
doChmod = Config.ChmodOnUpload
permissions = Config.ChmodOnUpload
except AttributeError: #ChmodOnUpload undefined
doChmod = True
permissions = 0755
if ( doChmod ):
oldumask = os.umask(0)
os.chmod( newFilePath, permissions )
os.umask( oldumask )
newFileUrl = self.webUserFilesFolder + currentFolder + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 203, customMsg = "Extension not allowed" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
"Minified version of the document.domain automatic fix script (#1919)."
"The original script can be found at _dev/domain_fix_template.js"
return """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| Python |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# After file is uploaded, sometimes it is required to change its permissions
# so that it was possible to access it at the later time.
# If possible, it is recommended to set more restrictive permissions, like 0755.
# Set to 0 to disable this feature.
# Note: not needed on Windows-based servers.
ChmodOnUpload = 0755
# See comments above.
# Used when creating folders that does not exist.
ChmodOnFolderCreate = 0755
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
files += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(someObject),
os.path.getsize(someObjectPath)
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
try:
permissions = Config.ChmodOnFolderCreate
if not permissions:
os.makedirs(folderPath)
except AttributeError: #ChmodOnFolderCreate undefined
permissions = 0755
if permissions:
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%04d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
doChmod = False
try:
doChmod = Config.ChmodOnUpload
permissions = Config.ChmodOnUpload
except AttributeError: #ChmodOnUpload undefined
doChmod = True
permissions = 0755
if ( doChmod ):
oldumask = os.umask(0)
os.chmod( newFilePath, permissions )
os.umask( oldumask )
newFileUrl = self.webUserFilesFolder + currentFolder + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 203, customMsg = "Extension not allowed" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# After file is uploaded, sometimes it is required to change its permissions
# so that it was possible to access it at the later time.
# If possible, it is recommended to set more restrictive permissions, like 0755.
# Set to 0 to disable this feature.
# Note: not needed on Windows-based servers.
ChmodOnUpload = 0755
# See comments above.
# Used when creating folders that does not exist.
ChmodOnFolderCreate = 0755
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the integration file for Python.
"""
import cgi
import os
import re
import string
def escape(text, replace=string.replace):
"""Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
text = replace(text, "'", ''')
return text
# The FCKeditor class
class FCKeditor(object):
def __init__(self, instanceName):
self.InstanceName = instanceName
self.BasePath = '/fckeditor/'
self.Width = '100%'
self.Height = '200'
self.ToolbarSet = 'Default'
self.Value = '';
self.Config = {}
def Create(self):
return self.CreateHtml()
def CreateHtml(self):
HtmlValue = escape(self.Value)
Html = ""
if (self.IsCompatible()):
File = "fckeditor.html"
Link = "%seditor/%s?InstanceName=%s" % (
self.BasePath,
File,
self.InstanceName
)
if (self.ToolbarSet is not None):
Link += "&Toolbar=%s" % self.ToolbarSet
# Render the linked hidden field
Html += "<input type=\"hidden\" id=\"%s\" name=\"%s\" value=\"%s\" style=\"display:none\" />" % (
self.InstanceName,
self.InstanceName,
HtmlValue
)
# Render the configurations hidden field
Html += "<input type=\"hidden\" id=\"%s___Config\" value=\"%s\" style=\"display:none\" />" % (
self.InstanceName,
self.GetConfigFieldString()
)
# Render the editor iframe
Html += "<iframe id=\"%s\__Frame\" src=\"%s\" width=\"%s\" height=\"%s\" frameborder=\"0\" scrolling=\"no\"></iframe>" % (
self.InstanceName,
Link,
self.Width,
self.Height
)
else:
if (self.Width.find("%%") < 0):
WidthCSS = "%spx" % self.Width
else:
WidthCSS = self.Width
if (self.Height.find("%%") < 0):
HeightCSS = "%spx" % self.Height
else:
HeightCSS = self.Height
Html += "<textarea name=\"%s\" rows=\"4\" cols=\"40\" style=\"width: %s; height: %s;\" wrap=\"virtual\">%s</textarea>" % (
self.InstanceName,
WidthCSS,
HeightCSS,
HtmlValue
)
return Html
def IsCompatible(self):
if (os.environ.has_key("HTTP_USER_AGENT")):
sAgent = os.environ.get("HTTP_USER_AGENT", "")
else:
sAgent = ""
if (sAgent.find("MSIE") >= 0) and (sAgent.find("mac") < 0) and (sAgent.find("Opera") < 0):
i = sAgent.find("MSIE")
iVersion = float(sAgent[i+5:i+5+3])
if (iVersion >= 5.5):
return True
return False
elif (sAgent.find("Gecko/") >= 0):
i = sAgent.find("Gecko/")
iVersion = int(sAgent[i+6:i+6+8])
if (iVersion >= 20030210):
return True
return False
elif (sAgent.find("Opera/") >= 0):
i = sAgent.find("Opera/")
iVersion = float(sAgent[i+6:i+6+4])
if (iVersion >= 9.5):
return True
return False
elif (sAgent.find("AppleWebKit/") >= 0):
p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE)
m = p.search(sAgent)
if (m.group(1) >= 522):
return True
return False
else:
return False
def GetConfigFieldString(self):
sParams = ""
bFirst = True
for sKey in self.Config.keys():
sValue = self.Config[sKey]
if (not bFirst):
sParams += "&"
else:
bFirst = False
if (sValue):
k = escape(sKey)
v = escape(sValue)
if (sValue == "true"):
sParams += "%s=true" % k
elif (sValue == "false"):
sParams += "%s=false" % k
else:
sParams += "%s=%s" % (k, v)
return sParams
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = getCurrentFolder(self.request.get("CurrentFolder",""))
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
"Minified version of the document.domain automatic fix script (#1919)."
"The original script can be found at _dev/domain_fix_template.js"
return """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? * " < > and control characters
return re.sub( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder or '\\' in currentFolder:
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = getCurrentFolder(self.request.get("CurrentFolder",""))
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? * " < > and control characters
return re.sub( '(?u)\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '/\\.(?![^.]*$)/', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '(?u)/\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[^\u0000-\u001f\u007f-\u009f]/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder or '\\' in currentFolder:
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
files += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(someObject),
os.path.getsize(someObjectPath)
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
try:
permissions = Config.ChmodOnFolderCreate
if not permissions:
os.makedirs(folderPath)
except AttributeError: #ChmodOnFolderCreate undefined
permissions = 0755
if permissions:
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%04d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
doChmod = False
try:
doChmod = Config.ChmodOnUpload
permissions = Config.ChmodOnUpload
except AttributeError: #ChmodOnUpload undefined
doChmod = True
permissions = 0755
if ( doChmod ):
oldumask = os.umask(0)
os.chmod( newFilePath, permissions )
os.umask( oldumask )
newFileUrl = self.webUserFilesFolder + currentFolder + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 203, customMsg = "Extension not allowed" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
"Minified version of the document.domain automatic fix script (#1919)."
"The original script can be found at _dev/domain_fix_template.js"
return """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| Python |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# After file is uploaded, sometimes it is required to change its permissions
# so that it was possible to access it at the later time.
# If possible, it is recommended to set more restrictive permissions, like 0755.
# Set to 0 to disable this feature.
# Note: not needed on Windows-based servers.
ChmodOnUpload = 0755
# See comments above.
# Used when creating folders that does not exist.
ChmodOnFolderCreate = 0755
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
files += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(someObject),
os.path.getsize(someObjectPath)
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
try:
permissions = Config.ChmodOnFolderCreate
if not permissions:
os.makedirs(folderPath)
except AttributeError: #ChmodOnFolderCreate undefined
permissions = 0755
if permissions:
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%04d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
doChmod = False
try:
doChmod = Config.ChmodOnUpload
permissions = Config.ChmodOnUpload
except AttributeError: #ChmodOnUpload undefined
doChmod = True
permissions = 0755
if ( doChmod ):
oldumask = os.umask(0)
os.chmod( newFilePath, permissions )
os.umask( oldumask )
newFileUrl = self.webUserFilesFolder + currentFolder + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 203, customMsg = "Extension not allowed" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# After file is uploaded, sometimes it is required to change its permissions
# so that it was possible to access it at the later time.
# If possible, it is recommended to set more restrictive permissions, like 0755.
# Set to 0 to disable this feature.
# Note: not needed on Windows-based servers.
ChmodOnUpload = 0755
# See comments above.
# Used when creating folders that does not exist.
ChmodOnFolderCreate = 0755
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This page lists the data posted by a form.
"""
import cgi
import os
# Tell the browser to render html
print "Content-Type: text/html"
print ""
try:
# Create a cgi object
form = cgi.FieldStorage()
except Exception, e:
print e
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Samples - Posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
"""
# This is the real work
print """
<h1>FCKeditor - Samples - Posted Data</h1>
This page lists all data posted by the form.
<hr>
<table border="1" cellspacing="0" id="outputSample">
<colgroup><col width="80"><col></colgroup>
<thead>
<tr>
<th>Field Name</th>
<th>Value</th>
</tr>
</thead>
"""
for key in form.keys():
try:
value = form[key].value
print """
<tr>
<th>%s</th>
<td><pre>%s</pre></td>
</tr>
""" % (key, value)
except Exception, e:
print e
print "</table>"
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2008 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Sample page.
"""
import cgi
import os
# Ensure that the fckeditor.py is included in your classpath
import fckeditor
# Tell the browser to render html
print "Content-Type: text/html"
print ""
# Document header
print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>FCKeditor - Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="robots" content="noindex, nofollow">
<link href="../sample.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>FCKeditor - Python - Sample 1</h1>
This sample displays a normal HTML form with an FCKeditor with full features
enabled.
<hr>
<form action="sampleposteddata.py" method="post" target="_blank">
"""
# This is the real work
try:
sBasePath = os.environ.get("SCRIPT_NAME")
sBasePath = sBasePath[0:sBasePath.find("_samples")]
oFCKeditor = fckeditor.FCKeditor('FCKeditor1')
oFCKeditor.BasePath = sBasePath
oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>"""
print oFCKeditor.Create()
except Exception, e:
print e
print """
<br>
<input type="submit" value="Submit">
</form>
"""
# For testing your environments
print "<hr>"
for key in os.environ.keys():
print "%s: %s<br>" % (key, os.environ.get(key, ""))
print "<hr>"
# Document footer
print """
</body>
</html>
"""
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.