Thursday, April 28, 2011

How to pass an array in Django to a template and use it with JavaScript

I want to pass an Array to a template and afterwards use it via JavaScript.

In my views.py I have: arry1= ['Str',500,20] return render_to_response('test.html', {'array1': arry1})

var array1 = {{ array1 }};

but when I visit the website it puts out:

var array1 = [&#_39;Str&#_39;,500,20]; (without the _ sign (otherwise stackoverflow changes the formatting) with which obviously breaks my code and doesn't work as intended.

What do I have to change?

From stackoverflow
  • Try using {{ array1|safe }} and see if that makes any difference. I haven't tested this, so I hope I don't get too downvoted if this is incorrect...

  • As mentioned, you could use the |safe filter so Django doesn't sanitize the array and leaves it as is.

    Another option, and probably the better one for the long term is to use the simplejson module (it's included with django) to format your Python list into a JSON object in which you can spit back to the Javascript. You can loop through the JSON object just like you would any array really.

    from django.utils import simplejson

    list = [1,2,3,'String1']

    json_list = simplejson.dumps(list)

    render_to_response(template_name, {'json_list': json_list})

    And in your Javascript, just {{ json_list }}

    Christian : json_list becomes [1, 2, 3, & q u o t ;String1& q u o t ;] (I added the spaces after &,q,u,o,t to prevent stackoverflow from reformating the output) That also doesn't seem to work.
    Christian : Maybe the best way is to use simplejson.dumps and afterwards the |safe filter?
    Bartek : You're right, you'd still need to use |safe in this case. Normally when I do JSON with Django I fetch it using an AJAX method (like $.getJSON from jQuery) so I never deal with having to use |safe.

Loading Complete graph from Sql using LINQ

Assume we have a Menu class that has SubMenus (which is the same type of Menu therefore can have SubMenus and Items too) and Items (which has a different type) and we stored them in two tables(One for Menus and one for Items). Is there any way to load complete graph of the Menu class (all of its SubMenus and Items) using LINQ to SQL?

From stackoverflow
  • If you define the relationships properly in SQL, LINQToSQL should give you back all of the menus/items with a single query on menus. However, this won't give it back to use as a graph, but as an enumeration of the menus (with related menus and items). You would need to iterate through this enumeration and construct the graph on your own.

    On the other hand, you might be able to do something like this:

    var roots = db.Menus.Where( m => !m.SubMenus.Count == 0 );
    

    Then, roots would be a collection of the base menus. This might be sufficient if you don't intend to perform any graph analysis algorithms on it, but only intend to traverse it from top to bottom to construct the GUI components.

    Mohammadreza : I want to serialize the complete graph to a XML file using DataContractSerializer, so I think i need to load all objects. Can I use LoadOptions somehow to eager load them?
    tvanfosson : If you want to serialize the graph structure instead of just the elements, I think you will need to construct the actual graph. In the enumeration you'll have duplicate elements in the parent/child properties for any shared menus. Check your DBML - the relations may already be eager loaded.
    Mohammadreza : I want to serialize the elements.
    tvanfosson : Try using partial classes to mark your entities as Serializable and see if that results in a usable format. If not, you may need to implement ISerializable as well to serialize the entity the way you want.
    Mohammadreza : My problem is not with the serialization method. How can I LOAD the data from file with a single query to pass it to the WriteObject method.
    tvanfosson : From a file or from the database. LINQToSQL only works with a MS SQL Server database. Loading the data from the database should just be a matter of executing the query I referenced in my answer assuming you have your Menus and Items tables mapped using the DBML designer.
    Mohammadreza : Maybe you got me wrong. Yes, I have used LINQToSQL ORM designer to create objects. The Menu class could have nested menus which will increase the levels of the graph. I am looking for a way to load all the levels from SQL instead of writing a recursive method to load them.
    tvanfosson : If you create the proper foreign key relationships on your table -- they can be self-referential -- then the designer will add collections to your Menu entity that will contain the related menus. I believe that these are eagerly loaded by default, but you can check in the designer...
    tvanfosson : ...if the relationships don't already exist, you can add them then either update your DBML by hand (search MSDN for adding associations to DBML) or remove/readd the tables in the designer to pick up the new relationships.
    tvanfosson : I don't think, however, that the entire relationship hierarchy can be loaded at once (probably only two levels). But you should be able to construct the graph in memory once you've done the initial query (not the one I mention in my answer, but simply iterating through Menus)...
    tvanfosson : ...since you will have an object for each menu and all of the direct connections between them.
    tvanfosson : You'd need to be careful that there aren't any cycles (perhaps by using a data structure that doesn't allow them to be added) when you construct the graph.
    Mohammadreza : Then I think I have to write the recursive method anyways. Thanks.

Get the key of an item on a Collection object

The environment is that the members I'm pushing into the Collection are nameless, un-identifiable (to avoid bad abstractions, and please, don't freak out: members are actually other Collection instances). In order to be able to make fast searches, I'm creating a meaningfull hash name for each new member, and provide it as the Key string, on the Add method of the "topmost" Collection.

When I have a key to seach with, everything's dandy... Problem is I'd like to iterate the members of the collection and get the Key that was provided on Add (the generated Hash, that unfortunetely is not possible to reverse-Hash).

I'm moving on by defining that the first member of the inserted sub-collection instance is a string, containing the mentioned hash, but if anyone cracks this, I'll be much obliged.

From stackoverflow
  • The simple approach would be to use a Dictionary instead of a Collection. The Dictionary is essentially an associative array of key, item pairs and support retrieval of its keys as an array. To use the Dictionary you will need to add a reference to the Microsoft Scripting Runtime. The drawback to using the dictionary is that it is not enumerable in the same way as the collection. A more elaborate solution would be to wrap the collection and dictionary to create an enumerable dictionary as outlined below.

    NB To get NewEnum to work properly in VBA the class module has to be exported and manually edited as follows and then re-imported.

    Public Property Get NewEnum() As IUnknown
    Attribute NewEnum.VB_UserMemId = -4
       Set NewEnum = someKeys.[_NewEnum]
    End Property
    

    example

    Option Explicit
    Private someKeys As Dictionary
    Private someCols As Collection
    Public Function Add(o As Object, Key As String) As Object
        someKeys.Add Key, o
        someCols.Add o, Key
    End Function
    Public Property Get Count() As Long
        Count = someCols.Count
    End Property
    Public Property Get Item(vKey As Variant) As Object
        Set Item = someCols.Item(vKey)
    End Property
    Public Sub Remove(vKey As Variant)
        someKeys.Remove vKey
        someCols.Remove vKey
    End Sub
    Public Property Get NewEnum() As IUnknown
       Set NewEnum = someCols.[_NewEnum]
    End Property
    Public Property Get Keys() As Variant
        Keys = someKeys.Keys
    End Property
    Private Sub Class_Initialize()
        Set someKeys = New Dictionary
        Set someCols = New Collection
    End Sub
    
    jpinto3912 : It crawls. There are Buts: i) Key can't be optional on Add method; ii) how do you remove the corresponding key during remove method?; iii) it's dumb-possible to aC.Keys().Delete I suggest: ii) someKeys.Add(Key, Key) allowing someKeys.Remove(vKey) later on; iii) Get Keys(anIndex as long) as String
    cmsjr : i. good point. ii. I didn't give that any consideration, and your suggestion is the better of the two alternatives offered, but Key, Key irks me. Maybe Dictionary would be better for the keys. iii. That Get would be redundant since the default member of the collection returned would be .Item
    cmsjr : Also, crawls in the sense of performance, or in the sense of is not complete?
    jpinto3912 : "crawls" in correcteness (but it's on polish). I think I didn't came across on iii) If you're giving a ref to a priv. member, I guess it gives a user the opport. to mess with it (don't know if vba errors). E.G. set myKeys=thisWrapCol.Keys() Call myKeys.Delete() Agree on ii? (yeah it's weird)
    cmsjr : Ok, I'm with you on iii. For ii I still wonder if it wouldn't make sense to make someKeys a Dictionary, add the key and collection during Add and expose its Keys collection through a property, this would give you a way to get the set of Keys or an individual Key without encapsulation issues.
    cmsjr : so iii is addressed, and the dictionary can remove by key or index, so ii is addressed as well.
    jpinto3912 : I guess that now I lost you on iii)... are you re-editing to not pass the priv member? Can't chew Public Property Get NewEnum() As IUnknown Set NewEnum = someCol.[_NewEnum] End Property I'm vba-only...
    cmsjr : Not totally, I'm with you on iii if we use two collections, I'm just suggesting that may not be the best way. If you can't support the NewEnum in VBA I don't think you will be able to do a foreach iteration over its members. Does that present a problem?
    cmsjr : Give me a few minutes and I'll edit the sample to clarify what I'm suggesting now.
    cmsjr : I think there is a workaround for the NewEnum, but I'll have to do more research. I'm sans IDE at the moment, so please pardon any syntax issues.
    cmsjr : Note that the keys collection of the dictionary being returned by the Get is read only.
    cmsjr : I'm waiting for a process to finish on this machine before I can fire up my work computer, but I think I am going to try wrapping the Dictionary and seeing if I can get the new enum to work in a VBA friendly way, that would remove the need for two aggregate objects.
    cmsjr : Dictionary requires a reference to Microsoft Scripting Runtime, is that a deal breaker?
    cmsjr : Ok sample reworked above, NewEnum about note is up there. I verified that assignment will not alter the dictionaries keys collection, or an individually indexed key. So I think exposing the read only attribute of the private member should be safe.
    jpinto3912 : hihihi... why have a Collection encaps. a Dic., when the Dictionary alone solves all our problems? I can Add whatever I want to a Dictionary (in my case, adding collections), and this class has property Keys. I just didn't know this class (it's usable in vba, checked).
    jpinto3912 : So, please, trim down all the prev. answer, give us a lesson on Dictionary (not to me, I'm already using it thanks to you) and i'll be happy to mark this answer correct. Nice work! Thanks !
    jpinto3912 : Personal taste:"using a Dictionary". BTW, don't forget to tell the kids that Keys array stars at 0.
    jpinto3912 : Let's polish that other thought: we can enumerate by myDic(myDic.Keys(enum_index)). But we could also wrap a Dictionary and provide a P. Prop. Get Enum(anIndex as long) as Object, (code to figure out whether object or variant.. and anIndex is withibounds) set Enum = innerDic(innerDic.Keys(anIndex))
    cmsjr : If we need to pass it an index then that Enum would just duplicate our classes Item method (though I agree some logic to make sure an invalid key/index doesn't cause an exception might be in order) The real point of wrapping them together is to support for each syntax.
    cmsjr : Surely, the kids know that arrays are 0 base.
    Mark Nold : Nice effort on the answer guys. @cmsjr did you ever work out how to simplify the export/import solution on NewEnum for VBA?
    cmsjr : If one has access to the Visual Studio 6 IDE, it can be coded normally in VB6 then imported into your VBA project. Not sure if there's any other way to handle it.
  • You could wrap your member collections in you own collection call that store the key and the collection. The is just a matter of iterating throw the collection and asking the elements for their key (i.e. you hash).

Non ASCII char in PHP?

Hello, I am trying to send something to serial port (r232) with PHP. I am using this class: http://www.phpclasses.org/browse/package/3679.html

The problem is that I am allowed to send only 1 byte. But if I send something like "1", I am actually sending 49 (ASCII for 1). Instead of send("1"), I tried with send(1) but it is no good, because this is integer which has 2 bytes. So is there a way to send a "real" char, not ASCII equivalent?

From stackoverflow
  • The chr() function returns a character given by the integer for the corresponding ascii character.

    Alan Storm : It returns a character, but as a PHP string. That won't help the OP
    Mark : Doesn't the library take a PHP string? It passes it into fwrite...
    Gumbo : To be more precise: `chr` turns an integer into a byte.
  • It looks like the library is expecting characters as input. If you need to send the character which would encode to 0x01, you just send "\001". The function chr() would convert characters to integer values and would be no use here.

    One more thing: The byte size of integers depends on the underlying system and is mostly 4 bytes.

    Mark : Not so. ord() converts characters to integer values, and chr() does the opposite.
  • I'm not sure what you are trying to accomplish. Are you trying to to send the integer 1? Not being familiar with the class, have you tried to give just the value 1 as an argument? If that doesn't work, try to wrap it with the chr() function.

WCF here to stay?

Currently reading quite a heavy WCF book. I have used it myself in production just the once, using tcp, worked a charm. Anyway what are your opinions on this technology, is it here to stay, is it worth the time invested learning all the complex features etc etc?

From stackoverflow
  • I think it is here to stay. It is easily configurable for moving endpoints, it seems robust and allows you to do (pretty much) everything you could do in web services and remoting without the overhead of separate implementations.

    I can see where you are coming from, with MS's recent leaks about ongoing support for, and maintenance of Linq to SQL, but I see WCF as a different beast altogether. This is a technology that allows interoperability, as well as de-complixifying (I know this isn't a real word, but it should be) communications between systems.

    Dave Markle : I'll add to that. WCF is the culmination of the lessons learned by MS in creating their earlier Web Service and Remoting infrastructures. And there were a LOT of lessons that needed to be learned! ;-)
  • I second what ZombieSheep says. Although complex, it greatly simplifies distributing applications across physical and logical boundaries, facilitates interoperability, and mostly decouples implementation details like ports/protocols for communication.

    It's definitely worth the time to learn, although depending on the solution, it may sometimes be overkill. I think you'll find that configuration will become easier as versions continue -- although that's pure speculation.

    While Linq to SQL had a larger cousin in the Entity Framework, WCF has no such relative. It's here to stay.

break a word in letters php

I want to accept a string from a form and then break it into an array of characters using PHP, for example:

$a = 'professor';
$b[0] == 'p';
$b[1] == 'r';
$b[2] == 'o';
.
.
.
.
.
$b[8] = 'r';
From stackoverflow
  • You don't need to do that. In PHP you can access your characters directly from the string as if it where an array:

    $var = "My String";
    echo $var[1]; // Will print "y".
    
    gargantaun : I didn't know that. good tip.
    whichdan : FYI, $var{1} will work, but it's being deprecated as of PHP6 in favor of $var[1].
  • str_split($word);
    

    This is faster than accessing $word as an array. (And also better in that you can iterate through it with foreach().) Documentation.

    St. John Johnson : Why is it faster? It just returns an array.
    Seb : It is not faster; in fact, it's slower - it has to create an additional array and see where to split the original string depending on the second parameter.
    orlandu63 : You're correct: a benchmark confirms that this is 50% slower than your method.
  • Be careful because the examples above only work if you are treating ASCII (single byte) strings.

  • If you really want the individual characters in a variable of array type, as opposed to just needing to access the character by index, use:

    $b = str_split($a)
    

    Otherwise, just use $a[0], $a[1], etc...

    PROFESSOR : thanks for the answer............it worked

PHP: what's an alternative to empty(), where string "0" is not treated as empty?

In PHP, empty() is a great shortcut because it allows you to check whether a variable is defined AND not empty at the same time.

What would you use when you don't want "0" (as a string) to be considered empty, but you still want false, null, 0 and "" treated as empty?

That is, I'm just wondering if you have your own shortcut for this:

if (isset($myvariable) && $myvariable != "") ;// do something
if (isset($othervar  ) && $othervar   != "") ;// do something
if (isset($anothervar) && $anothervar != "") ;// do something
// and so on, and so on

I don't think I can define a helper function for this, since the variable could be undefined (and therefore couldn't be passed as parameter).

From stackoverflow
  • if ((isset($var) && $var === "0") || !empty($var))
    {
    
    }
    

    This way you will enter the if-construct if the variable is set AND is "0", OR the variable is set AND not = null ("0",null,false)

    thomasrutter : This looks quite correct; it isn't really a shortcut for if (isset($myvariable) && $myvariable != "") though as it's longer. Thanks for the answer.
  • This should do what you want:

    function notempty($var) {
        return ($var==="0"||$var);
    }
    

    Edit: I guess tables only work in the preview, not in actual answer submissions. So please refer to the PHP type comparison tables for more info.

    notempty("")       : false
    notempty(null)     : false
    notempty(undefined): false
    notempty(array())  : false
    notempty(false)    : false
    notempty(true)     : true
    notempty(1)        : true
    notempty(0)        : false
    notempty(-1)       : true
    notempty("1")      : true
    notempty("0")      : true
    notempty("php")    : true
    

    Basically, notempty() is the same as !empty() for all values except for "0", for which it returns true.


    Edit: If you are using error_reporting(E_ALL), you will not be able to pass an undefined variable to custom functions by value. And as mercator points out, you should always use E_ALL to conform to best practices. This link (comment #11) he provides discusses why you shouldn't use any form of error suppression for performance and maintainability/debugging reasons.

    See orlandu63's answer for how to have arguments passed to a custom function by reference.

    mercator : That will fail when the variable is undefined.
    Calvin : How do you mean? If passed an undefined variable, the function returns false--which is the opposite of what empty() returns: http://us2.php.net/manual/en/types.comparisons.php That is the desired behavior.
    Milan Babuškov : It does not fail, but produces a warning. So, although it does work, it is not The Right Way(tm). You should use isset() before checking the variable with ===
    Calvin : Strange, it doesn't produce any warnings when I have error reporting set to E_STRICT. If does however produce an error when I use E_ALL. But then using isset() inside of the function does not prevent the error either.
    Calvin : It seems that you can't pass an undefined variable to a custom function in E_ALL regardless of whether your use isset() or not. Gushiken's implementation without a custom function does work in all circumstances however.
    mercator : E_STRICT isn't a superset of E_ALL: http://www.php.net/manual/en/errorfunc.constants.php. You should use (E_ALL | E_STRICT). You *could* use the @ operator, but that adds overhead (see http://www.smashingmagazine.com/2009/03/24/10 "tip" #9 and comment #11) and isn't The Right Way™ either.
    thomasrutter : Unfortunately this will not work for me because it will fail (ie produce PHP notice) when the variable is undefined. I rely on PHP notices. I hadn't realised, I guess, that it's not possible to define a function that can accept an undefined variable; empty() and isset() are magical in that way.
  • if(isset($var) && ($var === '0' || !empty($var)))
    {
    }
    
  • function Void($var)
    {
        if (empty($var) === true)
        {
         if (($var === 0) || ($var === '0'))
         {
          return false;
         }
    
         return true;
        }
    
        return false;
    }
    
    thomasrutter : This has the problem that if $var is undefined, it fails as soon as it's passed as an argument (to a function other than isset or empty, such as your Void function). I think what I was wanting is actually impossible, sorry.
  • function isempty(&$var) {
        return empty($var) || $var === '0';
    }
    

    The key is the & operator, which passes the variable by reference, creating it if it doesn't exist.

  • The answer to this is that it isn't possible to shorten what I already have.

    Suppressing notices or warnings is not something I want to have to do, so I will always need to check if empty() or isset() before checking the value, and you can't check if something is empty() or isset() within a function.

  • If ($var != null)