class CreatePackageForm(Form): name = StringField(word('Package name'), validators=[ validators.Required( word('Package name is required')), validate_name ]) submit = SubmitField(word('Get template'))
def caption(self): self.case.firstParty.gathered self.case.secondParty.gathered output = "" output += "[BOLDCENTER] " + (word("In the") + " " + self.case.court.name).upper() + "\n\n" output += "[BEGIN_CAPTION]" output += comma_and_list(self.case.firstParty.elements, comma_string=",[NEWLINE]", and_string=word('and'), before_and=" ", after_and='[NEWLINE]') + ",[NEWLINE]" output += "[TAB][TAB]" + word( self.case.firstParty.as_noun()).capitalize() + "[NEWLINE] " output += "[SKIPLINE][TAB]" + word('v.') + " [NEWLINE][SKIPLINE] " output += comma_and_list(self.case.secondParty.elements, comma_string=",[NEWLINE]", and_string=word('and'), before_and=" ", after_and='[NEWLINE]') + ",[NEWLINE]" output += "[TAB][TAB]" + word( self.case.secondParty.as_noun()).capitalize() output += "[VERTICAL_LINE]" output += word('Case No.') + " " + self.case.case_id output += "[END_CAPTION]\n\n" if self.title is not None: output += "[BOLDCENTER] " + self.title.upper() + "\n" return (output)
def object_name_convert(text): match = match_inside_and_outside_brackets.search(text) if match: index = noquote(match.group(2)) if is_number.match(index): prefix = ordinal(index) + ' ' else: prefix = index + ' ' return prefix + word(underscore_to_space(match.group(1))) return word(underscore_to_space(text))
def pronoun(self, **kwargs): if self == this_thread.user: output = word("you") if self.gender == "female": output = word("her") else: output = word("him") if "capitalize" in kwargs and kwargs["capitalize"]: return capitalize(output) else: return output
def pronoun(self, **kwargs): if self == this_thread.user: output = word('you') if self.gender == 'female': output = word('her') else: output = word('him') if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def pronoun_subjective(self, **kwargs): if self == this_thread.user and ("thirdperson" not in kwargs or not kwargs["thirdperson"]): output = word("you") elif self.gender == "female": output = word("she") else: output = word("he") if "capitalize" in kwargs and kwargs["capitalize"]: return capitalize(output) else: return output
def pronoun_subjective(self, **kwargs): if self == this_thread.user and ('thirdperson' not in kwargs or not kwargs['thirdperson']): output = word('you') elif self.gender == 'female': output = word('she') else: output = word('he') if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def pronoun(self, **kwargs): if self == this_thread.user: output = word('you') if self.gender == 'female': output = word('her') else: output = word('him') if 'capitalize' in kwargs and kwargs['capitalize']: return (capitalize(output)) else: return (output)
def pronoun(self, **kwargs): """Returns a pronoun like "you," "her," or "him," as appropriate.""" if self == this_thread.user: output = word('you', **kwargs) if self.gender == 'female': output = word('her', **kwargs) else: output = word('him', **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return (capitalize(output)) else: return (output)
def pronoun_subjective(self, **kwargs): if self == this_thread.user and ('thirdperson' not in kwargs or not kwargs['thirdperson']): output = word('you') elif self.gender == 'female': output = word('she') else: output = word('he') if 'capitalize' in kwargs and kwargs['capitalize']: return (capitalize(output)) else: return (output)
def pronoun(self, **kwargs): """Returns a pronoun like "you," "her," or "him," as appropriate.""" if self == this_thread.user: output = word('you', **kwargs) if self.gender == 'female': output = word('her', **kwargs) else: output = word('him', **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def pronoun_subjective(self, **kwargs): """Returns a pronoun like "you," "she," or "he," as appropriate.""" if self == this_thread.user and ('thirdperson' not in kwargs or not kwargs['thirdperson']): output = word('you', **kwargs) elif self.gender == 'female': output = word('she', **kwargs) else: output = word('he', **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def pronoun_subjective(self, **kwargs): """Returns a pronoun like "you," "she," or "he," as appropriate.""" if self == this_thread.user and ('thirdperson' not in kwargs or not kwargs['thirdperson']): output = word('you', **kwargs) elif self.gender == 'female': output = word('she', **kwargs) else: output = word('he', **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return (capitalize(output)) else: return (output)
def populate_tables(): existing_admin = Role.query.filter_by(name=word("admin")).first() if existing_admin: return defaults = daconfig.get( "default_admin_account", {"nickname": "admin", "email": "*****@*****.**", "password": "******"} ) docassemble_git_url = daconfig.get("docassemble_git_url", "https://github.com/jhpyle/docassemble") admin_role = Role(name=word("admin")) user_role = Role(name=word("user")) developer_role = Role(name=word("developer")) advocate_role = Role(name=word("advocate")) db.session.add(admin_role) db.session.add(user_role) db.session.add(developer_role) db.session.add(advocate_role) user_manager = UserManager(SQLAlchemyAdapter(db, User, UserAuthClass=UserAuth), app) user_auth = UserAuth(password=app.user_manager.hash_password(defaults["password"])) user = User( active=True, nickname=defaults["nickname"], social_id="local$" + "".join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32)), email=defaults["email"], user_auth=user_auth, ) user.roles.append(admin_role) db.session.add(user_auth) db.session.add(user) db.session.commit() installed_packages = sorted(get_installed_distributions()) for package in installed_packages: package_auth = PackageAuth(user_id=user.id) if package.key in ["docassemble", "docassemble.base", "docassemble.webapp", "docassemble.demo"]: package_entry = Package( name=package.key, package_auth=package_auth, giturl=docassemble_git_url, packageversion=package.version, gitsubdir=re.sub(r"\.", "_", package.key), type="git", core=True, ) else: package_entry = Package( name=package.key, package_auth=package_auth, packageversion=package.version, type="pip", core=True ) db.session.add(package_auth) db.session.add(package_entry) db.session.commit() return
def add_privilege(): form = NewPrivilegeForm(request.form, current_user) if request.method == 'POST' and form.validate(): for role in db.session.query(Role).order_by(Role.name): if role.name == form.name.data: flash(word('The privilege could not be added because it already exists.'), 'error') return redirect(url_for('privilege_list')) db.session.add(Role(name=form.name.data)) db.session.commit() flash(word('The privilege was added.'), 'success') return redirect(url_for('privilege_list')) return render_template('users/new_role_page.html', form=form)
def add_privilege(): form = NewPrivilegeForm(request.form, current_user) if request.method == "POST" and form.validate(): for role in db.session.query(Role).order_by(Role.name): if role.name == form.name.data: flash(word("The privilege could not be added because it already exists."), "error") return redirect(url_for("privilege_list")) db.session.add(Role(name=form.name.data)) db.session.commit() flash(word("The privilege was added."), "success") return redirect(url_for("privilege_list")) return render_template("users/new_role_page.html", form=form)
def read_fields(pdffile): outfields = list() fp = open(pdffile, 'rb') id_to_page = dict() parser = PDFParser(fp) doc = PDFDocument(parser) pageno = 1; for page in PDFPage.create_pages(doc): id_to_page[page.pageid] = pageno pageno += 1 fields = resolve1(doc.catalog['AcroForm'])['Fields'] for i in fields: field = resolve1(i) name, value, rect, page, field_type = field.get('T'), field.get('V'), field.get('Rect'), field.get('P'), field.get('FT') logmessage("name is " + str(name) + " and FT is |" + str(field_type) + "|") if page is not None: pageno = id_to_page[page.objid] else: pageno = 1 if str(field_type) == '/Btn': if value == '/Yes': default = "Yes" else: default = "No" elif str(field_type) == '/Sig': default = '${ user.signature }' else: if value is not None: default = value else: default = word("something") outfields.append((name, default, pageno, rect, field_type)) return outfields
def year_of(the_date): """Interprets the_date as a date and returns the year.""" date = dateutil.parser.parse(the_date) try: return(date.strftime('%Y')) except: return word("Bad date")
def day_of(the_date): """Interprets the_date as a date and returns the day of month.""" date = dateutil.parser.parse(the_date) try: return(date.strftime('%d')) except: return word("Bad date")
def validate(cls, item): # If there's no input in the item, it's valid if not isinstance(item, str) or item == "": return True else: # Otherwise it needs to be a date on or before today and after the year 1000. # We ourselves create this format if the user gives valid info. matches_date_pattern = re.search(r"^\d{1,2}\/\d{1,2}\/\d{4}$", item) try: date = as_datetime(item) except Exception as error: msg = f"{ item } {word('is not a valid date')}" raise DAValidationError(msg) if matches_date_pattern: date_diff = date_difference(starting=date, ending=today()) if date_diff.days >= 0.0: return True else: raise DAValidationError( word("Answer with a <strong>date of birth</strong>") ) else: msg = ( f"{ item } {word('is not a valid <strong>date of birth</strong>')}" ) raise DAValidationError(msg)
def edit_user_profile_page(id): user = User.query.filter_by(id=id).first() if user is None: abort(404) the_role_id = None for role in user.roles: the_role_id = role.id form = EditUserProfileForm(request.form, user, role_id=the_role_id) form.role_id.choices = [(r.id, r.name) for r in Role.query.order_by('name')] logmessage("Setting default to " + str(the_role_id)) if request.method == 'POST' and form.validate(): form.populate_obj(user) roles_to_remove = list() for role in user.roles: roles_to_remove.append(role) for role in roles_to_remove: user.roles.remove(role) for role in Role.query.order_by('id'): if role.id == form.role_id.data: user.roles.append(role) break db.session.commit() flash(word('The information was saved.'), 'success') return redirect(url_for('user_list')) return render_template('users/edit_user_profile_page.html', form=form)
def to_text(html_doc): output = "" soup = BeautifulSoup(html_doc, 'html.parser') [s.extract() for s in soup(['style', 'script', '[document]', 'head', 'title', 'audio', 'video', 'pre', 'attribution'])] [s.extract() for s in soup.find_all(hidden)] for s in soup.find_all(do_show): if s.name in ['input', 'textarea', 'img'] and s.has_attr('alt'): words = s.attrs['alt'] if s.has_attr('placeholder'): words += ", " + s.attrs['placeholder'] else: words = s.get_text() words = re.sub(r'\n\s*', ' ', words, flags=re.DOTALL) if len(words) and re.search(r'\w *$', words, re.UNICODE): words = words + '.' output += words + "\n" terms = dict() for s in soup.find_all('a'): if s.has_attr('class') and s.attrs['class'][0] == 'daterm' and s.has_attr('data-content'): terms[s.string] = s.attrs['data-content'] if len(terms): output += word("Terms used in this question:") + "\n" for term, definition in terms.iteritems(): output += term + '. ' + definition + '\n' output = re.sub(r'&gt;', '>', output) output = re.sub(r'&lt;', '<', output) output = re.sub(r'>', '>', output) output = re.sub(r'<', '<', output) output = re.sub(r'<[^>]+>', '', output) return output
def read_fields(pdffile): outfields = list() fp = open(pdffile, 'rb') id_to_page = dict() parser = PDFParser(fp) doc = PDFDocument(parser) pageno = 1 for page in PDFPage.create_pages(doc): id_to_page[page.pageid] = pageno pageno += 1 fields = resolve1(doc.catalog['AcroForm'])['Fields'] for i in fields: field = resolve1(i) name, value, rect, page, field_type = field.get('T'), field.get( 'V'), field.get('Rect'), field.get('P'), field.get('FT') logmessage("name is " + str(name) + " and FT is |" + str(field_type) + "|") if page is not None: pageno = id_to_page[page.objid] else: pageno = 1 if str(field_type) == '/Btn': if value == '/Yes': default = "Yes" else: default = "No" elif str(field_type) == '/Sig': default = '${ user.signature }' else: if value is not None: default = value else: default = word("something") outfields.append((name, default, pageno, rect, field_type)) return outfields
def pronoun_objective(self, **kwargs): """Returns "it" or "It" depending on the value of the optional keyword argument "capitalize." """ output = word('it', **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def pronoun_objective(self, **kwargs): """Returns "it" or "It" depending on the value of the optional keyword argument "capitalize." """ output = word('it', **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return (capitalize(output)) else: return (output)
def caption(self): self.case.firstParty.gathered self.case.secondParty.gathered output = "" output += "[BOLDCENTER] " + (word("In the") + " " + self.case.court.name).upper() + "\n\n" output += "[BEGIN_CAPTION]" output += comma_and_list(self.case.firstParty.elements, comma_string=",[NEWLINE]", and_string=word('and'), before_and=" ", after_and='[NEWLINE]') + ",[NEWLINE]" output += "[TAB][TAB]" + word(self.case.firstParty.as_noun()).capitalize() + "[NEWLINE] " output += "[SKIPLINE][TAB]" + word('v.') + " [NEWLINE][SKIPLINE] " output += comma_and_list(self.case.secondParty.elements, comma_string=",[NEWLINE]", and_string=word('and'), before_and=" ", after_and='[NEWLINE]') + ",[NEWLINE]" output += "[TAB][TAB]" + word(self.case.secondParty.as_noun()).capitalize() output += "[VERTICAL_LINE]" output += word('Case No.') + " " + self.case.case_id output += "[END_CAPTION]\n\n" if self.title is not None: output += "[BOLDCENTER] " + self.title.upper() + "\n" return(output)
def add_privilege(): form = NewPrivilegeForm(request.form, current_user) if request.method == 'POST' and form.validate(): for role in db.session.query(Role).order_by(Role.name): if role.name == form.name.data: flash( word( 'The privilege could not be added because it already exists.' ), 'error') return redirect(url_for('privilege_list')) db.session.add(Role(name=form.name.data)) db.session.commit() flash(word('The privilege was added.'), 'success') return redirect(url_for('privilege_list')) return render_template('users/new_role_page.html', form=form)
def yourself_or_name(self, **kwargs): if self == this_thread.user: output = word('yourself') else: output = self.name.full() if 'capitalize' in kwargs and kwargs['capitalize']: return (capitalize(output)) else: return (output)
def yourself_or_name(self, **kwargs): if self == this_thread.user: output = word("yourself") else: output = self.name.full() if "capitalize" in kwargs and kwargs["capitalize"]: return capitalize(output) else: return output
def yourself_or_name(self, **kwargs): if self == this_thread.user: output = word('yourself') else: output = self.name.full() if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def pronoun(self, **kwargs): """Returns a pronoun like "you," "her," or "him," "it", or "them," as appropriate.""" if len(self.elements) == 1: return self.elements[0].pronoun(**kwargs) output = word('them', **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def validate_signature(self, code): if code not in self.info_by_code: raise Exception("Invalid code") self.info_by_code[code]['signed'] = True self.info_by_code[code]['date'] = today() self.info_by_code[code]['datetime'] = current_datetime() self.info_by_code[code]['ip'] = device( ip=True) or word("Unable to determine IP address") self.check_if_final()
def pronoun_subjective(self, **kwargs): """Returns a pronoun like "you," "she," "he," or "they" as appropriate.""" if len(self.elements) == 1: return self.elements[0].pronoun_subjective(**kwargs) output = word('they', **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def month_of(the_date, as_word=False): """Interprets the_date as a date and returns the month. Set as_word to True if you want the month as a word.""" date = dateutil.parser.parse(the_date) try: if as_word: return(date.strftime('%B')) return(date.strftime('%m')) except: return word("Bad date")
def yourself_or_name(self, **kwargs): """Returns a "yourself" if the individual is the user, otherwise returns the individual's name.""" if self == this_thread.user: output = word('yourself', **kwargs) else: output = self.name.full() if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def is_are_you(self, **kwargs): """Returns "are you" if the object is the user, otherwise returns "is" followed by the object name.""" if self is this_thread.user: output = word('are you', **kwargs) else: output = is_word(self.full(), **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return (capitalize(output)) else: return (output)
def is_are_you(self, **kwargs): """Returns "are you" if the object is the user, otherwise returns "is" followed by the object name.""" if self is this_thread.user: output = word('are you', **kwargs) else: output = is_word(self.full(), **kwargs) if 'capitalize' in kwargs and kwargs['capitalize']: return(capitalize(output)) else: return(output)
def yourself_or_name(self, **kwargs): """Returns a "yourself" if the individual is the user, otherwise returns the individual's name.""" if self == this_thread.user: output = word('yourself', **kwargs) else: output = self.name.full() if 'capitalize' in kwargs and kwargs['capitalize']: return (capitalize(output)) else: return (output)
def delete_privilege(id): role = Role.query.filter_by(id=id).first() user_role = Role.query.filter_by(name="user").first() if role is None or role.name in ["user", "admin", "developer", "advocate"]: flash(word("The role could not be deleted."), "error") else: for user in db.session.query(User): roles_to_remove = list() for the_role in user.roles: if the_role.name == role.name: roles_to_remove.append(the_role) if len(roles_to_remove) > 0: for the_role in roles_to_remove: user.roles.remove(the_role) if len(user.roles) == 0: user.roles.append(user_role) db.session.commit() db.session.delete(role) db.session.commit() flash(word("The role " + role.name + " was deleted."), "success") return redirect(url_for("privilege_list"))
def delete_privilege(id): role = Role.query.filter_by(id=id).first() user_role = Role.query.filter_by(name='user').first() if role is None or role.name in ['user', 'admin', 'developer', 'advocate']: flash(word('The role could not be deleted.'), 'error') else: for user in db.session.query(User): roles_to_remove = list() for the_role in user.roles: if the_role.name == role.name: roles_to_remove.append(the_role) if len(roles_to_remove) > 0: for the_role in roles_to_remove: user.roles.remove(the_role) if len(user.roles) == 0: user.roles.append(user_role) db.session.commit() db.session.delete(role) db.session.commit() flash(word('The role ' + role.name + ' was deleted.'), 'success') return redirect(url_for('privilege_list'))
def read_fields_pdftk(pdffile): output = check_output([PDFTK_PATH, pdffile, 'dump_data_fields']) fields = list() if not len(output) > 0: return None for field in yaml.load_all(output): if 'FieldType' in field and field['FieldType'] == 'Button': default = "No" else: default = word("something") if 'FieldName' in field: fields.append((field['FieldName'], default)) return fields
def read_fields(pdffile): output = check_output([PDFTK_PATH, pdffile, "dump_data_fields"]) fields = list() if not len(output) > 0: return None for field in yaml.load_all(output): if "FieldType" in field and field["FieldType"] == "Button": default = "No" else: default = word("something") if "FieldName" in field: fields.append((field["FieldName"], default)) return fields
def user_profile_page(): form = UserProfileForm(request.form, current_user) if request.method == "POST" and form.validate(): form.populate_obj(current_user) db.session.commit() flash(word("Your information was saved."), "success") return redirect(url_for("index")) return render_template("users/user_profile_page.html", form=form)
def user_profile_page(): form = UserProfileForm(request.form, current_user) if request.method == 'POST' and form.validate(): form.populate_obj(current_user) db.session.commit() flash(word('Your information was saved.'), 'success') return redirect(url_for('index')) return render_template('users/user_profile_page.html', form=form, debug=debug_status())
class PlaygroundForm(Form): original_playground_name = StringField(word('Original Name')) playground_name = StringField(word('Name'), [validators.Length(min=1, max=255)]) playground_content = TextAreaField(word('Playground YAML')) submit = SubmitField(word('Save')) run = SubmitField(word('Save and Run')) delete = SubmitField(word('Delete'))
class ThreePartDateDataType(CustomDataType): name = 'textdate' input_type = 'textdate' jq_rule = 'textdate' jq_message = word("This date doesn't look right") @classmethod def validate(cls, aDate): # Try to change string into DADateTime try: as_datetime(aDate) return True # If error, date is not a valid DADateTime except: return False
class ThreePartsDate(CustomDataType): name = "ThreePartsDate" input_type = "ThreePartsDate" javascript = js_text jq_message = word("Answer with a valid date") is_object = True # Probably won't work because the input to validate is hidden jq_rule = "date" @classmethod def validate(cls, item): # If there's no input in the item, it's valid if not isinstance(item, str) or item == "": return True else: # Otherwise it needs to be a date after the year 1000. We ourselves make # sure this format is created if the user gives valid info. matches_date_pattern = re.search(r"^\d{1,2}\/\d{1,2}\/\d{4}$", item) if matches_date_pattern: try: date = as_datetime(item) except Exception as error: msg = f"{ item } {word('is not a valid date')}" raise DAValidationError(msg) return True else: raise DAValidationError(f"{ item } {word('is not a valid date')}") @classmethod def transform(cls, item): if item: return as_datetime(item) @classmethod def default_for(cls, item): if item: return item.format("MM/dd/yyyy")
def to_text(html_doc): output = "" soup = BeautifulSoup(html_doc, 'html.parser') [ s.extract() for s in soup([ 'style', 'script', '[document]', 'head', 'title', 'audio', 'video', 'pre', 'attribution' ]) ] [s.extract() for s in soup.find_all(hidden)] for s in soup.find_all(do_show): if s.name in ['input', 'textarea', 'img'] and s.has_attr('alt'): words = s.attrs['alt'] if s.has_attr('placeholder'): words += ", " + s.attrs['placeholder'] else: words = s.get_text() words = re.sub(r'\n\s*', ' ', words, flags=re.DOTALL) if len(words) and re.search(r'\w *$', words, re.UNICODE): words = words + '.' output += words + "\n" terms = dict() for s in soup.find_all('a'): if s.has_attr('class') and s.attrs['class'][ 0] == 'daterm' and s.has_attr('data-content'): terms[s.string] = s.attrs['data-content'] if len(terms): output += word("Terms used in this question:") + "\n" for term, definition in terms.iteritems(): output += term + '. ' + definition + '\n' output = re.sub(r'&gt;', '>', output) output = re.sub(r'&lt;', '<', output) output = re.sub(r'>', '>', output) output = re.sub(r'<', '<', output) output = re.sub(r'<[^>]+>', '', output) return output
class BirthDate(ThreePartsDate): name = "BirthDate" input_type = "BirthDate" javascript = js_text.replace("ThreePartsDate", "BirthDate") jq_message = word("Answer with a valid date of birth") is_object = True # Probably won't work because the input to validate is hidden jq_rule = "date" @classmethod def validate(cls, item): # If there's no input in the item, it's valid if not isinstance(item, str) or item == "": return True else: # Otherwise it needs to be a date on or before today and after the year 1000. # We ourselves create this format if the user gives valid info. matches_date_pattern = re.search(r"^\d{1,2}\/\d{1,2}\/\d{4}$", item) try: date = as_datetime(item) except Exception as error: msg = f"{ item } {word('is not a valid date')}" raise DAValidationError(msg) if matches_date_pattern: date_diff = date_difference(starting=date, ending=today()) if date_diff.days >= 0.0: return True else: raise DAValidationError( word("Answer with a <strong>date of birth</strong>") ) else: msg = ( f"{ item } {word('is not a valid <strong>date of birth</strong>')}" ) raise DAValidationError(msg)