def display_xref(b64xref): xref = b64xref.decode("base64") h = XHTML().html h.head.link(rel="stylesheet", href="/cdastatic/cda.css") body = h.body(klass="xref") body.div.div(xref, klass="xrefstitle") if xref in xref_cache: for obj in xref_cache[xref]: linkobj = obj.replace("#",",")+","+b64xref body.div.a(obj, onclick="location.replace('#"+linkobj+"')", klass="filelink") return str(body)
def send(self): note = self.note xhtml = XHTML() n = EvernoteTypeNote() n.title = note['title'] n.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' n.content += '<en-note><pre>%s</pre></en-note>' % xhtml.p(note['content'].encode('utf-8')) n.tagNames = [x.strip() for x in note['tags'].split(',') if x.strip()] try: n = self.noteStore.createNote(n) except Exception, e: sublime.error_message('Sublime2Note: Failed to create note. Error detail: %s' % e)
def display_xref(b64xref): xref = b64xref.decode("base64") h = XHTML().html h.head.link(rel="stylesheet", href="/cdastatic/cda.css") body = h.body(klass="xref") body.div.div(xref, klass="xrefstitle") if xref in xref_cache: for obj in xref_cache[xref]: linkobj = obj.replace("#", ",") + "," + b64xref body.div.a(obj, onclick="location.replace('#" + linkobj + "')", klass="filelink") return str(body)
def mk_report(ofile, records, records_before=None): """ dictionary of records to html tree """ htree = XHTML() _add_includes(htree) hbody = htree.body if records_before: hbody.span('Note: red text is for before/reference system') colnames = _get_colnames(records, records_before) mkcols = lambda h: _add_row(h, ['file'] + colnames, []) htable = _add_report_table(hbody, fill_head=mkcols) fnames = set(records.keys()) fnames = fnames | set(records_before.keys() if records_before else []) for fname in sorted(fnames): record_before = None if records_before is None\ else records_before.get(fname) record_after = records.get(fname, []) _add_rowset(fname, colnames, htable, record_after, record_before=record_before) _write_html(ofile, htree)
def on_tags(tags): xh = XHTML() note = Types.Note() note.title = title.encode('utf-8') note.content = '<?xml version="1.0" encoding="UTF-8"?>' note.content += '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' note.content += '<en-note><pre>%s'%xh.p(content.encode('utf-8')) note.content += '</pre></en-note>' note.tagNames = tags and tags.split(",") or [] try: sublime.status_message("please wait...") cnote = noteStore.createNote(authToken, note) sublime.status_message("send success guid:%s"%cnote.guid) except Errors.EDAMUserException,e: if e.errorCode == 9: self.connect(self.send_note) else: sublime.error_message('error %s'%e)
def sendnote(title, tags): xh = XHTML() note = Types.Note() note.title = title.encode('utf-8') note.content = '<?xml version="1.0" encoding="UTF-8"?>' note.content += '<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' note.content += '<en-note><pre>%s' % xh.p(content.encode('utf-8')) note.content += '</pre></en-note>' note.tagNames = tags and tags.split(",") or [] try: sublime.status_message("please wait...") cnote = noteStore.createNote(authToken, note) sublime.status_message("send success guid:%s" % cnote.guid) sublime.message_dialog("success") except Errors.EDAMUserException, e: args = dict(title=title, tags=tags) if e.errorCode == 9: self.connect(self.send_note, **args) else: if sublime.ok_cancel_dialog('error %s! retry?' % e): self.connect(self.send_note, **args)
def home(): # generate html h = XHTML().html h.head.link(rel="stylesheet", href="/cdastatic/cda.css") h.head.script(src="/cdastatic/socket.io.min.js") h.head.script(src="/cdastatic/jquery-2.1.0.js") h.head.script(src="/cdastatic/jquery.scrollTo.min.js") h.head.script(src="/cdastatic/cda.js?" + os.urandom(16).encode("hex")) body = h.body prog = body.div(id="program") xrefs = body.div(id="xrefs") return str(h)
def __send_note(title, tags): xh = XHTML() note = Types.Note() note.title = title.encode('utf-8') note.content = '<?xml version="1.0" encoding="UTF-8"?>' note.content += '<!DOCTYPE en-note SYSTEM \ "http://xml.evernote.com/pub/enml2.dtd">' note.content += '<en-note><pre>%s' % xh.p(content.encode('utf-8')) note.content += '</pre></en-note>' note.tagNames = tags and tags.split(",") or [] try: sublime.status_message("please wait...") cnote = noteStore.createNote(note) sublime.status_message("send success guid:%s" % cnote.guid) sublime.message_dialog("success") except Errors.EDAMUserException, e: args = dict(title=title, tags=tags) if e.errorCode == 9: self.connect(self. send_note, **args) else: if sublime.ok_cancel_dialog('error %s! retry?' % e): self.connect(self.send_note, **args)
def generateControls(self): """ A method that will generate an HTML representation of all the controls for all the modules, if they have already been instantiated. A form container will also be generated, as well as fieldsets for every individual module. :rtype: A complete HTML form with every control for every available module inserted. """ html = XHTML() form = html.form("", role="form", action="/toolStart", method="post", enctype="multipart/form-data") for node in self.instantiatedNodes: if node == "start": continue; fieldset = form.fieldset("", klass="set-"+str(node)) fieldset.legend(str(node)) controls = node.specifyControls() if controls == None: fieldset.p("No controls specified for this module.") continue; for key, control in controls.items(): group = fieldset.div(klass="form-group") name = control.name if control.name == None: name = "undefined" control.name = str(node)+"-"+control.name theControl = control.toHTML() label = group.label(control.label) label._attrs["for"] = "control-"+name; group += theControl form.input(type="submit",value="Submit", klass="btn btn-default") return str(form)
def __init__(self, name=None, value=None, **kwargs): self.name = name self.value = value self.html = XHTML() self.attributes = {} self.data = {} self.allowedAttributes = None self.label = "" for k,v in kwargs.items(): setattr(self, k, v) self.__disabledAttributes = ["value","name"] pass
def display_file(): path = request.query_string if path not in file_cache: return "file " + str(path) + " not found" # generate the HTML h = XHTML().html body = h.body body.div(path, id='filename') #body.iframe(id='bottomframe') # get parsed file (care, rdat) = file_cache[path] # add line numbers lc = len(rdat.split("\n")) ln = body.div(id="ln") for linenum in range(lc): ln.span("%5d \n" % (linenum + 1), id="l" + str(linenum + 1), onclick='go_to_line(' + str(linenum + 1) + ')') # add the code #print object_cache p = body.div(id="code") last = 0 for (start, end, klass, usr) in care: if last > start: # this is not the proper fix #print "OMG ISSUE ",last,start,klass,usr continue p.span(rdat[last:start]) if usr != None: if usr in object_cache: #p.span(klass=klass, usr=usr).a(rdat[start:end], href="/f/"+object_cache[usr][0]) #if usr in xref_cache: #p.span(rdat[start:end], klass=klass+"\x00link", usr=usr, targets='\x00'.join(object_cache[usr]), xrefs='\x00'.join(xref_cache[usr])) #else: p.span(rdat[start:end], klass=klass + "\x00link", name=usr, targets='\x00'.join(object_cache[usr])) else: p.span(rdat[start:end], klass=klass, name=usr) else: p.span(rdat[start:end], klass=klass) last = end p.span(rdat[last:]) return str(body)
def write_html(options): """ read JSON file of images. """ # read the input folder h = XHTML() head = h.head() head.link(rel="stylesheet", href="style.css") body = h.body() outerdiv = body.div(style="margin:auto") with open(options.jsonfile) as infile: imgs = sort_images(json.load(infile)) # add horizontal pixel offset info imgs = px_offset_images(imgs) for img in imgs: h_shift = img['horiz_px_shift'] ic = outerdiv.div(klass="imgcontainer", style="position:relative;left:{}px".format(h_shift)) imgsrc = img['gmapstatic'] ic.img(src=imgsrc) with open(options.outputfile, 'w') as f: f.write(str(h))
def mk_attribute_subreport(oprefix, all_attrs, attribute, counts_after, counts_before=None): """ Write a table showing the number of items each value for an attribute occurs :: (FilePath, [String], String, Counter String) -> IO () (the `all_attrs` is used for navigation; it lets us build links to the other attributes) """ def _mk_fname(attr): "filename for an attribute report" return "{}-{}.html".format(oprefix, attr) htree = XHTML() hhead = htree.head _add_includes(hhead) hbody = htree.body hbody.h2(u'see also') hnav = hbody.table(klass='navtable') hnav_tr = hnav.tr hnav_tr.td.a('overview', href='index.html') hnav_tr.td() for attr in all_attrs: if attr == attribute: hnav_tr.td.span(attr) else: hnav_tr.td.a(attr, href=fp.basename(_mk_fname(attr))) hbody.h2(u'overview of ' + attribute) _add_attribute_factoids(hbody, counts_after, counts_before) hbody.h2(u'values for ' + attribute) _add_attribute_counts(hbody, counts_after, counts_before) _write_html(_mk_fname(attribute), htree)
def _save_scores(ofile, agg_scores, indiv_scores, keys): """ Actually generate the scoring table given the computed scores """ htree = XHTML() hhead = htree.head _add_includes(hhead) def _fmt_score(score): "Float -> String" if score is None: return u'0 (N/A)' else: return u'{:.4}'.format(100. * score) def _add_header(thead): "add a header to a count table" _add_row(thead, ['file'] + SCORE_KEYS, []) def _flat_scores(scores): "scores as list of columns" return [_fmt_score(scores[x]) for x in SCORE_KEYS] hbody = htree.body hbody.h2(u'aggregate scores') h_aggr = _add_report_table(hbody, fill_head=_add_header) _add_row(h_aggr, [''], _flat_scores(agg_scores)) hbody.h2(u'individual scores') h_indiv = _add_report_table(hbody, fill_head=_add_header) for key in keys: _add_row(h_indiv, [key], _flat_scores(indiv_scores[key])) with open(fp.splitext(ofile)[0] + '.txt', 'w') as tfile: for key, val in zip(SCORE_KEYS, _flat_scores(agg_scores)): print("{: <15}: {}".format(key, val), file=tfile) _write_html(ofile, htree)
import pycurl import StringIO import json import socket from html import XHTML h = XHTML() data = {} #Below code checks internet connection validity REMOTE_SERVER = "www.google.com" def is_connected(): try: # see if we can resolve the host name -- tells us if there is # a DNS listening host = socket.gethostbyname(REMOTE_SERVER) # connect to the host -- tells us if the host is actually # reachable s = socket.create_connection((host, 80), 2) return True except: pass return False print is_connected()
self.note["content"] = self.view.substr(region) def do_update(**kwargs): for key, value in kwargs.items(): self.note[key] = value self.send() def update_title(title): def update_tags(tags): do_update(title=title, tags=tags) self.window.show_input_panel("tags:","",update_tags,None,None) self.window.show_input_panel("title:","",update_title,None,None) def send(self): note = self.note dev_token = "S=s1:U=3a529:E=146e0f0c800:C=13f893f9c03:P=1cd:A=en-devtoken:V=2:H=987718ca0ff7773fee5fe6d1e73fe99f" client = EvernoteClient(token=dev_token) try: noteStore = client.get_note_store() except EDAMUserException, e: print "Authentication Failed. Error: %s" % e else: xhtml = XHTML() n = EvernoteTypeNote() n.title = note["title"] n.content = '<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd">' n.content += '<en-note><pre>%s</pre></en-note>' % xhtml.p(note["content"].encode('utf-8')) n.tagNames = [x.strip() for x in note["tags"].split(',') if x.strip()] try: n = noteStore.createNote(n) except Exception, e: print "Note Creation Failed. Error: %s" % e def run(self, edit): self.process_note()
def list(): h = XHTML().html for f in sorted(file_cache.keys()): h.body.div.a(f, href="#" + f + ",0,") return str(h)
def mk_overview(ofile, records, records_before=None): """ Create an HTML report showing some useful numbers about our data """ odir = fp.dirname(ofile) htree = XHTML() hhead = htree.head _add_includes(hhead) hbody = htree.body def _add_header(thead): "add a header to a count table" cols = [''] if records_before is not None: cols.append('before total') cols.append('after total') cols.append('before mean') cols.append('after mean') else: cols.append('total') cols.append('mean') _add_row(thead, cols, []) def _add_stat(table, name, get_stat): "add a statistic to a count table" cols = [] hrow = table.tr() # link to the attribute report if we have one fname = "attr-" + name + ".html" if fp.exists(fp.join(odir, fname)): hrow.td.a(name, href=fname) else: cols.append(name) sum_aft, avg_aft = count_and_mean(get_stat, records.values()) if records_before is not None: sum_bef, avg_bef = count_and_mean(get_stat, records_before.values()) cols.append(unicode(sum_bef)) cols.append(unicode(sum_aft)) cols.append("{:.4}".format(avg_bef)) cols.append("{:.4}".format(avg_aft)) else: cols.append(unicode(sum_aft)) cols.append("{:.4}".format(avg_aft)) for col in cols: _add_column(hrow, False, col) _overview_add_toc(hbody, records_before is not None) hbody.h2('general counts') htotals = _add_report_table(hbody, fill_head=_add_header) _add_stat(htotals, 'files', lambda _: 1) _add_stat(htotals, 'records', len) _add_stat(htotals, 'attributes', get_num_attrs) hbody.h2('attributes') hattrs = _add_report_table(hbody, fill_head=_add_header) attrs = _get_colnames(records, records_before=records_before, default=[]) for attr in attrs: _add_stat(hattrs, attr, get_num_instances(attr)) _write_html(ofile, htree)
class Control(object): """ The abstract base class for all controls """ __metaclass__ = ABCMeta def __init__(self, name=None, value=None, **kwargs): self.name = name self.value = value self.html = XHTML() self.attributes = {} self.data = {} self.allowedAttributes = None self.label = "" for k,v in kwargs.items(): setattr(self, k, v) self.__disabledAttributes = ["value","name"] pass def checkDisabled(self): """ Returns whether or not this control is disabled. """ if "disabled" in self.attributes.keys(): return self.attributes["disabled"] return False def setValue(self, v): """ Sets the control value. Does not allow the disabled attribute to be bypassed. :param v: Sets the control value. :rtype: Whether or not the value was succesfully set. """ if not self.checkDisabled(): self.value = v return True return False def getValue(self): """ Returns the current control value. :rtype: The control value. """ return self.value def setAttribute(self, key, value): """ Sets a control attribute. If Control.allowedAttributes is not None, it will only accept the attributes listed there. Will never accept attributes listed in Control.__disabledAttributes. :param key: The name of the attribute. :param value: The value of the attribute. :rtype: Whether or not the attribute was succesfully set. """ if (self.allowedAttributes == None or key in self.allowedAttributes) and key not in self.__disabledAttributes: self.attributes[key] = value return True return False def getAttribute(self, key): """ Attempts to retrieve an attribute of the control. :param key: The key of the attribute. :rtype: Either the value of the attribute or None if it was not set. """ try: # It's easier to ask for forgiveness... return self.attributes[key] except: # Than it is to get permission. return None # Also apparently better for performance. def setName(self, n): self.name = n def wrapHTML(self): """ Wraps the HTML control in a control wrapper.""" control = self.html.div(klass="control-wrapper") control.text(self.toHTML(), escape=False) return str(control) @classmethod def toHTML(self): """ Representing the control as an HTML element. Take care to only define generic classes,