MonoRail Select Using Enum - castle-monorail

I've been following this guide and coming up with my own concoction in order to use MonoRail's FormHelper.Select that is generated from an enum. So here's the Brail syntax:
${FormHelper.Select("user.Role", ${LS.EnumToPairs(Roles)}, {"value":"First", "text":"Second"})}
"LS" is just my own helper, which I've defined as follows:
public IEnumerable<Pair<int, string>> EnumToPairs(Type e)
{
IList<Pair<int, string>> pairs = new List<Pair<int, string>>();
foreach (int val in Enum.GetValues(e))
pairs.Add(new Pair<int, string>(val, Enum.GetName(e, val)));
return pairs;
}
Yet from this, despite being the correct syntax, I get the following error:
Node '$({ return Castle.MonoRail.Views.Brail.ExpandDuckTypedExpressions_WorkaroundForDuplicateVirtualMethods.Invoke(self.GetParameter('LS'), 'EnumToPairs', (self.GetParameter('Roles'),)) })' has not been correctly
The source error doesn't help much unfortunately:
Line 15: output FormHelper.TextField("user.Role", {"class":"text-input full-width"})
Line 16: output """
Line 17: """
Line 18: output FormHelper.Select("user.Role", ${LS.EnumToPairs(Roles)}, {"value":"First", "text":"Second"})
Line 19: output """
Any ideas what I'm doing wrong here?
EDIT
Based on the answer given below, the solution was finally this:
${FormHelper.Select("user.Role", LS.EnumToPairs(Roles), {"value":"First","text":"Second"})}
Where Roles was PropertyBag["Roles"] = typeof(Role);

Try this:
${FormHelper.Select("user.Role", LS.EnumToPairs(typeof(Roles)), {"value":"First", "text":"Second"})}

Related

How to get rid of \r\n from a string?

I recently had to upgrade to Jython 2.7.2. I send in a Java map instance into my python script.
Previously my python script would print out the key, value in the map as in the below format
message: Community: public
This same string now appears as
u'message': u'Community:\t\tpublic\r
I managed to get rid of the u' prefix by doing the following
encode(encoding = 'UTF-8', errors = 'strict')
But am still left with the \t\r in the string
'message': 'Community:\t\tpublic\r
and it feels very clumsy to manually remove these from the string. Is there any good utility method that would help me to preserve the pre 2.7.7 handling of strings?
Normally the character \r comes from a windows' file and the easiest way to get rid of them is just use replace
mystring = u'asd\r'
mystring = mystring.replace("\r", "")
print(repr(mystring))
Gives the output:
u'asd'
Why not use the toString() method and then replace the unwanted characters?
Sample code:
import java.util.HashMap as HashMap
import re
def test_2():
my_map = HashMap()
inner_map = HashMap()
inner_map.put("community", "public")
my_map.put("message", inner_map)
print re.sub(r"[{}]*", "", my_map.toString()).replace("=", ": ")
if __name__ == '__main__':
test_2()
Output:
message: community: public

Error creating PDF with Zend (fontWithName)

I'm trying to generate a PDF file using Zend but I keep getting errors when trying to set the font.
Here is my code:
$pdf = new Zend_Pdf();
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
$font = new Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font,24)
->drawText("Hello world!",72,720);
$pdf->$page;
$pdf->save("example.pdf");
And this is the error:
Parse error: syntax error, unexpected 'fontWithName' (T_STRING), expecting variable (T_VARIABLE) or '$' in /Users/pawel/Sites/Zend/application/modules/default/controllers/IndexController.php on line 83
I think you can just remove new for the font declaration:
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$style = new Zend_Pdf_Style();
$style->setFont($font, 24);
$page->setStyle($style);
fontWithName is a static function and Zend_Pdf_Font is an abstract class.
See the documentation for example.
There is another problem:
Replace
$pdf->$page;
by
$pdf->pages[] = $page;

Doxygen - Generating Dynamic Groups with an Alias Command with a parameter

I'm looking to create a group hierarchy automatically, by having some kind of Alias command. E.g. I want the groups
Extension Methods
String Extensions
Stream Extensions
...
to be created with doxygen comments such as
/** Documentation for the method
* \extension{string}
*/
public void ExtensionMethod(this string str){
...
}
Where \extension{string} would map to something like
\addtogroup stringExtensions string Extensions
\ingroup ExtnMethods
Unfortunately this means that all the documentation written for the method gets associated with the group instead.
The closest I've got is that if you have something like
/** \addtogroup stringExtensions string Extensions
* \ingroup ExtnMethods
* \#{
* \#}
*/
/** \ingroup stringExtensions
* Documentation for the method
*/
public void ExtensionMethod(this string str){
...
}
it would work, but this needs the 2 separate comment blocks and I can't find any way to do that using an Alias.
I know that something can probably be achieved with an inputfilter - but I'm hoping something far simpler can be achieved.
I've found an answer using inputfilters that was neater than I first supposed - parse the entire file looking for \extension{...}, replacing it with an appropriate \ingroup command, and then append the desired \addgroup commands at the bottom of the file.
This can then be run as an inputfilter
The following is a python script that does this. Note that it doesn't check that what it's replacing is actually within a doxygen comment, but it's good enough for my purposes.
#!python
import sys, re
if(len(sys.argv) != 2):
print "Need exactly one argument, the file to filter"
exit(1)
extnFinder = re.compile("\\\\extension{(\w+)}")
extnTypes = set();
filename = sys.argv[1]
fileIn = open(filename, "r")
line = fileIn.readline()
def extnSub(matchobj):
extnTypes.add(matchobj.group(1))
return "\ingroup %(extn)sExtensions" % {'extn':matchobj.group(1)}
while line:
matches = extnFinder.findall(line)
sys.stdout.write(re.sub(extnFinder,extnSub,line))
line = fileIn.readline()
for extn in extnTypes:
print "\n\n/**\\addtogroup %(extn)sExtensions %(extn)s Extensions\n\\ingroup ExtnMethods\n */\n" % {'extn':extn}

Django: Django generated sql query causes error

Updated question:
Django is giving me the following sql query:
SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" = %s args=('andrew',);
If I execute the sql query in the postgresql command line, I get the following error:
ERROR: syntax error at or near "%"
LINE 1: ..." FROM "auth_user" WHERE "auth_user"."username" = %s args=(...
^
However, when I slightly modify the statement, then I get the cirrect result from postgresql.
SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."username" = 'andrew';
Is the Django generated query incorrect?
Hi Stackoverflow people,
Very simple code which drives me crazy:
I want to extract the user information from user_auth with
user = get_object_or_404(User, pk = request.user.pk)
However, I get an error message in Django:
'NoneType' object does not support item assignment
When I check the sql query and execute it in the psql command line, psql gives me also an error message, which makes me thinking that the statement might be incorrect.
psql statement is:
SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = %s ; args=(7,)
Why does it say %s in the WHERE statement? The user id is not a string.
I believe the solution must be very simple - but I can figure out what the issue is here.
Thank you for your help and suggestions!
Additional explanation
I am using the django_social_auth package for the user authentification. The user will be directed to the dashboard site once the 3rd part cleared the credentials, therefore I would assume that request.user is not None.
Complete traceback
Environment:
Request Method: GET
Request URL: http://login.test.com:8000/profile/dashboard/
Django Version: 1.3.1
Python Version: 2.7.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.gis',
'django.contrib.messages',
'django.contrib.markup',
'django.contrib.staticfiles',
'django.contrib.flatpages',
'django.contrib.humanize',
'guardian',
'easy_thumbnails',
'userena',
'userena.contrib.umessages',
'south',
'django_extensions',
'debug_toolbar',
'social_auth',
'djangoratings',
'about',
'apps.profiles',
'apps.map',
'apps.contact',
]
Installed Middleware:
['django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "/Users/neurix/Development/test/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/Users/neurix/Development/test/test/apps/profiles/views.py" in dashboard
35. extra_context['username'] = user.username
Exception Type: TypeError at /profile/dashboard/
Exception Value: 'NoneType' object does not support item assignment
views.py
...
31: print "user: %s" %(request.user.pk)
32: user = get_object_or_404(User, pk = request.user.pk)
33:
34:
35: extra_context['username'] = user.username
36: if user.first_name:
37: extra_context['name'] = user.first_name
...
Could it be that request.user is None?
if request.user is not None:
user = get_object_or_404(User, pk = request.user.pk)

SQL error 1064 in simple cakePHP setup

I am using the simplest controller and model as shown here:
http://book.cakephp.org/view/1341/Basic-Usage
But when i go to www.mysite.com/categories
the code that causes it is:
<?php
class CategoriesController extends AppController {
var $name = 'Categories';
function index() {
$this->data = $this->Category->generatetreelist(null, null, null, ' ');
debug ($this->data); die;
}
}
?>
i get the following error:
Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'recover' at line 1 [CORE/cake/libs/model/datasources/dbo_source.php, line 684]
Code | Context
$out = null;
if ($error) {
trigger_error('<span style="color:Red;text-align:left"><b>' . __('SQL Error:', true) . "</b> {$this->error}</span>", E_USER_WARNING);
$sql = "recover"
$error = "1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'recover' at line 1"
$out = null
DboSource::showQuery() - CORE/cake/libs/model/datasources/dbo_source.php, line 684
DboSource::execute() - CORE/cake/libs/model/datasources/dbo_source.php, line 266
DboSource::fetchAll() - CORE/cake/libs/model/datasources/dbo_source.php, line 410
DboSource::query() - CORE/cake/libs/model/datasources/dbo_source.php, line 364
Model::call__() - CORE/cake/libs/model/model.php, line 502
Overloadable::__call() - CORE/cake/libs/overloadable_php5.php, line 50
AppModel::recover() - [internal], line ??
CategoriesController::index() - APP/controllers/categories_controller.php, line 7
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83
Query: recover
app/controllers/categories_controller.php (line 8)
I am totally confused, since I just copy-pasted from the original cakephp cookbook tutorial.
I have:
controllers/categories_controller.php
models/category_model.php
and the code is copy paste from the tutorial.
Any help?
Problem solved. Misnaming the model file.
It Was: category_model.php
Should have been: category.php =(
Have you created the Category Model?
I am not sure but I belive you should tell the controller which model u intend to use by specifying:
var $name = 'Categories';
var $uses = array("Category");
function index() {
$this->data = $this->Category->generatetreelist(null, null, null, ' ');
debug ($this->data); die;
}