def isLoggedIn(self): """ return true if logged in properly. boolean wrapper on getLoginUID() """ if bool(self.getLoginUID()): return True else: # check if perhaps the user has a autologin cookie cookie_key = COOKIEKEY_AUTOLOGIN_UID autologin_uid = self.get_cookie(cookie_key, None) if autologin_uid: try: uid = int(autologin_uid) except ValueError: return False # check that the user exits if self.hasUser(uid): # autologin! debug("Autologin user with uid=%r" % uid, steps=4) self._loginUID(uid) return True else: # ...there is something very wrong about that uid debug("Autologin UID=%r does NOT exist" % uid) # delete the autologin cookie self.expire_cookie(cookie_key) return False
def retrain(self, epochs): debug('[Trainer]: Removing model...') try: os.remove(modelPath) except Exception: pass train(epochs)
def __init__(self, id, title, connection_id, arguments, template, relpath): self.id = str(id) try: self.manage_edit(title, connection_id, arguments, template) except: debug("id=%r, title=%r, arguments=%r" % (id, title, arguments), f=1) raise self.relpath = relpath
def build_response(res): data = {} debug(res) data["code"] = res.code data["short"] = res.short data["long"] = res.long data["page"] = res.page data["image"] = res.image return jsonify(data)
def generate(self, length, initx): debug('[Trainer]: Generating {} characters...'.format(length)) if initx == None: ix = [np.random.randint(self.VOCAB_SIZE)] else: ix = [initx] y_char = [self.ix_to_char[ix[-1]]] X = np.zeros((1, length, self.VOCAB_SIZE)) for i in range(length): X[0, i, :][ix[-1]] = 1 ix = np.argmax(self.model.predict(X[:, :i+1, :])[0], 1) y_char.append(self.ix_to_char[ix[-1]]) return ('').join(y_char)
def auth(): token = request.headers.get('token') date, key = token.split("-") computed_key = hash(date) currTime = int(round(time.time() * 1000)) timeDiff = abs(int(date) - currTime) debug("Date: " + date + " CurrDate: " + str(currTime) + " Diff: " + str(timeDiff)) debug("Token: " + key + " ComputedToken: " + computed_key) if not key == computed_key or timeDiff > 30000: raise MError("Unable to authenticate.")
def load(self): if self.MODEL == None: raise ValueError('No model given for loading') m = None if os.path.isfile(self.MODEL): try: debug('[ModelHandler]: Attempting to load model...') m = load_model(self.MODEL) except ValueError: debug('[ModelHandler]: Unable to load model...') pass if m == None: debug('[ModelHandler]: Creating model...') m = create(self.HIDDEN_DIM, self.VOCAB_SIZE, self.LAYER_NUM) return m
def wookiepedia(): res = {} try: auth() req = build_request() res = get_wookiepedia_abstract(req) except MError as exc: debug(exc.reason) res = build_error(exc.reason, exc.code) except: e = sys.exc_info()[0] debug(e) debug(e.args[0]) res = build_error("Wookiepedia Failed") finally: return build_response(res)
def _uploadImage(self, container, filename, data): """ upload a plain image """ debug("Adding Image %r inside %s" % (filename, container.absolute_url_path())) container.manage_addImage(filename, title='', file=data)
def _uploadDTMLDocument(self, container, filename, content): """ create the DTML Document """ debug("Adding DTMLDocument %r inside %s" % (filename, container.absolute_url_path())) container.manage_addDTMLDocument(filename, title='', file=content)
def _uploadInto(self, os_folderpath, zope_container, clean=False, create_zope_folder=True): """ upload all files in 'os_folderpath' into 'zope_container' """ folders_to_skip = 'examples', 'CVS', '_template' # basename assert os.path.isdir( os_folderpath), "os_folderpath is not a filesystem directory" basename = os_folderpath.split(os.path.sep)[-1] zope_container_base = getattr(zope_container, 'aq_base', zope_container) if clean and hasattr(zope_container_base, basename): zope_container.manage_delObjects([basename]) if create_zope_folder: if not hasattr(zope_container_base, basename): zope_container.manage_addFolder(basename) container = getattr(zope_container, basename) else: container = zope_container for o in os.listdir(os_folderpath): os_folderpath_o = os.path.join(os_folderpath, o) if os.path.isdir(os_folderpath_o): if o not in folders_to_skip: self._uploadInto(os_folderpath_o, container, clean=clean) else: content_buffer = open(os_folderpath_o, 'rb') if clean and hasattr(getattr(container, 'aq_base', container), o): # delete it first container.manage_delObjects([o]) if hasattr(getattr(container, 'aq_base', container), o): # it already exists if DEBUG: print "++SKIP++", o, "because it already exists" #print "\t", o in container.objectIds() continue if o.endswith('.js'): try: self._uploadJavaScriptDTMLDocument( container, o, content_buffer) except Exception, m: _t = "_uploadJavaScriptDTMLDocument(%r, %r," _t = _t % (container.absolute_url_path(), o) debug(_t, 1) raise Exception, m elif o.endswith('.css'): self._uploadCSSDTMLDocument(container, o, content_buffer) elif anyTrue(o.lower().endswith, ('jpg', 'gif', 'png')): self._uploadImage(container, o, content_buffer)
def train(self, epochs): debug('[Trainer]: Training model {} times...'.format(epochs)) self.model.fit(self.X, self.y, batch_size=self.BATCH_SIZE, verbose=0, epochs=epochs) debug('[Trainer]: Saving model...') self.model.save(self.MODEL, overwrite=True)