示例#1
0
文件: views.py 项目: deecewan/based
def create():
    form = ContactForm()
    if form.validate_on_submit():
        new_contact = Contact()
        new_name = Name()
        new_contact.email = form.email.data
        new_name.first_name = form.first_name.data
        new_name.last_name = form.last_name.data
        new_contact.name = new_name
        new_contact.group = form.group.data
        new_contact.known_from = form.known_from.data
        new_contact.general_comment = form.general_note.data
        new_contact.current_status = form.status.data
        for language in form.languages.data:
            if language:
                new_contact.tags.append(language)
        other_tags = form.other_tags.data.replace(', ', ',').split(',')
        for tag in other_tags:
            new_contact.tags.append(tag)
        try:
            new_contact.save()
            flash_string = '<a href=\"/{}\">{} {}</a> was added to the database.'
            flash_string = flash_string.format(new_contact.email, new_contact.name.first_name,
                                               new_contact.name.last_name)
            flash(Markup(flash_string))
            update_p_dict()
            return redirect(url_for('index'))
        except NotUniqueError:
            msg = "That email address is already in use.  <a href=\"/" + form.email.data + "\">View Entry.</a>"
            form.email.errors.append(Markup(msg))
        except Exception as e:
            flash("There were database-raised errors in the form.  Specifically, " + e.message)

    return render_template('create_contact.html', form=form)
示例#2
0
    def iati_organisations__iati_organisation__name(self, element):
        model = self.get_model('Organisation')
        name = Name()
        name.organisation = model
        self.register_model('Name', name)

        return element
示例#3
0
def insert_names_into_db(batch_size: int = 10000, limit: int = 200000):
    with open('name.basics.tsv') as names_tsv:
        names_tsv.readline()
        reader = csv.reader(names_tsv, delimiter='\t')
        counter = 0

        names = []
        number_in_batch = 0
        for row in tqdm(reader):
            if number_in_batch > batch_size:
                number_in_batch = 0
                db_session.add_all(names)
                db_session.commit()
                names = []
                counter += batch_size
                print(f'added {counter} names')
                if limit and counter >= limit:
                    return
            row = list(map(map_null, row))
            name = Name(
                nconst=row[0],
                primaryName=row[1],
                birthYear=row[2],
                deathYear=row[3],
                primaryProfession=row[4],
            )
            if row[5]:
                titles = Title.query.filter(Title.tconst.in_(
                    row[5].split(',')))
            name.knownForTitles = list(titles)
            names.append(name)
            number_in_batch += 1
        db_session.commit()
示例#4
0
def create():
    form = ContactForm()
    if form.validate_on_submit():
        new_contact = Contact()
        new_name = Name()
        new_contact.email = form.email.data
        new_name.first_name = form.first_name.data
        new_name.last_name = form.last_name.data
        new_contact.name = new_name
        new_contact.group = form.group.data
        for language in form.languages.data:
            if language:
                new_contact.tags.append(language)
        other_tags = form.other_tags.data.replace(", ", ",").split(",")
        for tag in other_tags:
            new_contact.tags.append(tag)
        try:
            new_contact.save()
            print new_contact.name.first_name, new_contact.name.last_name
            flash_string = '<a href="/{}">{} {}</a> was added to the database.'
            print flash_string
            flash_string = flash_string.format(
                new_contact.email, new_contact.name.first_name, new_contact.name.last_name
            )
            flash(Markup(flash_string))
            return redirect(url_for("index"))
        except Exception as e:
            print "Errors in the form"
            flash("There were errors in the form.  Specifically, " + e.message)

    return render_template("create_contact.html", form=form)
示例#5
0
def add_name():
    # add a name to the DB
    new_name = Name()
    new_name.id = determine_next_id()
    new_name.name = request.json["name"]
    new_name.gender = request.json["gender"]
    db.session.add(new_name)
    db.session.commit()
    return jsonify(success=True)
示例#6
0
def name():
    if request.method == 'POST':
        if 'Projects' in request.form:
            return redirect(url_for('projects'))
        elif 'About' in request.form:
            return redirect(url_for('about'))

        names = request.form['name']
        n = Name(name=names)
        db.session.add(n)
        db.session.commit()
        '''
    	
		
		    
	    

		print('lalalal')
		details = request.form
		namez = details['name']
		namez=Names(name=namez,)
		db.session.add(namez)
		db.session.commit()
		'''

        return render_template('Names.html', name=Names.query.all())

    else:

        return render_template('Names.html', name=Names.query.all())
示例#7
0
文件: main.py 项目: nameerased/Pars
def get_genders():
    genders = {}
    query = Name.select().where(Name.gender.is_null(False)).dicts()
    for i in query:
        genders[i['username']] = i['gender']
    print(len(genders))

    return genders
示例#8
0
def add_name():

    name = request.values.get('name')
    email = request.values.get('email')
    contact_number = request.values.get('contact_number')

    name = Name(name=name, email=email, contact_number=contact_number)

    db.session.add(name)
    db.session.commit()

    return "Successfully added"
示例#9
0
def do(request, nid, browser_tab):
    WZ = Z.SetWhoZwho(request, browser_tab)
    if WZ['ErrorMessage']:
        return GoLogout(request, WZ)

    if nid != '0':
        try:
            name = Name.objects.get(pk=int(nid))
        except:
            return GoLogout(request, WZ, "[PC01]: URL containd an invalid name ID.")

        if WZ['Authority'] < Z.Admin and name.owner != WZ['AuthorizedOwner']:
            return GoLogout(request, WZ, "[PC02]: URL containd an invalid name ID.")

        if WZ['Authority'] >= Z.Admin:
            WZ['AuthorizedOwner'] = name.owner

    if request.method == 'POST': # If the form has been submitted...
        form = DirectoryEditPCForm(request.POST, request.FILES)
        if form.is_valid():
            if nid == '0':
                try:
                    name = Name.objects.get(pk=int(WZ['Nid']))
                except:
                    return GoLogout(request, WZ, "[PC03]: Invalid name ID.")

                new_user = User()
                new_user.username = '******' + str(time.time())
                new_user.first_name = form.cleaned_data['first']
                new_user.last_name = form.cleaned_data['last']
                new_user.email = name.user.email
                new_user.save()

                new_name = Name()
                new_name.user = new_user
                new_name.approved = True
                new_name.authority = Z.NewRO
                new_name.private = True
                new_name.owner = name.owner

                new_name.first = form.cleaned_data['first']
                new_name.last = form.cleaned_data['last']
                new_name.email = form.cleaned_data['email']
                new_name.cell = form.cleaned_data['cell']
                new_name.work_email = form.cleaned_data['work_email']
                new_name.work_phone = form.cleaned_data['work_phone']
                new_name.birthday = form.cleaned_data['birthday']
                new_name.title = form.cleaned_data['title']
                new_name.gender = form.cleaned_data['gender']
                new_name.save()
                new_name.save()
            else:
                name.first = form.cleaned_data['first']
                name.last = form.cleaned_data['last']
                name.email = form.cleaned_data['email']
                name.cell = form.cleaned_data['cell']
                name.work_email = form.cleaned_data['work_email']
                name.work_phone = form.cleaned_data['work_phone']
                name.birthday = form.cleaned_data['birthday']
                name.title = form.cleaned_data['title']
                name.gender = form.cleaned_data['gender']
                name.save()

            logger.info(WZ['User'] + ' PC ' + str(request.POST))

            if WZ['ErrorMessage'] == "":
                if WZ['Authority'] >= Z.Admin:
                    return HttpResponseRedirect('/WhoZwho/aelst')
                else:
                    return HttpResponseRedirect('/WhoZwho/delst')
        else:
            WZ['ErrorMessage'] = str(form.errors)
    else:
        if nid == '0':
            form = DirectoryEditPCForm()
            edit_pc_title = 'Add a New Personal Contact'
            addresses = []
            name = None
            schoices = []
            spouse = []
        else:
            form = DirectoryEditPCForm(initial={
                'first': name.first,
                'last': name.last,
                'email': name.email,
                'cell': name.cell,
                'work_email': name.work_email,
                'work_phone': name.work_phone,
                'birthday': name.birthday,
                'title': name.title,
                'gender': name.gender
                }) 

            addresses = Address.objects.all(). \
                filter(owner__exact=WZ['AuthorizedOwner']). \
                order_by('street')

            if name.wedding:
                spouse = name.wedding.name_set.all(). \
                    exclude(id__exact=name.id)
                schoices = []
            else:
                spouse = []
                schoices = Name.objects.all(). \
                    filter(owner__exact=WZ['AuthorizedOwner']). \
                    filter(wedding__exact=None). \
                    exclude(gender__exact=name.gender). \
                    exclude(id__exact=name.id). \
                    order_by('first')

            edit_pc_title = 'Edit Personal Contact: ' + name.first + ' ' + name.last


        context = {
            'EditPCTitle': edit_pc_title,
            'Admin': Z.Admin,
            'addresses': addresses,
            'browser_tab': WZ['Tabs'][WZ['ActiveTab']][2],
            'form': form,
            'name': name,
            'nid': nid,
            'picture': WZ['httpURL'] + 'static/pics/defaults/greyman.gif',
            'spouse': spouse,
            'schoices': schoices,
            'WZ': WZ
            }

        context.update(csrf(request))
        return render_to_response('DirectoryEditPC.html', context )
示例#10
0
            ctarcode=ctarcode,
            extrcode=extrcode,
            sextcode=sextcode,
            livestatus=livestatus,
            names=names)

        session.add(place)
        session.commit()

        i += 1
        if i % 10000 == 0:
            print i


if __name__ == "__main__":
    import sys

    filename = sys.argv[1]
    _initdb(filename)

    text = u"""Посреди предложения встречаются два
    наименования город Казань
    и его часть улица Баумана, остальные слова -
    для заполнения"""

    from models import Name
    # import ipdb; ipdb.set_trace()
    addresses = Name.extract_addresses(text)
    for addr in addresses:
        print addresses[addr], unicode(addr).encode('utf-8')
示例#11
0
def read_file(filename):
	with codecs.open(filename, mode='r') as file:
		reader = csv.reader(file)
		first_line = reader.next()

		# maintain stack of taxa that are parents of the current taxon
		stack = []
		# name of parent of root taxon should be in cell A1
		root_name = first_line[0]
		if root_name != '':
			root_parent = Taxon.filter(Taxon.valid_name == root_name)[0]
			stack.append(root_parent)

		# current valid taxon (for synonyms)
		current_valid = None
		# whether current taxon should be marked as root of a page
		is_page_root = True
		error_occurred = False
		for row in reader:
			try:
				# ignore blank rows
				if row[14] == '' and row[8] == '':
					continue
				data = parse_row(row)
				# deal with "nHT", which is a pain. Some of these may need to be manually
				# readded to the DB
				if data['kind'] == 'nHT':
					if data['valid_name'] in ignored_nHT:
						continue
					else:
						raise Exception("Unrecognized nHT: " + str(data))
				# nsgen is i.s., just ignore
				if data['kind'] == 'nsgen':
					continue

				if data['status'] == STATUS_VALID:
					# get stuff off the stack
					rank = data['rank']
					if rank == ROOT:
						current_valid = Taxon.create(
							valid_name=data['valid_name'], age=data['age'],
							rank=data['rank'], is_page_root=True
						)
					else:
						# TODO: make this somehow unranked-clade-aware
						while rank >= stack[-1].rank:
							stack.pop()
						# create new Taxon
						current_valid = Taxon.create(
							valid_name=data['valid_name'], age=data['age'],
							rank=data['rank'], parent=stack[-1], is_page_root=is_page_root
						)
					if is_page_root:
						is_page_root = False
					stack.append(current_valid)
				# create new Name
				data['taxon'] = current_valid
				if data['status'] == STATUS_DUBIOUS:
					# current system is inadequate for properly marking si species
					# assume there's only genera and species
					if ' ' in data['valid_name']:
						data['group'] = GROUP_SPECIES
					else:
						data['group'] = GROUP_GENUS
					# si species don't have a meaningful "valid name", but preserve what's there now
					data['data']['si_valid_name'] = data['valid_name']
				else:
					# this will be wrong in the few cases where a high-ranked name is listed
					# as a synonym of a family-group name. Don't see a way to correct that
					# programmatically.
					data['group'] = helpers.group_of_rank(current_valid.rank)
					if data['status'] == STATUS_SYNONYM:
						if data['kind'] == 'synHT':
							valid_name = data['valid_name'].split(' ', 1)[1]
						else:
							valid_name = data['valid_name']
						if valid_name != current_valid.valid_name:
							raise Exception("Valid name of synonym does not match: " + data['valid_name'] + " and " + current_valid.valid_name)
				# shorten root name for family-group names
				if data['group'] == GROUP_FAMILY:
					data['root_name'] = helpers.strip_rank(data['root_name'], current_valid.rank)
				del data['kind']
				data['data'] = json.dumps(remove_null(data['data']))

				# Detect whether a name object is already present (Principle of Coordination)
				nm = None
				if data['status'] == STATUS_VALID:
					root_name = data['root_name']
					if current_valid.rank == FAMILY:
						nm = detect_super(root_name + 'oidea', SUPERFAMILY)
					elif current_valid.rank == SUBFAMILY:
						nm = detect_super(root_name + 'idae', FAMILY)
					elif current_valid.rank == TRIBE:
						nm = detect_super(root_name + 'inae', SUBFAMILY)
					elif current_valid.rank == SUBTRIBE:
						nm = detect_super(root_name + 'ini', TRIBE)
					elif current_valid.rank == SUBGENUS:
						nm = detect_super(root_name, GENUS)
					elif current_valid.rank == SPECIES:
						spg_name = helpers.spg_of_species(current_valid.valid_name)
						nm = detect_super(spg_name, SPECIES_GROUP)
					elif current_valid.rank == SUBSPECIES and helpers.is_nominate_subspecies(current_valid.valid_name):
						sp_name = helpers.species_of_subspecies(current_valid.valid_name)
						nm = detect_super(sp_name, SPECIES)
					if nm is not None:
						del data['taxon']
						nm.add_additional_data(data)
						# nm's Taxon should be the lowest-ranking one
						nm.taxon = current_valid

				# create a new Name if none was found
				if nm is None:
					nm = Name.create(**data)

				# set base_name field
				if data['status'] == STATUS_VALID:
					current_valid.base_name = nm
				if 'additional_synonyms' in data:
					group = helpers.group_of_rank(current_valid.rank)
					for synonym in data['additional_synonyms']:
						Name.create(taxon=current_valid, root_name=synonym, group=group, status=STATUS_SYNONYM)

			except Exception:
				traceback.print_exc()
				error_occurred = True
				# ignore error and happily go on with the next
	return not error_occurred
示例#12
0
def do(request, nid, browser_tab):
    WZ = Z.SetWhoZwho(request, browser_tab)
    if WZ['ErrorMessage']:
        return GoLogout(request, WZ)

    if nid != '0':
        try:
            name = Name.objects.get(pk=int(nid))
        except:
            return GoLogout(request, WZ, "[AN01]: URL containd an invalid name ID.")

        if WZ['Authority'] < Z.Admin and name.owner != WZ['AuthorizedOwner']:
            return GoLogout(request, WZ, "[AN02]: URL containd an invalid name ID.")

    if request.method == 'POST': # If the form has been submitted...
        form = DirectoryAddNameForm(request.POST, request.FILES)
        if form.is_valid():
            users = User.objects.all().filter(username__exact=form.cleaned_data['login_id'])
            if len(users) < 1:
                temporary_password = GenerateTemporaryPassword()

                new_user = User()
                new_user.username = form.cleaned_data['login_id']
                new_user.first_name = form.cleaned_data['first_name']
                new_user.last_name = form.cleaned_data['last_name']
                new_user.email = form.cleaned_data['email']
                new_user.set_password(temporary_password)
                new_user.save()

                new_name = Name()
                new_name.user = new_user
                new_name.first = form.cleaned_data['first_name']
                new_name.last = form.cleaned_data['last_name']

                if form.cleaned_data['privileges'] == '1':
                    new_name.authority = Z.NewRO
                else:
                    new_name.authority = Z.NewRW

                if nid != '0':
                    new_name.owner = name.owner

                new_name.save()

                if nid == '0':
                    new_name.owner = new_name.id
                    new_name.save()

                logger.info(WZ['User'] + ' AN ' + str(request.POST))

                send_mail(
                    'Your new WhoZwho directory account.',
                    'A new account, ' + new_user.username + \
                    ', has been created for you on the WhoZwho directory. ' + \
                    'To obtain a password, visit ' + WZ['httpURL'] + '/fgpwd.',
                    WZ['AdminEmail'],
                    [new_user.email],
                    fail_silently=False)

                return HttpResponseRedirect('/WhoZwho/ename/' + str(new_name.id) + '/' + browser_tab)
            else:
                WZ['ErrorMessage'] = "Error: The selected Login ID is already in use."
        else:
            WZ['ErrorMessage'] = str(form.errors)
    else:
        form = DirectoryAddNameForm(initial={
            'privileges': str(Z.NewRW),
            }) 

    if nid == '0':
        AddNameTitle = 'Add a New Name'
    else:
        AddNameTitle = 'Add a New Family Member'

    context = {
        'AddNameTitle': AddNameTitle,
        'browser_tab': WZ['Tabs'][WZ['ActiveTab']][2],
        'form': form,
        'nid': nid,
        'WZ': WZ
        }

    context.update(csrf(request))
    return render_to_response('DirectoryAddName.html', context )
            incarceration_type=models.IncarcerationType.JAIL,
            duration=timedelta(days=90)),
        fine=False))
ARREST_INFO_2 = models.ArrestInfo(arrest_id='9483488DIP657',
                                  name_as_charged_id=2,
                                  date=datetime(1994, 6, 10),
                                  city='SAN JOSE')
EVENT_2 = models.Event(
    arrest_info=ARREST_INFO_2,
    listed_dob=datetime(1953, 4, 20),
    associated_cases=[CASE_INFO_2_1],
    probation_modifications=[]  # todo
)

RAP_SHEET_1 = models.RAPSheet(names_as_charged=[
    Name('ALEXANDER', 'ROBIN RAE'),
    Name('MOAN', 'ROBIN', 'RAE'),
    Name('LEDEL', 'ROBIN', 'RAE'),
    Name('LEDEL', 'ROBIN'),
    Name('SUMMERS', 'KARLA'),
    Name('LEDEL', 'RUBIN', 'RAE'),
    Name('SUMMERS', 'CARTA'),
    Name('TYREE', 'ROBIN'),
    Name('TYREE', 'ROBIN', 'RAE'),
    Name('ALEXANDER', 'ROBIN'),
    Name('TYREE', 'ROBIN', 'R')
],
                              dob=datetime(1953, 4, 20, 0, 0),
                              sex='F',
                              events=[EVENT_0, EVENT_1, EVENT_2])
示例#14
0
def create_name(db, name, contest):
    name = Name(name=name, contest=contest)
    add_and_commit(db, name)
    return name
示例#15
0
def now(request):
    WZ = Z.SetWhoZwho(request)
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid(): 
            check_captcha = captcha.submit (form.cleaned_data['recaptcha_challenge_field'], form.cleaned_data['recaptcha_response_field'], WZ['CaptchaPrivate'], "127.0.0.1")
            if not check_captcha.is_valid:
                WZ['ErrorMessage'] = "[UR01]: Captcha response was incorrect."
            else:
                users = User.objects.all().filter(username__exact=form.cleaned_data['login_id'])
                if len(users) < 1:
                    new_user = User()
                    new_user.username = form.cleaned_data['login_id']
                    new_user.first_name = form.cleaned_data['first_name']
                    new_user.last_name = form.cleaned_data['last_name']
                    new_user.email = form.cleaned_data['email']
                    new_user.set_password(form.cleaned_data['password'])
                    new_user.save()

                    new_name = Name()
                    new_name.preferred = form.cleaned_data['first_name']
                    new_name.first = form.cleaned_data['first_name']
                    new_name.last = form.cleaned_data['last_name']
                    new_name.authority = Z.NewRW
                    new_name.user = new_user
                    new_name.save()

                    new_name.owner = new_name.id
                    new_name.save()

                    auth_user = authenticate(username=new_user, password=form.cleaned_data['password'])
                    if auth_user is not None:
                        if auth_user.is_active:
                            login(request, auth_user)
                            WZ['Authenticated'] = 1
                            request.session['last_time'] = time()
                            WZ = Z.SetWhoZwho(request, '.')
                            return HttpResponseRedirect('/WhoZwho/' + WZ['Tabs'][WZ['ActiveTab']][3])
                        else:
                            WZ['ErrorMessage'] = "[UR02]: Login ID disabled."
                    else:
                        WZ['ErrorMessage'] = "[UR03]: Login ID is invalid."
                else:
                    WZ['ErrorMessage'] = "[UR04]: The selected Login ID is already in use."
        else:
            WZ['ErrorMessage'] = str(form.errors)
    else:
        form = RegistrationForm() # An unbound form

    captcha_html = captcha.displayhtml(WZ['CaptchaPublic'], use_ssl = True)

    c = { 'form': form, 'WZ': WZ, 'captcha_html': captcha_html }
    c.update(csrf(request))
    return render_to_response('UserRegistration.html', c )
示例#16
0
from models import Name  # models에 .붙이면 에러남

name = Name('Pewww')

print(name.getName())