Thursday, August 28, 2008

Django|A Cache Status View for Django

A Cache Status View for Django

Fredrik Lundh | August 2007

Since I'm running effbot.org on a shared server with limited memory for long-running processes, I'm quite interested in keeping track of my Django application's resource usage.

As part of this, I wanted an easy way to see what the memcached server I'm using for caching is up to, and came up with a a simple Django view that grabs the current status from the server.

Here's how to implement this on your own Django site:

The first step is to add an entry to the URL configuration file that points to the view module; something like:

urlpatterns = patterns('',
...
(r'^status/cache/$', 'mysite.memcached_status.view'),
)

Next, add the following view to your application, in the location you specified in the URL file:

# memcached_status.py

from django import http
from django.shortcuts import render_to_response
from django.conf import settings

import datetime, re

def view(request):

try:
import memcache
except ImportError:
raise http.Http404

if not (request.user.is_authenticated() and
request.user.is_staff):
raise http.Http404

# get first memcached URI
m = re.match(
"memcached://([.\w]+:\d+)", settings.CACHE_BACKEND
)
if not m:
raise http.Http404

host = memcache._Host(m.group(1))
host.connect()
host.send_cmd("stats")

class Stats:
pass

stats = Stats()

while 1:
line = host.readline().split(None, 2)
if line[0] == "END":
break
stat, key, value = line
try:
# convert to native type, if possible
value = int(value)
if key == "uptime":
value = datetime.timedelta(seconds=value)
elif key == "time":
value = datetime.datetime.fromtimestamp(value)
except ValueError:
pass
setattr(stats, key, value)

host.close_socket()

return render_to_response(
'memcached_status.html', dict(
stats=stats,
hit_rate=100 * stats.get_hits / stats.cmd_get,
time=datetime.datetime.now(), # server time
))

This, somewhat rough, view collects all statistics and other status variables from the memcached server in a stats object that's passed on to the template, and also calculates the hit rate.

Finally, to view the statistics, you need a suitable template. Here's a simple one that displays some of the variables, plus the hit rate:

<!-- templates/memcached_status.html -->

<h1>cache status</h1>

<ul>
<li>memory usage:
{{ stats.bytes|filesizeformat }}
<li>keys in cache:
{{ stats.curr_items }} of {{ stats.total_items }}
<li>cache hits:
{{ stats.get_hits }} of {{ stats.cmd_get }}:
<b>{{ hit_rate }}%</b>
<li>cache traffic:
{{ stats.bytes_read|filesizeformat }} in,
{{ stats.bytes_written|filesizeformat }} out
<li>uptime: {{ stats.uptime }}
</ul>

With this in place, restart the server and point your browser to the URL you specified in the URL configuration file (e.g. /status/cache), and provided that you're logged in as a "staff member", you'll get something like:

cache status

  • memory usage: 11.3 MB
  • keys in cache: 2867 of 14624
  • cache hits: 24025 of 38102: 63%
  • cache traffic: 62.0 MB in, 129.4 MB out
  • uptime: 2:18:54

The memory usage and hit rate figures are probably what's most interesting here.

When you use small caches, memcached has a tendency to grab noticably more memory than it's allowed to use, and usage grows somewhat over time even after the cache has filled up; I'm not sure if this is a bug, or if it's just including I/O buffers and other extra structures in the reported memory usage, but not in the cache size checks.

The hit rate depends a lot on your site's characteristics, user access patterns, and cache timeouts. The higher the value, the less work your Django server has to do. But there's a trade-off here, of course: you can reach nearly 100% hit rate by making the cache large enough and setting CACHE_MIDDLEWARE_SECONDS to something really big, but that'll make your server extremely static — even if you change things, old versions will keep being served from your cache, and will be stuck in caches around the net, for a very long time.

I recommend values from a few minutes for commonly updated sites to one hour for more static sites. For highly dynamic sites, with lots of user interaction, you should probably not use the cache middleware at all; let your views use the cache to store individual page fragments and database result sets instead.

More Statistics #

The full set of variables is described in the memcached protocol specification:

http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt

For your convenience, here's a template that displays all documented variables, without any formatting:

<pre>
pid {{ stats.pid }}
uptime {{ stats.uptime }}
time {{ stats.time }}
version {{ stats.version }}
rusage_user {{ stats.rusage_user }}
rusage_system {{ stats.rusage_system }}
curr_items {{ stats.curr_items }}
total_items {{ stats.total_items }}
bytes {{ stats.bytes }}
curr_connections {{ stats.curr_connections }}
total_connections {{ stats.total_connections }}
connection_structures {{ stats.connection_structures }}
cmd_get {{ stats.cmd_get }}
cmd_set {{ stats.cmd_set }}
get_hits {{ stats.get_hits }}
get_misses {{ stats.get_misses }}
evictions {{ stats.evictions }}
bytes_read {{ stats.bytes_read }}
bytes_written {{ stats.bytes_written }}
limit_maxbytes {{ stats.limit_maxbytes }}
</pre>

You can include this temporarily when tweaking the status template, or, if you like raw data, just use it instead of the nicely formatted version.

Wednesday, August 27, 2008

Health|感冒了不吃抗生素吃什么

风寒感冒起病较急,发热,畏寒,甚至寒战,无汗,鼻塞,流清涕,咳嗽,痰稀色白,头痛,周身酸痛,食欲减退,大小便正常,舌苔薄白等。风热感冒主要表现为 发烧重,但畏寒不明显,鼻子堵塞、流浊涕,咳嗽声重,或有黄痰粘稠,头痛,口渴喜饮,咽红、干、痛痒,大便干,小便黄,检查可见扁桃体红肿,咽部充血,舌 苔薄黄或黄厚,舌质红,脉浮而快。

风寒感冒其实只要想办法出汗就行。比如喝热茶吧,别太浓。还可以喝生姜汤。

宜进食藕粉、牛奶、稀饭、米汤、新鲜蔬菜和水果。

感冒时饮食要清淡。

室内空气要新鲜,注意通风。

以下是一些缓解方法

对于感冒虽然我们不能制服它,但我们还是有预防和缓解症状的办法,在又一个感冒多发季来临之时,一些对付感冒的方法,你都可以试试。

冬季感冒治疗七法

热水泡脚

每晚用较热的水(温度以热到不能忍受为止)泡脚15分钟,要注意泡脚时水量要没过脚面,泡后双脚要发红,才可预防感冒。

生吃大葱

生吃大葱时,可将油烧热浇在切细的葱丝上,再与豆腐等凉拌吃,不仅可口,而且可以预防感冒。

盐水漱口

每日早晚、餐后用淡盐水漱口,以清除口腔病菌。在流感流行的时候更应注意盐水漱口,此时,仰头含漱使盐水充分冲洗咽部效果更佳。

健康警钟:

感冒期间饮食误区――感冒期间应吃些滋补食物以增强抵抗力,对付病毒,这是非常错误的观念。

冷水浴面

每天洗脸时要用冷水,用手掬一捧水洗鼻孔,即用鼻孔轻轻吸入少许水(注意勿吸入过深以免呛着)再擤出,反复多次

按摩鼻沟

两手对搓,掌心热后按摩迎香穴(位于鼻沟内、横平鼻外缘中点)十余次,可以预防感冒及在感冒后减轻鼻塞症状。

鼻子插葱

感冒后鼻子不通气怎么办呢?可以睡觉时在两个鼻孔内各塞进一鲜葱条,3小时后取出,通常一次可愈。倘若不行,可于次日再塞一次。值得提醒的是:首先,葱条 要选择粗一点,细了,一是药力小;二是容易吸入鼻腔深部,不易取出;其次,若患者的鼻腔接触鲜葱过敏,可在葱条的外面包上一层薄薄的药棉。

白酒擦身

用铜钱、硬币等光滑硬物蘸白酒,轻刮前后胸、曲池及下肢曲窝处,直至皮肤发红发热,然后喝一碗热姜糖水,约15分钟后便大汗淋漓。汗后周身轻松舒适,此时注意免受风寒,感冒很快痊愈。

可乐煮姜

鲜姜20至30克,去皮切碎,放入一大瓶可口可乐中,用铝锅煮开,稍凉后趁热喝下,防治流感效果良好。

呼吸蒸汽
初发感冒时,在杯中倒入开水,对着热气做深呼吸,直到杯中水凉为止,每日数次,可减轻鼻塞症状。

热风吹面

感冒初起时,可用电吹风对着太阳穴吹3至5分钟热风,每日数次,可减少症状,加速痊愈。

蒜泥蜂蜜

将等份的蒜泥与蜂蜜混匀后,用白开水送服,每次一汤匙,每天4至6次,对治疗流感有佳效。

香油拌蛋

将一两香油加热后打入一鲜鸡蛋,再冲进沸水搅匀,然后趁热喝下,早晚各服一次,2至3天便可治好感冒愈后的咳嗽

不用抗生素也能治。

Tuesday, August 26, 2008

Web|Comparative table of WYSIWYG web editors

Comparative table of WYSIWYG web editors

This table is underdefinition right now. Extend it with any attribute you also think that need to be reviewed.

Former comparatives found in the net:

Editors compared:

Those are the editors that were evaluated:

Name Demo License KB Rated Reviewer Comment
FCKeditor here GPL ?? ?? Xavi Real good editor. It's very easy to upload pics. Cannot attach videos.
Trogodor ...? GPL? ?? ?? Xavi It seems to be in development. No clues about an existing web editor
Dobrado You need to log in GPL ?? ?? Xavi It is exactly like FCK Editor. I found that maybe, it is a little bit more difficult to upload pictures than the FCK: doesn't show any option to upload from your hard drive, just url's.
TinyMCE here LGPL? ?? ?? Rocio Hay implementados diferentes skin, por lo tanto ya nos serviria para tener una idea básica de como podria ser una interficie para niños pequeños y otra para no tan pequeños.
Dojo RichTextEditor here LGPL? ?? ?? Rocio

El hecho de que se pueda modificar solo con ponerte encima hace que su uso sea mucho más sencillo de cara a los niños de temprana edad

Spaw here LGPL? ?? ?? Rocio

Es un editor simple, con el cual se pueden realizar las funciones básicas de un editor de texto

TinyFCK here LGPL? ?? ?? ?? TinyMCE + Free Upload plugin.
openWYSIWYG You need to download the product GPL? ?? ?? Xavi Too much simple.
Xinha
BSD


.
Fill with the rest... visit "Status of the art" to find more web editors.

Let's review the different categories.

Comparative by categories:

Font Formating:

  • BFF: Basic Font Edition means support for Bold, Italic, Underline, Strike, Sub and Super.
  • FSS: Font Size Selector.
  • FSP: Font Size Preview (at Selector).
  • FFTS: Font Family Type.
  • FFTP: Font Family Type Preview (at Selector).
  • FFS: Font Format Selector for some basic html tags (hx, div, pre, adress).
  • FFP: Font Format Preview for some basic html tags (hx, div, pre, adress) at Selector.
  • FFC: Font Foreground Color (with eyedropper).
  • FBC: Font Background Color (with eyedropper).
Name BFF FSS FSP FFTS FFTP FFS FFP FFC FBC
FCKeditor Y Y Y Y. Just 6 Y N N Y Y
TinyMCE Y Y N Y N Y N Y Y
Dojo RichTextEditor Y N N Y N N N Y Y
Spaw Y Y N Y N N N Y Y
WYSIWYG Y. Not Strike Y Y Y Y N N Y Y

Cascade Style Sheets Support:

  • CSS: CSS Style Selector.
  • CSP: CSS Style Preview (at selector).
  • WCA: Web CSS Applied.
  • OCA: Own CSS Applied.
  • ECA: Extra CSS Applied.
Name CSS CSP WCA OCA ECA
FCKeditor Y. Just 5 Y Y N N
TinyMCE Y N Y N N
Dojo RichTextEditor N N Y N N
Spaw N N N N N
WYSIWYG N N N N N

Paragraph Actions:

  • TA: Text Aligment (left, right, center, justify).
  • BL: Bullet List.
  • NL: Numeric List.
  • ID: Identation.
  • OD: Outdentation.
Name TA BL NL ID OD
FCKeditor Y Y Y ? ?
TinyMCE Y Y Y Y Y
Dojo RichTextEditor Y Y Y Y Y
Spaw Y Y Y Y Y
WYSIWYG Y Y Y ? ?

Text Operations:

  • SE: Search (button and "Ctrl+F" shortcut).
  • SR: Search and Replace (button and "Ctrl+V" shortcut).
Name SE SR
FCKeditor Y Y
TinyMCE Y Y
Dojo RichTextEditor N N
Spaw N N
WYSIWYG N N

Edition Actions:

  • UD: Undo (button and "Ctrl+Z" shortcut). Unlimited?
  • RD: Redo (button and "Ctrl+Y" shortcut). Unlimited?
  • CO: Copying (button and "Ctrl+C" shortcut).
  • CU: Cutting (button and "Ctrl+X" shortcut).
  • PA: Pasting (button and "Ctrl+V" shortcut).
  • PP: Paste as Plain Text (losing any copied style).
  • PW: Paste from Word (clean word mess). How effective is it?
  • PWA: Paste from Word Autodetection.
Name UD RD CO CU PA PP PW PWA
FCKeditor Y Y Y Y Y Y Y. You can choose if you want to keep the "Word style" N
TinyMCE Y. Se puede hasta llegar a la versión guardada Y Y Y Y Y Y N
Dojo RichTextEditor N N N. No hay un boton directo pero si haces CTRL+C funciona, es por eso que en el caso de los niños se podria considerar que le manca esta funcionalidad, lo mismo pasa con el pegar y cortar N N N N N
Spaw Y Y N. No hay un boton directo pero si haces CTRL+C funciona, es por eso que en el caso de los niños se podria considerar que le manca esta funcionalidad, lo mismo pasa con el pegar y cortar N N N N N
WYSIWYG Y Y Y Y Y N N N

Links and Anchors:

  • IL: Insert Link.
  • AIL: Advanced Insert Link as a popup requesting some info about the link (protocol, target...)
  • AA: Add Anchor to be linked.
  • LA: Easy interface to Link Anchor.
Name IL AIL AA LA
FCKeditor Y Y Y Y
TinyMCE Y Y Y Y
Dojo RichTextEditor Y N N N
Spaw Y N Y N
WYSIWYG Y N N N

File Upload:

  • GFU: General File Upload to send any kind of file to the server .
  • FTF: File Type Filtering (for instance, avoid php files).
  • FUC: File User's cuota.
  • GFSB: General File Server Browsing and Insertion (instead of simple linking an url).
  • IFSB: Image File Server Browsing and Insertion
  • VFSB: Video File Server Browsing and Insertion
  • MSB: Music File Server Browsing and Insertion
  • FSB: Flash File Server Browsing and Insertion
Name GFU FTF FUC GFSB IFSB VFSB MSB FSB
FCKeditor N N N ? Y N N Y
TinyMCE Y ? ? Y Y Y Y Y
Dojo RichTextEditor N ? ? N Y N N N
Spaw N ? ? N Y N N N
WYSIWYG N N N N N N N N

Media inclussion (just linking an url):

  • GFI: General File Insertion.
  • IFI: Image File Insertion.
  • VFI: Video File Insertion.
  • MFI: Music File Insertion.
  • FFI: Flash File Insertion.
Name GFI IFI VFI MFI FFI
FCKeditor N Y N N Y
TinyMCE Y Y Y Y Y
Dojo RichTextEditor N Y N N N
Spaw N Y N N N
WYSIWYG N Y N N N

Table and cell Operations:

  • TI: Table Insertion.
  • TS: Table Size.
  • TE: Table Edition (add, delete rows and/or columns).
  • CE: Cell Edition (size, colors, aligments)
Name TI TS TE CE
FCKeditor Y Y Y Y
TinyMCE Y Y Y Y
Dojo RichTextEditor N N N N
Spaw Y Y Y Y
WYSIWYG Y Y N Y |

Web elements

  • FFI: Form Fields Insertion.
  • HL: Horizontal Lines (HR).
Name FFI HL
FCKeditor Y Y
TinyMCE N Y
Dojo RichTextEditor N N
Spaw N Y
WYSIWYG N N

Usability and other tools for easiness:

  • ESH: Editor Show/Hide.
  • FSM: Full Size Mode
  • PV: Preview.
  • PR: Printing.
  • DD: Drag&Drop for images, blocks of text, tables and every html element.
  • TI: Template Include (see fck).
  • VS: View Source
  • DCE: Double click to Edit.
  • EOP: Edit On Place. After an "edit mode" activation, you edit the code in the same place it's shown.
  • AS: AutoSave? (every n minutes).
  • IEI: Insert Emoticons.
  • ICC: Insert custom Character.
  • RCM: Rightclick Context Menu (see fck).
  • SHC: Show Hidden Chars.
  • EZR: Edition Zone Resize.
  • UK: Universal Keyboard (see fck)
Name ESH FSM PV PR DD TI VS DCE EOP AS IEI ICC RCM SHC EZR UK
FCKeditor Y Y Y Y Y Y Y ? ? Y Y Y ? ? Y
TinyMCE Y Y Y Y

Y N
N Y Y

? ?
Dojo RichTextEditor N N N N N N N Y N N N N N N ? ?
Spaw N N N N N N N N ? N N N N N N N
WYSIWYG N N N N N N Y N N N N N N N N N

Localization

  • MLS: Multi Language Support.
  • ITE: Interface Translated to English.
  • ITS: Interface Translated to Spanish.
  • ITC: Interface Translated to Catalan.
  • SCE: SpellChecker? (English).
  • SCS: SpellChecker? (Spanish).
  • SCC: SpellChecker? (Catalan).
  • ALD: Automatic user Language Detection (including Right to Left scripting)
Name MLS ITE ITS ITC SCE SCS SCC ALD
TinyMCE Y N N N N N N Y
Dojo RichTextEditor N N N N N N N N
Spaw N N N N N N N N
WYSIWYG N Y N N N N N N

AJAX:

  • BL: Background loading of elements.
  • SAS: "Silent" Auto Save.
  • II: Improved interface with blur... effects.
Name BL SAS II
TinyMCE Y N Y
Dojo RichTextEditor Y N Y
Spaw Y N Y
WYSIWYG ? N ?

Miscelania:

  • IT: Insert Time
  • ID: Insert Date
Name IT ID
TinyMCE Y Y
Dojo RichTextEditor N N
Spaw N N
WYSIWYG N N

Technical information

Browser Compatibility:

  • IE5: Internet Explorer 5.5+
  • IE6: Internet Explorer 6.0+
  • IE7: Internet Explorer 7+
  • FF10: Firefox 1.0+
  • FF15: Firefox 1.5+
  • SAF: Safari.
  • OP6: Opera 6.0+
Name IE5 IE6 IE7 FF10 FF15 SAF OP6
TinyMCE Y Y Y Y Y ? ?

Output generated:

  • HTML: HTML 4.0 standard.
  • XHTML: XHTML 1.0 standard.
  • WIKI: WIKI syntax code.

Adaptability:

  • SK: Skinable.
  • TC: Toolbar Customization.
  • BC: Button Customization.

Server Side Compatiblity Details:

  • ILL: Integrated with... Languages List (for instance: PHP, JSP, ASP...)
  • SC: Script Compression (see tinyMCE).

Avaliable Plugins

  • LAP: List of Avaliable Plugins (for instance: UploadPlugin?, SpellChecker? ...)
Name LAP
TinyMCE Y

Final questions

  • Easy to integrate in Moodle?

HTMLArea (not reviewed in this comparative) is the web editor included by default in moodle, so no installation/integration will be needed. Any case the existing HTMLArea delivered with moodle is quite outdated, so if we need to spend time to fix, now days, other products look more appropriate.

Former efforts where done in moodle to integrate TinyMCE so moodle includes a tinyMCE release quite ready to use. We tested it and is buggy (specially on IE7), but we expect it could be fixed updating the tinyMCE to it's last version.

  • Easy to use?

FCKeditor --> Very easy. The interface is so similar (I'd say exactly) with other microsoft software interfaces.

Spaw --> El uso es muy sencillo puesto que es el mismo formato que el Word, pero desde mi punto de vista es demasiado simple para cierto rango de edad y a su vez complicado para niños de temprana edad.

  • Quality of the Documentation avaliable for the editor?

FCKeditor We can find the documentation here Spaw No he encontrado grandes cosas sobre este editor

  • Quality of the Documentation avaliable to develop plugins?
  • Community Activity (evaluate: forums, last release, dissemination...)?