node placer classes
authorcavaliet
Wed, 09 Jul 2014 12:26:11 +0200
changeset 290 fb86765b4c54
parent 289 eb479baeb2bf
child 291 44af3e5e4114
node placer classes
.pydevproject
src/hdalab/utils.py
src/hdalab/views/ajax.py
src/hdalab/views/renkan.py
--- a/.pydevproject	Tue Jul 08 12:03:06 2014 +0200
+++ b/.pydevproject	Wed Jul 09 12:26:11 2014 +0200
@@ -5,6 +5,6 @@
 <pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">hdabo_python</pydev_property>
 <pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
 <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
-<path>/hdabo/web</path>
+<path>/${PROJECT_DIR_NAME}/src</path>
 </pydev_pathproperty>
 </pydev_project>
--- a/src/hdalab/utils.py	Tue Jul 08 12:03:06 2014 +0200
+++ b/src/hdalab/utils.py	Wed Jul 09 12:26:11 2014 +0200
@@ -2,17 +2,56 @@
 '''
 Created on Mar 13, 2012
 
-@author: ymh
+@author: ymh and tc
 '''
 from django.core.cache import cache
+from django.http.response import Http404
 from django.utils.encoding import smart_str
 import md5
 import re
 
+import logging
+logger = logging.getLogger(__name__)
+
 
 def fix_cache_key(key):
     cache_key = re.sub(r'\s+', '-', key)
     cache_key = smart_str(cache_key)
     if len(cache_key) > (250-(2+len(cache.key_prefix)+len(str(cache.version)))-33):
         cache_key = cache_key[:(250-(2+len(cache.key_prefix)+len(str(cache.version)))-33)] + '-' + md5.new(cache_key).hexdigest()
-    return cache_key
\ No newline at end of file
+    return cache_key
+
+
+
+class NodePlacer():
+    
+    cat_nb_nodes = {}
+    
+    def init(self, cat_nb_nodes_initial):
+        raise NotImplementedError( "Should have implemented get_place" )
+    
+    def get_place(self, category):
+        if not category or category not in self.cat_nb_nodes:
+            raise Http404
+        return self.cat_nb_nodes[category].pop(0)
+
+
+
+class LineNodePlacer(NodePlacer):
+    
+    max_length = 0
+    
+    def init(self, cat_nb_nodes_initial):
+        for c in cat_nb_nodes_initial:
+            self.max_length = cat_nb_nodes_initial[c] if cat_nb_nodes_initial[c] > self.max_length else self.max_length
+        for i_cat,c in enumerate(cat_nb_nodes_initial):
+            self.cat_nb_nodes[c] = []
+            offset = float(self.max_length - cat_nb_nodes_initial[c]) / 2
+            for i in xrange(cat_nb_nodes_initial[c]):
+                self.cat_nb_nodes[c].append({ "x": i_cat*200, "y": 100*(i+offset) })
+        #logger.debug(self.cat_nb_nodes)
+        
+                
+    
+        
+        
\ No newline at end of file
--- a/src/hdalab/views/ajax.py	Tue Jul 08 12:03:06 2014 +0200
+++ b/src/hdalab/views/ajax.py	Wed Jul 09 12:26:11 2014 +0200
@@ -11,7 +11,7 @@
 from hdabo.models import Tag, Datasheet, TaggedSheet
 from hdalab.models import HdaSession, Country, TagYears, DatasheetExtras
 from hdalab.models.dataviz import DbpediaFieldsTranslation, DbpediaFields
-from hdalab.models.categories import WpCategory, WpCategoryInclusion, TagWpCategory
+from hdalab.models.categories import WpCategory
 from hdalab.utils import fix_cache_key
 import copy
 import json
@@ -170,7 +170,7 @@
         HdaSession.objects.filter(sessionid=sessionid).update(data=json.dumps(data))
     else:
         data = HdaSession.objects.get(sessionid=sessionid).data
-        data = json.loads(data) if data else {}           
+        data = json.loads(data) if data else {}
          
     resobj = {'data': data, "write_allowed" : write, "sessionid": sessionid }
     if write:
@@ -241,7 +241,7 @@
     
     # On ne récupère que les catégories qui sont également des tags
     qrx = '(\\m|\\b)%s'%q
-    qs = Tag.objects.filter(label__iregex=q)
+    qs = Tag.objects.filter(label__iregex=qrx)
     
     labels = [tag.label for tag in qs]
     
--- a/src/hdalab/views/renkan.py	Tue Jul 08 12:03:06 2014 +0200
+++ b/src/hdalab/views/renkan.py	Wed Jul 09 12:26:11 2014 +0200
@@ -5,12 +5,12 @@
 @author: tc
 '''
 from datetime import datetime
-from django.conf import settings
 from django.db.models import Q
 from django.http.response import HttpResponse
 from django.views.generic import View
 from django.views.decorators.csrf import csrf_exempt
-from hdabo.models import Tag, Datasheet, TaggedSheet
+from hdabo.models import Tag
+from hdalab.utils import LineNodePlacer
 from hdalab.views.ajax import filter_generic
 import json
 import uuid
@@ -51,37 +51,36 @@
         country_list = [c for c in countries if c!=""]
         all_tags = Tag.objects.filter( Q(label__in=label_list) | Q(dbpedia_uri__in=country_list) )
         
+        # Get datasheets from ajax filter search
+        filter_output = filter_generic(request.GET.get('lang',request.LANGUAGE_CODE), None, ",".join(label_list), ",".join(country_list))
+        filter_output = json.loads(filter_output)
+        
+        # Prepare Node placer :
+        np = LineNodePlacer()
+        np.init({"tags": len(all_tags), "datasheet":len(filter_output["contents"])})
+        
         project_id = unicode(uuid.uuid1())
         
-        for i,t in enumerate(all_tags):
+        for t in all_tags:
             content["nodes"].append({
               "id": unicode(uuid.uuid1()),
               "title": t.label,
               "description": t.dbpedia_uri,
               "uri": t.dbpedia_uri,
-              "position": {
-                "x": 0,
-                "y": 100*i
-              },
+              "position": np.get_place("tags"),
               "image": None,
               "size": 0,
               "project_id": project_id,
               #"created_by": "roster_user-84fe909f-ba37-48e6-a25f-9d2f129a95b7"
             })
         
-        # Get datasheets from ajax filter search
-        filter_output = filter_generic(request.GET.get('lang',request.LANGUAGE_CODE), None, ",".join(label_list), ",".join(country_list))
-        filter_output = json.loads(filter_output)
-        for i,c in enumerate(filter_output["contents"]):
+        for c in filter_output["contents"]  :
             content["nodes"].append({
               "id": unicode(uuid.uuid1()),
               "title": c["title"],
               "description": c["description"],
               "uri": c["url"],
-              "position": {
-                "x": 200,
-                "y": 100*i - 50
-              },
+              "position": np.get_place("datasheet"),
               "image": None,
               "size": 0,
               "project_id": project_id,
@@ -96,4 +95,5 @@
     def put(self, request):
         
         return HttpResponse("OK")
-    
+        
+    
\ No newline at end of file