text
stringlengths
0
1.05M
meta
dict
from flask_wtf import Form from wtforms import TextField, TextAreaField, SelectField, PasswordField, BooleanField, validators from wtforms.validators import Required, EqualTo, Email class LoginForm(Form): username = TextField('User Name:', [Required()]) password = PasswordField('Password:', [Required()]) rememberme = BooleanField('Remember me') class RegisterForm(Form): username = TextField('User Name:', [Required()]) password = PasswordField('Password:', [Required()]) confirm = PasswordField('Repeat Password:', [ Required(), EqualTo('password', message='Passwords must match') ]) name = TextField('Contact Name (for support only):') phone = TextField('Phone Number (for support only):') email = TextField('Email address (for verification only):', [Required(), Email()]) accept_tos = BooleanField('I agree to <a href="http://givn.us">Givn Terms</a>', [Required()]) class AccountSettingsForm(Form): username = TextField('User Name:') password = PasswordField('Password:') confirm = PasswordField('Repeat Password:', [ EqualTo('password', message='Passwords must match') ]) name = TextField('Contact Name:', [Required()]) phone = TextField('Phone Number (optional):') email = TextField('Email address:', [Required(), Email()])
{ "repo_name": "teamgivn/givnapp", "path": "app/blueprints/auth/forms.py", "copies": "1", "size": "1339", "license": "mit", "hash": 3577591467524913000, "line_mean": 40.875, "line_max": 98, "alpha_frac": 0.6751306945, "autogenerated": false, "ratio": 4.237341772151899, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0028564574292142533, "num_lines": 32 }
from flask_wtf import Form from wtforms import TextField, widgets, RadioField, validators from wtforms.fields import SelectMultipleField from wtformsparsleyjs import StringField, SelectField import pycountry class TextSelect(Form): texts=[("http://readsy.co/static/txt/ironman.html", "Iron Man"), ("http://readsy.co/static/txt/gulls.html", "Gulls")] textChooser = SelectMultipleField('Text to be Spritzed', choices=texts) class UserSurvey1(Form): age = [("u10", "Under 10"), ("11-20", "11-20"), ("21-40", "21-40"), ("41-60", "41-60"), ("61-80", "61-80"), ("81+", "Over 81")] allDifficulties = [("AMD", "Age Related Macular Degeneration"), ("BI", "Brain Injury"), ("D", "Dyslexia"), ("VI", "Vision Issues"), ("O", "Other"), ("N", "None")] nativelang = [("yes", "Yes"), ("no", "No")] device = [("desktop", "Desktop"), ("laptop", "Laptop"), ("tablet", "Tablet"), ("mobile", "Smartphone")] cc = {} t = list(pycountry.countries) for country in t: cc[country.name]=country.name cc = [(v, v) for v, v in cc.iteritems()] cc.sort() cc.insert(0, (None, "")) age.insert(0, (None, "")) country = SelectField('Country', [validators.DataRequired(message='Sorry, this is a required field.')], choices=cc) agerange = SelectField('Age Range', [validators.DataRequired(message='Sorry, this is a required field.')], choices=age) difficulties = SelectMultipleField('Reading Difficulties (select all that apply)', [validators.DataRequired(message='Sorry, this is a required field.')], choices=allDifficulties, coerce=unicode, option_widget=widgets.CheckboxInput(), widget=widgets.ListWidget(prefix_label=False)) nativelang = RadioField('Is English your native language?', [validators.DataRequired(message='Sorry, this is a required field.')], choices=nativelang) deviceused = RadioField('What device are you using?', [validators.DataRequired(message='Sorry, this is a required field.')], choices=device) aq1_label = "How tall was the Iron Man?" aq2_label = "His eyes were like?" aq3_label = "What flew over and landed?" aq4_label = "What did they have on the cliff?" aq5_label = "What did the seagull pick up first?" aq1_answers = [("a", "very tall"), ("b", "short"), ("c", "taller than a house"), ("d", "taller than a boulder")] aq2_answers = [("a", "headlamps"), ("b", "rocks"), ("c", "cats"), ("d", "flames")] aq3_answers = [("a", "a hummingbird"), ("b", "a bat"), ("c", "two seagulls"), ("d", "a plane")] aq4_answers = [("a", "a houseboat"), ("b", "two chicks in a nest"), ("c", "a nest"), ("d", "a drum of oil")] aq5_answers = [("a", "nothing"), ("b", "a finger"), ("c", "a knife blade"), ("d", "one of the Iron Man's eyes")] aq1 = RadioField(aq1_label, choices=aq1_answers) aq2 = RadioField(aq2_label, choices=aq2_answers) aq3 = RadioField(aq3_label, choices=aq3_answers) aq4 = RadioField(aq4_label, choices=aq4_answers) aq5 = RadioField(aq5_label, choices=aq5_answers) bq1_label = "What did the second seagull pickup?" bq2_label = "What color did the eye glow?" bq3_label = "What did the Iron Man try to pick up, stuck between the rocks?" bq4_label = "What was the eye doing when they found it?" bq5_label = "How did the legs move?" bq1_answers = [("a", "a clam"), ("b", "the right hand"), ("c", "a house"), ("d", "bridseed")] bq2_answers = [("a", "blue"), ("b", "purple"), ("c", "white"), ("d", "pink")] bq3_answers = [("a", "a hummingbird"), ("b", "the left arm"), ("c", "two seagulls"), ("d", "a plane")] bq4_answers = [("a", "waving"), ("b", "blinking at them"), ("c", "sleeping"), ("d", "nothing")] bq5_answers = [("a", "running"), ("b", "skip"), ("c", "with a limp"), ("d", "Hop, hop, hop, hop")] bq1 = RadioField(bq1_label, choices=bq1_answers) bq2 = RadioField(bq2_label, choices=bq2_answers) bq3 = RadioField(bq3_label, choices=bq3_answers) bq4 = RadioField(bq4_label, choices=bq4_answers) bq5 = RadioField(bq5_label, choices=bq5_answers)
{ "repo_name": "a-jain/Readsy", "path": "form.py", "copies": "1", "size": "3889", "license": "mit", "hash": 7737854421564574000, "line_mean": 61.7419354839, "line_max": 281, "alpha_frac": 0.6523527899, "autogenerated": false, "ratio": 2.8324836125273123, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3984836402427312, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import ValidationError, BooleanField, TextField, PasswordField, validators from codeta.models.user import User class RegistrationForm(Form): username = TextField('Username', [validators.Length(min=1, max=100)]) email = TextField('Email Address', [ validators.Length(min=1, max=100), validators.Required(), validators.EqualTo('confirm_email', message='Email addresses must match.'), validators.Email(message='You must enter a valid email address.') ]) confirm_email = TextField('Repeat email address', [validators.Length(min=3, max=100)]) password = PasswordField('New Password', [ validators.Required(), validators.EqualTo('confirm_password', message='Passwords must match.'), validators.Length(min=9) ]) confirm_password = PasswordField('Repeat Password') fname = TextField('First Name', [validators.Length(min=1, max=100)]) lname = TextField('Last Name', [validators.Length(min=1, max=100)]) def validate_username(form, field): """ make sure username is not already taken """ if User.check_username(field.data): raise ValidationError("Sorry, that username is already taken.")
{ "repo_name": "CapstoneGrader/codeta", "path": "codeta/forms/registration.py", "copies": "1", "size": "1255", "license": "mit", "hash": 2229515133709542100, "line_mean": 42.275862069, "line_max": 90, "alpha_frac": 0.6820717131, "autogenerated": false, "ratio": 4.254237288135593, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5436309001235593, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import ValidationError from wtforms.ext.sqlalchemy.fields import QuerySelectField from wtforms.fields import PasswordField, StringField, SubmitField, HiddenField from wtforms.fields.html5 import EmailField, DateField from wtforms.validators import Email, EqualTo, InputRequired, Length, Optional from .. import db from ..models import Role, User class ChangeUserEmailForm(Form): email = EmailField( 'New email', validators=[InputRequired(), Length(1, 64), Email()]) submit = SubmitField('Update email') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.') class ChangeAccountTypeForm(Form): role = QuerySelectField( 'New account type', validators=[InputRequired()], get_label='name', query_factory=lambda: db.session.query(Role).order_by('permissions')) submit = SubmitField('Update role') class InviteUserForm(Form): role = QuerySelectField( 'Account type', validators=[InputRequired()], get_label='name', query_factory=lambda: db.session.query(Role).order_by('permissions')) first_name = StringField( 'First name', validators=[InputRequired(), Length(1, 64)]) last_name = StringField( 'Last name', validators=[InputRequired(), Length(1, 64)]) email = EmailField( 'Email', validators=[InputRequired(), Length(1, 64), Email()]) submit = SubmitField('Invite') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.') class NewUserForm(InviteUserForm): password = PasswordField( 'Password', validators=[ InputRequired(), EqualTo('password2', 'Passwords must match.') ]) password2 = PasswordField('Confirm password', validators=[InputRequired()]) submit = SubmitField('Create') class AddChecklistItemForm(Form): item_text = StringField( 'Checklist Item', validators=[InputRequired(), Length(1, 64)]) date = DateField('Deadline', format='%Y-%m-%d', validators=[Optional()]) assignee_ids = HiddenField('Assignee Ids') submit = SubmitField('Add checklist item')
{ "repo_name": "hack4impact/next-gen-scholars", "path": "app/admin/forms.py", "copies": "1", "size": "2562", "license": "mit", "hash": 3250718168843847000, "line_mean": 34.095890411, "line_max": 79, "alpha_frac": 0.6163153786, "autogenerated": false, "ratio": 4.542553191489362, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5658868570089362, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import ValidationError from wtforms.ext.sqlalchemy.fields import QuerySelectField from wtforms.fields import PasswordField, StringField, SubmitField from wtforms.fields.html5 import EmailField from wtforms.validators import Email, EqualTo, InputRequired, Length from app import db from app.models import Role, User class ChangeUserEmailForm(Form): email = EmailField( 'New email', validators=[InputRequired(), Length(1, 64), Email()]) submit = SubmitField('Update Email') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.') class ChangeAccountTypeForm(Form): role = QuerySelectField( 'New account type', validators=[InputRequired()], get_label='name', query_factory=lambda: db.session.query(Role).order_by('permissions')) submit = SubmitField('Update role') class InviteUserForm(Form): role = QuerySelectField( 'Account type', validators=[InputRequired()], get_label='name', query_factory=lambda: db.session.query(Role).order_by('permissions')) first_name = StringField( 'First name', validators=[InputRequired(), Length(1, 64)]) last_name = StringField( 'Last name', validators=[InputRequired(), Length(1, 64)]) email = EmailField( 'Email', validators=[InputRequired(), Length(1, 64), Email()]) submit = SubmitField('Invite') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.') class NewUserForm(InviteUserForm): password = PasswordField( 'Password', validators=[ InputRequired(), EqualTo('password2', 'Passwords must match.') ]) password2 = PasswordField('Confirm password', validators=[InputRequired()]) submit = SubmitField('Create')
{ "repo_name": "infrascloudy/flask-base", "path": "app/admin/forms.py", "copies": "1", "size": "2187", "license": "mit", "hash": -1747259222828174000, "line_mean": 32.6461538462, "line_max": 79, "alpha_frac": 0.6172839506, "autogenerated": false, "ratio": 4.604210526315789, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5721494476915789, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import ValidationError from wtforms.fields import StringField, SubmitField, SelectField from wtforms.fields.html5 import EmailField, TelField from wtforms.ext.sqlalchemy.fields import QuerySelectField from wtforms.validators import Length, Email, Optional, InputRequired from ..custom_validators import ( UniqueEmail, UniquePhoneNumber, PhoneNumberLength ) from ..models import Role from .. import db class ChangeUserEmailForm(Form): email = EmailField('New email', validators=[ InputRequired(), Length(1, 64), Email(), UniqueEmail(), ]) submit = SubmitField('Update email') class ChangeUserPhoneNumberForm(Form): phone_number = TelField('New phone number', validators=[ InputRequired(), PhoneNumberLength(10, 15), UniquePhoneNumber(), ]) submit = SubmitField('Update phone number') class ChangeAccountTypeForm(Form): role = QuerySelectField('New account type', validators=[InputRequired()], get_label='name', query_factory=lambda: db.session.query(Role). order_by('permissions')) submit = SubmitField('Update role') class InviteUserForm(Form): role = QuerySelectField( 'Account type', validators=[InputRequired()], get_label='name', query_factory=lambda: db.session.query(Role).order_by('permissions') ) first_name = StringField('First name', validators=[InputRequired(), Length(1, 64)]) last_name = StringField('Last name', validators=[InputRequired(), Length(1, 64)]) email = EmailField('Email', validators=[ InputRequired(), Length(1, 64), Email(), UniqueEmail() ]) phone_number = TelField('Phone Number', validators=[ Optional(), PhoneNumberLength(10, 15), UniquePhoneNumber(), ]) submit = SubmitField('Invite')
{ "repo_name": "hack4impact/vision-zero-philly", "path": "app/admin/forms.py", "copies": "1", "size": "2108", "license": "mit", "hash": -2143127781073263400, "line_mean": 31.4307692308, "line_max": 76, "alpha_frac": 0.6067362429, "autogenerated": false, "ratio": 4.705357142857143, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005494505494505495, "num_lines": 65 }
from flask_wtf import Form from wtforms import validators,PasswordField, StringField from wtforms.validators import DataRequired from models import db, User from werkzeug.security import generate_password_hash, check_password_hash #from auth import bcrypt #User Login Form class UserLoginForm(Form): username = StringField('username', validators=[DataRequired()]) password = PasswordField('password', validators=[DataRequired()]) def validate_login(self): user = self.get_user() if user is None: # raise validators.ValidationError('Invalid User') return False if not check_password_hash(user.password, self.password.data): # raise validators.ValidationError('Invalid Password') return False return user def get_user(self): return db.session.query(User).filter_by(username=self.username.data).first() return db.session.query(User).filter_by(password=self.password.data).first() #Register Login Form class UserRegisterForm(Form): first_name = StringField('first_name', validators=[DataRequired()]) last_name = StringField('last_name', validators=[DataRequired()]) username = StringField('username', validators=[DataRequired()]) email = StringField('email', validators=[DataRequired()]) password = PasswordField('password', validators=[DataRequired()]) password = PasswordField('password', [ validators.Required(), validators.EqualTo('password_confirm', message='Passwords must match') ]) password_confirm = PasswordField('Repeat Password')
{ "repo_name": "BugisDev/Capture-TheGepeng", "path": "app/user/form.py", "copies": "1", "size": "1609", "license": "apache-2.0", "hash": -8404035610114854000, "line_mean": 34.7555555556, "line_max": 84, "alpha_frac": 0.7047855811, "autogenerated": false, "ratio": 4.5710227272727275, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5775808308372729, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import validators, StringField, PasswordField, TextAreaField from flask_wtf.file import FileField, FileAllowed from wtforms.ext.sqlalchemy.fields import QuerySelectField from wtforms.fields.html5 import EmailField from blog.models import Category class SetupForm(Form): name = StringField('Blog Name', [ validators.Required(), validators.Length(max=80) ]) fullname = StringField('Full Name', [validators.Required()]) email = EmailField('Email Address', [validators.DataRequired(), validators.Email()]) username = StringField('Username', [ validators.Required(), validators.length(min=4, max=32) ]) password = PasswordField('New Password', [ validators.Required(), validators.length(min=4, max=80), validators.EqualTo('confirm', message='Password must match') ]) confirm = PasswordField('Repeat Password') def categories(): return Category.query class PostForm(Form): image = FileField('image', validators= [ FileAllowed(['jpg','png','gif'], 'Images only!') ]) title = StringField('Title', [ validators.Required(), validators.Length(max=80) ]) body = TextAreaField('Content', validators=[validators.Required()]) category = QuerySelectField('Category', query_factory=categories, allow_blank=True) new_category = StringField('New Category')
{ "repo_name": "SocialProgrammingUnion/SamaritanAnalytics", "path": "SPU-Front_templates/SPU_BLOG/blog/form.py", "copies": "1", "size": "1433", "license": "mit", "hash": 4414659510034616000, "line_mean": 35.7435897436, "line_max": 88, "alpha_frac": 0.6859734822, "autogenerated": false, "ratio": 4.329305135951661, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5515278618151661, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import validators, SubmitField, SelectField, HiddenField, TextAreaField from flask_wtf.file import FileField, FileAllowed, FileRequired from wtforms.widgets import TextArea from app import code_upload_set from app.user.models import User from app.submission.models import Submission from app.submission import constants as SUBMISSION class CreateSubmissionForm(Form): user_id = HiddenField('user_id') problem_id = HiddenField('problem_id') submit = SubmitField('Submit') language = SelectField('Language', choices=[(str(k), v) for k, v in SUBMISSION.LANGUAGES.items()]) code = TextAreaField('Code', widget=TextArea()) def __init__(self, current_user, current_problem, *args, **kwargs): if current_user.is_authenticated(): self.current_user_id = current_user.id else: self.current_user_id = None self.current_problem_id = current_problem.id Form.__init__(self, *args, **kwargs) def validate(self): if not Form.validate(self): return False user = User.query.get(self.user_id.data) if not user or user.id != self.current_user_id: self.user_id.errors.append('Invalid user') return False else: return True problem = Problem.query.get(self.problem_id.data) if not problem or problem.id != self.current_problem_id: self.problem_id.errors.append('Invalid problem') return False else: return True
{ "repo_name": "vigov5/oshougatsu2015", "path": "app/submission/forms.py", "copies": "1", "size": "1560", "license": "mit", "hash": -466005805498025150, "line_mean": 33.6888888889, "line_max": 102, "alpha_frac": 0.658974359, "autogenerated": false, "ratio": 3.979591836734694, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002677939114923364, "num_lines": 45 }
from flask_wtf import Form from wtforms import widgets, StringField, TextAreaField, RadioField, SelectMultipleField, BooleanField, PasswordField from wtforms.fields.html5 import EmailField from wtforms.validators import DataRequired, Length class MultiCheckboxField(SelectMultipleField): widget = widgets.ListWidget(prefix_label=False) option_widget = widgets.CheckboxInput() class LoginForm(Form): email = EmailField('email', validators=[DataRequired()]) password = PasswordField('password', validators=[DataRequired()]) remember_me = BooleanField('remember_me', default=False) class ChangePwdForm(Form): currentpassword = PasswordField('currentpassword', validators=[DataRequired()]) newpassword1 = PasswordField('newpassword1', validators=[DataRequired()]) newpassword2 = PasswordField('newpassword2', validators=[DataRequired()]) class SpeakerForm(Form): availableTracks = [ ('Front', 'Front End'), ('Back', 'Back End'), ('DevOps', 'DevOps'), ('Data', 'Data Science'), ('Agile', 'Agile'), ('Quality', 'Quality'), ('Soft', 'Soft Skills'), ('Design', 'Design'), ('IoT', 'Hardware/IoT'), ('Other', 'Other') ] title = StringField('title', validators=[DataRequired(), Length(max=80)]) abstract = TextAreaField('abstract', validators=[DataRequired()]) time = RadioField('time', choices=[('60','60 Minutes'),('30','30 Minutes'),('45','30 or 60 Minutes - just let me know')]) tracks = MultiCheckboxField('tracks', choices=availableTracks) firstName = StringField('name', validators=[DataRequired(), Length(max=30)]) lastName = StringField('name', validators=[DataRequired(), Length(max=30)]) email = EmailField('email', validators=[DataRequired(), Length(max=80)]) twitter = StringField('twitter') bio = TextAreaField('bio', validators=[DataRequired()]) comments = TextAreaField('comments') agree = BooleanField('agree', validators=[DataRequired(message='You must agree to our code of conduct in order to submit a talk.')])
{ "repo_name": "PghTechFest/pypghtechfest", "path": "app/forms.py", "copies": "1", "size": "2006", "license": "bsd-2-clause", "hash": -4031697469917560000, "line_mean": 44.6136363636, "line_max": 134, "alpha_frac": 0.7148554337, "autogenerated": false, "ratio": 4.012, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.52268554337, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms.meta import DefaultMeta from flask import current_app, session class TabNode(): def __init__(self, name): self.name = name self.unbound_children = [] self.tabs = [] self.children = [] def get_tab(self, tabname): for c in self.tabs: if c.name == tabname: return c return None def find(self, name): idx = 0 for idx, child in enumerate(self.unbound_children): if child.kwargs.get("name") == name: return idx return len(self.unbound_children) class OrderedFieldList(): def __init__(self): self.root = TabNode("Root") def __getitem__(self, item): i = self.find_by_name(item) if not i: raise(IndexError("No item named %s" % item)) return i def __delitem__(self, item): def delete_unbound_child(tab): for c in tab.unbound_children: if c.kwargs["name"] == item: tab.unbound_children.remove(c) return True for t in tab.tabs: return delete_unbound_child(t) ret_val = delete_unbound_child(self.root) def get_tab(self, location, create_tabs=False): location = location.split('.') print(location) node = prev_node = self.root if location[0] == "Root": del location[0] else: raise UserWarning("Error: Root must be in location") for l in location: node = prev_node.get_tab(l) if not node and not create_tabs: raise(IndexError("Tab %r not found!" % location)) return None elif not node and create_tabs: node = TabNode(l) prev_node.tabs.append(node) prev_node = node return node def find_by_name(self, name, tab=None, unbound=False): if not tab: tab = self.root print(tab, tab.tabs) for c in tab.children: print(c.name, name) if c.name == name: return c for t in tab.tabs: elem = self.find_by_name(name, t) if elem: return elem return None def add_to_tab(self, tabname, field, before=None): fieldname = field.kwargs["name"] try: del self[fieldname] except IndexError: pass node = self.get_tab(tabname, True) index = node.find(before) node.unbound_children.insert(index, field) def items(self, tab=None): returnlist = [] def append_items(tab): for c in tab.children: returnlist.append((c.name, c)) for t in tab.tabs: append_items(t) append_items(tab if tab else self.root) return returnlist def __iter__(self): yield self.items() class OrderedForm(Form): """ An extension to the generic WTForm that can keep track of sorting in a manner different from the general usage pattern of WTForms. This class is useful for usage inside the CMS where its nice to not having to repeat all form code everytime. It is a "forms-just-work approach". The form is split into tabs. There is always a ``Root`` tab where all form elements and tabnodes are attached to. E.g. :: form = type(PageOrderedForm, (OrderedForm, ), {}) form.add_to_tab("Root.Main", new StringField("abc", name="abc")) form.add_to_tab("Root.Main", new StringField("def", name="def"), "abc") form.add_to_tab("Root.Settings", new BooleanField("booleansetting", name="booleansetting")) return form """ _fields = OrderedFieldList() tabbed_form = True def __init__(self, formdata=None, obj=None, data=None, csrf_enabled=None, csrf_context=None, secret_key=None, prefix='', meta=DefaultMeta()): if csrf_enabled is None: csrf_enabled = current_app.config.get('WTF_CSRF_ENABLED', True) self.csrf_enabled = csrf_enabled if self.csrf_enabled: if csrf_context is None: csrf_context = session if secret_key is None: # It wasn't passed in, check if the class has a SECRET_KEY secret_key = getattr(self, "SECRET_KEY", None) self.SECRET_KEY = secret_key else: csrf_context = {} self.SECRET_KEY = '' if prefix and prefix[-1] not in '-_;:/.': prefix += '-' self.meta = meta self._prefix = prefix self._errors = None translations = self._get_translations() extra_fields = [] if meta.csrf: self._csrf = meta.build_csrf(self) extra_fields.extend(self._csrf.setup_form(self)) def bind_fields(tab): tab.children = [] for field in tab.unbound_children: name = field.kwargs["name"] del field.kwargs["name"] tab.children.append(field.bind(self, name)) tab.unbound_children = [] for t in tab.tabs: c = bind_fields(t) if c == 0: print(t) print(t.name) del t print(tab.children) return len(tab.children) bind_fields(self._fields.root) self.process(formdata, obj, data) @classmethod def add_to_tab(cls, tabname, field, before=None): """ Adds a form field to a tab. :param tabname: The tabname is a dot-delimited tab location. The tab name should be a camel cased name. ``Root`` is always existing and always the root tab. Examples: ``Root.Main``, ``Root.PageContent``, ``Root.Main.ImageGallery`` :param field: An instantiated WTForm field. Note that field names have to be unique to the form :param before: Optional: sort the field before another field if it exists in a specific tab. :return: None """ return cls._fields.add_to_tab(tabname, field, before) def get_tab(self, location): """ Get a specific tab by name indicator :param location: e.g. ``Root.Main`` :return: """ return self._fields.get_tab(location) def get_root(self): """ Get root tab :return: root tab """ return self._fields.root def get_field(self, field_name): """ Find a specific field by name in all tabs :param field_name: name of the field :return: """ all_fields = self._fields.items(self._fields.root) print("all_fields", all_fields) for name, field in all_fields: print(name, field_name) if name == field_name: return field class OrderedFormFactory: def __init__(self): self.fields = OrderedFieldList() def __call__(self, *args, **kwargs): return self.create()(*args, **kwargs) def create(self): return type('OrderedFactoryForm', (OrderedForm, ), { "_fields": self.fields }) def add_to_tab(self, tabname, field, before=None): """ Adds a form field to a tab. :param tabname: The tabname is a dot-delimited tab location. The tab name should be a camel cased name. ``Root`` is always existing and always the root tab. Examples: ``Root.Main``, ``Root.PageContent``, ``Root.Main.ImageGallery`` :param field: An instantiated WTForm field. Note that field names have to be unique to the form :param before: Optional: sort the field before another field if it exists in a specific tab. :return: None """ return self.fields.add_to_tab(tabname, field, before)
{ "repo_name": "wolfv/SilverFlask", "path": "silverflask/models/OrderedForm.py", "copies": "1", "size": "8058", "license": "bsd-2-clause", "hash": -1628963435782706000, "line_mean": 31.8897959184, "line_max": 120, "alpha_frac": 0.5482750062, "autogenerated": false, "ratio": 4.14293059125964, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.519120559745964, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms.validators import DataRequired, Length from wtforms import StringField, TextAreaField, BooleanField, SelectField, SubmitField from wtforms.ext.sqlalchemy.fields import QuerySelectField from wtforms.validators import Required, Length, Email, Regexp from wtforms import ValidationError from flask_pagedown.fields import PageDownField from ..models import Role, User, Category class NameForm(Form): name = StringField('What is your name?', validators=[Required()]) submit = SubmitField('Submit') class EditProfileForm(Form): name = StringField('Real name', validators=[Length(0, 64)]) location = StringField('Location', validators=[Length(0, 64)]) about_me = TextAreaField('About me') submit = SubmitField('Submit') class EditProfileAdminForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) username = StringField('Username', validators=[ Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, ' 'numbers, dots or underscores')]) confirmed = BooleanField('Confirmed') role = SelectField('Role', coerce=int) name = StringField('Real name', validators=[Length(0, 64)]) location = StringField('Location', validators=[Length(0, 64)]) about_me = TextAreaField('About me') submit = SubmitField('Submit') def __init__(self, user, *args, **kwargs): super(EditProfileAdminForm, self).__init__(*args, **kwargs) self.role.choices = [(role.id, role.name) for role in Role.query.order_by(Role.name).all()] self.user = user def validate_email(self, field): if field.data != self.user.email and \ User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.') def validate_username(self, field): if field.data != self.user.username and \ User.query.filter_by(username=field.data).first(): raise ValidationError('Username already in use.') class PostForm(Form): title = StringField("TITLE",validators = [DataRequired('A title is required.'), Length(1, 52)]) body = PageDownField("What's on your mind?", validators = [DataRequired('The main context is required.')]) summary = PageDownField('SUMMARY', validators=[DataRequired('A summary is required.'), Length(1, 800)]) category = SelectField('Category', coerce=int) submit = SubmitField('Submit') def __init__(self, *args, **kwargs): super(PostForm, self).__init__(*args, **kwargs) self.category.choices = [(category.id, category.tag) for category in Category.query.order_by(Category.tag).all()] class CommentForm(Form): body = StringField('Enter your comment', validators=[Required()]) submit = SubmitField('Submit')
{ "repo_name": "ACLeiChen/personalBlog", "path": "app/main/forms.py", "copies": "1", "size": "3003", "license": "mit", "hash": -7762482509948438000, "line_mean": 40.7083333333, "line_max": 121, "alpha_frac": 0.6473526474, "autogenerated": false, "ratio": 4.241525423728813, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5388878071128813, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms.validators import Required, Length, Email, EqualTo, NumberRange from wtforms import (TextField, PasswordField, BooleanField, IntegerField, DecimalField, TextAreaField) class ContactForm(Form): email = TextField( 'Your Email', validators=[Required("Please enter a valid email address"), Email(message=(u'That\'s not a valid email address'))]) header = TextField('Topic', [Required()]) message = TextAreaField('Message', [Required()]) class LoginForm(Form): username = TextField('Username', [Required()]) password = PasswordField('Password', [Required()]) remember_me = BooleanField('remember_me', default=False) class SignUpForm(Form): username = TextField( 'Enter a Username', validators=[Length(min=4, max=25, message=(u'Username must be between 4 and 25 characters')), Required("Please enter a username")]) email = TextField( 'Enter Your Email', validators=[Required("Please enter a valid email address"), Email(message=(u'That\'s not a valid email address'))]) password = PasswordField( 'Enter a Password', validators=[Required("Enter a secure password"), EqualTo('confirm', message=(u'Passwords must match'))]) confirm = PasswordField( 'Password Confirmation', validators=[Required("Please repeat your password")]) class PercentPref(Form): threshold_percent = IntegerField( 'percent threshold', validators=[Required("Please enter a number between 1-100"), NumberRange(min=1, max=100)]) class AmountPref(Form): threshold_amount = DecimalField( 'amount threshold', validators=[Required("Please enter an amount between .01 and 1000.00"), NumberRange(min=.01, max=1000.0)]) class GamesSearch(Form): search_term = TextField( 'Enter a Game', validators=[Required("Please enter a game to search for")])
{ "repo_name": "ChanChar/SteamScout", "path": "SteamScout/forms.py", "copies": "1", "size": "2095", "license": "mit", "hash": -5687352763185015000, "line_mean": 34.5084745763, "line_max": 103, "alpha_frac": 0.630548926, "autogenerated": false, "ratio": 4.554347826086956, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5684896752086956, "avg_score": null, "num_lines": null }
from flask_wtf import Form import wtforms from wtforms.validators import DataRequired, Email from wtforms.fields.html5 import EmailField from shuttl.Models.User import User class BaseUserForm(Form): username = wtforms.StringField("Your Username", validators=[DataRequired()], render_kw={"placeholder": "Username"}) firstname = wtforms.StringField('Your first name', validators=[DataRequired()], render_kw={"placeholder": "First name"}) lastname = wtforms.StringField('Your last name', validators=[DataRequired()], render_kw={"placeholder": "Last name"}) email = EmailField("Your Email Address", validators=[DataRequired(), Email()], render_kw={"placeholder": "Email"}) password = wtforms.PasswordField("Password", validators=[DataRequired()], render_kw={"placeholder": "Password"}) def save(self, commit=True): username = self.username.data email = self.email.data user = User(username=username, email=email) user.firstName = self.firstname.data user.lastName = self.lastname.data user.setPassword(self.password.data) if commit: user.save() pass return user pass
{ "repo_name": "shuttl-io/shuttl", "path": "shuttl/Forms/UserForm.py", "copies": "1", "size": "1183", "license": "mit", "hash": -32720999932311350, "line_mean": 42.8148148148, "line_max": 124, "alpha_frac": 0.6923076923, "autogenerated": false, "ratio": 4.286231884057971, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.547853957635797, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import PasswordField, StringField, HiddenField, TextAreaField, IntegerField from wtforms.validators import DataRequired, NumberRange, url from flask_wtf.html5 import URLField class PasswordForm(Form): next = HiddenField("next", validators=[DataRequired()]) password = PasswordField("password", validators=[DataRequired()]) class BlogPost(Form): id = HiddenField("id") topic = StringField("topic", validators=[DataRequired()]) content = TextAreaField("content", validators=[DataRequired()]) tags = StringField("tags", validators=[DataRequired()]) class ProgressForm(Form): id = HiddenField("id") progress = IntegerField("name", validators=[NumberRange(min=0, max=100)]) class BookInfoForm(Form): id = HiddenField("id") author = StringField("author", validators=[DataRequired()]) name = StringField("name", validators=[DataRequired()]) img = URLField(validators=[url()]) url = URLField(validators=[url()]) description = TextAreaField(validators=[DataRequired()]) class CommentForm(Form): comment = TextAreaField(validators=[DataRequired()])
{ "repo_name": "Ignotus/bookclub", "path": "core/forms.py", "copies": "1", "size": "1150", "license": "mit", "hash": -8870087523379631000, "line_mean": 31.8571428571, "line_max": 88, "alpha_frac": 0.7217391304, "autogenerated": false, "ratio": 4.2592592592592595, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.548099838965926, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import SubmitField, TextAreaField from wtforms.validators import DataRequired from wtforms.widgets import TextArea def get_angularjs_class(base_class): """ Returns a dynamic class widget to allow "ng-" attributes for wtforms. Parameter base_class is a wtforms.widget class. Template requires argument of ng_*='value' to set the attribute. Adapted version of solution from: http://stackoverflow.com/questions/20440056/custom-attributes-for-flask-wtforms """ class AngularJSClass(base_class): def __call__(self, field, **kwargs): for key in list(kwargs): if key.startswith('ng_'): kwargs['ng-' + key[3:]] = kwargs.pop(key) return super(AngularJSClass, self).__call__(field, **kwargs) return AngularJSClass class DataForm(Form): """ Input field for dataset {widget=AngularJSTextInput}. """ dataset = TextAreaField('Dataset:', validators=[DataRequired()], widget=get_angularjs_class(TextArea)()) dictionary = TextAreaField('Dictionary:', validators=[DataRequired()], widget=get_angularjs_class(TextArea)()) submit = SubmitField('Submit')
{ "repo_name": "rouzazari/fuzzyflask", "path": "app/main/forms.py", "copies": "1", "size": "1328", "license": "mit", "hash": 404239851696777660, "line_mean": 33.9473684211, "line_max": 83, "alpha_frac": 0.6219879518, "autogenerated": false, "ratio": 4.311688311688312, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 38 }
from flask_wtf import Form from wtforms import (TextField, PasswordField, BooleanField, TextAreaField, SelectField, SelectMultipleField, IntegerField, FieldList, ValidationError, FormField) from wtforms.validators import (DataRequired, Optional, Length, NumberRange, URL) from flask_wtf.file import (FileField, FileRequired) from squall.models import (User, Algorithm, Implementation, DataCollection, DataSet, Experiment, Batch, Tag) import wtforms import yaml import json import copy import numpy as np class UniqueName(object): """Validates An Objects Selected Name to Ensure It Has A Unique Name""" def __init__(self, cls, message=None): self.cls = cls if not message: message = "{} Name Unavailable".format(self.cls.__name__) self.message = message def __call__(self, form, field): """ Function Used To Validate Form Field """ if self.cls.query.filter_by(_name=field.data).first() is not None: raise ValidationError(self.message) class ValidParamFile(object): """Validates An Uploaded Parameter File By: 1. TODO: Ensuring it is properly formatted 2. TODO: Ensuring the arguments are correct for the batch """ def __init__(self, message='Uploaded File Improperly Formatted'): self.message = message def __call__(self, form, field): # TODO: Param Validation """Upload and parse yaml file to ensure proper formatting""" try: # Validate Presence of Yaml File filename = field.data.filename assert '.' in filename assert filename.rsplit('.', 1)[1] in set(['yaml', 'yml']) assert field.has_file() # Validate & Parse Contents of Yaml File field.data = self.parse(yaml.load(field.data)) except AssertionError: raise ValidationError('Valid file extensions: ".yaml" or ".yml"') except: # TODO: Identify possible Error Types raise ValidationError(self.message) def parse(self, params): """ Expands Yaml Fields List Of Param Files For Each Job""" try: # If Expand Fields Doesn't Exist, Nothing To Be Done expand_fields = params['ExpandFields'] del params['ExpandFields'] except KeyError: return params # Copy Only Static Fields static_data = copy.copy(params) for field in expand_fields: if isinstance(field, list): # TODO: Make More Robust/Elegant for subfield in field: del static_data[subfield] else: del static_data[field] # Count Number Of Values Per Expand Field field_lengths = np.zeros(len(expand_fields)) for idx, field in enumerate(expand_fields): if isinstance(field, list) or isinstance(field, tuple): subfields = [len(params[key]) for key in field] if not all(map(lambda x: x is subfields[0], subfields)): raise RuntimeError('Incompatible Length: ExpandFields') field_lengths[idx] = subfields[0] else: field_lengths[idx] = len(params[field]) enum_params = [copy.copy(static_data) for _ in xrange(int(field_lengths.prod()))] # Enumerate Expand Fields for cdx, enum_param in enumerate(enum_params): for idx, field in zip( np.unravel_index(cdx, field_lengths), expand_fields): if isinstance(field, list) or isinstance(field, tuple): for k in field: enum_param[k] = params[k][idx] else: enum_param[field] = params[field][idx] return enum_params class ValidResultsFile(object): """Validates An Uploaded Results Parameter File By: 1. Ensuring the filename/extension is correct 2. TODO: Ensuring it is properly formatted """ def __init__(self, message='Uploaded File Improperly Formatted'): self.message = message def __call__(self, form, field): try: # Validate Presence of JSON File filename = field.data.filename assert '.' in filename assert filename.rsplit('.', 1)[1] in set(['json']) assert field.has_file() field.data = self.parse(field.data) # Parse & Format Results JSON except AssertionError: raise ValidationError('Valid file extensions: ".json"') except: raise ValidationError(self.message) def parse(self, json_file): """Sift through results, validate contents, & format""" return [dict(id=jid, **results) for jid, results in json.load(json_file).iteritems()] class ValidResultsBatch(object): """ Validates A Batch To Add Results To By: 1. Ensuring the batch doesn't already have an associated results file """ def __init__(self, message='Selected Batch Is Already Completed'): self.message = message def __call__(self, form, field): try: batch = Batch.query.filter_by(id=field.data).first() assert not batch.completed pass except AssertionError: raise ValidationError(self.message) class URLForm(wtforms.Form): url = TextField('URL', validators=[DataRequired(), URL()]) def validate(self): if super(URLForm, self).validate(): return True # If Our Validators Pass return False class ScriptForm(wtforms.Form): path = TextField('Path', validators=[DataRequired()]) def validate(self): if super(ScriptForm, self).validate(): return True # If Our Validators Pass return False class AlgorithmForm(Form): name = TextField(u'Name', [DataRequired(), UniqueName(Algorithm), Length(max=64)]) description = TextAreaField(u'Desciption', [Optional(), Length(max=512)]) tags = SelectMultipleField(u'Tags', [Optional()], coerce=int) def validate(self): if super(AlgorithmForm, self).validate(): return True # If Our Validators Pass return False class ImplementationForm(Form): algorithm = SelectField(u'Algorithm', [DataRequired()], coerce=int) name = TextField(u'Name', [DataRequired(), UniqueName(Implementation), Length(max=64)]) description = TextAreaField(u'Desciption', [Optional(), Length(max=512)]) tags = SelectMultipleField(u'Tags', [Optional()], coerce=int) url_forms = FieldList(FormField(URLForm), min_entries=1, max_entries=10) setup_scripts = FieldList(FormField(ScriptForm), min_entries=1, max_entries=10) executable = TextField(u'Executable', [DataRequired(), Length(max=64)]) def validate(self): if super(ImplementationForm, self).validate(): return True # If Our Validators Pass return False class DataCollectionForm(Form): name = TextField(u'Name', [DataRequired(), UniqueName(DataCollection), Length(max=64)]) description = TextAreaField(u'Desciption', [Optional(), Length(max=512)]) tags = SelectMultipleField(u'Tags', [Optional()], coerce=int) def validate(self): if super(DataCollectionForm, self).validate(): return True # If Our Validators Pass return False class DataSetForm(Form): data_collection = SelectField(u'Data Collection', [DataRequired()], coerce=int) name = TextField(u'Name', [DataRequired(), UniqueName(DataSet), Length(max=64)]) description = TextAreaField(u'Description', [Optional(), Length(max=512)]) tags = SelectMultipleField(u'Tags', [Optional()], coerce=int) url_forms = FieldList(FormField(URLForm), min_entries=1, max_entries=10) def validate(self): if super(DataSetForm, self).validate(): return True # If Our Validators Pass return False class ExperimentForm(Form): name = TextField(u'Name', [DataRequired(), UniqueName(Experiment), Length(max=64)]) description = TextAreaField(u'Description', [Optional(), Length(max=512)]) tags = SelectMultipleField(u'Tags', [Optional()], coerce=int) algorithms = SelectMultipleField(u'Algorithms', [DataRequired()], coerce=int) collections = SelectMultipleField(u'Collections', [DataRequired()], coerce=int) def validate(self): if super(ExperimentForm, self).validate(): return True # If Our Validators Pass return False class BatchForm(Form): name = TextField(u'Name', [DataRequired(), UniqueName(Batch), Length(max=64)]) description = TextAreaField(u'Desciption', [Optional(), Length(max=512)]) experiment = SelectField(u'Experiment', [DataRequired()], coerce=int) data_set = SelectField(u'Data Set', [DataRequired()], coerce=int) implementation = SelectField(u'Implementation', [DataRequired()], coerce=int) params = FileField(u'Parameter File', [FileRequired(), ValidParamFile()]) memory = IntegerField(u'Memory (MB)', [DataRequired(), NumberRange()]) disk = IntegerField(u'Disk Space (KB)', [DataRequired(), NumberRange()]) flock = BooleanField(u'Flock') glide = BooleanField(u'Glide') tags = SelectMultipleField(u'Tags', [Optional()], coerce=int) def validate(self): # TODO Validate Param File if super(BatchForm, self).validate(): return True # If Our Validators Pass return False class DownloadBatchForm(Form): batch = SelectField(u'Batch', [DataRequired()], coerce=int) def validate(self): if super(DownloadBatchForm, self).validate(): return True return False class UploadResultsForm(Form): batch = SelectField(u'Batch', [DataRequired(), ValidResultsBatch()], coerce=int) results = FileField(u'Results.json', [FileRequired(), ValidResultsFile()]) def validate(self): if super(UploadResultsForm, self).validate(): return True # If Our Validators Pass return False class TagForm(Form): """ User will create new tags used to add metadata to other entities """ name = TextField(u'Name', [DataRequired(), UniqueName(Tag), Length(max=64)]) def validate(self): if super(TagForm, self).validate(): return True # If Our Validators Pass return False class LoginForm(Form): username = TextField(u'Username', [DataRequired(), Length(max=64)]) password = PasswordField(u'Password', [Optional(), Length(max=64)]) def validate(self): # if our validators do not pass if not super(LoginForm, self).validate(): return False # Does the username exist user = User.query.filter_by(username=self.username.data).first() if not user: self.username.errors.append('Invalid username or password') return False # Do the passwords match if not user.check_password(self.password.data): self.username.errors.append('Invalid username or password') return False return True class CreateUserForm(Form): username = TextField(u'Username', [DataRequired(), Length(max=64)]) launch_directory = TextField(u'HTCondor Submit Node Launch Directory', [DataRequired(), Length(max=128)]) password = PasswordField(u'Password', [DataRequired(), Length(max=64)]) def validate(self): # if our validators do not pass if not super(CreateUserForm, self).validate(): return False # Does the user exist user = User.query.filter_by(username=self.username.data).first() if not user: return True self.username.errors.append('Username Unavailable') return False """ TODO: For Parameter Validation class ArgumentForm(Form): name = TextField(u'Name', [DataRequired(), Length(max=64)]) data_type = SelectField(u'Data Type', [DataRequired()], choices=[(0, 'Int'), (1, 'Float'), (2, 'Array'), (3, 'String'), (4, 'Boolean')]) optional = BooleanField(u'Optional') def validate(self): if super(ArgumentForm, self).validate(): return True # If Our Validators Pass return False """ class AlgorithmViewForm(Form): algorithms = SelectField(u'Algorithms', [Optional()], coerce=int) implementations = SelectField(u'Implementations', [Optional()], coerce=int) def validate(self): if super(AlgorithmViewForm, self).validate(): return True # If Our Validators Pass return False class DataViewForm(Form): collections = SelectField(u'Data Collections', [Optional()], coerce=int) sets = SelectField(u'Data Sets', [Optional()], coerce=int) def validate(self): if super(DataViewForm, self).validate(): return True # If Our Validators Pass return False class ExperimentViewForm(Form): experiments = SelectField(u'Experiments', [Optional()], coerce=int) batches = SelectField(u'Batches', [Optional()], coerce=int) def validate(self): if super(ExperimentViewForm, self).validate(): return True # If Our Validators Pass return False class BatchViewForm(Form): batches = SelectField(u'Batches', [Optional()], coerce=int) def validate(self): if super(BatchViewForm, self).validate(): return True # If Our Validators Pass return False class UserViewForm(Form): users = SelectField(u'Users', [Optional()], coerce=int) def validate(self): if super(UserViewForm, self).validate(): return True # If Our Validators Pass return False class EditUserForm(Form): edit_username = TextField(u'Username') edit_dir = TextField(u'HTCondor Submit Node Launch Directory', [DataRequired(), Length(max=128)]) edit_pw = PasswordField(u'Password', [DataRequired(), Length(max=64)]) def validate(self): if super(EditUserForm, self).validate(): return True # If Our Validators Pass return False
{ "repo_name": "ikinsella/squall", "path": "flaskapp/squall/forms.py", "copies": "1", "size": "16354", "license": "bsd-3-clause", "hash": -4531469849155140600, "line_mean": 34.4750542299, "line_max": 79, "alpha_frac": 0.5490399902, "autogenerated": false, "ratio": 4.77349678925861, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.582253677945861, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from flask_wtf.file import FileField from wtforms import TextField, HiddenField, ValidationError, RadioField,\ BooleanField, SubmitField, IntegerField, FormField, validators from wtforms.validators import Required # straight from the wtforms docs: class TelephoneForm(Form): country_code = IntegerField('Country Code', [validators.required()]) area_code = IntegerField('Area Code/Exchange', [validators.required()]) number = TextField('Number') class ExampleForm(Form): field1 = TextField('First Field', description='This is field one.') field2 = TextField('Second Field', description='This is field two.', validators=[Required()]) hidden_field = HiddenField('You cannot see this', description='Nope') recaptcha = RecaptchaField('A sample recaptcha field') radio_field = RadioField('This is a radio field', choices=[ ('head_radio', 'Head radio'), ('radio_76fm', "Radio '76 FM"), ('lips_106', 'Lips 106'), ('wctr', 'WCTR'), ]) checkbox_field = BooleanField('This is a checkbox', description='Checkboxes can be tricky.') # subforms mobile_phone = FormField(TelephoneForm) # you can change the label as well office_phone = FormField(TelephoneForm, label='Your office phone') ff = FileField('Sample upload') submit_button = SubmitField('Submit Form') def validate_hidden_field(form, field): raise ValidationError('Always wrong')
{ "repo_name": "HellerCommaA/flask-template-materialize", "path": "forms.py", "copies": "1", "size": "1544", "license": "mit", "hash": 5495480496883344000, "line_mean": 37.625, "line_max": 75, "alpha_frac": 0.6742227979, "autogenerated": false, "ratio": 4.20708446866485, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0030496632996633, "num_lines": 40 }
from flask_wtf import Form, RecaptchaField from wtforms import ( StringField, TextAreaField, PasswordField, BooleanField, SelectField ) from wtforms.validators import DataRequired, Length, EqualTo, URL from webapp.models import User class CommentForm(Form): name = StringField( 'Name', validators=[DataRequired(), Length(max=255)] ) text = TextAreaField(u'Comment', validators=[DataRequired()]) class PostForm(Form): title = StringField('Title', [DataRequired(), Length(max=255)]) type = SelectField('Post Type', choices=[ ('blog', 'Blog Post'), ('image', 'Image'), ('video', 'Video'), ('quote', 'Quote') ]) text = TextAreaField('Content') image = StringField('Image URL', [URL(), Length(max=255)]) video = StringField('Video Code', [Length(max=255)]) author = StringField('Author', [Length(max=255)]) class LoginForm(Form): username = StringField('Username', [DataRequired(), Length(max=255)]) password = PasswordField('Password', [DataRequired()]) remember = BooleanField("Remember Me") def validate(self): check_validate = super(LoginForm, self).validate() # if our validators do not pass if not check_validate: return False # Does our the exist user = User.query.filter_by(username=self.username.data).first() if not user: self.username.errors.append('Invalid username or password') return False # Do the passwords match if not user.check_password(self.password.data): self.username.errors.append('Invalid username or password') return False return True class OpenIDForm(Form): openid = StringField('OpenID URL', [DataRequired(), URL()]) class RegisterForm(Form): username = StringField('Username', [DataRequired(), Length(max=255)]) password = PasswordField('Password', [DataRequired(), Length(min=8)]) confirm = PasswordField('Confirm Password', [ DataRequired(), EqualTo('password') ]) recaptcha = RecaptchaField() def validate(self): check_validate = super(RegisterForm, self).validate() # if our validators do not pass if not check_validate: return False user = User.query.filter_by(username=self.username.data).first() # Is the username already being used if user: self.username.errors.append("User with that name already exists") return False return True
{ "repo_name": "abacuspix/NFV_project", "path": "Mastering Flask_Code Bundle/chapter_7/webapp/forms.py", "copies": "2", "size": "2579", "license": "mit", "hash": -7187928434789878000, "line_mean": 27.9775280899, "line_max": 77, "alpha_frac": 0.6312524234, "autogenerated": false, "ratio": 4.319932998324958, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5951185421724958, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from wtforms import ( widgets, StringField, TextAreaField, PasswordField, BooleanField ) from wtforms.validators import DataRequired, Length, EqualTo, URL from webapp.models import User class CKTextAreaWidget(widgets.TextArea): def __call__(self, field, **kwargs): kwargs.setdefault('class_', 'ckeditor') return super(CKTextAreaWidget, self).__call__(field, **kwargs) class CKTextAreaField(TextAreaField): widget = CKTextAreaWidget() class CommentForm(Form): name = StringField( 'Name', validators=[DataRequired(), Length(max=255)] ) text = TextAreaField(u'Comment', validators=[DataRequired()]) class PostForm(Form): title = StringField('Title', [DataRequired(), Length(max=255)]) text = TextAreaField('Content', [DataRequired()]) class LoginForm(Form): username = StringField('Username', [DataRequired(), Length(max=255)]) password = PasswordField('Password', [DataRequired()]) remember = BooleanField("Remember Me") def validate(self): check_validate = super(LoginForm, self).validate() # if our validators do not pass if not check_validate: return False # Does our the exist user = User.query.filter_by(username=self.username.data).first() if not user: self.username.errors.append('Invalid username or password') return False # Do the passwords match if not user.check_password(self.password.data): self.username.errors.append('Invalid username or password') return False return True class OpenIDForm(Form): openid = StringField('OpenID URL', [DataRequired(), URL()]) class RegisterForm(Form): username = StringField('Username', [DataRequired(), Length(max=255)]) password = PasswordField('Password', [DataRequired(), Length(min=8)]) confirm = PasswordField('Confirm Password', [ DataRequired(), EqualTo('password') ]) recaptcha = RecaptchaField() def validate(self): check_validate = super(RegisterForm, self).validate() # if our validators do not pass if not check_validate: return False user = User.query.filter_by(username=self.username.data).first() # Is the username already being used if user: self.username.errors.append("User with that name already exists") return False return True
{ "repo_name": "nikitabrazhnik/flask2", "path": "Module 3/Chapter10/Chapter 10/webapp/forms.py", "copies": "7", "size": "2528", "license": "mit", "hash": -699289168625867300, "line_mean": 27.0888888889, "line_max": 77, "alpha_frac": 0.6491297468, "autogenerated": false, "ratio": 4.292020373514431, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.844115012031443, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from wtforms import StringField, HiddenField, SelectField, RadioField, FormField, Form as WtfForm from wtforms.validators import DataRequired, Length from wtforms.fields.html5 import EmailField class PracticeForm(Form): practice_code = StringField('Practice Code', validators=[DataRequired(), Length(max=10)]) # recaptcha = RecaptchaField() class DelegateEditForm(Form): id = HiddenField('id') fullname = StringField('Name', validators=[DataRequired(), Length(max=100)]) email = EmailField('Email', validators=[DataRequired(), Length(max=200)]) role = SelectField('Role', choices=[('', ''), ('GP', 'GP'), ('Practice Manager', 'Practice Manager'), ('Nurse', 'Nurse'), ('Health Care Assisstant', 'Health Care Assisstant'), ('Phlebotomist', 'Phlebotomists'), ('Administrator', 'Administrator'), ('Other', 'Other')]) dietary = StringField('Special Dietary Needs', validators=[Length(max=200)]) carReg = StringField('Car Registration (if parking permit required)', validators=[Length(max=10)]) meetingId = RadioField('Meeting', coerce=int) class DelegateDeleteForm(Form): id = HiddenField('id')
{ "repo_name": "rabramley/lcbru-events", "path": "lcbru_events/forms/genvasc_collaborators.py", "copies": "1", "size": "1175", "license": "mit", "hash": -379593830135886800, "line_mean": 55, "line_max": 271, "alpha_frac": 0.7208510638, "autogenerated": false, "ratio": 3.766025641025641, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49868767048256407, "avg_score": null, "num_lines": null }
from flask_wtf import Form # , RecaptchaField from wtforms import StringField, IntegerField, DateField from wtforms import SubmitField, SelectField, FloatField from wtforms import validators from wtforms.validators import Required, Email, Length from wtforms.validators import Regexp from datetime import datetime from ..models import Employee class ApproveBorrower(Form): first_name = StringField('First Name', validators=[Required()]) last_name = StringField('Last Name', validators=[Required()]) national_id = IntegerField('National ID Number', validators=[Required()]) max_credit_amt = FloatField('Maximum Credit Amount', validators=[Required()]) submit = SubmitField('Approve Borrower') class AddEmployee(Form): username = StringField('Username', validators=[ Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, ' 'numbers, dots or underscores')]) first_name = StringField('First Name', validators=[ Required(), Length(1, 64)]) last_name = StringField('Last Name', validators=[ Required(), Length(1, 64)]) email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) max_allowable_amt = IntegerField('Maximum allowable amount') submit = SubmitField('Add Employee') class ApproveEmployee(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) username = StringField('Username', validators=[ Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, ' 'numbers, dots or underscores')]) submit = SubmitField('Approve Employee') class ApproveLoan(Form): full_name = StringField('Full Names', validators=[Required()]) nickname = StringField('User name', validators=[Required()]) approved_on = DateField('Approved On') loan_amt = FloatField('Borrowed Amount') submit = SubmitField('Approve Loan') class ApproveLoanPayment(Form): full_name = StringField('Full Names', validators=[Required()]) nickname = StringField('User name', validators=[Required()]) amt_charged = FloatField('Borrowed Amount') approved_on = DateField('Date Approved') repaid_on = DateField('Date Repaid', default=datetime.utcnow) my_funds = FloatField('Amount Paid') submit = SubmitField('Approve Payment') '''This form is a simple assign a user to an employee form''' class AssignUserToEmployee(Form): '''This form is a simple assign a user to an employee form''' nickname = StringField('User Name') employee = SelectField('Employee To Assign', [validators.Required( message='Employee required.')], coerce=int) submit = SubmitField('Assign') def __init__(self, *args, **kwargs): super(AssignUserToEmployee, self).__init__(*args, **kwargs) self.employee.choices = [ (employee.id, employee.username) for employee in Employee.query.all()] class RemoveLoan(Form): loan_amt = FloatField('Loan Amount') submit = SubmitField('Remove Loan')
{ "repo_name": "Kimanicodes/wananchi", "path": "app/admin/forms.py", "copies": "1", "size": "3458", "license": "mit", "hash": -5324183961729842000, "line_mean": 40.1666666667, "line_max": 78, "alpha_frac": 0.6127819549, "autogenerated": false, "ratio": 4.544021024967148, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00019201228878648233, "num_lines": 84 }
from flask_wtf import Form # , RecaptchaField from wtforms import StringField, IntegerField, SelectField, TextAreaField from wtforms import validators, SubmitField, BooleanField from wtforms import ValidationError from wtforms.validators import Required, Email, Length, Regexp from ..models import User # from wtforms import BooleanField # , SubmitField, validators """from wtforms.validators import Required, Email, Length from wtforms.validators import Regexp, EqualTo, ValidationError""" class EditProfileForm(Form): first_name = StringField('First Name', [validators.Required(), validators.Length(max=80)]) last_name = StringField('Last Name', [validators.Required(), validators.Length(min=4, max=25)]) national_id = IntegerField('National Identification Number', [validators.Required()]) phone_number = IntegerField('Mobile Phone Number', [validators.Required()]) location = StringField('Location', [validators.Required(), validators.Length(min=4, max=25)]) d_o_b = IntegerField('Date of Birth', [validators.Required()]) marital_status = SelectField('Marital Status', choices=[ ('married', 'Married'), ('single', 'Single'), ('divorced', 'Divorced')]) gender = SelectField( 'Gender', choices=[('male', 'Male'), ('female', 'Female')]) submit = SubmitField('Submit') class EditProfileAdminForm(Form): first_name = StringField('First Name', [validators.Required(), validators.Length(max=80)]) last_name = StringField('Last Name', [validators.Length(min=4, max=25)]) national_id = IntegerField('National Identification Number') phone_number = IntegerField('Mobile Phone Number') location = StringField('Location', [validators.Length(min=4, max=25)]) d_o_b = IntegerField('Date of Birth') marital_status = SelectField('Marital Status', choices=[ ('married', 'Married'), ('single', 'Single'), ('divorced', 'Divorced')]) gender = SelectField( 'Gender', choices=[('male', 'Male'), ('female', 'Female')]) home_add_desc = TextAreaField('Home Description', [validators.required( message='Please describe how to get to your place of residence.')]) home_ownership = SelectField( 'Home Ownership', choices=[('yes', 'Yes'), ('no', 'No')]) submit = SubmitField('Submit')
{ "repo_name": "Kimanicodes/wananchi", "path": "app/main/forms.py", "copies": "1", "size": "2589", "license": "mit", "hash": -371565112954454100, "line_mean": 50.78, "line_max": 105, "alpha_frac": 0.6195442256, "autogenerated": false, "ratio": 4.418088737201365, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00018867924528301886, "num_lines": 50 }
from flask_wtf import Form,RecaptchaField from wtforms import StringField, PasswordField,IntegerField,TextAreaField from wtforms.validators import InputRequired,Email,EqualTo,Length,Regexp,\ AnyOf,Optional,NumberRange,ValidationError from flask.ext.login import current_user from app.models import User,Category RESERVED_WORDS = [ 'root', 'admin', 'bot', 'robot', 'master', 'webmaster', 'account', 'people', 'user', 'users', 'project', 'projects', 'search', 'action', 'favorite', 'like', 'love', 'none', 'team', 'teams', 'group', 'groups', 'organization', 'organizations', 'package', 'packages', 'org', 'com', 'net', 'help', 'doc', 'docs', 'document', 'documentation', 'blog', 'bbs', 'forum', 'forums', 'static', 'assets', 'repository', 'public', 'private', 'mac', 'windows', 'ios', 'lab', ] class UserForm(Form): username = StringField('Username',validators=[ InputRequired(), Length(min=3,max=30), Regexp('^[a-z0-9A-z_]+$')]) email = StringField('Email',validators=[ InputRequired(message='Need a email'), Email(), Length(max=100)]) nick = StringField('nick',validators=[ Optional(), Length(max=80)]) gender = StringField('gender',validators=[ Optional(), AnyOf(['male','female'])]) age = IntegerField('age',validators=[ Optional(), NumberRange(0,100)]) department = StringField('department',validators=[ Optional(), Length(max=120)]) phone = StringField('phone',validators=[ Optional()]) qq = IntegerField('qq',validators=[ Optional()]) class CategoryForm(Form): name = StringField('Category Name',validators=[ InputRequired(), Length(max=40)]) description = StringField('Category decription',validators=[ Optional()]) def validate_name(form,field): # print(field.data) if Category.query.filter_by(name=field.data).count(): raise ValidationError('This category already exists.')
{ "repo_name": "Aaron1992/shiguang", "path": "app/admin/forms.py", "copies": "1", "size": "2059", "license": "apache-2.0", "hash": 6997517398962166000, "line_mean": 32.2096774194, "line_max": 74, "alpha_frac": 0.6211753278, "autogenerated": false, "ratio": 4.029354207436399, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5150529535236399, "avg_score": null, "num_lines": null }
from flask_wtf import Form,RecaptchaField from wtforms import StringField, PasswordField,IntegerField,TextAreaField,SelectField from wtforms.validators import InputRequired,Email,EqualTo,Length,Regexp,\ AnyOf,Optional,NumberRange,ValidationError from flask.ext.login import current_user from .models import User,Category RESERVED_WORDS = [ 'root', 'admin', 'bot', 'robot', 'master', 'webmaster', 'account', 'people', 'user', 'users', 'project', 'projects', 'search', 'action', 'favorite', 'like', 'love', 'none', 'team', 'teams', 'group', 'groups', 'organization', 'organizations', 'package', 'packages', 'org', 'com', 'net', 'help', 'doc', 'docs', 'document', 'documentation', 'blog', 'bbs', 'forum', 'forums', 'static', 'assets', 'repository', 'public', 'private', 'mac', 'windows', 'ios', 'lab', ] class LoginForm(Form): username = StringField('username',validators=[ InputRequired(message='Need a username'), Length(min=3,max=20)]) password = PasswordField('password',validators=[ InputRequired(message='Need a password')]) #recaptcha = RecaptchaField() class RegisterForm(LoginForm): username = StringField('Username',validators=[ InputRequired(), Length(min=3,max=30), Regexp('^[a-z0-9A-z_]+$')]) email = StringField('Email',validators=[ InputRequired(message='Need a email'), Email(), Length(max=100)]) password = PasswordField('New Password',validators=[ InputRequired(message='Need a password'), EqualTo('confirm',message='Passwords must match')]) confirm = PasswordField('Reqeat Password') def validate_username(form,field): data = field.data.lower() if data in RESERVED_WORDS: raise ValidationError('This is a reserved name.') if User.query.filter_by(username=field.data).count(): raise ValidationError('This name has been registered.') def validate_email(form,field): if User.query.filter_by(email=field.data.lower()).count(): raise ValidationError('This email has been registered.') class ProfileForm(Form): nick = StringField('nick',validators=[ Optional(), Length(max=80)]) gender = StringField('gender',validators=[ Optional(), AnyOf(['male','female'])]) age = IntegerField('age',validators=[ Optional(), NumberRange(0,100)]) department = StringField('department',validators=[ Optional(), Length(max=120)]) phone = StringField('phone',validators=[ Optional()]) qq = IntegerField('qq',validators=[ Optional()]) class ChangePasswordForm(Form): old_password = PasswordField("Old Password",validators=[ InputRequired(message="需要输入密码")]) new_password = PasswordField("Password",validators=[ InputRequired(), EqualTo('confirm_new_password',message="密码必须相同")]) confirm_new_password = PasswordField('Confirm New Password') def validate_old_password(form,field): if not current_user.check_password(field.data): raise ValidationError('Password is wrong.') class PostForm(Form): title = StringField('Post Title',validators=[ InputRequired(), Length(max=225)]) content = TextAreaField('Post Title',validators=[ InputRequired() ]) category_id = SelectField('Category id',coerce=int,validators=[ InputRequired()]) '''====== The admin fetures ============''' #class CategoryForm(Form): # name = StringField('Category Name',validators=[ # InputRequired(), # Length(max=40)]) # description = StringField('Category decription',validators=[ # Optional()]) #def validate_name(form,field): # print(field.data) # if Category.query.filter_by(name=field.data).count(): # raise ValidationError('This category already exists.')
{ "repo_name": "Aaron1992/shiguang", "path": "app/forms.py", "copies": "1", "size": "3982", "license": "apache-2.0", "hash": 2916267502030966000, "line_mean": 30.664, "line_max": 85, "alpha_frac": 0.6364325417, "autogenerated": false, "ratio": 4.097308488612836, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.017000036179956497, "num_lines": 125 }
from flask_wtf import Form # , RecaptchaField from wtforms import StringField, PasswordField from wtforms import BooleanField, SubmitField from wtforms.validators import Required, Email, Length from wtforms.validators import Regexp, EqualTo, ValidationError from ..models import User class LoginForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) password = PasswordField('Password', validators=[Required()]) remember_me = BooleanField('Keep me logged in') submit = SubmitField('Log In') class RegistrationForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) username = StringField('Username', validators=[ Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, ' 'numbers, dots or underscores')]) password = PasswordField('Password', validators=[ Required(), EqualTo('password2', message='Passwords must match.')]) password2 = PasswordField('Confirm password', validators=[Required()]) submit = SubmitField('Register') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.') def validate_username(self, field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Username already in use.') class ChangePasswordForm(Form): old_password = PasswordField('Old password', validators=[Required()]) password = PasswordField('New password', validators=[ Required(), EqualTo('password2', message='Passwords must match')]) password2 = PasswordField('Confirm new password', validators=[Required()]) submit = SubmitField('Update Password') class PasswordResetRequestForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) submit = SubmitField('Reset Password') class PasswordResetForm(Form): email = StringField('Email', validators=[Required(), Length(1, 64), Email()]) password = PasswordField('New Password', validators=[ Required(), EqualTo('password2', message='Passwords must match')]) password2 = PasswordField('Confirm password', validators=[Required()]) submit = SubmitField('Reset Password') def validate_email(self, field): if User.query.filter_by(email=field.data).first() is None: raise ValidationError('Unknown email address.') class ChangeEmailForm(Form): email = StringField('New Email', validators=[Required(), Length(1, 64), Email()]) password = PasswordField('Password', validators=[Required()]) submit = SubmitField('Update Email Address') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Email already registered.')
{ "repo_name": "Kimanicodes/wananchi", "path": "app/auth/forms.py", "copies": "1", "size": "3187", "license": "mit", "hash": 6978204596313866000, "line_mean": 42.6575342466, "line_max": 78, "alpha_frac": 0.6284907436, "autogenerated": false, "ratio": 4.828787878787879, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5957278622387879, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from wtforms import StringField, TextAreaField, PasswordField, BooleanField from wtforms.validators import DataRequired, Length, EqualTo, URL from webapp.models import User class CommentForm(Form): name = StringField( 'Name', validators=[DataRequired(), Length(max=255)] ) text = TextAreaField(u'Comment', validators=[DataRequired()]) class PostForm(Form): title = StringField('Title', [DataRequired(), Length(max=255)]) text = TextAreaField('Content', [DataRequired()]) class LoginForm(Form): username = StringField('Username', [DataRequired(), Length(max=255)]) password = PasswordField('Password', [DataRequired()]) remember = BooleanField("Remember Me") def validate(self): check_validate = super(LoginForm, self).validate() # if our validators do not pass if not check_validate: return False # Does our the exist user = User.query.filter_by(username=self.username.data).first() if not user: self.username.errors.append('Invalid username or password') return False # Do the passwords match if not user.check_password(self.password.data): self.username.errors.append('Invalid username or password') return False return True class OpenIDForm(Form): openid = StringField('OpenID URL', [DataRequired(), URL()]) class RegisterForm(Form): username = StringField('Username', [DataRequired(), Length(max=255)]) password = PasswordField('Password', [DataRequired(), Length(min=8)]) confirm = PasswordField('Confirm Password', [ DataRequired(), EqualTo('password') ]) recaptcha = RecaptchaField() def validate(self): check_validate = super(RegisterForm, self).validate() # if our validators do not pass if not check_validate: return False user = User.query.filter_by(username=self.username.data).first() # Is the username already being used if user: self.username.errors.append("User with that name already exists") return False return True
{ "repo_name": "abacuspix/NFV_project", "path": "Mastering Flask_Code Bundle/chapter_9/webapp/forms.py", "copies": "6", "size": "2219", "license": "mit", "hash": -5551808543196390000, "line_mean": 28.9864864865, "line_max": 77, "alpha_frac": 0.6516448851, "autogenerated": false, "ratio": 4.420318725099602, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8071963610199602, "avg_score": null, "num_lines": null }
from flask_wtf import Form # , RecaptchaField from wtforms import StringField, validators, SelectField from wtforms import TextAreaField from wtforms import SubmitField, IntegerField, FloatField from wtforms.validators import Required, Length, Regexp, Email class AddBorrower(Form): nickname = StringField('Username', validators=[ Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, ' 'numbers, dots or underscores')]) national_id = IntegerField('National ID Number', validators=[Required()]) submit = SubmitField('Add Borrower') class EditProfileEmployeeForm(Form): nickname = StringField('Username', validators=[ Required(), Length(1, 64), Regexp('^[A-Za-z][A-Za-z0-9_.]*$', 0, 'Usernames must have only letters, ' 'numbers, dots or underscores')]) first_name = StringField('First Name', [validators.Required(), validators.Length(max=80)]) last_name = StringField('Last Name', [validators.Length(min=4, max=25)]) national_id = IntegerField('National Identification Number') phone_number = IntegerField('Mobile Phone Number', validators=[Required()]) location = StringField('Location', [validators.Length(min=4, max=25)]) d_o_b = IntegerField('Date of Birth') marital_status = SelectField('Marital Status', choices=[ ('married', 'Married'), ('single', 'Single'), ('divorced', 'Divorced')]) gender = SelectField( 'Gender', choices=[('male', 'Male'), ('female', 'Female')]) home_add_desc = TextAreaField('Home Description', [validators.required( message='Please describe how to get to your place of residence.')]) home_ownership = SelectField( 'Home Ownership', choices=[('yes', 'Yes'), ('no', 'No')]) submit = SubmitField('Submit') class EditProfileBusinessForm(Form): has_business = SelectField( 'Has Business', choices=[('no', 'No'), ('yes', 'Yes')]) business_location = StringField('Location of your business', [validators.Length(min=4, max=25)]) business_type = StringField('Type of Business', [validators.Length(min=4, max=25)]) bus_desc = TextAreaField('Brief explanation of how business transacts') bus_gross_per_day = FloatField('Gross Per Day') bus_gross_per_mo = FloatField('Gross Per Month') bus_expenditure_per_day = FloatField('Expenditure Per Day') bus_expenditure_per_mo = FloatField('Expenditure Per Month') business_profit_pd = FloatField('Profit Made Per Day if Applicable') business_profit_pm = FloatField('Profit Made Per Day if Applicable') submit = SubmitField('Submit') '''Approve User Employee Form ''' class LoanApplicationForm(Form): loan_amt = FloatField('Loan Amount') submit = SubmitField('Submit Application') class RepayLoan(Form): my_funds = FloatField('Amount in Ksh') submit = SubmitField('Repay Loan')
{ "repo_name": "Kimanicodes/wananchi", "path": "app/employees/forms.py", "copies": "1", "size": "3224", "license": "mit", "hash": 8763934199694434000, "line_mean": 47.1194029851, "line_max": 105, "alpha_frac": 0.6150744417, "autogenerated": false, "ratio": 4.0810126582278485, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5196087099927849, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from wtforms import TextAreaField, PasswordField, BooleanField, HiddenField, FileField, SelectMultipleField, \ SelectField, RadioField, SubmitField, StringField from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo, url, Optional from wtforms.fields.html5 import URLField from wtforms.fields import FieldList from wtforms import ValidationError from ..models import Module, Objective, User class SignupForm(Form): email = StringField('Email', validators=[ DataRequired('Please provide a valid email address'), Email(message=(u'That\'s not a valid email address'))]) password = PasswordField('Pick a secure password', validators=[ DataRequired('Please enter a password'), Length(min=6, message=(u'Password must be at least 6 characters'))]) confirm_password = PasswordField('Confirm password', validators=[ EqualTo('password', message='Password confirmation did not match')]) username = StringField('Username', validators=[ DataRequired(), Length(min=1, message='Username is too short'), Regexp('^[A-Za-z][A-Za-z0-9_.\- ]*$', 0, 'Usernames must have only letters, numbers, dots, dashes, underscores, or spaces')]) forename = StringField('Forename', validators=[ Optional(), Length(min=1, message='Forename is too short'), Regexp('^[A-Za-z][A-Za-z0-9_.\- ]*$', 0, 'Forenames must have only letters, numbers, dots, dashes, underscores, or spaces')]) surname = StringField('Surname', validators=[ Optional(), Length(min=1, message='Forename is too short'), Regexp('^[A-Za-z][A-Za-z0-9_.\- ]*$', 0, 'Surnames must have only letters, numbers, dots, dashes, underscores, or spaces')]) agree = BooleanField('By signing up your agree to follow our <a href="#">Terms and Conditions</a>', validators=[DataRequired(u'You must agree the Terms of Service')]) remember_me = BooleanField('Remember me', default=True) recaptcha = RecaptchaField() submit = SubmitField('Sign-up') def validate_email(self, field): if User.query.filter_by(email=field.data).first(): raise ValidationError('This email address has already been registered') class LoginForm(Form): email = StringField('Email', validators=[ DataRequired('Please enter the email address you used to sign up'), Email(message=(u"That\'s not a valid email address"))]) password = PasswordField('Enter password', validators=[ DataRequired('Please enter your password')]) remember_me = BooleanField('Remember me', default=True) submit = SubmitField('Login') def validate_email(self, field): if not User.user_by_email(field.data): raise ValidationError('This email address is not recognised') class PasswordResetRequestForm(Form): email = StringField('Email', validators=[ DataRequired('Please enter the email address you used to sign up'), Email('Please enter the email address you used to sign up')]) submit = SubmitField('Reset Password') def validate_email(self, field): if not User.user_by_email(field.data): raise ValidationError('This email address is not recognised') class PasswordResetForm(Form): email = StringField('Email', validators=[ DataRequired('Please enter the email address you used to sign up'), Email('Please enter the email address you used to sign up')]) password = PasswordField('New Password', validators=[ DataRequired('Please enter a new password'), EqualTo('password2', message='Passwords do not match')]) password2 = PasswordField('Confirm password', validators=[ DataRequired('Please reenter your new password')]) submit = SubmitField('Reset Password') def validate_email(self, field): if not User.user_by_email(field.data): raise ValidationError('This email address is not recognised')
{ "repo_name": "BigPoppaG/CourseMe", "path": "courseme/auth/forms.py", "copies": "1", "size": "4071", "license": "mit", "hash": 5987850999738413000, "line_mean": 47.4761904762, "line_max": 110, "alpha_frac": 0.677229182, "autogenerated": false, "ratio": 4.307936507936508, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5485165689936508, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from wtforms import TextField, PasswordField, BooleanField from wtforms.validators import DataRequired, Length, EqualTo class LoginForm(Form): """Form with generic login fields.""" email = TextField('email', validators=[DataRequired()]) password = PasswordField('password', validators=[DataRequired()]) remember_me = BooleanField('remember_me', default=False) class RegisterForm(Form): """Form with generic register fields, as well as Recaptcha and an invite code field.""" firstname = TextField('firstname', validators=[DataRequired(), Length(min=1, max=32)]) lastname = TextField('lastname', validators=[DataRequired(), Length(min=1, max=32)]) username = TextField('username', validators=[DataRequired(), Length(min=1, max=32)]) email = TextField('email', validators=[DataRequired(), Length(min=1, max=32)]) password = PasswordField('password', validators=[DataRequired(), Length(min=8, max=64), EqualTo('confirm', message='Passwords must match.')]) confirm = PasswordField('Repeat Password') invite = TextField('invite', validators=[DataRequired(), Length(min=16, max=16)]) recaptcha = RecaptchaField()
{ "repo_name": "kylewmoser/HistoryEmergent", "path": "historyemergent/users/forms.py", "copies": "1", "size": "1257", "license": "mit", "hash": -2898813340328333300, "line_mean": 53.6956521739, "line_max": 106, "alpha_frac": 0.69291965, "autogenerated": false, "ratio": 4.232323232323233, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5425242882323232, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from wtforms import TextField, PasswordField,\ SubmitField, SelectField, TextAreaField, StringField, SelectMultipleField, widgets, BooleanField from wtforms.validators import DataRequired, Email, EqualTo, Length, IPAddress, Optional class SearchForm(Form): search = StringField('Search') submit = SubmitField(label='Submit') class BlacklistCharacterForm(Form): character_name = TextAreaField("Character Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) main_name = TextAreaField("Main Name", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) corporation = TextAreaField("Corporation", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) alliance = TextAreaField("Alliance", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) ip_address = TextAreaField("IP Address", validators=[IPAddress(), Optional()]) notes = TextAreaField("Notes", validators=[Length(min=-1, max=2000, message='Max length %(max)d')]) submit = SubmitField(label='Submit Entry')
{ "repo_name": "tyler274/Recruitment-App", "path": "recruit_app/blacklist/forms.py", "copies": "1", "size": "1169", "license": "bsd-3-clause", "hash": 3220300832082848300, "line_mean": 57.45, "line_max": 121, "alpha_frac": 0.6971770744, "autogenerated": false, "ratio": 3.8966666666666665, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5093843741066666, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from wtforms import TextField, PasswordField, SubmitField from wtforms.validators import DataRequired from recruit_app.user.models import User from recruit_app.extensions import user_datastore from flask_security.forms import ConfirmRegisterForm, PasswordConfirmFormMixin class LoginForm(Form): email = TextField('Email', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) submit = SubmitField(label='Log In') def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.user = None def validate(self): initial_validation = super(LoginForm, self).validate() if not initial_validation: return False self.user = user_datastore.get_user(self.email.data) if not self.user: self.email.errors.append('Unknown email address') return False if not self.user.check_password(self.password.data): self.password.errors.append('Invalid password') return False if not self.user.active: self.email.errors.append('User not activated') return False return True class ConfirmRegisterFormRecaptcha(ConfirmRegisterForm, PasswordConfirmFormMixin): recaptcha = RecaptchaField() def __init__(self, *args, **kwargs): super(ConfirmRegisterForm, self).__init__(*args, **kwargs)
{ "repo_name": "tyler274/Recruitment-App", "path": "recruit_app/public/forms.py", "copies": "1", "size": "1473", "license": "bsd-3-clause", "hash": 1596901255470355000, "line_mean": 31.7333333333, "line_max": 82, "alpha_frac": 0.6802443992, "autogenerated": false, "ratio": 4.294460641399417, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5474705040599417, "avg_score": null, "num_lines": null }
from flask_wtf import Form, RecaptchaField from wtforms import TextField, TextAreaField, PasswordField, BooleanField, HiddenField, FileField, SelectMultipleField, \ SelectField, RadioField, ValidationError from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo, url, optional from wtforms.fields.html5 import URLField from wtforms.fields import FieldList from .. models import Module, Objective, User from courseme.util.wtform_utils import blank_to_none class EditObjective(Form): id = HiddenField(filters=[blank_to_none]) name = TextField('Objective', validators=[ DataRequired('Enter a description of the objective'), Length(min=4, message=(u'Description must be at least 4 characters'))]) topic_id = SelectField('Topic') prerequisites = SelectMultipleField('Prerequisites', choices=[]) # authors = FieldList(TextField('Name')) #DJG - Try this as way of geting proper ordered list back from form def __init__(self, topic_choices, **kwargs): """Construct a new EditObjective form. :param topic_choices: a list of 2-tuples representing the IDs and labels of available Topics. """ super(EditObjective, self).__init__(**kwargs) self.topic_id.choices = topic_choices class EditModule(Form): edit_module_id = HiddenField() # DJG - don't know if I need this name = TextField('Module name', validators=[DataRequired('Please enter a name for your module')]) description = TextAreaField('Brief description') notes = TextAreaField('Notes') module_objectives = SelectMultipleField('Objectives', choices=[]) material_type = RadioField('Material Type', choices=[('Lecture', 'Lecture'), ('Exercise', 'Exercise'), ('Course', 'Course (select individual modules to include later)')], default='Lecture', validators=[DataRequired('Please specify what type of material you are creating')]) material_source = RadioField('Material Source', choices=[('upload', 'Upload video'), ('youtube', 'youtube link')], default='upload') # validators = [DataRequired('Please specify how you are providing the material')]) material_upload = FileField( 'Select File') # DJG - would be nice to have these be DataRequired when they apply #validators=[DataRequired('Please upload your material')]) material_youtube = URLField( 'Enter URL') # validators=[url, DataRequired('Please provide a link to your material')]) subtitles = BooleanField('Subtitles', default=False) easy_language = BooleanField('Simple Language', default=False) extension = BooleanField('Extension Material', default=False) for_teachers = BooleanField('Ideas for Teachers', default=False) class EditQuestion(Form): edit_question_id = HiddenField() question = TextAreaField('Question') answer = TextAreaField('Answer') # objective = SelectField('Objectives', choices=Objective.Choices()) extension = BooleanField('Extension Material', default=False) visually_impaired = BooleanField('Audio Assistance', default=False) question_objectives = SelectMultipleField('Objectives', choices=[]) class EditGroup(Form): edit_group_id = HiddenField() edit_group_name = TextField('Group Name', validators=[DataRequired('Enter a group name')]) edit_group_members = SelectMultipleField('Members', choices=[]) class EditScheme(Form): edit_scheme_id = HiddenField() edit_scheme_name = TextField('Scheme Name', validators=[DataRequired('Enter a name for this scheme of work')]) edit_scheme_objectives = SelectMultipleField('Objectives', choices=[]) class SendMessage(Form): message_type = RadioField('Group or Individual Message', choices=[('Individual', 'Individual'), ('Group', 'Group')], default='Individual', validators=[DataRequired( 'Please specify whether you are sending an individual or a group message')]) message_to = TextField('To', validators=[optional()]) message_to_group = SelectField('To', choices=[], validators=[optional()]) message_subject = TextField('Message Subject') message_body = TextAreaField('Message Content') recommended_material = SelectField('Recommend Material', choices=[]) assign_objective = SelectField('Assign Objective', choices=[]) assign_scheme = SelectField('Assign Scheme of Work', choices=[]) request_access = BooleanField("Request to view students' progress", default=False) #def validate_message_to(self, field): # if not User.user_by_email(field.data): # raise ValidationError('This email address is not recognised')
{ "repo_name": "BigPoppaG/CourseMe", "path": "courseme/main/forms.py", "copies": "1", "size": "4939", "license": "mit", "hash": 1177127219359198500, "line_mean": 51.5531914894, "line_max": 154, "alpha_frac": 0.6669366268, "autogenerated": false, "ratio": 4.481851179673321, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5648787806473321, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import Email, InputRequired, EqualTo class LoginForm(Form): username = StringField('Username', validators=[InputRequired()]) password = PasswordField('Password', validators=[InputRequired()]) class ForgotPasswordForm(Form): username = StringField('Username', validators=[InputRequired()]) email = StringField('E-Mail', validators=[InputRequired(), Email()]) class RegistrationForm(Form): username = StringField('Username', validators=[InputRequired()]) email = StringField('E-Mail', validators=[InputRequired(), Email()]) password = PasswordField('Password', validators=[InputRequired(), EqualTo('confirm', message='Passwords must match!')]) confirm = PasswordField('Confirm Password') class NewPasswordForm(Form): password = PasswordField('New Password', validators=[InputRequired(), EqualTo('confirm', message='Passwords must match!')]) confirm = PasswordField('Confirm Password')
{ "repo_name": "hreeder/ignition", "path": "manager/core/forms.py", "copies": "1", "size": "1046", "license": "mit", "hash": 5251273130170653000, "line_mean": 47.8095238095, "line_max": 127, "alpha_frac": 0.7304015296, "autogenerated": false, "ratio": 4.669642857142857, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5900044386742856, "avg_score": null, "num_lines": null }
from flask_wtf import Form from wtforms import StringField, TextField, IntegerField, SubmitField, SelectField, validators class GetuserForm(Form): customer_id = IntegerField('Customer ID') domain = TextField('Domain') user = TextField('User') mbx_type = SelectField(u'Mailbox Type', choices=[('rs', 'rs'), ('ex', 'ex')]) class GetdomainForm(Form): customer_id = IntegerField('Customer ID') domain = TextField('Domain') mbx_type = SelectField(u'Mailbox Type', choices=[('rs', 'rs'), ('ex', 'ex')]) class GetallForm(Form): customer_id = IntegerField('Customer ID') domain = TextField('Domain') mbx_type = SelectField(u'Mailbox Type', choices=[('rs', 'rs'), ('ex', 'ex')]) class PutuservexForm(Form): customer_id = IntegerField('Customer ID') domain = TextField('Domain') user = TextField('User') mbx_type = SelectField(u'Mailbox Type', choices=[('rs', 'rs'), ('ex', 'ex')]) user_vex_val = SelectField(u'Value', choices=[('true', 'true'), ('false', 'false')]) class PutdomainvexForm(Form): customer_id = IntegerField('Customer ID') domain = TextField('Domain') mbx_type = SelectField(u'Mailbox Type', choices=[('rs', 'rs'), ('ex', 'ex')]) domain_vex_val = SelectField(u'Value', choices=[('true', 'true'), ('false', 'false')])
{ "repo_name": "drogomarks/heimdallv2", "path": "forms.py", "copies": "1", "size": "1337", "license": "mit", "hash": -1474717406234659800, "line_mean": 39.78125, "line_max": 94, "alpha_frac": 0.6297681376, "autogenerated": false, "ratio": 3.5653333333333332, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9657938866488185, "avg_score": 0.007432520889029622, "num_lines": 32 }
from flask_wtf import Form from wtforms import TextField, PasswordField from wtforms.validators import DataRequired, Email, EqualTo, Length from .models import User class RegisterForm(Form): first_name = TextField('First Name') last_name = TextField('Last Name') username = TextField('Username', validators=[DataRequired(), Length(min=3, max=25)]) email = TextField( 'Email', validators=[DataRequired(), Email(), Length(min=6, max=40)] ) password = PasswordField( 'Password', validators=[DataRequired(), Length(min=6, max=40)] ) confirm = PasswordField( 'Verify password', [DataRequired(), EqualTo('password', message='Passwords must match')] ) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.user = None def validate(self): initial_validation = super(RegisterForm, self).validate() if not initial_validation: return False user = User.query.filter_by(username=self.username.data).first() if user: self.username.errors.append("Username already registered") return False user = User.query.filter_by(email=self.email.data).first() if user: self.email.errors.append("Email already registered") return False return True
{ "repo_name": "brotherjack/Rood-Kamer", "path": "roodkamer/user/forms.py", "copies": "1", "size": "1457", "license": "bsd-3-clause", "hash": -7678109102494796000, "line_mean": 32.6904761905, "line_max": 77, "alpha_frac": 0.6026080988, "autogenerated": false, "ratio": 4.3234421364985165, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 42 }
from flask_wtf import Form from wtforms import TextField, PasswordField from wtforms.validators import DataRequired from roodkamer.user.models import User class LoginForm(Form): username = TextField('Username', validators=[DataRequired()]) password = PasswordField('Password', validators=[DataRequired()]) def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.user = None def validate(self): initial_validation = super(LoginForm, self).validate() if not initial_validation: return False self.user = User.query.filter_by(username=self.username.data).first() if not self.user: self.username.errors.append('Unknown username') return False if not self.user.check_password(self.password.data): self.password.errors.append('Invalid password') return False if not self.user.active: self.username.errors.append('User not activated') return False return True
{ "repo_name": "brotherjack/Rood-Kamer", "path": "roodkamer/public/forms.py", "copies": "1", "size": "1100", "license": "bsd-3-clause", "hash": 486545473941322700, "line_mean": 31.3333333333, "line_max": 77, "alpha_frac": 0.6309090909, "autogenerated": false, "ratio": 4.471544715447155, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 33 }
from flask_wtf import Form from wtforms import TextField, StringField,SubmitField,TextAreaField,IntegerField,BooleanField,\ RadioField,SelectField,SelectMultipleField from wtforms.validators import Required from wtforms import fields from wtforms.validators import DataRequired from wtforms import validators from flask_wtf import FlaskForm as Form #from flask_wtf import Form import numpy as np import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn.metrics import mean_squared_error #from sklearn.cross_validation import train_test_split import neurolab as nl import neurolab.error as error import math import pymysql import random from pyecharts import Scatter3D from pyecharts.constants import DEFAULT_HOST from pyecharts import Bar import random import scipy.stats as sts data_num=0 data=[] samples=[] hist_selected_column="" Selected_1_default_item=0 Selected_2_default_item=0 x=[] y=[] x_linear_regression=[] y_linear_regression=[] choices=[] class NameForm(Form): name=StringField('What is your name?',validators=[Required()]) submit=SubmitField('Submit') class Get_Data_Submit(Form): db_name=StringField('数据库名',[DataRequired()],render_kw={\ "style":"width:100px"}) table_name=StringField('表名',[DataRequired()],render_kw={\ "style":"width:100px"}) submit=SubmitField('读取数据',render_kw={"style":"class:btn btn-primary"}) class Samping_Submit(Form): sampling_count=StringField('采样个数') sampling_ratio=StringField('采样比例') Repetition=BooleanField('放回采样') submit=SubmitField('采样',render_kw={"style":"class:btn btn-primary"}) class Missing_Process_Submit(Form): Missing_Process=RadioField('缺失值处理',choices=[(1,'删除缺失值'),(2,'删除包含缺失值的行'),(3,'删除所有字段都是缺失值的行'),\ (4,'删除只针对xx字段包含缺失值的行')],default=1) submit=SubmitField('处理',render_kw={"style":"class:btn btn-primary"}) class Describe_Statistics_Submit(Form): submit=SubmitField('处理',render_kw={"style":"class:btn btn-primary"}) class Pearson_cal_Submit(Form): submit_pearson=SubmitField('处理',render_kw={"style":"class:btn btn-primary"}) class Hist_Graph(Form): item=SelectField("选择列表",coerce=int,choices=[(0,'1'),(1,'2'),(2,'3'),(3,'4'),(4,'5')],default=0) submit1=SubmitField("提交") class Selected_1(Form): global Selected_1_default_item item2=SelectField("因变量",coerce=int,choices=[(0,'1'),(1,'2'),(2,'3'),(3,'4'),(4,'5')],default=Selected_1_default_item) submit2=SubmitField("提交") class Selected_2(Form): global Selected_2_default_item item3=SelectField("自变量",coerce=int,choices=[(0,'1'),(1,'2'),(2,'3'),(3,'4'),(4,'5')],default=Selected_2_default_item) submit3=SubmitField("提交") class MultipleSelect(Form): item_multiple=SelectMultipleField("自变量",coerce=int,choices=[(0,'1'),(1,'2'),(2,'3'),(3,'4'),(4,'5')],default=0) submit_multiple=SubmitField('提交') class NeuralNet(Form): layers_num=StringField('网络层数') neuron_num=StringField('隐层神经元数') error_goal=StringField('期望误差') epochs=StringField('最大迭代次数') submit_Neural=SubmitField('计算',render_kw={"style":"class:btn btn-primary"}) class RandomForest(Form): n_estimators=StringField('树的数目') max_features=StringField('最大选取特征数') max_depth=StringField('树的最大深度') min_samples_split=StringField('节点最小分裂数') min_samples_leaf=StringField('叶子节点上的最小样本数') submit_RF=SubmitField('计算',render_kw={"style":"class:btn btn-primary"})
{ "repo_name": "Data-Analysis-Team/Data-Analysis-Platform_V0.1", "path": "Fault Diagnosis/app/main/forms.py", "copies": "1", "size": "3992", "license": "apache-2.0", "hash": 4898789929813750000, "line_mean": 34.8, "line_max": 121, "alpha_frac": 0.679076087, "autogenerated": false, "ratio": 2.9252782193958664, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8883347543871498, "avg_score": 0.044201352504873545, "num_lines": 100 }
from flask_wtf import Form, widgets from wtforms import StringField, SubmitField, SelectField, FormField, FieldList, TextAreaField, IntegerField, DateField from wtforms.validators import Required, Optional from wtforms.widgets import ListWidget, TableWidget, TextInput, HiddenInput from werkzeug import MultiDict class SetattrFieldList (FieldList): def setAttributes(self, **kwargs): for key, value in kwargs.items(): setattr(self,key,value) class StoreForm(Form): storename = StringField('Store name', validators=None) class ProductForm(Form): productname = SelectField(u'Product', choices=[('a', 'A'), \ ('b', 'B'), ('c', 'C')]) brand= StringField('Brand', validators=None) stores = SetattrFieldList(FormField(StoreForm), min_entries=6) class CategoryForm(Form): categoryname = StringField('Category name', validators=[Required()]) property_id = IntegerField('Property ID', validators=[Optional()]) products = SetattrFieldList(FormField(ProductForm), min_entries=8, widget=ListWidget(html_tag=u'ul', prefix_label=True)) submit = SubmitField('Submit') class SearchForm(Form): searchname = StringField('Please type in the category name', validators=[Required()]) submit = SubmitField('Submit') class ChoiceForm(Form): results = SelectField(u'Choose one!', choices=[]) submit = SubmitField('Submit')
{ "repo_name": "doraadong/product_info", "path": "app/main/forms.py", "copies": "1", "size": "1408", "license": "mit", "hash": 3440486294300336000, "line_mean": 38.1111111111, "line_max": 124, "alpha_frac": 0.7123579545, "autogenerated": false, "ratio": 4.069364161849711, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.009140137415382542, "num_lines": 36 }
from flask_wtf import validators, Form from wtforms import StringField, PasswordField, validators, BooleanField class LoginForm(Form): username = StringField('username', [validators.DataRequired()]) password = PasswordField('password', [validators.DataRequired()]) class AddUser(Form): username = StringField('Username', [validators.DataRequired()]) email = StringField('Email', [validators.DataRequired(), validators.Email()]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password') adminuser = BooleanField('Admin?') class EditUser(Form): username = StringField('Username') email = StringField('Email', [validators.Email()]) oldpassword = PasswordField('Old Password') password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match')]) confirm = PasswordField('Repeat Password')
{ "repo_name": "number13dev/mincloud", "path": "app/forms.py", "copies": "1", "size": "1060", "license": "mit", "hash": 2860008446719192000, "line_mean": 36.8571428571, "line_max": 81, "alpha_frac": 0.708490566, "autogenerated": false, "ratio": 4.711111111111111, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00043554006968641115, "num_lines": 28 }
from flask_yoloapi import endpoint, parameter from findex_gui.web import app, db from findex_gui.orm.models import MetaMovies from findex_gui.controllers.meta.controller import MetaPopcornController @app.route("/api/v2/meta/popcorn/actor/search/<string:key>", methods=["GET"]) @endpoint.api() def api_meta_popcorn_cast_search(key): results = MetaPopcornController.get_actors(search=key) return { "items": [{"actor": z, "id": z} for z in results], "total_count": len(results), "incomplete_results": False } @app.route("/api/v2/meta/popcorn/director/search/<string:key>", methods=["GET"]) @endpoint.api() def api_meta_popcorn_director_search(key): results = MetaPopcornController.get_director(search=key) return { "items": [{"director": z, "id": z} for z in results], "total_count": len(results), "incomplete_results": False } @app.route("/api/v2/meta/popcorn/details/<int:meta_movie_id>", methods=["GET"]) @endpoint.api() def api_meta_popcorn_get_details(meta_movie_id): meta_movie = db.session.query(MetaMovies).filter(MetaMovies.id == meta_movie_id).first() if not meta_movie: raise Exception("meta_movie_id by that id not found") local_files = MetaPopcornController.get_details(meta_movie_id) return { "local_files": local_files, "meta_movie": meta_movie }
{ "repo_name": "skftn/findex-gui", "path": "findex_gui/controllers/meta/api.py", "copies": "1", "size": "1381", "license": "mit", "hash": 4164947140819948000, "line_mean": 34.4102564103, "line_max": 92, "alpha_frac": 0.6770456191, "autogenerated": false, "ratio": 3.2041763341067284, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9378260624080526, "avg_score": 0.0005922658252407357, "num_lines": 39 }
from flask_yoloapi import endpoint, parameter from findex_gui.web import app from findex_gui.bin import validators from findex_gui.controllers.user.decorators import admin_required from findex_gui.controllers.amqp.amqp import MqController from findex_gui.controllers.amqp.amqp import AmqpConnectionController @app.route("/api/v2/admin/mq/add", methods=["POST"]) @admin_required @endpoint.api( parameter("name", type=str, required=True), parameter("broker", type=str, required=True, default="rabbitmq", validator=validators.amqp_broker), parameter("host", type=str, required=True), parameter("port", type=int, required=True), parameter("vhost", type=str, required=True), parameter("queue", type=str, required=True), parameter("ssl", type=bool, required=False, default=False), parameter("auth_user", type=str, required=True), parameter("auth_pass", type=str, required=True), ) def api_admin_mq_add(name, broker, host, port, vhost, queue, ssl, auth_user, auth_pass): """ Adds a MQ server, for now, only rabbitmq is supported :param name: name of the 'mq' broker :param broker: broker type (rabbitmq, ...) :param host: 'mq' server address :param port: 'mq' server port :param vhost: 'mq' vhost :param queue: 'mq' queue name :param ssl: connect via SSL? :param auth_user: 'mq' user :param auth_pass: 'mq' pwd :return: mq """ MqController.add( name=name, host=host, port=port, vhost=vhost, queue=queue, ssl=ssl, auth_user=auth_user, auth_pass=auth_pass) return True @app.route("/api/v2/admin/mq/get", methods=["GET"]) @admin_required @endpoint.api( parameter("uid", type=int, required=False), parameter("name", type=str, required=False), parameter("host", type=str, required=False), parameter("port", type=int, required=False), parameter("limit", type=int, default=10), parameter("offset", type=int, default=0), parameter("search", type=str, required=False, default=None) ) def api_admin_mq_get(uid, name, host, port, limit, offset, search): """ Gets a MQ broker :param uid: db row id :param name: name of the 'mq' broker :param host: 'mq' server address :param port: 'mq' server port :param limit: :param offset: :return: mq """ args = { "limit": limit, "offset": offset } records = MqController.get(uid=uid, name=name, host=host, port=port, limit=args['limit'], offset=args['offset']) # bleh args.pop('limit') args.pop('offset') total = MqController.get(uid=uid, name=name, host=host, port=port) return { "records": records, "queryRecordCount": len(total), "totalRecordCount": len(records) } @app.route("/api/v2/admin/amqp/test", methods=["POST"]) @admin_required @endpoint.api( parameter("broker", type=str, required=True, default="rabbitmq", validator=validators.amqp_broker), parameter("host", type=str, required=True), parameter("port", type=int, required=True), parameter("vhost", type=str, required=True), parameter("queue", type=str, required=True), parameter("ssl", type=bool, required=False, default=False), parameter("auth_user", type=str, required=True), parameter("auth_pass", type=str, required=True) ) def api_admin_mq_test(broker, host, port, vhost, queue, ssl, auth_user, auth_pass): """ Test if a MQ broker can be reached. :param host: 'mq' server address :param port: 'mq' server port :param broker: rabbitmq or another type of message broker :param auth_user: 'mq' user :param auth_pass: 'mq' pwd :param vhost: 'mq' vhost :return: """ if broker == "rabbitmq": return AmqpConnectionController.test_amqp(auth_user, auth_pass, host, vhost, queue, port)
{ "repo_name": "skftn/findex-gui", "path": "findex_gui/controllers/amqp/api.py", "copies": "1", "size": "3847", "license": "mit", "hash": 689819751984978700, "line_mean": 33.9727272727, "line_max": 103, "alpha_frac": 0.6592149727, "autogenerated": false, "ratio": 3.404424778761062, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4563639751461062, "avg_score": null, "num_lines": null }
from FlatCAMGUI import FlatCAMActivityView from PyQt4 import QtCore import weakref # import logging # log = logging.getLogger('base2') # #log.setLevel(logging.DEBUG) # log.setLevel(logging.WARNING) # #log.setLevel(logging.INFO) # formatter = logging.Formatter('[%(levelname)s] %(message)s') # handler = logging.StreamHandler() # handler.setFormatter(formatter) # log.addHandler(handler) class FCProcess(object): app = None def __init__(self, descr): self.callbacks = { "done": [] } self.descr = descr self.status = "Active" def __del__(self): self.done() def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is not None: self.app.log.error("Abnormal termination of process!") self.app.log.error(exc_type) self.app.log.error(exc_val) self.app.log.error(exc_tb) self.done() def done(self): for fcn in self.callbacks["done"]: fcn(self) def connect(self, callback, event="done"): if callback not in self.callbacks[event]: self.callbacks[event].append(callback) def disconnect(self, callback, event="done"): try: self.callbacks[event].remove(callback) except ValueError: pass def set_status(self, status_string): self.status = status_string def status_msg(self): return self.descr class FCProcessContainer(object): """ This is the process container, or controller (as in MVC) of the Process/Activity tracking. FCProcessContainer keeps weak references to the FCProcess'es such that their __del__ method is called when the user looses track of their reference. """ app = None def __init__(self): self.procs = [] def add(self, proc): self.procs.append(weakref.ref(proc)) def new(self, descr): proc = FCProcess(descr) proc.connect(self.on_done, event="done") self.add(proc) self.on_change(proc) return proc def on_change(self, proc): pass def on_done(self, proc): self.remove(proc) def remove(self, proc): to_be_removed = [] for pref in self.procs: if pref() == proc or pref() is None: to_be_removed.append(pref) for pref in to_be_removed: self.procs.remove(pref) class FCVisibleProcessContainer(QtCore.QObject, FCProcessContainer): something_changed = QtCore.pyqtSignal() def __init__(self, view): assert isinstance(view, FlatCAMActivityView), \ "Expected a FlatCAMActivityView, got %s" % type(view) FCProcessContainer.__init__(self) QtCore.QObject.__init__(self) self.view = view self.something_changed.connect(self.update_view) def on_done(self, proc): self.app.log.debug("FCVisibleProcessContainer.on_done()") super(FCVisibleProcessContainer, self).on_done(proc) self.something_changed.emit() def on_change(self, proc): self.app.log.debug("FCVisibleProcessContainer.on_change()") super(FCVisibleProcessContainer, self).on_change(proc) self.something_changed.emit() def update_view(self): if len(self.procs) == 0: self.view.set_idle() elif len(self.procs) == 1: self.view.set_busy(self.procs[0]().status_msg()) else: self.view.set_busy("%d processes running." % len(self.procs))
{ "repo_name": "Denvi/FlatCAM", "path": "FlatCAMProcess.py", "copies": "1", "size": "3584", "license": "mit", "hash": -1686428012294067500, "line_mean": 23.222972973, "line_max": 73, "alpha_frac": 0.6046316964, "autogenerated": false, "ratio": 3.8454935622317596, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.495012525863176, "avg_score": null, "num_lines": null }
from .flatfile import FlatFileDB, Query from kool.utils import camel_to_snake, now class Model(object): db = None # database def __init__(self, * args, ** kwargs): """ Model provides save, delete, purge operations to every class that inherits it. """ # Get class name, so as to set the table name cls_name = self.__class__.__name__ table_name = camel_to_snake(cls_name) self._table = Model.db.create_table(name=table_name) self.last_modified = None self.date_created = None self._id = None def save(self, * args, ** kwargs): """ Saves current object to database. It also updates the `last_modified` and `date_created` fields. """ data = {} self.last_modified = '{}'.format(now()) if not self.date_created: self.date_created = '{}'.format(now()) # Get objects dict data = self.props() if data: # Creates a new instance self._id = self._table.insert(data) return self._id def update(self, * args, ** kwargs): """ Update method provides a way of updating the values of an object. """ data = {} self.last_modified = '{}'.format(now()) if not self.date_created: self.date_created = '{}'.format(now()) # Get objects dict data = self.props() # Fetch exising object obj = self._table.get(rid=self._id) if self._id else None if obj and data: # Updates an existing instance ids = self._table.update(data, rids=[self._id]) self._id = ids[0] return self._id def delete(self, cond=None, rids=None, * args): rids = [] rids = ([self._id,] if self._id else []) or rids or list(args) if rids: self._table.remove(cond=cond, rids=rids) else: raise ValueError('Record must be saved to delete') def purge(self, confirm=False): """ Truncates the table. Operation is irreversible. Keyword Arguments: confirm {bool} -- user confirmation (default: {False}) """ if confirm: self._table.purge() else: raise ValueError('Confirm argument has to be set true') def props(self): """Converts object to dictionary""" return dict( (key, value) for (key, value) in self.__dict__.items() if not (key.startswith('_') or key.startswith('__'))) def __getattr__(self, name): """ Forward all unknown attribute calls to the underlying standard table. """ return getattr(self._table, name) # Instantiate database Model.db = FlatFileDB() def where(key): return Query()[key] def table(cls): """Returns a table object given a class""" cls_name = cls.__name__ table_name = camel_to_snake(cls_name) return Model().db.table(table_name)
{ "repo_name": "edasi/kool", "path": "kool/db/models.py", "copies": "1", "size": "3094", "license": "mit", "hash": -8561684113111442000, "line_mean": 27.1272727273, "line_max": 77, "alpha_frac": 0.5400775695, "autogenerated": false, "ratio": 4.14190093708166, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.518197850658166, "avg_score": null, "num_lines": null }
from flat_game import carmunk import numpy as np import random import csv from nn import neural_net, LossHistory import os.path import timeit NUM_INPUT = 3 GAMMA = 0.9 # Forgetting. TUNING = False # If False, just use arbitrary, pre-selected params. def train_net(model, params): filename = params_to_filename(params) observe = 1000 # Number of frames to observe before training. epsilon = 1 train_frames = 100000 # Number of frames to play. batchSize = params['batchSize'] buffer = params['buffer'] # Just stuff used below. max_car_distance = 0 car_distance = 0 t = 0 data_collect = [] replay = [] # stores tuples of (S, A, R, S'). loss_log = [] # Create a new game instance. game_state = carmunk.GameState() # Get initial state by doing nothing and getting the state. _, state = game_state.frame_step((2)) # Let's time it. start_time = timeit.default_timer() # Run the frames. while t < train_frames: t += 1 car_distance += 1 # Choose an action. if random.random() < epsilon or t < observe: action = np.random.randint(0, 3) # random else: # Get Q values for each action. qval = model.predict(state, batch_size=1) action = (np.argmax(qval)) # best # Take action, observe new state and get our treat. reward, new_state = game_state.frame_step(action) # Experience replay storage. replay.append((state, action, reward, new_state)) # If we're done observing, start training. if t > observe: # If we've stored enough in our buffer, pop the oldest. if len(replay) > buffer: replay.pop(0) # Randomly sample our experience replay memory minibatch = random.sample(replay, batchSize) # Get training values. X_train, y_train = process_minibatch2(minibatch, model) # Train the model on this batch. history = LossHistory() model.fit( X_train, y_train, batch_size=batchSize, nb_epoch=1, verbose=0, callbacks=[history] ) loss_log.append(history.losses) # Update the starting state with S'. state = new_state # Decrement epsilon over time. if epsilon > 0.1 and t > observe: epsilon -= (1.0/train_frames) # We died, so update stuff. if reward == -500: # Log the car's distance at this T. data_collect.append([t, car_distance]) # Update max. if car_distance > max_car_distance: max_car_distance = car_distance # Time it. tot_time = timeit.default_timer() - start_time fps = car_distance / tot_time # Output some stuff so we can watch. print("Max: %d at %d\tepsilon %f\t(%d)\t%f fps" % (max_car_distance, t, epsilon, car_distance, fps)) # Reset. car_distance = 0 start_time = timeit.default_timer() # Save the model every 25,000 frames. if t % 25000 == 0: model.save_weights('saved-models/' + filename + '-' + str(t) + '.h5', overwrite=True) print("Saving model %s - %d" % (filename, t)) # Log results after we're done all frames. log_results(filename, data_collect, loss_log) def log_results(filename, data_collect, loss_log): # Save the results to a file so we can graph it later. with open('results/sonar-frames/learn_data-' + filename + '.csv', 'w') as data_dump: wr = csv.writer(data_dump) wr.writerows(data_collect) with open('results/sonar-frames/loss_data-' + filename + '.csv', 'w') as lf: wr = csv.writer(lf) for loss_item in loss_log: wr.writerow(loss_item) def process_minibatch2(minibatch, model): # by Microos, improve this batch processing function # and gain 50~60x faster speed (tested on GTX 1080) # significantly increase the training FPS # instead of feeding data to the model one by one, # feed the whole batch is much more efficient mb_len = len(minibatch) old_states = np.zeros(shape=(mb_len, 3)) actions = np.zeros(shape=(mb_len,)) rewards = np.zeros(shape=(mb_len,)) new_states = np.zeros(shape=(mb_len, 3)) for i, m in enumerate(minibatch): old_state_m, action_m, reward_m, new_state_m = m old_states[i, :] = old_state_m[...] actions[i] = action_m rewards[i] = reward_m new_states[i, :] = new_state_m[...] old_qvals = model.predict(old_states, batch_size=mb_len) new_qvals = model.predict(new_states, batch_size=mb_len) maxQs = np.max(new_qvals, axis=1) y = old_qvals non_term_inds = np.where(rewards != -500)[0] term_inds = np.where(rewards == -500)[0] y[non_term_inds, actions[non_term_inds].astype(int)] = rewards[non_term_inds] + (GAMMA * maxQs[non_term_inds]) y[term_inds, actions[term_inds].astype(int)] = rewards[term_inds] X_train = old_states y_train = y return X_train, y_train def process_minibatch(minibatch, model): """This does the heavy lifting, aka, the training. It's super jacked.""" X_train = [] y_train = [] # Loop through our batch and create arrays for X and y # so that we can fit our model at every step. for memory in minibatch: # Get stored values. old_state_m, action_m, reward_m, new_state_m = memory # Get prediction on old state. old_qval = model.predict(old_state_m, batch_size=1) # Get prediction on new state. newQ = model.predict(new_state_m, batch_size=1) # Get our predicted best move. maxQ = np.max(newQ) y = np.zeros((1, 3)) y[:] = old_qval[:] # Check for terminal state. if reward_m != -500: # non-terminal state update = (reward_m + (GAMMA * maxQ)) else: # terminal state update = reward_m # Update the value for the action we took. y[0][action_m] = update X_train.append(old_state_m.reshape(NUM_INPUT,)) y_train.append(y.reshape(3,)) X_train = np.array(X_train) y_train = np.array(y_train) return X_train, y_train def params_to_filename(params): return str(params['nn'][0]) + '-' + str(params['nn'][1]) + '-' + \ str(params['batchSize']) + '-' + str(params['buffer']) def launch_learn(params): filename = params_to_filename(params) print("Trying %s" % filename) # Make sure we haven't run this one. if not os.path.isfile('results/sonar-frames/loss_data-' + filename + '.csv'): # Create file so we don't double test when we run multiple # instances of the script at the same time. open('results/sonar-frames/loss_data-' + filename + '.csv', 'a').close() print("Starting test.") # Train. model = neural_net(NUM_INPUT, params['nn']) train_net(model, params) else: print("Already tested.") if __name__ == "__main__": if TUNING: param_list = [] nn_params = [[164, 150], [256, 256], [512, 512], [1000, 1000]] batchSizes = [40, 100, 400] buffers = [10000, 50000] for nn_param in nn_params: for batchSize in batchSizes: for buffer in buffers: params = { "batchSize": batchSize, "buffer": buffer, "nn": nn_param } param_list.append(params) for param_set in param_list: launch_learn(param_set) else: nn_param = [128, 128] params = { "batchSize": 64, "buffer": 50000, "nn": nn_param } model = neural_net(NUM_INPUT, nn_param) train_net(model, params)
{ "repo_name": "harvitronix/reinforcement-learning-car", "path": "learning.py", "copies": "1", "size": "8116", "license": "mit", "hash": -5473993308338742000, "line_mean": 31.0790513834, "line_max": 114, "alpha_frac": 0.5620995564, "autogenerated": false, "ratio": 3.595923792645104, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4658023349045104, "avg_score": null, "num_lines": null }
from flatland import Array, String from tests.markup._util import desired_output def scalar_schema(): schema = String.named(u'scalar') return schema(u'abc') def multivalue_schema(): schema = Array.named(u'multi').of(String) return schema([u'abc', u'xyz']) @desired_output('xhtml', scalar_schema) def select(): """ <select name="scalar"> <option value="abc" selected="selected"></option> <option value="def">DEF</option> <option selected="selected">abc</option> <option value="abc" selected="selected">abc</option> </select> """ @select.genshi def test_select_genshi(): """ <select form:bind="form"> <option value="abc" form:bind="form"></option> <option value="def">DEF</option> <option>abc</option> <option value="abc">abc</option> </select> """ @select.markup def test_select_markup(gen, el): output = [] output += [gen.select.open(el)] output += [gen.option(el, value=u'abc')] output += [gen.option(el, value=u'def', contents=u'DEF')] output += [gen.option(el, contents=u'abc')] output += [gen.option(el, value=u'abc', contents=u'abc')] output += [gen.select.close()] return u'\n'.join(output) @desired_output('xhtml', multivalue_schema) def multiselect(): """ <select name="multi" multiple="multiple"> <option value="abc" selected="selected"></option> <option value="def">DEF</option> <option selected="selected">xyz</option> </select> """ @multiselect.genshi def test_multiselect_genshi(): """ <select name="multi" form:bind="form" multiple="multiple"> <option value="abc"></option> <option value="def">DEF</option> <option>xyz</option> </select> """ @multiselect.markup def test_multiselect_markup(gen, el): output = [] output += [gen.select.open(el, multiple=u'multiple')] output += [gen.option(el, value=u'abc')] output += [gen.option(el, value=u'def', contents=u'DEF')] output += [gen.option(el, contents=u'xyz')] output += [gen.select.close()] return u'\n'.join(output)
{ "repo_name": "wheeler-microfluidics/flatland-fork", "path": "tests/markup/test_tag_rendering.py", "copies": "2", "size": "1997", "license": "mit", "hash": -5448882428303498000, "line_mean": 23.3536585366, "line_max": 61, "alpha_frac": 0.6534802203, "autogenerated": false, "ratio": 3.1598101265822787, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9813290346882279, "avg_score": 0, "num_lines": 82 }
from flatland import Array, String from tests._util import fails from tests.markup._util import desired_output def scalar_schema(): schema = String.named(u'scalar') return schema(u'abc') def multivalue_schema(): schema = Array.named(u'multi').of(String) return schema([u'abc', u'xyz']) @desired_output('xhtml', scalar_schema) def select(): """ <select name="scalar"> <option value="abc" selected="selected"></option> <option value="def">DEF</option> <option selected="selected">abc</option> <option value="abc" selected="selected">abc</option> </select> """ @select.genshi_06 def test_select_genshi_06(): """ <select form:bind="form"> <option value="abc" form:bind="form"></option> <option value="def">DEF</option> <option>abc</option> <option value="abc">abc</option> </select> """ @select.genshi_05 def test_select_genshi_05(): """ <select form:bind="form"> <option value="abc"></option> <option value="def">DEF</option> <option>abc</option> <option value="abc">abc</option> </select> """ @select.markup def test_select_markup(gen, el): output = [] output += [gen.select.open(el)] output += [gen.option(el, value=u'abc')] output += [gen.option(el, value=u'def', contents=u'DEF')] output += [gen.option(el, contents=u'abc')] output += [gen.option(el, value=u'abc', contents=u'abc')] output += [gen.select.close()] return u'\n'.join(output) @desired_output('xhtml', multivalue_schema) def multiselect(): """ <select name="multi" multiple="multiple"> <option value="abc" selected="selected"></option> <option value="def">DEF</option> <option selected="selected">xyz</option> </select> """ @multiselect.genshi_06 def test_multiselect_genshi_06(): """ <select name="multi" form:bind="form" multiple="multiple"> <option value="abc"></option> <option value="def">DEF</option> <option>xyz</option> </select> """ @fails("No multiselect on genshi 05") @multiselect.genshi_05 def test_multiselect_genshi_05(): """ <select form:bind="${form.bind}" multiple="multiple"> <option value="abc"></option> <option value="def">DEF</option> <option>xyz</option> </select> """ @multiselect.markup def test_multiselect_markup(gen, el): output = [] output += [gen.select.open(el, multiple=u'multiple')] output += [gen.option(el, value=u'abc')] output += [gen.option(el, value=u'def', contents=u'DEF')] output += [gen.option(el, contents=u'xyz')] output += [gen.select.close()] return u'\n'.join(output)
{ "repo_name": "dag/flatland", "path": "tests/markup/test_tag_rendering.py", "copies": "2", "size": "2515", "license": "mit", "hash": -908015087005194900, "line_mean": 23.1826923077, "line_max": 61, "alpha_frac": 0.6568588469, "autogenerated": false, "ratio": 3.1087762669962915, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47656351138962916, "avg_score": null, "num_lines": null }
from flatland import DateYYYYMMDD, Dict, Enum, Form, Integer, JoinedString, List, String from flatland.validation import Converted, Present, ValueGreaterThan class ContactForm(Form): name = String.validated_by(Present()) addresses = List.of( Dict.of( String.named('street'), String.named('city'), String.named('country'), List.named('phone_numbers').of( Dict.of( String.named('label'), String.named('number') ) ).using(default=1) ) ).using(default=1) class PhoneNumber(Form): label = String number = String PhoneNumberDict = Dict.of( String.named('label'), String.named('number') ) class Address(Form): street = String city = String country = String phone_numbers = List.of(PhoneNumber).using(default=1) AddressDict = Dict.of( String.named('street'), String.named('city'), String.named('country'), List.named('phone_numbers').of(PhoneNumber) ) class ContactForm(Form): name = String.validated_by(Present()) addresses = Address.using(default=1) GuardianContentSearch = Dict.of( String.named('q').using(label='Search' ).validated_by(Converted()), String.named('tag').using(label='Tag filter', optional=True ).validated_by(Converted()), String.named('section').using(label='Section filter', optional=True ).validated_by(Converted()), DateYYYYMMDD.named('from-date').using(label='From Date filter', optional=True ).validated_by(Converted()), DateYYYYMMDD.named('to-date').using(label='To Date filter', optional=True ).validated_by(Converted()), Enum.named('order-by').valued(['newest', 'oldest', 'relevance'] ).using(default='newest', optional=True), Integer.named('page').using(label='Page Index', default=1 ).validated_by(Converted(), ValueGreaterThan(0)), Integer.named('page-size').using(label='Page Size', default=10 ).validated_by(Converted(), ValueGreaterThan(0)), Enum.named('format').valued(['json', 'xml']).using(default='json' ).validated_by(Converted()), JoinedString.named('show-fields').using(label='Show fields', default=['all'] ).validated_by(Converted()), JoinedString.named('show-tags').using(label='Show tabs', default=['all'] ).validated_by(Converted()), JoinedString.named('show-refinements').using(label='Show refinements', default=['all'] ).validated_by(Converted()), Integer.named('refinements-size').using(label='Refinement size', default=10 ).validated_by(Converted(), ValueGreaterThan(0)), )
{ "repo_name": "scooterXL/flatland-europython-2010", "path": "examples/forms.py", "copies": "2", "size": "2789", "license": "mit", "hash": -578652880189841400, "line_mean": 35.2207792208, "line_max": 90, "alpha_frac": 0.6138400861, "autogenerated": false, "ratio": 3.917134831460674, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5530974917560675, "avg_score": null, "num_lines": null }
from flatland import Dict, Form, List, Boolean, String from flatland.validation import LengthBetween, Present, ValuesEqual class RegistrationForm(Form): username = String.using( label='Username', validators=[Present(), LengthBetween(4,25)] ) email = String.using( label='Email Address', optional=True, validators=[LengthBetween(6, 35)] ) password = String.using( label='New Password', validators=[Present()] ) confirm = String.using( label='Repeat Password', validators=[Present(), ValuesEqual('../confirm', '../password')] ) accept_tos = Boolean.using( label='I accept the TOS', validators=[Present()] ) class PasswordCompareForm(Form): password = String.using( label='New Password', validators=[Present(), LengthBetween(5,25)] ) confirm = String.using( label='Repeat Password', validators=[Present()] ) validators = [ ValuesEqual('password', 'confirm') ] class PasswordCompareElement(Form): password = String.using( label='New Password', validators=[Present(), LengthBetween(5, 25)] ) confirm = String.using( label='Repeat Password', validators=[Present(), ValuesEqual('../confirm', '../password')] ) class ContactForm(Form): name = String.validated_by(Present()) addresses = List.of( Dict.of( String.named('street'), String.named('city'), String.named('country'), List.named('phone_numbers').of( Dict.of( String.named('label'), String.named('number') ) ).using(default=1) ) ).using(default=1) class PhoneNumber(Form): label = String number = String class Address(Form): street = String city = String country = String phone_numbers = List.of(PhoneNumber).using(default=1) class ContactForm(Form): name = String.validated_by(Present()) addresses = List.of(Address.using(default=1))
{ "repo_name": "scottynomad/flatland-europython-2010", "path": "examples/flaskr_flatland/flaskr_flatland/forms.py", "copies": "2", "size": "2169", "license": "mit", "hash": -8796907859393947000, "line_mean": 23.9310344828, "line_max": 67, "alpha_frac": 0.5726141079, "autogenerated": false, "ratio": 4.364185110663984, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5936799218563984, "avg_score": null, "num_lines": null }
from flatland import Form, Float from flatland.validation import ValueAtLeast from pygtkhelpers.ui.form_view_dialog import create_form_view from pygtkhelpers.ui.views.select import ListSelect import gtk import pandas as pd import pygtkhelpers.ui.extra_widgets # Include widget for `Float` form fields def get_channel_sweep_parameters(voltage=100, frequency=10e3, channels=None, parent=None): ''' Show dialog to select parameters for a sweep across a selected set of channels. Parameters ---------- voltage : int Default actuation voltage. frequency : int Default actuation frequency. channels : pandas.Series Default channels selection, encoded as boolean array indexed by channel number, where `True` values indicate selected channel(s). parent : gtk.Window If not ``None``, parent window for dialog. For example, display dialog at position relative to the parent window. Returns ------- dict Values collected from widgets with the following keys: `'frequency'`, `voltage'`, and (optionally) `'channels'`. ''' # Create a form view containing widgets to set the waveform attributes # (i.e., voltage and frequency). form = Form.of(Float.named('voltage') .using(default=voltage, validators=[ValueAtLeast(minimum=0)]), Float.named('frequency') .using(default=frequency, validators=[ValueAtLeast(minimum=1)])) form_view = create_form_view(form) # If default channel selection was provided, create a treeview with one row # per channel, and a checkbox in each row to mark the selection status of # the corresponding channel. if channels is not None: df_channel_select = pd.DataFrame(channels.index, columns=['channel']) df_channel_select.insert(1, 'select', channels.values) view_channels = ListSelect(df_channel_select) # Create dialog window. dialog = gtk.Dialog(title='Channel sweep parameters', buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK, gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)) # Add waveform widgets to dialog window. frame_waveform = gtk.Frame('Waveform properties') frame_waveform.add(form_view.widget) dialog.vbox.pack_start(child=frame_waveform, expand=False, fill=False, padding=5) # Add channel selection widgets to dialog window. if channels is not None: frame_channels = gtk.Frame('Select channels to sweep') frame_channels.add(view_channels.widget) dialog.vbox.pack_start(child=frame_channels, expand=True, fill=True, padding=5) # Mark all widgets as visible. dialog.vbox.show_all() if parent is not None: dialog.window.set_transient_for(parent) response = dialog.run() dialog.destroy() if response != gtk.RESPONSE_OK: raise RuntimeError('Dialog cancelled.') # Collection waveform and channel selection values from dialog. form_values = {name: f.element.value for name, f in form_view.form.fields.items()} if channels is not None: form_values['channels'] = (df_channel_select .loc[df_channel_select['select'], 'channel'].values) return form_values
{ "repo_name": "wheeler-microfluidics/microdrop", "path": "microdrop/gui/channel_sweep.py", "copies": "1", "size": "3518", "license": "bsd-3-clause", "hash": -7354033135315151000, "line_mean": 37.2391304348, "line_max": 79, "alpha_frac": 0.6293348493, "autogenerated": false, "ratio": 4.447534766118837, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5576869615418837, "avg_score": null, "num_lines": null }
from flatland import Form, String from flatland.ext.creditcard import CreditCardNumber, VISA, MASTERCARD def test_simple(): class Schema(Form): num = CreditCardNumber.named('num') data = Schema({}) assert not data.validate() assert data.el('num').errors e1 = list(data.el('num').errors) data = Schema({'num': 'asdf'}) assert not data.validate() assert data['num'].errors assert data['num'].errors != e1 e2 = list(data['num'].errors) data = Schema({'num': '1234'}) assert not data.validate() assert data['num'].errors assert data['num'].errors == e2 e3 = list(data['num'].errors) data = Schema({'num': '4100000000000009'}) assert not data.validate() assert data['num'].errors assert data['num'].errors != e3 e4 = list(data['num'].errors) data = Schema({'num': '4100000000000001'}) assert data.validate() assert isinstance(data['num'].value, long) assert data['num'].u == '4100-0000-0000-0001' def test_subclass(): class MyCreditCard(CreditCardNumber): class Present(CreditCardNumber.Present): missing = u'Yo! You need a %(label)s!' class Schema(Form): num = MyCreditCard.using(label='Visa/MC Number', accepted=(VISA, MASTERCARD)) name = String.using(optional=True) data = Schema.from_flat({}) assert not data.validate() assert data['num'].errors err = data['num'].errors[0] assert err.startswith('Yo!') assert 'Visa/MC Number' in err
{ "repo_name": "wheeler-microfluidics/flatland-fork", "path": "tests/test_richtypes.py", "copies": "4", "size": "1554", "license": "mit", "hash": -3830483522696857000, "line_mean": 25.7931034483, "line_max": 70, "alpha_frac": 0.6151866152, "autogenerated": false, "ratio": 3.7177033492822966, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0005387931034482759, "num_lines": 58 }
from flatland import ( Array, Dict, Integer, List, String, ) from flatland.validation import ( HasAtLeast, HasAtMost, HasBetween, NotDuplicated, ) from tests._util import assert_raises def valid_of_children(element): return [e.valid for e in element.children] def validated_string(*validators): return List.named('test').of(String.using(name=u'foo', validators=validators)) def test_no_duplicates_message(): schema = validated_string(NotDuplicated()) el = schema([u'foo', u'foo']) assert not el.validate() assert el[1].errors == [u'foo may not be repeated within test.'] def test_no_duplicates_context(): el = String(validators=[NotDuplicated()]) assert_raises(TypeError, el.validate) def test_no_duplicates_comparator(): comparator = lambda a, b: True schema = validated_string(NotDuplicated(comparator=comparator)) el = schema([u'a', u'b']) assert not el.validate() def _test_no_duplicates(schema, a, b): label = schema.label el = schema([a, b]) assert el.validate() assert valid_of_children(el) == [True, True] el = schema([a, b, a]) assert not el.validate() assert valid_of_children(el) == [True, True, False] assert el[2].errors == [u'%s %s' % (label, 3)] el = schema([a, b, a, b]) assert not el.validate() assert valid_of_children(el) == [True, True, False, False] assert el[2].errors == [u'%s %s' % (label, 3)] assert el[3].errors == [u'%s %s' % (label, 4)] el = schema([a, a, a, a]) assert not el.validate() assert valid_of_children(el) == [True, False, False, False] assert el[1].errors == [u'%s %s' % (label, 2)] assert el[2].errors == [u'%s %s' % (label, 3)] assert el[3].errors == [u'%s %s' % (label, 4)] def test_no_duplicates_list_scalar(): nd = NotDuplicated(failure=u'%(container_label)s %(position)s') schema = validated_string(nd) _test_no_duplicates(schema, u'foo', u'bar') def test_no_duplicates_array(): nd = NotDuplicated(failure=u'%(container_label)s %(position)s') schema = validated_string(nd) _test_no_duplicates(schema, u'foo', u'bar') def test_no_duplicates_list_anon_dict(): nd = NotDuplicated(failure=u'%(container_label)s %(position)s') schema = (List.named('test'). of(Dict.of(Integer.named('x'), Integer.named('y')). using(validators=[nd]))) _test_no_duplicates(schema, {'x': 1, 'y': 2}, {'x': 3, 'y': 4}) def test_no_duplicates_list_dict(): nd = NotDuplicated(failure=u'%(container_label)s %(position)s') schema = (List.named('test'). of(Dict.named('xyz'). of(Integer.named('x'), Integer.named('y')). using(validators=[nd]))) _test_no_duplicates(schema, {'x': 1, 'y': 2}, {'x': 3, 'y': 4}) def validated_list(*validators): return List.named('outer').of(String.named('inner')).using( validators=validators) def test_has_at_least_none(): schema = validated_list(HasAtLeast(minimum=0)) el = schema(['a']) assert el.validate() el = schema() assert el.validate() def test_has_at_least_one(): schema = validated_list(HasAtLeast()) el = schema() assert not el.validate() assert el.errors == [u'outer must contain at least one inner'] el = schema(['a']) assert el.validate() def test_has_at_least_two(): schema = validated_list(HasAtLeast(minimum=2)) el = schema(['a']) assert not el.validate() assert el.errors == [u'outer must contain at least 2 inners'] el = schema(['a', 'b']) assert el.validate() def test_has_at_most_none(): schema = validated_list(HasAtMost(maximum=0)) el = schema(['a']) assert not el.validate() assert el.errors == [u'outer must contain at most 0 inners'] el = schema() assert el.validate() def test_has_at_most_one(): schema = validated_list(HasAtMost(maximum=1)) el = schema() assert el.validate() el = schema(['a']) assert el.validate() el = schema(['a', 'b']) assert not el.validate() assert el.errors == [u'outer must contain at most one inner'] def test_has_at_most_two(): schema = validated_list(HasAtMost(maximum=2)) el = schema() assert el.validate() el = schema(['a', 'b']) assert el.validate() el = schema(['a', 'b', 'c']) assert not el.validate() assert el.errors == [u'outer must contain at most 2 inners'] def test_has_between_none(): schema = validated_list(HasBetween(minimum=0, maximum=0)) el = schema() assert el.validate() el = schema(['a']) assert not el.validate() assert el.errors == [u'outer must contain exactly 0 inners'] def test_has_between_one(): schema = validated_list(HasBetween(minimum=1, maximum=1)) el = schema() assert not el.validate() assert el.errors == [u'outer must contain exactly one inner'] el = schema(['a']) assert el.validate() el = schema(['a', 'b']) assert not el.validate() assert el.errors == [u'outer must contain exactly one inner'] def test_has_between_two(): schema = validated_list(HasBetween(minimum=2, maximum=2)) el = schema() assert not el.validate() assert el.errors == [u'outer must contain exactly 2 inners'] el = schema(['b']) assert not el.validate() assert el.errors == [u'outer must contain exactly 2 inners'] el = schema(['a', 'b']) assert el.validate() def test_has_between_none_and_one(): schema = validated_list(HasBetween(minimum=0, maximum=1)) el = schema() assert el.validate() el = schema(['b']) assert el.validate() el = schema(['a', 'b']) assert not el.validate() assert el.errors == [u'outer must contain at least 0 and at most 1 inner'] def test_has_between_none_and_two(): schema = validated_list(HasBetween(minimum=0, maximum=2)) el = schema() assert el.validate() el = schema(['a', 'b']) assert el.validate() el = schema(['a', 'b', 'c']) assert not el.validate() assert el.errors == [u'outer must contain at least 0 and at most 2 inners'] def test_has_between_one_and_two(): schema = validated_list(HasBetween(minimum=1, maximum=2)) el = schema() assert not el.validate() assert el.errors == [u'outer must contain at least 1 and at most 2 inners'] el = schema(['b']) assert el.validate() el = schema(['a', 'b']) assert el.validate() el = schema(['a', 'b', 'c']) assert not el.validate() assert el.errors == [u'outer must contain at least 1 and at most 2 inners']
{ "repo_name": "jek/flatland", "path": "tests/validation/test_containers.py", "copies": "4", "size": "6734", "license": "mit", "hash": -5173267988403088000, "line_mean": 24.8007662835, "line_max": 79, "alpha_frac": 0.6040986041, "autogenerated": false, "ratio": 3.375438596491228, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5979537200591228, "avg_score": null, "num_lines": null }
from flatland import ( Array, Dict, Integer, List, String, ) from flatland.validation import ( HasAtLeast, HasAtMost, HasBetween, NotDuplicated, ) import pytest def valid_of_children(element): return [e.valid for e in element.children] def validated_string(*validators): return List.named('test').of(String.using(name=u'foo', validators=validators)) def test_no_duplicates_message(): schema = validated_string(NotDuplicated()) el = schema([u'foo', u'foo']) assert not el.validate() assert el[1].errors == [u'foo may not be repeated within test.'] def test_no_duplicates_context(): el = String(validators=[NotDuplicated()]) with pytest.raises(TypeError): el.validate() def test_no_duplicates_comparator(): comparator = lambda a, b: True schema = validated_string(NotDuplicated(comparator=comparator)) el = schema([u'a', u'b']) assert not el.validate() def _test_no_duplicates(schema, a, b): label = schema.label el = schema([a, b]) assert el.validate() assert valid_of_children(el) == [True, True] el = schema([a, b, a]) assert not el.validate() assert valid_of_children(el) == [True, True, False] assert el[2].errors == [u'%s %s' % (label, 3)] el = schema([a, b, a, b]) assert not el.validate() assert valid_of_children(el) == [True, True, False, False] assert el[2].errors == [u'%s %s' % (label, 3)] assert el[3].errors == [u'%s %s' % (label, 4)] el = schema([a, a, a, a]) assert not el.validate() assert valid_of_children(el) == [True, False, False, False] assert el[1].errors == [u'%s %s' % (label, 2)] assert el[2].errors == [u'%s %s' % (label, 3)] assert el[3].errors == [u'%s %s' % (label, 4)] def test_no_duplicates_list_scalar(): nd = NotDuplicated(failure=u'%(container_label)s %(position)s') schema = validated_string(nd) _test_no_duplicates(schema, u'foo', u'bar') def test_no_duplicates_array(): nd = NotDuplicated(failure=u'%(container_label)s %(position)s') schema = validated_string(nd) _test_no_duplicates(schema, u'foo', u'bar') def test_no_duplicates_list_anon_dict(): nd = NotDuplicated(failure=u'%(container_label)s %(position)s') schema = (List.named('test'). of(Dict.of(Integer.named('x'), Integer.named('y')). using(validators=[nd]))) _test_no_duplicates(schema, {'x': 1, 'y': 2}, {'x': 3, 'y': 4}) def test_no_duplicates_list_dict(): nd = NotDuplicated(failure=u'%(container_label)s %(position)s') schema = (List.named('test'). of(Dict.named('xyz'). of(Integer.named('x'), Integer.named('y')). using(validators=[nd]))) _test_no_duplicates(schema, {'x': 1, 'y': 2}, {'x': 3, 'y': 4}) def validated_list(*validators): return List.named('outer').of(String.named('inner')).using( validators=validators) def test_has_at_least_none(): schema = validated_list(HasAtLeast(minimum=0)) el = schema(['a']) assert el.validate() el = schema() assert el.validate() def test_has_at_least_one(): schema = validated_list(HasAtLeast()) el = schema() assert not el.validate() assert el.errors == [u'outer must contain at least one inner'] el = schema(['a']) assert el.validate() def test_has_at_least_two(): schema = validated_list(HasAtLeast(minimum=2)) el = schema(['a']) assert not el.validate() assert el.errors == [u'outer must contain at least 2 inners'] el = schema(['a', 'b']) assert el.validate() def test_has_at_most_none(): schema = validated_list(HasAtMost(maximum=0)) el = schema(['a']) assert not el.validate() assert el.errors == [u'outer must contain at most 0 inners'] el = schema() assert el.validate() def test_has_at_most_one(): schema = validated_list(HasAtMost(maximum=1)) el = schema() assert el.validate() el = schema(['a']) assert el.validate() el = schema(['a', 'b']) assert not el.validate() assert el.errors == [u'outer must contain at most one inner'] def test_has_at_most_two(): schema = validated_list(HasAtMost(maximum=2)) el = schema() assert el.validate() el = schema(['a', 'b']) assert el.validate() el = schema(['a', 'b', 'c']) assert not el.validate() assert el.errors == [u'outer must contain at most 2 inners'] def test_has_between_none(): schema = validated_list(HasBetween(minimum=0, maximum=0)) el = schema() assert el.validate() el = schema(['a']) assert not el.validate() assert el.errors == [u'outer must contain exactly 0 inners'] def test_has_between_one(): schema = validated_list(HasBetween(minimum=1, maximum=1)) el = schema() assert not el.validate() assert el.errors == [u'outer must contain exactly one inner'] el = schema(['a']) assert el.validate() el = schema(['a', 'b']) assert not el.validate() assert el.errors == [u'outer must contain exactly one inner'] def test_has_between_two(): schema = validated_list(HasBetween(minimum=2, maximum=2)) el = schema() assert not el.validate() assert el.errors == [u'outer must contain exactly 2 inners'] el = schema(['b']) assert not el.validate() assert el.errors == [u'outer must contain exactly 2 inners'] el = schema(['a', 'b']) assert el.validate() def test_has_between_none_and_one(): schema = validated_list(HasBetween(minimum=0, maximum=1)) el = schema() assert el.validate() el = schema(['b']) assert el.validate() el = schema(['a', 'b']) assert not el.validate() assert el.errors == [u'outer must contain at least 0 and at most 1 inner'] def test_has_between_none_and_two(): schema = validated_list(HasBetween(minimum=0, maximum=2)) el = schema() assert el.validate() el = schema(['a', 'b']) assert el.validate() el = schema(['a', 'b', 'c']) assert not el.validate() assert el.errors == [u'outer must contain at least 0 and at most 2 inners'] def test_has_between_one_and_two(): schema = validated_list(HasBetween(minimum=1, maximum=2)) el = schema() assert not el.validate() assert el.errors == [u'outer must contain at least 1 and at most 2 inners'] el = schema(['b']) assert el.validate() el = schema(['a', 'b']) assert el.validate() el = schema(['a', 'b', 'c']) assert not el.validate() assert el.errors == [u'outer must contain at least 1 and at most 2 inners']
{ "repo_name": "mbr/flatland0", "path": "tests/validation/test_containers.py", "copies": "1", "size": "6728", "license": "mit", "hash": -5967342977281102000, "line_mean": 24.4848484848, "line_max": 79, "alpha_frac": 0.6024078478, "autogenerated": false, "ratio": 3.379206428930186, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9481073151189061, "avg_score": 0.00010822510822510823, "num_lines": 264 }
from flatland import ( Dict, Form, Integer, ) from flatland.validation import ( Converted, Present, Validator, ) class Age(Integer): class IsNumber(Converted): incorrect = u'%(label)s is not a valid number.' class ValidAge(Validator): minage = 1 maxage = 150 too_young = u'%(label)s must be at least %(minage)s.' too_old = u'%(label)s may not be larger than %(maxage)s' at_min = '%(label)s is at the minimum age.' at_max = '%(label)s is at the maximum age.' def validate(self, element, state): age = element.value if age < self.minage: return self.note_error(element, state, 'too_young') elif age == self.minage: return self.note_warning(element, state, 'at_min') elif age == self.maxage: return self.note_warning(element, state, 'at_max') elif age > self.maxage: return self.note_error(element, state, 'too_old') return True validators = (Present(), IsNumber(), ValidAge()) class ThirtySomething(Age): validators = (Present(), Age.IsNumber(), Age.ValidAge(minage=30, maxage=39)) def test_custom_validation(): class MyForm(Form): age = ThirtySomething f = MyForm.from_flat({}) assert not f.validate() assert f['age'].errors == ['age may not be blank.'] f = MyForm.from_flat({u'age': u''}) assert not f.validate() assert f['age'].errors == ['age may not be blank.'] f = MyForm.from_flat({u'age': u'crunch'}) assert not f.validate() assert f['age'].errors == ['age is not a valid number.'] f = MyForm.from_flat({u'age': u'10'}) assert not f.validate() assert f['age'].errors == ['age must be at least 30.'] def test_child_validation(): class MyForm(Form): x = Integer.using(validators=[Present()]) form = MyForm() assert not form.validate() form.set({u'x': 10}) assert form.validate() def test_nested_validation(): class MyForm(Form): x = Integer.using(validators=[Present()]) d2 = Dict.of(Integer.named('x2').using(validators=[Present()])) form = MyForm() assert not form.validate() form['x'].set(1) assert not form.validate() assert form.validate(recurse=False) form.el('d2.x2').set(2) assert form.validate()
{ "repo_name": "mbr/flatland0", "path": "tests/test_validation.py", "copies": "5", "size": "2494", "license": "mit", "hash": 2664215242720374300, "line_mean": 23.94, "line_max": 71, "alpha_frac": 0.5657578188, "autogenerated": false, "ratio": 3.646198830409357, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6711956649209357, "avg_score": null, "num_lines": null }
from flatland import ( Dict, Integer, List, Sequence, SkipAll, SkipAllFalse, String, Unevaluated, ) from flatland.schema.base import Root from tests._util import eq_, assert_raises def test_dsl_of(): assert_raises(TypeError, Sequence.of) t1 = Sequence.of(Integer) assert t1.member_schema is Integer t2 = Sequence.of(Integer.named(u'x'), Integer.named(u'y')) assert issubclass(t2.member_schema, Dict) assert sorted(t2.member_schema().keys()) == [u'x', u'y'] def test_dsl_descent_validated_by(): s = Sequence.using(descent_validators=(123, 456)) eq_(s.descent_validators, (123, 456)) s = Sequence.descent_validated_by(123, 456) eq_(s.descent_validators, [123, 456]) s = Sequence.using(descent_validators=(123, 456)).descent_validated_by(789) eq_(s.descent_validators, [789]) assert_raises(TypeError, Sequence.descent_validated_by, int) def test_dsl_including_descent_validators(): base = Sequence.descent_validated_by(1, 2, 3) eq_(base.descent_validators, [1, 2, 3]) s = base.including_descent_validators(4, 5, 6) eq_(s.descent_validators, [1, 2, 3, 4, 5, 6]) s = base.including_descent_validators(4, 5, 6, position=0) eq_(s.descent_validators, [4, 5, 6, 1, 2, 3]) s = base.including_descent_validators(4, 5, 6, position=1) eq_(s.descent_validators, [1, 4, 5, 6, 2, 3]) s = base.including_descent_validators(4, 5, 6, position=-2) eq_(s.descent_validators, [1, 2, 4, 5, 6, 3]) s = Sequence.including_descent_validators(1) eq_(s.descent_validators, [1]) def test_simple_validation_shortcircuit(): Regular = Dict.of(Integer.using(optional=False)) el = Regular() assert not el.validate() def boom(element, state): assert False all_ok = lambda element, state: SkipAll Boom = Integer.named(u'i').using(validators=[boom]) ShortCircuited = Dict.of(Boom).using(descent_validators=[all_ok]) el = ShortCircuited() assert el.validate() class TestContainerValidation(object): def setup(self): self.canary = [] def validator(self, name, result): def fn(element, state): self.canary.append(name) return result fn.__name__ = name return fn def test_regular(self): schema = (Dict.of(Integer). using(validators=[self.validator('1', True)])) el = schema() assert not el.validate() eq_(self.canary, ['1']) assert el.valid assert not el.all_valid def test_descent(self): schema = Dict.of(Integer).using( descent_validators=[self.validator('1', True)]) el = schema() assert not el.validate() eq_(self.canary, ['1']) assert el.valid assert not el.all_valid def test_paired(self): schema = Dict.of(Integer).using( descent_validators=[self.validator('1', True)], validators=[self.validator('2', True)]) el = schema() assert not el.validate() eq_(self.canary, ['1', '2']) assert el.valid assert not el.all_valid def test_paired2(self): schema = Dict.of(Integer).using( descent_validators=[self.validator('1', False)], validators=[self.validator('2', True)]) el = schema() assert not el.validate() eq_(self.canary, ['1', '2']) assert not el.valid assert not el.all_valid def test_paired3(self): schema = ( Dict.of( Integer.using(validators=[self.validator('2', True)])). using( descent_validators=[self.validator('1', True)], validators=[self.validator('3', True)])) el = schema() assert el.validate() eq_(self.canary, ['1', '2', '3']) assert el.valid assert el.all_valid def test_shortcircuit_down_true(self): schema = ( Dict.of( Integer.using(validators=[self.validator('2', False)])). using( descent_validators=[self.validator('1', SkipAll)], validators=[self.validator('3', True)])) el = schema() assert el.validate() eq_(self.canary, ['1', '3']) assert el.valid assert el.all_valid def test_shortcircuit_down_false(self): schema = ( Dict.of( Integer.named(u'i').using( validators=[self.validator('2', True)])). using(descent_validators=[self.validator('1', SkipAllFalse)], validators=[self.validator('3', True)])) el = schema() assert not el.validate() eq_(self.canary, ['1', '3']) assert not el.valid assert not el.all_valid assert el[u'i'].valid is Unevaluated def test_shortcircuit_up(self): schema = ( Dict.of( Integer.using(validators=[self.validator('2', True)])). using( descent_validators=[self.validator('1', True)], validators=[self.validator('3', SkipAll)])) el = schema() assert el.validate() eq_(self.canary, ['1', '2', '3']) assert el.valid assert el.all_valid def test_sequence(): schema = Sequence.named(u's') assert hasattr(schema, 'member_schema') def test_mixed_all_children(): data = {u'A1': u'1', u'A2': u'2', u'A3': {u'A3B1': {u'A3B1C1': u'1', u'A3B1C2': u'2'}, u'A3B2': {u'A3B2C1': u'1'}, u'A3B3': [[u'A3B3C0D0', u'A3B3C0D1'], [u'A3B3C1D0', u'A3B3C1D1'], [u'A3B3C2D0', u'A3B3C2D1']]}} schema = ( Dict.named(u'R').of( String.named(u'A1'), String.named(u'A2'), Dict.named(u'A3').of( Dict.named(u'A3B1').of( String.named(u'A3B1C1'), String.named(u'A3B1C2')), Dict.named(u'A3B2').of( String.named(u'A3B2C1')), List.named(u'A3B3').of( List.named(u'A3B3Cx').of( String.named(u'A3B3x')))))) top = schema(data) names = list(e.name for e in top.all_children) assert set(names[0:3]) == set([u'A1', u'A2', u'A3']) assert set(names[3:6]) == set([u'A3B1', u'A3B2', u'A3B3']) assert set(names[6:12]) == set([u'A3B1C1', u'A3B1C2', u'A3B2C1', u'A3B3Cx']) assert set(names[12:]) == set([u'A3B3x']) assert len(names[12:]) == 6 def test_corrupt_all_children(): # Ensure all_children won't spin out if the graph becomes cyclic. schema = List.of(String) el = schema() el.append(String(u'x')) el.append(String(u'y')) dupe = String(u'z') el.append(dupe) el.append(dupe) assert list(_.value for _ in el.children) == list(u'xyzz') assert list(_.value for _ in el.all_children) == list(u'xyz') def test_naming_bogus(): e = String(name=u's') assert e.el(u'.') is e assert_raises(LookupError, e.el, u'') assert_raises(TypeError, e.el, None) assert_raises(LookupError, e.el, ()) assert_raises(LookupError, e.el, iter(())) assert_raises(TypeError, e.el) def test_naming_shallow(): root = String(name=u's') assert root.fq_name() == u'.' assert root.flattened_name() == u's' assert root.el(u'.') is root root = String(name=None) assert root.fq_name() == u'.' assert root.flattened_name() == u'' assert root.el(u'.') is root assert_raises(LookupError, root.el, ()) assert root.el([Root]) is root def test_naming_dict(): for name, root_flat, leaf_flat in ((u'd', u'd', u'd_s'), (None, u'', u's')): schema = Dict.named(name).of(String.named(u's')) root = schema() leaf = root[u's'] assert root.fq_name() == u'.' assert root.flattened_name() == root_flat assert root.el(u'.') is root assert leaf.fq_name() == u'.s' assert leaf.flattened_name() == leaf_flat assert root.el(u'.s') is leaf assert root.el(u's') is leaf assert leaf.el(u'.s') is leaf assert_raises(LookupError, leaf.el, u's') assert leaf.el(u'.') is root assert root.el([Root]) is root assert root.el([u's']) is leaf assert root.el([Root, u's']) is leaf assert root.el(iter([u's'])) is leaf assert root.el(iter([Root, u's'])) is leaf def test_naming_dict_dict(): for name, root_flat, leaf_flat in ((u'd', u'd', u'd_d2_s'), (None, u'', u'd2_s')): schema = Dict.named(name).of( Dict.named(u'd2').of(String.named(u's'))) root = schema() leaf = root[u'd2'][u's'] assert root.fq_name() == u'.' assert root.flattened_name() == root_flat assert root.el(u'.') is root assert leaf.fq_name() == u'.d2.s' assert leaf.flattened_name() == leaf_flat assert root.el(u'.d2.s') is leaf assert root.el(u'd2.s') is leaf assert leaf.el(u'.d2.s') is leaf assert_raises(LookupError, leaf.el, u'd2.s') assert leaf.el(u'.') is root assert root.el([u'd2', u's']) is leaf def test_naming_list(): for name, root_flat, leaf_flat in ((u'l', u'l', u'l_0_s'), (None, u'', u'0_s')): schema = List.named(name).of(String.named(u's')) root = schema([u'x']) leaf = root[0] assert root.fq_name() == u'.' assert root.flattened_name() == root_flat assert root.el(u'.') is root assert leaf.fq_name() == u'.0' assert leaf.flattened_name() == leaf_flat assert root.el(u'.0') is leaf assert root.el(u'0') is leaf assert leaf.el(u'.0') is leaf assert_raises(LookupError, leaf.el, u'0') assert_raises(LookupError, leaf.el, u's') assert leaf.el(u'.') is root assert root.el([u'0']) is leaf def test_naming_list_list(): # make sure nested Slots-users don't bork for name, root_flat, leaf_flat in ((u'l', u'l', u'l_0_l2_0_s'), (None, u'', u'0_l2_0_s')): schema = List.named(name).of(List.named(u'l2').of(String.named(u's'))) root = schema([u'x']) leaf = root[0][0] assert root.fq_name() == u'.' assert root.flattened_name() == root_flat assert root.el(u'.') is root assert leaf.fq_name() == u'.0.0' assert leaf.flattened_name() == leaf_flat assert root.el(u'.0.0') is leaf assert root.el(u'0.0') is leaf assert leaf.el(u'.0.0') is leaf assert_raises(LookupError, leaf.el, u'0') assert_raises(LookupError, leaf.el, u's') assert leaf.el(u'.') is root assert root.el([u'0', u'0']) is leaf
{ "repo_name": "mmerickel/flatland", "path": "tests/schema/test_containers.py", "copies": "4", "size": "11097", "license": "mit", "hash": 6224693529035291000, "line_mean": 30.1713483146, "line_max": 79, "alpha_frac": 0.5390646121, "autogenerated": false, "ratio": 3.3334334635025535, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00016073113741227083, "num_lines": 356 }
from flatland import ( Dict, Integer, List, Sequence, SkipAll, SkipAllFalse, String, Unevaluated, ) from flatland.schema.base import Root import pytest def test_dsl_of(): with pytest.raises(TypeError): Sequence.of() t1 = Sequence.of(Integer) assert t1.member_schema is Integer t2 = Sequence.of(Integer.named(u'x'), Integer.named(u'y')) assert issubclass(t2.member_schema, Dict) assert sorted(t2.member_schema().keys()) == [u'x', u'y'] def test_dsl_descent_validated_by(): s = Sequence.using(descent_validators=(123, 456)) assert s.descent_validators == (123, 456) s = Sequence.descent_validated_by(123, 456) assert s.descent_validators == [123, 456] s = Sequence.using(descent_validators=(123, 456)).descent_validated_by(789) assert s.descent_validators == [789] with pytest.raises(TypeError): Sequence.descent_validated_by(int) def test_dsl_including_descent_validators(): base = Sequence.descent_validated_by(1, 2, 3) assert base.descent_validators == [1, 2, 3] s = base.including_descent_validators(4, 5, 6) assert s.descent_validators == [1, 2, 3, 4, 5, 6] s = base.including_descent_validators(4, 5, 6, position=0) assert s.descent_validators == [4, 5, 6, 1, 2, 3] s = base.including_descent_validators(4, 5, 6, position=1) assert s.descent_validators == [1, 4, 5, 6, 2, 3] s = base.including_descent_validators(4, 5, 6, position=-2) assert s.descent_validators == [1, 2, 4, 5, 6, 3] s = Sequence.including_descent_validators(1) assert s.descent_validators == [1] def test_simple_validation_shortcircuit(): Regular = Dict.of(Integer.using(optional=False)) el = Regular() assert not el.validate() def boom(element, state): assert False all_ok = lambda element, state: SkipAll Boom = Integer.named(u'i').using(validators=[boom]) ShortCircuited = Dict.of(Boom).using(descent_validators=[all_ok]) el = ShortCircuited() assert el.validate() class TestContainerValidation(object): def setup(self): self.canary = [] def validator(self, name, result): def fn(element, state): self.canary.append(name) return result fn.__name__ = name return fn def test_regular(self): schema = (Dict.of(Integer). using(validators=[self.validator('1', True)])) el = schema() assert not el.validate() assert self.canary == ['1'] assert el.valid assert not el.all_valid def test_descent(self): schema = Dict.of(Integer).using( descent_validators=[self.validator('1', True)]) el = schema() assert not el.validate() assert self.canary == ['1'] assert el.valid assert not el.all_valid def test_paired(self): schema = Dict.of(Integer).using( descent_validators=[self.validator('1', True)], validators=[self.validator('2', True)]) el = schema() assert not el.validate() assert self.canary == ['1', '2'] assert el.valid assert not el.all_valid def test_paired2(self): schema = Dict.of(Integer).using( descent_validators=[self.validator('1', False)], validators=[self.validator('2', True)]) el = schema() assert not el.validate() assert self.canary == ['1', '2'] assert not el.valid assert not el.all_valid def test_paired3(self): schema = ( Dict.of( Integer.using(validators=[self.validator('2', True)])). using( descent_validators=[self.validator('1', True)], validators=[self.validator('3', True)])) el = schema() assert el.validate() assert self.canary == ['1', '2', '3'] assert el.valid assert el.all_valid def test_shortcircuit_down_true(self): schema = ( Dict.of( Integer.using(validators=[self.validator('2', False)])). using( descent_validators=[self.validator('1', SkipAll)], validators=[self.validator('3', True)])) el = schema() assert el.validate() assert self.canary == ['1', '3'] assert el.valid assert el.all_valid def test_shortcircuit_down_false(self): schema = ( Dict.of( Integer.named(u'i').using( validators=[self.validator('2', True)])). using(descent_validators=[self.validator('1', SkipAllFalse)], validators=[self.validator('3', True)])) el = schema() assert not el.validate() assert self.canary == ['1', '3'] assert not el.valid assert not el.all_valid assert el[u'i'].valid is Unevaluated def test_shortcircuit_up(self): schema = ( Dict.of( Integer.using(validators=[self.validator('2', True)])). using( descent_validators=[self.validator('1', True)], validators=[self.validator('3', SkipAll)])) el = schema() assert el.validate() assert self.canary == ['1', '2', '3'] assert el.valid assert el.all_valid def test_sequence(): schema = Sequence.named(u's') assert hasattr(schema, 'member_schema') def test_mixed_all_children(): data = {u'A1': u'1', u'A2': u'2', u'A3': {u'A3B1': {u'A3B1C1': u'1', u'A3B1C2': u'2'}, u'A3B2': {u'A3B2C1': u'1'}, u'A3B3': [[u'A3B3C0D0', u'A3B3C0D1'], [u'A3B3C1D0', u'A3B3C1D1'], [u'A3B3C2D0', u'A3B3C2D1']]}} schema = ( Dict.named(u'R').of( String.named(u'A1'), String.named(u'A2'), Dict.named(u'A3').of( Dict.named(u'A3B1').of( String.named(u'A3B1C1'), String.named(u'A3B1C2')), Dict.named(u'A3B2').of( String.named(u'A3B2C1')), List.named(u'A3B3').of( List.named(u'A3B3Cx').of( String.named(u'A3B3x')))))) top = schema(data) names = list(e.name for e in top.all_children) assert set(names[0:3]) == set([u'A1', u'A2', u'A3']) assert set(names[3:6]) == set([u'A3B1', u'A3B2', u'A3B3']) assert set(names[6:12]) == set([u'A3B1C1', u'A3B1C2', u'A3B2C1', u'A3B3Cx']) assert set(names[12:]) == set([u'A3B3x']) assert len(names[12:]) == 6 def test_corrupt_all_children(): # Ensure all_children won't spin out if the graph becomes cyclic. schema = List.of(String) el = schema() el.append(String(u'x')) el.append(String(u'y')) dupe = String(u'z') el.append(dupe) el.append(dupe) assert list(_.value for _ in el.children) == list(u'xyzz') assert list(_.value for _ in el.all_children) == list(u'xyz') def test_naming_bogus(): e = String(name=u's') assert e.el(u'.') is e with pytest.raises(LookupError): e.el(u'') with pytest.raises(TypeError): e.el(None) with pytest.raises(LookupError): e.el(()) with pytest.raises(LookupError): e.el(iter(())) with pytest.raises(TypeError): e.el() def test_naming_shallow(): root = String(name=u's') assert root.fq_name() == u'.' assert root.flattened_name() == u's' assert root.el(u'.') is root root = String(name=None) assert root.fq_name() == u'.' assert root.flattened_name() == u'' assert root.el(u'.') is root with pytest.raises(LookupError): root.el(()) assert root.el([Root]) is root def test_naming_dict(): for name, root_flat, leaf_flat in ((u'd', u'd', u'd_s'), (None, u'', u's')): schema = Dict.named(name).of(String.named(u's')) root = schema() leaf = root[u's'] assert root.fq_name() == u'.' assert root.flattened_name() == root_flat assert root.el(u'.') is root assert leaf.fq_name() == u'.s' assert leaf.flattened_name() == leaf_flat assert root.el(u'.s') is leaf assert root.el(u's') is leaf assert leaf.el(u'.s') is leaf with pytest.raises(LookupError): leaf.el(u's') assert leaf.el(u'.') is root assert root.el([Root]) is root assert root.el([u's']) is leaf assert root.el([Root, u's']) is leaf assert root.el(iter([u's'])) is leaf assert root.el(iter([Root, u's'])) is leaf def test_naming_dict_dict(): for name, root_flat, leaf_flat in ((u'd', u'd', u'd_d2_s'), (None, u'', u'd2_s')): schema = Dict.named(name).of( Dict.named(u'd2').of(String.named(u's'))) root = schema() leaf = root[u'd2'][u's'] assert root.fq_name() == u'.' assert root.flattened_name() == root_flat assert root.el(u'.') is root assert leaf.fq_name() == u'.d2.s' assert leaf.flattened_name() == leaf_flat assert root.el(u'.d2.s') is leaf assert root.el(u'd2.s') is leaf assert leaf.el(u'.d2.s') is leaf with pytest.raises(LookupError): leaf.el(u'd2.s') assert leaf.el(u'.') is root assert root.el([u'd2', u's']) is leaf def test_naming_list(): for name, root_flat, leaf_flat in ((u'l', u'l', u'l_0_s'), (None, u'', u'0_s')): schema = List.named(name).of(String.named(u's')) root = schema([u'x']) leaf = root[0] assert root.fq_name() == u'.' assert root.flattened_name() == root_flat assert root.el(u'.') is root assert leaf.fq_name() == u'.0' assert leaf.flattened_name() == leaf_flat assert root.el(u'.0') is leaf assert root.el(u'0') is leaf assert leaf.el(u'.0') is leaf with pytest.raises(LookupError): leaf.el(u'0') with pytest.raises(LookupError): leaf.el(u's') assert leaf.el(u'.') is root assert root.el([u'0']) is leaf def test_naming_list_list(): # make sure nested Slots-users don't bork for name, root_flat, leaf_flat in ((u'l', u'l', u'l_0_l2_0_s'), (None, u'', u'0_l2_0_s')): schema = List.named(name).of(List.named(u'l2').of(String.named(u's'))) root = schema([u'x']) leaf = root[0][0] assert root.fq_name() == u'.' assert root.flattened_name() == root_flat assert root.el(u'.') is root assert leaf.fq_name() == u'.0.0' assert leaf.flattened_name() == leaf_flat assert root.el(u'.0.0') is leaf assert root.el(u'0.0') is leaf assert leaf.el(u'.0.0') is leaf with pytest.raises(LookupError): leaf.el(u'0') with pytest.raises(LookupError): leaf.el(u's') assert leaf.el(u'.') is root assert root.el([u'0', u'0']) is leaf
{ "repo_name": "mbr/flatland0", "path": "tests/schema/test_containers.py", "copies": "1", "size": "11343", "license": "mit", "hash": -3987296993260824600, "line_mean": 29.5741239892, "line_max": 79, "alpha_frac": 0.5364542008, "autogenerated": false, "ratio": 3.4052836985890123, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4441737899389012, "avg_score": null, "num_lines": null }
from flatland import ( Dict, List, String, ) from tests.genshi._util import FilteredRenderTest, from_docstring class TestExpressions(FilteredRenderTest): def form(): schema = Dict.named(u'field0').of( String.named(u'field1'), String.named(u'field2'), List.named(u'field3').of(String.named(u'field4')), List.named(u'field5').of( List.named(u'field6').of(String.named(u'field7')))) element = schema( {u'field1': u'val1', u'field2': u'val2', u'field3': [u'val3'], u'field5': [[u'val4']]}) element.set_prefix(u'form') return {'form': element, 'bound': element.bind} @from_docstring(context_factory=form) def test_field0(self): """ :: test ${form} :: eq # FIXME: b0rk3n, hash sensitive field2field3field1field5 :: endtest :: test ${bound} :: eq form.el(u'.') :: endtest :: test ${form.bind} :: eq form.el(u'.') :: endtest :: test <py:for each="name in form">${type(name).__name__} </py:for> ::eq unicode unicode unicode unicode :: endtest """ @from_docstring(context_factory=form) def test_field1(self): """ :: test ${form['field1']} :: eq val1 :: endtest :: test ${form.field1} :: eq val1 :: endtest :: test ${form.field1.u} :: eq val1 :: endtest :: test ${form.field1.bind.u} :: eq val1 :: endtest :: test ${form.field1.bind.bind.bind.u} :: eq val1 :: endtest """ @from_docstring(context_factory=form) def test_field3(self): """ :: test ${form.field3} :: eq val3 :: endtest :: test ${form.field3.bind} :: eq form.el(u'.field3') :: endtest :: test ${form.field3[0]} :: eq val3 :: endtest :: test ${form.field3[0].bind} :: eq form.el(u'.field3.0') :: endtest :: test <py:for each="x in form.field3.binds">${x}</py:for> :: eq field4 :: endtest :: test ${type(form.binds.field3).__name__} :: eq WrappedElement :: endtest :: test <py:for each="x in form.binds.field3">${type(x).__name__}</py:for> :: eq WrappedElement :: endtest :: test <py:for each="x in form.binds.field3">${x}</py:for> :: eq form.el(u'.field3.0') :: endtest """ @from_docstring(context_factory=form) def test_field5(self): """ :: test ${bound.field5} :: eq form.el(u'.field5') :: endtest :: test ${form.field5.value} :: eq [u'val4'] :: endtest :: test ${bound.field5[0]} :: eq form.el(u'.field5.0') :: endtest :: test ${form['field5'][0].bind} :: eq form.el(u'.field5.0') :: endtest :: test <py:for each="e in bound.field5">${type(e).__name__}</py:for> :: eq WrappedElement :: endtest :: test <py:for each="e in bound.field5">${e}</py:for> :: eq form.el(u'.field5.0') :: endtest """ @from_docstring(context_factory=form) def test_field7(self): """ :: test ${bound.field5[0][0]} :: eq form.el(u'.field5.0.0') :: endtest :: test ${form.field5[0][0].bind} :: eq form.el(u'.field5.0.0') :: endtest :: test ${form.field5[0][0].u} :: eq val4 :: endtest """ del form class TestShadowed(FilteredRenderTest): def shadow(): schema = Dict.named(u'dict_name').of( String.named(u'name'), String.named(u'u')) element = schema({u'name': u'string name', u'u': u'string u'}) element.set_prefix(u'top') return {'top': element, 'bound': element.bind} @from_docstring(context_factory=shadow) def test_shadow(self): """ :: test ${bound} :: eq top.el(u'.') :: endtest :: test ${bound} :: eq top.el(u'.') :: endtest :: test ${top.name} :: eq dict_name :: endtest :: test ${top.binds.name} :: eq top.el(u'.name') :: endtest :: test ${top.binds.name.name} :: eq name :: endtest :: test ${top.binds.u} :: eq top.el(u'.u') :: endtest :: test ${top.binds.u.name} :: eq u :: endtest :: test ${top['name']} :: eq string name :: endtest :: test ${top['name'].u} :: eq string name :: endtest :: test ${top['name'].name} :: eq name :: endtest """ del shadow class TestPrefixes(FilteredRenderTest): def elements(): from flatland import Dict, String anon = Dict.of(String.named(u'anon_field'))() named = Dict.named(u'named').of(String.named(u'named_field'))() prefixed = Dict.named(u'prefixed').of(String.named(u'prefixed_field'))() prefixed.set_prefix(u'three.levels.down') return {'form': anon, 'forms': {'named': named }, 'three': {'levels': {'down': prefixed}}} @from_docstring(context_factory=elements) def test_prefixes(self): """ :: test ${form.bind} :: eq form.el(u'.') :: endtest :: test ${form.binds} :: eq anon_field :: endtest :: test ${form.anon_field.bind} :: eq form.el(u'.anon_field') :: endtest :: test ${form.binds.anon_field} :: eq form.el(u'.anon_field') :: endtest :: test ${forms.named.named_field.bind} :: eq forms.named.el(u'.named_field') :: endtest :: test ${forms.named.binds.named_field} :: eq forms.named.el(u'.named_field') :: endtest :: test ${three.levels.down.prefixed_field.bind} :: eq three.levels.down.el(u'.prefixed_field') :: endtest :: test ${three.levels.down.binds.prefixed_field} :: eq three.levels.down.el(u'.prefixed_field') :: endtest """ del elements
{ "repo_name": "jek/flatland", "path": "tests/genshi/test_expressions.py", "copies": "2", "size": "5301", "license": "mit", "hash": 1416788814895020500, "line_mean": 14.1457142857, "line_max": 80, "alpha_frac": 0.5778155065, "autogenerated": false, "ratio": 2.7423693740300052, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4320184880530006, "avg_score": null, "num_lines": null }
from flatland import ( Dict, String, ) from flatland.validation import ( Converted, NoLongerThan, ) class GetTextish(object): """Mimics a gettext translation.""" catalog = { u'%(label)s is not correct.': u'reg %(label)s', u'%(label)s may not exceed %(maxlength)s characters.': u'default %(label)s %(maxlength)s', u'%(label)s max is %(maxlength)s characters.': u'plural %(label)s %(maxlength)s', u'%(label)s max is %(maxlength)s character.': u'single %(label)s %(maxlength)s', u'age': u'AGE', u'name': u'NAME', } def ugettext(self, text): try: return self.catalog[text] except KeyError: return text def ungettext(self, single, plural, n): lookup = single if n == 1 else plural return self.ugettext(lookup) class LocalizedShort(NoLongerThan): exceeded = (u'%(label)s max is %(maxlength)s character.', u'%(label)s max is %(maxlength)s characters.', 'maxlength') def test_regular_gettext(): catalog = GetTextish() # translators placed at the top of the form schema = Dict.of(String.named('age').using(validators=[Converted()])).\ using(ugettext=catalog.ugettext, ungettext=catalog.ungettext) data = schema() data.validate() assert data['age'].errors == [u'reg AGE'] def test_local_gettext(): catalog = GetTextish() # translators placed on a specific form element schema = Dict.of(String.named('age').using(validators=[Converted()], ugettext=catalog.ugettext, ungettext=catalog.ungettext)) data = schema() data.validate() assert data['age'].errors == [u'reg AGE'] def test_local_gettext_search_is_not_overeager(): catalog = GetTextish() def poison(*a): assert False # if a translator is found on an element, its parents won't be searched schema = (Dict.of(String.named('age'). using(validators=[Converted()], ugettext=catalog.ugettext, ungettext=catalog.ungettext)). using(ugettext=poison, ungettext=poison)) data = schema() data.validate() assert data['age'].errors == [u'reg AGE'] def test_builtin_gettext(): catalog = GetTextish() schema = Dict.of(String.named('age').using(validators=[Converted()])) data = schema() try: # translators can go into the builtins from six.moves import builtins builtins.ugettext = catalog.ugettext builtins.ungettext = catalog.ungettext data.validate() assert data['age'].errors == [u'reg AGE'] finally: del builtins.ugettext del builtins.ungettext def test_state_gettext(): catalog = GetTextish() schema = Dict.of(String.named('age').using(validators=[Converted()])) # if state has ugettext or ungettext attributes, those will be used data = schema() data.validate(catalog) assert data['age'].errors == [u'reg AGE'] # also works if state is dict-like data = schema() state = dict(ugettext=catalog.ugettext, ungettext=catalog.ungettext) data.validate(state) assert data['age'].errors == [u'reg AGE'] def test_tuple_single(): catalog = GetTextish() schema = Dict.of(String.named('name'). using(validators=[LocalizedShort(1)])) data = schema(dict(name='xxx')) data.validate(catalog) assert data['name'].errors == [u'single NAME 1'] def test_tuple_plural(): catalog = GetTextish() schema = Dict.of(String.named('name'). using(validators=[LocalizedShort(2)])) data = schema(dict(name='xxx')) data.validate(catalog) assert data['name'].errors == [u'plural NAME 2']
{ "repo_name": "mbr/flatland0", "path": "tests/test_i18n.py", "copies": "1", "size": "3995", "license": "mit", "hash": -5495094351789552000, "line_mean": 26.1768707483, "line_max": 76, "alpha_frac": 0.5824780976, "autogenerated": false, "ratio": 4.0476190476190474, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5130097145219048, "avg_score": null, "num_lines": null }
from flatland import ( Dict, String, ) from tests._util import eq_ def test_dict(): s = Dict.named('dict').of(String.named('k1'), String.named('k2')) el = s() assert s assert el def test_string_element(): el1 = String() el1.set_default() el2 = String(default=None) el2.set_default() el3 = String(default=u'') el3.set_default() assert el1.value == None assert el1.u == u'' assert not el1 assert el2.value == None assert el2.u == u'' assert not el2 assert el3.value == u'' assert el3.u == u'' assert not el3 assert el1 == el2 assert el1 != el3 assert el2 != el3 el4 = String(default=u' ', strip=True) el4.set_default() el5 = String(default=u' ', strip=False) el5.set_default() assert el4 != el5 assert el4.u == u'' assert el4.value == u'' el4.set(u' ') assert el4.u == u'' assert el4.value == u'' assert el5.u == u' ' assert el5.value == u' ' el5.set(u' ') assert el5.u == u' ' assert el5.value == u' ' def test_path(): schema = Dict.named('root').of( String.named('element'), Dict.named('dict').of(String.named('dict_element'))) element = schema() eq_(list(element.el(['dict', 'dict_element']).path), [element, element['dict'], element['dict']['dict_element']])
{ "repo_name": "wheeler-microfluidics/flatland-fork", "path": "tests/test_schema.py", "copies": "4", "size": "1411", "license": "mit", "hash": -8520647968970509000, "line_mean": 19.75, "line_max": 68, "alpha_frac": 0.5414599575, "autogenerated": false, "ratio": 3.1355555555555554, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0010141987829614604, "num_lines": 68 }
from flatland import ( Dict, String, ) def test_dict(): s = Dict.named('dict').of(String.named('k1'), String.named('k2')) el = s() assert s assert el def test_string_element(): el1 = String() el1.set_default() el2 = String(default=None) el2.set_default() el3 = String(default=u'') el3.set_default() assert el1.value is None assert el1.u == u'' assert not el1 assert el2.value is None assert el2.u == u'' assert not el2 assert el3.value == u'' assert el3.u == u'' assert not el3 assert el1 == el2 assert el1 != el3 assert el2 != el3 el4 = String(default=u' ', strip=True) el4.set_default() el5 = String(default=u' ', strip=False) el5.set_default() assert el4 != el5 assert el4.u == u'' assert el4.value == u'' el4.set(u' ') assert el4.u == u'' assert el4.value == u'' assert el5.u == u' ' assert el5.value == u' ' el5.set(u' ') assert el5.u == u' ' assert el5.value == u' ' def test_path(): schema = Dict.named('root').of( String.named('element'), Dict.named('dict').of(String.named('dict_element'))) element = schema() assert (list(element.el(['dict', 'dict_element']).path) == [element, element['dict'], element['dict']['dict_element']])
{ "repo_name": "mbr/flatland0", "path": "tests/test_schema.py", "copies": "1", "size": "1388", "license": "mit", "hash": -4171009307318780000, "line_mean": 20.0303030303, "line_max": 72, "alpha_frac": 0.5410662824, "autogenerated": false, "ratio": 3.1402714932126696, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.918133777561267, "avg_score": 0, "num_lines": 66 }
from flatland import ( Element, Skip, SkipAll, SkipAllFalse, Unevaluated, ) from tests._util import assert_raises, eq_, requires_unicode_coercion def test_cloning(): new_element = Element.named(u'x') assert isinstance(new_element, type) assert new_element.__module__ != Element.__module__ assert 'test_base' in new_element.__module__ @requires_unicode_coercion def test_naming(): for arg in (u'unicode', 'sysencoding', None): schema = Element.named(arg) eq_(schema.name, arg) eq_(schema.label, arg) for arg in (u'unicode', 'sysencoding', None): schema = Element.named(arg).using(label=u'fleem') eq_(schema.name, arg) eq_(schema.label, u'fleem') def test_validators(): # Validators may be inherited or supplied at construction. el = Element() assert not el.validators # argument is transformed into a list copy el = Element(validators=(123, 456)) eq_(el.validators, [123, 456]) el = Element(validators=xrange(3)) eq_(el.validators, list(xrange(3))) schema = Element.using(validators=xrange(3)) eq_(schema.validators, list(xrange(3))) def test_dsl_validated_by(): s = Element.using(validators=(123, 456)) eq_(s.validators, [123, 456]) s = Element.validated_by(123, 456) eq_(s.validators, [123, 456]) s = Element.using(validators=(123, 456)).validated_by(789) eq_(s.validators, [789]) assert_raises(TypeError, Element.validated_by, int) def test_dsl_including_validators(): base = Element.validated_by(1, 2, 3) eq_(base.validators, [1, 2, 3]) s = base.including_validators(4, 5, 6) eq_(s.validators, [1, 2, 3, 4, 5, 6]) s = base.including_validators(4, 5, 6, position=0) eq_(s.validators, [4, 5, 6, 1, 2, 3]) s = base.including_validators(4, 5, 6, position=1) eq_(s.validators, [1, 4, 5, 6, 2, 3]) s = base.including_validators(4, 5, 6, position=-2) eq_(s.validators, [1, 2, 4, 5, 6, 3]) s = Element.including_validators(1) eq_(s.validators, [1]) def test_optional(): # Required is the default. el = Element() assert not el.optional el = Element(optional=True) assert el.optional el = Element(optional=False) assert not el.optional def test_label(): # .label fallback to .name works for instances and classes for item in Element.named(u'x'), Element.named(u'x')(), Element(name=u'x'): assert item.label == u'x' for item in (Element.using(name=u'x', label=u'L'), Element.using(name=u'x', label=u'L')(), Element(name=u'x', label=u'L')): assert item.label == u'L' def test_instance_defaults(): el = Element() eq_(el.name, None) eq_(el.label, None) eq_(el.optional, False) eq_(el.default, None) eq_(el.default_factory, None) eq_(el.default_value, None) eq_(el.validators, ()) eq_(el.valid, Unevaluated) eq_(el.errors, []) eq_(el.warnings, []) eq_(tuple(_.name for _ in el.path), (None,)) eq_(el.parent, None) eq_(el.root, el) eq_(el.flattened_name(), u'') eq_(el.value, None) eq_(el.u, u'') def test_abstract(): element = Element() assert_raises(NotImplementedError, element.set, None) assert_raises(NotImplementedError, element.set_flat, ()) assert_raises(NotImplementedError, element.el, u'foo') def test_message_buckets(): el = Element() el.add_error('error') eq_(el.errors, ['error']) el.add_error('error') eq_(el.errors, ['error']) el.add_error('error2') eq_(el.errors, ['error', 'error2']) el.add_warning('warning') eq_(el.warnings, ['warning']) el.add_warning('warning') eq_(el.warnings, ['warning']) def test_validation(): ok = lambda item, data: True not_ok = lambda item, data: False none = lambda item, data: None skip = lambda item, data: Skip all_ok = lambda item, data: SkipAll all_not_ok = lambda item, data: SkipAllFalse for res, validators in ((True, (ok,)), (True, (ok, ok)), (True, (skip,)), (True, (skip, not_ok)), (True, (ok, skip, not_ok)), (True, (all_ok,)), (True, (all_ok, not_ok)), (False, (none,)), (False, (ok, none)), (False, (not_ok,)), (False, (ok, not_ok,)), (False, (ok, not_ok, ok,)), (False, (all_not_ok,)), (False, (ok, all_not_ok, ok))): el = Element(validators=validators, validates_down='validators') valid = el.validate() assert valid == res assert bool(valid) is res assert el.valid is res assert el.all_valid is res element = None def got_element(item, data): assert item is element, repr(item) return True element = Element(validators=(got_element,), validates_down='validators') assert element.validate() def test_validator_return(): # Validator returns can be bool, int or None. class Bool(object): """A truthy object that does not implement __and__""" def __init__(self, val): self.val = val def __nonzero__(self): return bool(self.val) Validatable = Element.using(validates_down='validators') # mostly we care about allowing None for False true = lambda *a: True skip = lambda *a: Skip skipall = lambda *a: SkipAll one = lambda *a: 1 false = lambda *a: False skipallfalse = lambda *a: SkipAllFalse zero = lambda *a: 0 none = lambda *a: None no = lambda *a: Bool(False) for validator in true, one, skip, skipall: el = Validatable(validators=(validator,)) assert el.validate() for validator in false, zero, none, skipallfalse: el = Validatable(validators=(validator,)) assert not el.validate() for validator in [no]: el = Validatable(validators=(validator,)) assert_raises(TypeError, el.validate) def test_default_value(): el = Element() assert el.default_value is None el = Element(default='abc') assert el.default_value == 'abc' el = Element(default_factory=lambda x: 'def') assert el.default_value == 'def' el = Element(default='ghi', default_factory=lambda x: 'jkl') assert el.default_value == 'jkl' # a default_factory may reference el.default el = Element(default='mno', default_factory=lambda x: x.default) assert el.default_value == 'mno'
{ "repo_name": "jek/flatland", "path": "tests/schema/test_base.py", "copies": "4", "size": "6753", "license": "mit", "hash": -5125898719707476000, "line_mean": 27.020746888, "line_max": 79, "alpha_frac": 0.5782615134, "autogenerated": false, "ratio": 3.54302203567681, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.612128354907681, "avg_score": null, "num_lines": null }
from flatland import ( Form, Integer, String, ) from tests._util import eq_, requires_unicode_coercion @requires_unicode_coercion def test_from_object(): class Obj(object): def __init__(self, **kw): for (k, v) in kw.items(): setattr(self, k, v) class Schema(Form): x = String y = String from_obj = lambda obj, **kw: Schema.from_object(obj, **kw).value eq_(from_obj(None), dict(x=None, y=None)) eq_(from_obj([]), dict(x=None, y=None)) eq_(from_obj(123), dict(x=None, y=None)) eq_(from_obj(Obj()), dict(x=None, y=None)) eq_(from_obj(Obj(x='x!')), dict(x='x!', y=None)) eq_(from_obj(Obj(x='x!', y='y!')), dict(x='x!', y='y!')) eq_(from_obj(Obj(x='x!', z='z!')), dict(x='x!', y=None)) eq_(from_obj(Obj(x='x!', y='y!'), include=['x']), dict(x='x!', y=None)) eq_(from_obj(Obj(x='x!', y='y!'), omit=['y']), dict(x='x!', y=None)) eq_(from_obj(Obj(x='x!', z='z!'), rename={'z': 'y'}), dict(x='x!', y='z!')) eq_(from_obj(Obj(x='x!', z='z!'), rename={'z': 'x'}), dict(x='z!', y=None)) eq_(from_obj(Obj(x='x!', z='z!'), rename={'z': 'z'}), dict(x='x!', y=None)) eq_(from_obj(Obj(x='x!', z='z!'), rename={'x': 'z'}), dict(x=None, y=None)) @requires_unicode_coercion def test_composition(): class Inner(Form): sound = String.using(default='bleep') class Outer(Form): the_in = Inner way_out = String.using(default='mooooog') unset = {'the_in': {'sound': None}, 'way_out': None} wanted = {'the_in': {'sound': 'bleep'}, 'way_out': 'mooooog'} el = Outer.from_defaults() eq_(el.value, wanted) el = Outer() eq_(el.value, unset) el.set(wanted) eq_(el.value, wanted) @requires_unicode_coercion def test_inheritance_straight(): class Base(Form): base_member = String assert len(Base.field_schema) == 1 assert Base().keys() == ['base_member'] class Sub(Base): added_member = String assert len(Base.field_schema) == 1 assert Base().keys() == ['base_member'] assert len(Sub.field_schema) == 2 assert set(Sub().keys()) == set(['base_member', 'added_member']) @requires_unicode_coercion def test_inheritance_diamond(): class A(Form): a_member = String class B(Form): b_member = String class AB1(A, B): pass class BA1(B, A): pass for cls in AB1, BA1: assert len(cls.field_schema) == 2 assert set(cls().keys()) == set(['a_member', 'b_member']) class AB2(A, B): ab_member = String assert len(AB2.field_schema) == 3 assert set(AB2().keys()) == set(['a_member', 'b_member', 'ab_member']) class AB3(A, B): a_member = Integer assert len(AB3.field_schema) == 2 assert isinstance(AB3()['a_member'], Integer) class BA2(B, A): a_member = Integer b_member = Integer assert len(BA2.field_schema) == 2 assert isinstance(BA2()['a_member'], Integer) assert isinstance(BA2()['b_member'], Integer) class BA3(B, A): field_schema = [Integer.named('b_member')] a_member = Integer assert len(BA3.field_schema) == 2 assert isinstance(BA3()['a_member'], Integer) assert isinstance(BA3()['b_member'], Integer) class BA4(B, A): field_schema = [Integer.named('ab_member')] ab_member = String assert len(BA4.field_schema) == 3 assert isinstance(BA4()['ab_member'], String)
{ "repo_name": "jek/flatland", "path": "tests/schema/test_forms.py", "copies": "4", "size": "3558", "license": "mit", "hash": -6771176189061596000, "line_mean": 22.8791946309, "line_max": 74, "alpha_frac": 0.542158516, "autogenerated": false, "ratio": 3.0751944684528953, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00009726680284019065, "num_lines": 149 }
from flatland import String from flatland.out.generic import Markup from genshi.template.base import TemplateSyntaxError from tests._util import assert_raises from tests.markup._util import render_genshi_06 as render, need schema = String.named('element').using(default=u'val') @need('genshi_06') def setup(): pass def test_version_sensor(): from flatland.out import genshi_06 template = 'not a Genshi 0.6 template' assert_raises(RuntimeError, genshi_06.setup, template) def test_bogus_tags(): for snippet in [ u'<form:auto-name/>', u'<form:auto-value/>', u'<form:auto-domid/>', u'<form:auto-for/>', u'<form:auto-tabindex/>', ]: assert_raises(TemplateSyntaxError, render, snippet, 'xml', schema) def test_bogus_elements(): for snippet in [ u'<div form:with="snacks" />', u'<div form:set="snacks" />', ]: assert_raises(TemplateSyntaxError, render, snippet, 'xml', schema) def test_directive_ordering(): markup = """\ <form form:bind="form" py:if="True"> <input form:bind="form" py:if="False"/> <input py:with="foo=form" form:bind="foo" /> </form> """ expected = """\ <form name="element"> <input name="element" value="" /> </form>""" rendered = render(markup, 'xhtml', schema) assert rendered == expected def test_attribute_interpolation(): markup = """\ <input form:bind="form" form:auto-domid="${ON}" /> <input form:bind="form" form:auto-domid="o${N}" /> <input type="checkbox" value="${VAL}" form:bind="form" /> <input type="checkbox" value="v${A}l" form:bind="form" /> <input type="checkbox" value="${V}a${L}" form:bind="form" /> """ expected = """\ <input name="element" value="val" id="f_element" /> <input name="element" value="val" id="f_element" /> <input type="checkbox" value="val" name="element" checked="checked" /> <input type="checkbox" value="val" name="element" checked="checked" /> <input type="checkbox" value="val" name="element" checked="checked" />""" rendered = render(markup, 'xhtml', schema.from_defaults, ON=u'on', N=u'n', VAL=Markup(u'val'), V=u'v', A=u'a', L=u'l', ) assert rendered == expected def test_pruned_tag(): markup = """\ <form:with auto-name="off" py:if="False">xxx</form:with> """ expected = "" rendered = render(markup, 'xhtml', schema) assert rendered == expected def test_attributes_preserved(): markup = """\ <div xmlns:xyzzy="yo"> <input xyzzy:blat="pow" class="abc" form:bind="form" /> </div> """ expected = """\ <div xmlns:xyzzy="yo"> <input xyzzy:blat="pow" class="abc" name="element" value="" /> </div>""" rendered = render(markup, 'xhtml', schema) assert rendered == expected def test_attribute_removal(): markup = """\ <input type="checkbox" form:bind="form" value="xyzzy" checked="checked" /> """ expected = """\ <input type="checkbox" value="xyzzy" name="element" />""" rendered = render(markup, 'xhtml', schema) assert rendered == expected def test_stream_preserved(): markup = """\ <py:def function="stream_fn()"><b py:if="1">lumpy.</b></py:def> <py:def function="flattenable_fn()"><py:if test="1">flat.</py:if></py:def> <button form:bind="form"> <em>wow!</em> ${1 + 1} </button> <button form:bind="form">${stream_fn()}</button> <button form:bind="form">${flattenable_fn()}</button> """ expected = """\ <button name="element" value=""> <em>wow!</em> 2 </button> <button name="element" value=""><b>lumpy.</b></button> <button name="element" value="">flat.</button>""" rendered = render(markup, 'xhtml', schema) assert rendered == expected def test_tortured_select(): markup = """\ <select form:bind="form"> <option value="hit"/> <option value="miss"/> <option value="hit" form:bind=""/> <optgroup label="nested"> <option> h${"i"}t </option> <option value="miss"/> </optgroup> <optgroup label="nested"> <option value="hit" form:bind=""/> </optgroup> <option value="hit" py:if="True"> <option value="hit"> <option value="hit" form:bind="form" py:if="True"/> </option> </option> </select> """ expected = """\ <select name="element"> <option value="hit" selected="selected"></option> <option value="miss"></option> <option value="hit"></option> <optgroup label="nested"> <option selected="selected"> hit </option> <option value="miss"></option> </optgroup> <optgroup label="nested"> <option value="hit"></option> </optgroup> <option value="hit" selected="selected"> <option value="hit" selected="selected"> <option value="hit" selected="selected"></option> </option> </option> </select>""" factory = schema.using(default=u'hit').from_defaults rendered = render(markup, 'xhtml', factory) if rendered != expected: print "\n" + __name__ print "Expected:\n" + expected print "Got:\n" + rendered assert rendered == expected
{ "repo_name": "dag/flatland", "path": "tests/markup/test_genshi_06.py", "copies": "2", "size": "5138", "license": "mit", "hash": 3120819324881054000, "line_mean": 25.7604166667, "line_max": 74, "alpha_frac": 0.5980926431, "autogenerated": false, "ratio": 3.3981481481481484, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4996240791248149, "avg_score": null, "num_lines": null }
from flatland import String from tests.genshi._util import ( FilteredRenderTest, from_docstring, ) def simple_context(): schema = String.named(u'field1') el = schema() el.set_prefix(u'field1') return {'field1': el} class TestWith(FilteredRenderTest): @from_docstring(context_factory=simple_context) def test_tag_options(self): """ :: test nothing in context ${value_of('auto-domid')} ${value_of('auto-for')} ${value_of('auto-name')} ${value_of('auto-tabindex')} ${value_of('auto-value')} :: eq :: endtest :: test auto-domid <form:with auto-domid="auto"> ${value_of('auto-domid')} </form:with> :: eq Maybe :: endtest :: test auto-for <form:with auto-for="auto"> ${value_of('auto-for')} </form:with> :: eq Maybe :: endtest :: test auto-name <form:with auto-name="auto"> ${value_of('auto-name')} </form:with> :: eq Maybe :: endtest :: test auto-tabindex <form:with auto-tabindex="auto"> ${value_of('auto-tabindex')} </form:with> :: eq Maybe :: endtest :: test auto-value <form:with auto-value="auto"> ${value_of('auto-value')} </form:with> :: eq Maybe :: endtest :: test tabindex <div form:auto-tabindex="on"/> <form:with tabindex="1000"> <div form:auto-tabindex="on"/> </form:with> <div form:auto-tabindex="on"/> :: eq <div /> <div tabindex="1000" /> <div /> :: endtest :: test domid format <div form:bind="${field1.bind}" form:auto-domid="on" /> <form:with domid-format="id_%s_di"> <div form:bind="${field1.bind}" form:auto-domid="on" /> </form:with> <div form:bind="${field1.bind}" form:auto-domid="on" /> :: eq <div id="f_field1" /> <div id="id_field1_di" /> <div id="f_field1" /> :: endtest """ class TestSet(FilteredRenderTest): @from_docstring(context_factory=simple_context) def test_tag_options(self): """ :: test nothing in context ${value_of('auto-domid')} ${value_of('auto-for')} ${value_of('auto-name')} ${value_of('auto-tabindex')} ${value_of('auto-value')} :: eq :: endtest :: test auto-domid <form:set auto-domid="auto" /> ${value_of('auto-domid')} :: eq Maybe :: endtest :: test auto-for <form:set auto-for="auto" /> ${value_of('auto-for')} :: eq Maybe :: endtest :: test auto-name <form:set auto-name="auto" /> ${value_of('auto-name')} :: eq Maybe :: endtest :: test auto-tabindex <form:set auto-tabindex="auto" /> ${value_of('auto-tabindex')} :: eq Maybe :: endtest :: test auto-value <form:set auto-value="auto" /> ${value_of('auto-value')} :: eq Maybe :: endtest :: test tabindex <div form:auto-tabindex="on"/> <form:set tabindex="1000" /> <div form:auto-tabindex="on"/> <div form:auto-tabindex="on"/> :: eq <div /> <div tabindex="1000" /> <div tabindex="1001" /> :: endtest :: test domid format <div form:bind="${field1.bind}" form:auto-domid="on" /> <form:set domid-format="id_%s_di" /> <div form:bind="${field1.bind}" form:auto-domid="on" /> <div form:bind="${field1.bind}" form:auto-domid="on" /> :: eq <div id="f_field1" /> <div id="id_field1_di" /> <div id="id_field1_di" /> :: endtest """
{ "repo_name": "jek/flatland", "path": "tests/genshi/test_directives.py", "copies": "2", "size": "3024", "license": "mit", "hash": -356899102410342500, "line_mean": 16.0847457627, "line_max": 55, "alpha_frac": 0.6299603175, "autogenerated": false, "ratio": 2.61139896373057, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9240075254522815, "avg_score": 0.00025680534155110427, "num_lines": 177 }
from flatland import String, signals from flatland.schema.base import NotEmpty from flatland.validation import ( Converted, NoLongerThan, Present, ) from tests._util import eq_ def test_validator_validated(): sentinel = [] def listener(**kw): sentinel.append(kw) signals.validator_validated.connect(listener) schema = String.using(validators=[Present(), Converted(), NoLongerThan(5)]) el = schema() assert not el.validate() eq_(sentinel, [dict(sender=schema.validators[0], element=el, state=None, result=False)]) del sentinel[:] el = schema(value='abcd') assert el.validate() assert len(sentinel) == 3 assert sentinel[-1]['result'] del sentinel[:] el = schema('squiznart') assert not el.validate() assert len(sentinel) == 3 assert not sentinel[-1]['result'] s2 = String.using(optional=False) del sentinel[:] el = s2() assert not el.validate() eq_(sentinel, [dict(sender=NotEmpty, element=el, state=None, result=False)]) del sentinel[:] el = s2('squiznart') assert el.validate() eq_(sentinel, [dict(sender=NotEmpty, element=el, state=None, result=True)]) del listener del sentinel[:] el = schema('squiznart') assert not el.validate() assert not sentinel signals.validator_validated._clear_state()
{ "repo_name": "jek/flatland", "path": "tests/validation/test_signals.py", "copies": "2", "size": "1556", "license": "mit", "hash": -1424616242606183200, "line_mean": 24.5081967213, "line_max": 55, "alpha_frac": 0.5719794344, "autogenerated": false, "ratio": 4.2168021680216805, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 61 }
from flatland import String, signals from flatland.schema.base import NotEmpty from flatland.validation import ( Converted, NoLongerThan, Present, ) def test_validator_validated(): sentinel = [] def listener(sender, **kw): kw['sender'] = sender sentinel.append(kw) signals.validator_validated.connect(listener) schema = String.using(validators=[Present(), Converted(), NoLongerThan(5)]) el = schema() assert not el.validate() assert sentinel == [dict(sender=schema.validators[0], element=el, state=None, result=False)] del sentinel[:] el = schema(value='abcd') assert el.validate() assert len(sentinel) == 3 assert sentinel[-1]['result'] del sentinel[:] el = schema('squiznart') assert not el.validate() assert len(sentinel) == 3 assert not sentinel[-1]['result'] s2 = String.using(optional=False) del sentinel[:] el = s2() assert not el.validate() assert sentinel == [dict(sender=NotEmpty, element=el, state=None, result=False)] del sentinel[:] el = s2('squiznart') assert el.validate() assert sentinel == [dict(sender=NotEmpty, element=el, state=None, result=True)] signals.validator_validated._clear_state()
{ "repo_name": "mbr/flatland0", "path": "tests/validation/test_signals.py", "copies": "1", "size": "1454", "license": "mit", "hash": 974699609422148000, "line_mean": 25.4363636364, "line_max": 57, "alpha_frac": 0.568088033, "autogenerated": false, "ratio": 4.289085545722714, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 55 }
from flatland import Unspecified class AttributeDict(dict): """Dict exposing keys as instance properties. For demonstrating Form.from_object and Form.update_object """ def __getattr__(self, key, default=Unspecified): if key in self: return self[key] up = super(AttributeDict, self).__getattr__ if default is Unspecified: return up(key) else: return up(key, default) def __setattr__(self, key, value): if key not in self: raise AttributeError() self['key'] = value def error_filter_factory(class_='error'): """Returns an HTML generation filter annotating field CSS class on error. :param class: The css class to apply in case of validation error on a field. Default: 'error' """ def error_filter(tagname, attributes, contents, context, bind): if bind is not None and bind.errors: current_css_classes = attributes.get('class', '').split() attributes['class'] = ' '.join(current_css_classes + [class_]) return contents return error_filter class AttributeCSSClassFilter(object): """Markup generation filter. :param class: CSS class to append when *predicate* is True. :param tags: Tags types the filter applies to (e.g. (input, textarea). :param predicate: One-argument callable that decides whether or not the filter gets applied. Default: bool(element.errors) """ @classmethod def _has_error(cls, bind): return bind.errors def __init__(self, class_='error', tags=None, predicate=None): self.class_ = class_ self.tags = tags self.predicate = predicate or AttributeCSSClassFilter._has_error def __call__(self, tagname, attributes, contents, context, bind): if bind is not None and self.predicate(bind): current_css_classes = attributes.get('class', '').split() attributes['class'] = ' '.join(current_css_classes + [class_]) return contents
{ "repo_name": "scottynomad/flatland-europython-2010", "path": "examples/util.py", "copies": "2", "size": "2102", "license": "mit", "hash": 7995692153658358000, "line_mean": 30.3731343284, "line_max": 77, "alpha_frac": 0.6165556613, "autogenerated": false, "ratio": 4.3429752066115705, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5959530867911571, "avg_score": null, "num_lines": null }
from flatland.out.genshi.filter import flatland_filter ___all__ = ['flatland_filter', 'setup'] def setup(template, use_version=None): """Register the flatland directives with a template. :param template: a `Template` instance """ if use_version is None: use_version = 6 if hasattr(template, 'add_directives') else 5 if use_version == 6: from flatland.out.genshi_06 import setup setup(template) else: install_element_mixin() template.filters.append(flatland_filter) def install_element_mixin(): from flatland.out.genshi.elements import GenshiAccessMixin from flatland.schema.base import Element if GenshiAccessMixin in Element.__bases__: return assert Element.__bases__ != (object,) Element.__bases__ += (GenshiAccessMixin,) def uninstall_element_mixin(): from flatland.out.genshi.elements import GenshiAccessMixin from flatland.schema.base import Element if GenshiAccessMixin not in Element.__bases__: return bases = list(Element.__bases__) bases.remove(GenshiAccessMixin) Element.__bases__ = tuple(bases)
{ "repo_name": "dag/flatland", "path": "flatland/out/genshi/__init__.py", "copies": "2", "size": "1139", "license": "mit", "hash": 4213247118082257400, "line_mean": 28.9736842105, "line_max": 69, "alpha_frac": 0.6830553117, "autogenerated": false, "ratio": 3.9411764705882355, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 38 }
from flatland.schema import base # FIXME: # unicode(wrapped) should probably eval to either the fq_name or the # result of a configured formatting function. clean up the set_prefix # bandaid and make it do this. # # FIXME: continue to simplify the wrapper. this is all hella bogus :( class GenshiAccessMixin(object): def set_prefix(self, prefix): self._genshi_prefix = prefix @property def bind(self): return WrappedElement(self) @property def binds(self): return dict((child.name, WrappedElement(child)) for child in self.children) def get_prefix(element): if hasattr(element, '_genshi_prefix'): return element._genshi_prefix else: for element in element.parents: if hasattr(element, '_genshi_prefix'): return element._genshi_prefix return None class WrappedElement(unicode): """Wrap an Element into something Genshi expressions can use. Genshi AST transformations don't play well with rich objects like Elements. Anything iterable will iterate on insert into the template, even if it defines a __unicode__. Normal objects defining __getitem__ or __getattr__ or even __getattribute__ confuse Genshi's dotted expression adapter. ``unicode``-derived objects are immune from these problems. These wrappers will str() as Genshi-evalable string. """ def __new__(cls, element): return unicode.__new__(cls, cls._format(element)) def __init__(self, element): self.element = element @staticmethod def _format(element): prefix = get_prefix(element) path = element.fq_name() if not prefix: root = element.root if root.name is None: prefix = u'form' else: prefix = u'forms.%s' % (root.name,) return u"%s.el(%s)" % (prefix, repr(path).decode('raw_unicode_escape')) def __getitem__(self, key): if isinstance(key, str): try: key = key.decode('ascii') except UnicodeError: raise KeyError(key) item = self.element._index(key) if isinstance(item, base.Element): return WrappedElement(item) else: return item def __getattr__(self, attribute): return getattr(self.element, attribute) def __unicode__(self): return self._format(self.element) def __iter__(self): return (WrappedElement(child) if isinstance(child, base.Element) else child for child in self.element.children)
{ "repo_name": "dag/flatland", "path": "flatland/out/genshi/elements.py", "copies": "2", "size": "2673", "license": "mit", "hash": 1643196010973025300, "line_mean": 30.0813953488, "line_max": 79, "alpha_frac": 0.607557052, "autogenerated": false, "ratio": 4.318255250403877, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5925812302403877, "avg_score": null, "num_lines": null }
from flatland.util.signals import ( ANY, ANY_ID, NamedSignal, Namespace, Signal, receiver_connected, ) from tests._util import eq_, assert_raises def test_meta_connect(): sentinel = [] def meta_received(**kw): sentinel.append(kw) assert not receiver_connected.receivers receiver_connected.connect(meta_received) assert not sentinel def receiver(**kw): pass sig = Signal() sig.connect(receiver) eq_(sentinel, [dict(sender=sig, receiver_arg=receiver, sender_arg=ANY, weak_arg=True)]) receiver_connected._clear_state() def test_meta_connect_failure(): def meta_received(**kw): raise TypeError('boom') assert not receiver_connected.receivers receiver_connected.connect(meta_received) def receiver(**kw): pass sig = Signal() assert_raises(TypeError, sig.connect, receiver) assert not sig.receivers assert not sig._by_receiver eq_(sig._by_sender, {ANY_ID: set()}) receiver_connected._clear_state() def test_singletons(): ns = Namespace() assert not ns.signals s1 = ns.signal('abc') assert s1 is ns.signal('abc') assert s1 is not ns.signal('def') assert 'abc' in ns.signals # weak by default, already out of scope assert 'def' not in ns.signals del s1 assert 'abc' not in ns.signals def test_weak_receiver(): sentinel = [] def received(**kw): sentinel.append(kw) sig = Signal() sig.connect(received, weak=True) del received assert not sentinel sig.send() assert not sentinel assert not sig.receivers values_are_empty_sets_(sig._by_receiver) values_are_empty_sets_(sig._by_sender) def test_strong_receiver(): sentinel = [] def received(**kw): sentinel.append(kw) fn_id = id(received) sig = Signal() sig.connect(received, weak=False) del received assert not sentinel sig.send() assert sentinel eq_([id(fn) for fn in sig.receivers.values()], [fn_id]) def test_filtered_receiver(): sentinel = [] def received(sender): sentinel.append(sender) sig = Signal() sig.connect(received, 123) assert not sentinel sig.send() assert not sentinel sig.send(123) assert sentinel == [123] sig.send() assert sentinel == [123] def test_filtered_receiver_weakref(): sentinel = [] def received(sender): sentinel.append(sender) class Object(object): pass obj = Object() sig = Signal() sig.connect(received, obj) assert not sentinel sig.send(obj) assert sentinel == [obj] del sentinel[:] del obj # general index isn't cleaned up assert sig.receivers # but receiver/sender pairs are values_are_empty_sets_(sig._by_receiver) values_are_empty_sets_(sig._by_sender) def test_no_double_send(): sentinel = [] def received(sender): sentinel.append(sender) sig = Signal() sig.connect(received, 123) sig.connect(received) assert not sentinel sig.send() assert sentinel == [None] sig.send(123) assert sentinel == [None, 123] sig.send() assert sentinel == [None, 123, None] def test_has_receivers(): received = lambda sender: None sig = Signal() assert not sig.has_receivers_for(None) assert not sig.has_receivers_for(ANY) sig.connect(received, 'xyz') assert not sig.has_receivers_for(None) assert not sig.has_receivers_for(ANY) assert sig.has_receivers_for('xyz') class Object(object): pass o = Object() sig.connect(received, o) assert sig.has_receivers_for(o) del received assert not sig.has_receivers_for('xyz') assert list(sig.receivers_for('xyz')) == [] assert list(sig.receivers_for(o)) == [] sig.connect(lambda sender: None, weak=False) assert sig.has_receivers_for('xyz') assert sig.has_receivers_for(o) assert sig.has_receivers_for(None) assert sig.has_receivers_for(ANY) assert sig.has_receivers_for('xyz') def test_instance_doc(): sig = Signal(doc='x') assert sig.__doc__ == 'x' sig = Signal('x') assert sig.__doc__ == 'x' def test_named_signals(): sig = NamedSignal('squiznart') assert 'squiznart' in repr(sig) def values_are_empty_sets_(dictionary): for val in dictionary.itervalues(): eq_(val, set())
{ "repo_name": "dag/flatland", "path": "tests/test_signals.py", "copies": "2", "size": "4505", "license": "mit", "hash": -8531077717117772000, "line_mean": 19.8564814815, "line_max": 59, "alpha_frac": 0.6199778024, "autogenerated": false, "ratio": 3.732394366197183, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00013227513227513228, "num_lines": 216 }
from flatlib.datetime import Datetime from flatlib.geopos import GeoPos from flatlib.chart import Chart from flatlib import const, aspects ASPECT_LABELS = {0: 'conjunction', 60: 'sextile', 90: 'square', 120: 'trine', 180: 'opposition'} LIST_PLANETS = const.LIST_SEVEN_PLANETS + [const.URANUS, const.NEPTUNE, const.PLUTO, const.ASC] class Person: """Wrapper for API query input, person and birth info""" def __init__(self, name, birthdate, birth_lat, birth_lon, birth_utc_offset): self.name = name self.birthdate = birthdate self.birth_lat = birth_lat self.birth_lon = birth_lon self.birth_utc_offset = birth_utc_offset def birth_date_str(self): return "{:%Y/%m/%d}".format(self.birthdate) def birth_time_str(self): return "{:%H:%M}".format(self.birthdate) def __repr__(self): return "<Person {} Born {:%y-%m-%d}>".format(self.name, self.birthdate) def __eq__(self, other): return self.name == other.name and self.birthdate == other.birthdate def __hash__(self): return hash("{}_{}".format(self.name, self.birthdate.timestamp())) class NatalChart: """Calculator and wrapper for results of natal charts, per Person""" def __init__(self, person): self.planets = {} self.houses = {} self.person = person self.date = Datetime(person.birth_date_str(), person.birth_time_str(), person.birth_utc_offset) self.pos = GeoPos(person.birth_lat, person.birth_lon) self.chart = Chart(self.date, self.pos, IDs=const.LIST_OBJECTS, hsys=const.HOUSES_PLACIDUS) for body in LIST_PLANETS: self.planets[body] = NatalPlanet(self.chart, body) for house in const.LIST_HOUSES: self.houses[house] = NatalHouse(self.chart, house) def to_dict(self): output = { 'person': { 'name': self.person.name, 'birthdate': self.person.birthdate.timestamp(), 'birth_geo': [self.person.birth_lat, self.person.birth_lon], 'birth_utc_offset': self.person.birth_utc_offset }, 'chart': { 'planets': {self.planets[k].name: self.planets[k].to_dict() for k in self.planets}, 'houses': {k: self.houses[k].to_dict() for k in self.houses} } } return output class NatalPlanet: """Positioning for planets""" def __init__(self, chart, body): self.planet = chart.get(body) self.house = chart.houses.getObjectHouse(self.planet).id self.aspects = [] self.name = body if body != 'Asc' else 'Ascendant' for house_id in const.LIST_HOUSES: house = chart.get(house_id) if house.sign == self.planet.sign: self.house = house_id break for other_body in LIST_PLANETS: other_planet = chart.get(other_body) aspect = aspects.getAspect(self.planet, other_planet, const.MAJOR_ASPECTS) if aspect.type != -1: aspect_part = aspect.active if aspect.active.id != body else aspect.passive if aspect_part.id not in LIST_PLANETS: # don't care about Lilith and nodes continue if aspect.orb > 10: # maybe #TODO: use different values per type? continue self.aspects.append({ 'first': self.name, 'second': aspect_part.id, 'type': aspect.type, 'type_name': ASPECT_LABELS[aspect.type], 'orb': aspect.orb }) def to_dict(self): obj = { 'planet': self.planet.__dict__, 'house': self.house, } if self.aspects: obj['aspects'] = [x for x in self.aspects] return obj def __repr__(self): return "<Natal Planet {} in {}>".format(self.planet, self.house) class NatalHouse: """Whose who for the houses at moment of birth""" def __init__(self, chart, body): self.house = chart.get(body) def to_dict(self): return self.house.__dict__ def __repr__(self): return "<Natal House {}>".format(self.house)
{ "repo_name": "jc4p/natal-charts", "path": "api/models.py", "copies": "1", "size": "3858", "license": "mit", "hash": -4227777378254148600, "line_mean": 31.1583333333, "line_max": 99, "alpha_frac": 0.6314152411, "autogenerated": false, "ratio": 3.2230576441102756, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43544728852102754, "avg_score": null, "num_lines": null }
from flatlib import const, aspects from models import * from datetime import timedelta from flask import make_response, request, current_app from functools import update_wrapper def get_chart_aspects_for_planet(planetName, baseChart, chart): planet = baseChart.get(planetName) res = [] for other_body in LIST_PLANETS: other_planet = chart.get(other_body) aspect = aspects.getAspect(planet, other_planet, const.MAJOR_ASPECTS) if aspect.type != -1: aspect_part = aspect.active if aspect.active.id != planetName else aspect.passive if aspect_part.id not in LIST_PLANETS: # don't care about Lilith and nodes continue if not aspect.inOrb(planet.id): continue if not aspect.mutualAspect(): continue if planetName in ['Sun', 'Moon', 'Asc']: if aspect.orb > 2.5: continue elif aspect.orb > 2: continue res.append({ 'first': planetName, 'second': aspect_part.id, 'type': aspect.type, 'type_name': ASPECT_LABELS[aspect.type], 'orb': aspect.orb }) return res def crossdomain(origin=None, methods=None, headers=None, max_age=21600, attach_to_all=True, automatic_options=True): if methods is not None: methods = ', '.join(sorted(x.upper() for x in methods)) if headers is not None and not isinstance(headers, str): headers = ', '.join(x.upper() for x in headers) if not isinstance(origin, str): origin = ', '.join(origin) if isinstance(max_age, timedelta): max_age = max_age.total_seconds() def get_methods(): if methods is not None: return methods options_resp = current_app.make_default_options_response() return options_resp.headers['allow'] def decorator(f): def wrapped_function(*args, **kwargs): if automatic_options and request.method == 'OPTIONS': resp = current_app.make_default_options_response() else: resp = make_response(f(*args, **kwargs)) if not attach_to_all and request.method != 'OPTIONS': return resp h = resp.headers h['Access-Control-Allow-Origin'] = origin h['Access-Control-Allow-Methods'] = get_methods() h['Access-Control-Max-Age'] = str(max_age) if headers is not None: h['Access-Control-Allow-Headers'] = headers return resp f.provide_automatic_options = False return update_wrapper(wrapped_function, f) return decorator
{ "repo_name": "jc4p/natal-charts", "path": "api/utils.py", "copies": "1", "size": "2777", "license": "mit", "hash": -21241101552426204, "line_mean": 34.1518987342, "line_max": 93, "alpha_frac": 0.5761613252, "autogenerated": false, "ratio": 4.114074074074074, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008573480563784899, "num_lines": 79 }
from flatlib import const from flatlib.tools import planetarytime from flatlib.dignities import essential from flatlib.tools import arabicparts # List of dignities DIGNITY_LIST = [ 'ruler', 'exalt', 'dayTrip', 'nightTrip', 'partTrip', 'term', 'face' ] # List of objects OBJECT_LIST = const.LIST_SEVEN_PLANETS def newRow(): """ Returns a new Almutem table row. """ row = {} for obj in OBJECT_LIST: row[obj] = { 'string': '', 'score': 0 } return row # Computes the topical almuten (TA) table. def computeTA(chart, TA): almutems = {} # SECOND HOUSE, # source: Omar of Tiberias - Three Books on Nativities, p. 57; Persian Nativities II, p. 52 if TA == "TA_2H": TA_LIST = [ chart.getHouse(const.HOUSE2) ] TA_LIST.extend( [v for k, v in chart.objects.getObjectsInHouse(chart.getHouse(const.HOUSE2)).content.items()]) TA_LIST.extend( [chart.getObject(essential.ruler(chart.getHouse(const.HOUSE2).sign)), arabicparts.getPart(arabicparts.PARS_SUBSTANCE, chart), chart.getObject(essential.ruler(arabicparts.getPart(arabicparts.PARS_SUBSTANCE, chart).sign)), chart.getObject(const.JUPITER), chart.getObject(const.PARS_FORTUNA), chart.getObject(essential.ruler(chart.getObject(const.PARS_FORTUNA).sign)) ]) # THIRD HOUSE, # source: Omar of Tiberias - Three Books on Nativities, p. 58-59; Persian Nativities II, p. 53 if TA == "TA_3H": TA_LIST = [ chart.getHouse(const.HOUSE3) ] TA_LIST.extend( [v for k, v in chart.objects.getObjectsInHouse(chart.getHouse(const.HOUSE3)).content.items()]) TA_LIST.extend( [chart.getObject(essential.ruler(chart.getHouse(const.HOUSE3).sign)), arabicparts.getPart(arabicparts.PARS_BROTHERS, chart), chart.getObject(essential.ruler(arabicparts.getPart(arabicparts.PARS_BROTHERS, chart).sign)), chart.getObject(const.MARS), chart.getObject(essential.dayTrip(chart.getObject(const.MARS).sign)), chart.getObject(essential.nightTrip(chart.getObject(const.MARS).sign)), chart.getObject(essential.partTrip(chart.getObject(const.MARS).sign)) ]) # 4th HOUSE, # Status of father - source: Persian Nativities II, p. 204 if TA == "TA_4H_Father_Status": TA_LIST = [ chart.getHouse(const.HOUSE4) ] TA_LIST.extend( [v for k, v in chart.objects.getObjectsInHouse(chart.getHouse(const.HOUSE4)).content.items()]) TA_LIST.extend( [chart.getObject(essential.ruler(chart.getHouse(const.HOUSE4).sign)), arabicparts.getPart(arabicparts.PARS_FATHER, chart), chart.getObject(essential.ruler(arabicparts.getPart(arabicparts.PARS_FATHER, chart).sign)), chart.getObject(const.SATURN), chart.getObject(const.SUN), chart.getObject(const.SYZYGY), ]) # Father - source: JOHANNES SCHOENER, p. 51 if TA == "TA_4H_Father_SCHOENER": TA_LIST = [ chart.getHouse(const.HOUSE4) ] TA_LIST.extend( [chart.getObject(essential.ruler(chart.getHouse(const.HOUSE4).sign)), chart.getObject(const.SUN), chart.getObject(essential.ruler(chart.getObject(const.SUN))), arabicparts.getPart(arabicparts.PARS_FATHER, chart), chart.getObject(essential.ruler(arabicparts.getPart(arabicparts.PARS_FATHER, chart).sign)), ]) if chart.isDiurnal(): TA_LIST.extend([chart.getObject(essential.dayTrip(chart.getHouse(const.HOUSE4).sign]))) else: TA_LIST.extend([chart.getObject(essential.nightTrip(chart.getHouse(const.HOUSE4).sign]))) # 10th HOUSE, # Status of mother - source: Persian Nativities II, p. 51 if TA == "TA_4H_Mother_Status": TA_LIST = [ chart.getHouse(const.HOUSE10) ] TA_LIST.extend( [v for k, v in chart.objects.getObjectsInHouse(chart.getHouse(const.HOUSE10)).content.items()]) TA_LIST.extend( [chart.getObject(essential.ruler(chart.getHouse(const.HOUSE10).sign)), arabicparts.getPart(arabicparts.PARS_MOTHER, chart), chart.getObject(essential.ruler(arabicparts.getPart(arabicparts.PARS_MOTHER, chart).sign)), chart.getObject(const.MOON), chart.getObject(const.VENUS), chart.getObject(const.SYZYGY), ]) # And many more... for hyleg in TA_LIST: row = newRow() digInfo = essential.getInfo(hyleg.sign, hyleg.signlon) # Add the scores of each planet where hyleg has dignities for dignity in DIGNITY_LIST: objID = digInfo[dignity] if objID: score = essential.SCORES[dignity] row[objID]['string'] += '+%s' % score row[objID]['score'] += score almutems[hyleg.id] = row # Compute scores scores = newRow() for _property, _list in almutems.items(): for objID, values in _list.items(): scores[objID]['string'] += values['string'] scores[objID]['score'] += values['score'] almutems['Score'] = scores return almutems
{ "repo_name": "flatangle/flatlib", "path": "contrib/topical_almuten.py", "copies": "1", "size": "5509", "license": "mit", "hash": -5697886786368102000, "line_mean": 35.9731543624, "line_max": 107, "alpha_frac": 0.6008349973, "autogenerated": false, "ratio": 3.2178738317757007, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9234971858211314, "avg_score": 0.01674739417287737, "num_lines": 149 }
from .flattened import flatten from datetime import date def year_plus_term(year, term): return int(f'{year}{term}') def find_terms_for_year(year, now=date.today()): current_month = now.month current_year = now.year all_terms = [1, 2, 3, 4, 5] limited_terms = [1, 2, 3] # St. Olaf publishes initial Fall, Interim, and Spring data in April # of each year. Full data is published by August. if year == current_year: if current_month < 3: return [] elif current_month <= 7: return [year_plus_term(year, term) for term in limited_terms] else: return [year_plus_term(year, term) for term in all_terms] elif year > current_year: return [] else: return [year_plus_term(year, term) for term in all_terms] def find_terms(start_year=None, end_year=None, this_year=False, now=date.today()): start_year = start_year or 1994 end_year = end_year or now.year current_year = end_year if end_year is not start_year else end_year + 1 current_month = now.month if this_year: start_year = current_year - 1 if current_month <= 7 else current_year if current_month >= 3: current_year = current_year + 1 most_years = range(start_year, current_year) term_list = [find_terms_for_year(year, now=now) for year in most_years] # Sort the list of terms to 20081, 20082, 20091 # (instead of 20081, 20091, 20082) term_list = sorted(term_list) return term_list def get_years_and_terms(terms_and_years): terms_and_years = flatten([item.split(' ') if type(item) is str else item for item in terms_and_years]) years, terms = [], [] for item in terms_and_years: str_item = str(item) if len(str_item) is 4: years.append(item) elif len(str_item) is 5: terms.append(item) return years, terms def calculate_terms(terms_and_years, now=date.today()): years, terms = get_years_and_terms(terms_and_years) if (not terms) and (not years): calculated_terms = find_terms(now=now) elif 0 in years: calculated_terms = find_terms(this_year=True, now=now) else: calculated_terms = terms + \ [find_terms(start_year=year, end_year=year, now=now) for year in years] return flatten(calculated_terms)
{ "repo_name": "StoDevX/course-data-tools", "path": "lib/calculate_terms.py", "copies": "1", "size": "2459", "license": "mit", "hash": 7249287749253165000, "line_mean": 28.6265060241, "line_max": 83, "alpha_frac": 0.6030906873, "autogenerated": false, "ratio": 3.463380281690141, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9565028019913283, "avg_score": 0.00028858981537164147, "num_lines": 83 }
from .flatten import InputContour, OutputContour from .exceptions import ( InvalidSubjectContourError, InvalidClippingContourError, ExecutionError) import pyclipper """ General Suggestions: - Contours should only be sent here if they actually overlap. This can be checked easily using contour bounds. - Only perform operations on closed contours. - contours must have an on curve point - some kind of a log """ _operationMap = { "union": pyclipper.CT_UNION, "intersection": pyclipper.CT_INTERSECTION, "difference": pyclipper.CT_DIFFERENCE, "xor": pyclipper.CT_XOR, } _fillTypeMap = { "evenOdd": pyclipper.PFT_EVENODD, "nonZero": pyclipper.PFT_NONZERO, # we keep the misspelling for compatibility with earlier versions "noneZero": pyclipper.PFT_NONZERO, } def clipExecute(subjectContours, clipContours, operation, subjectFillType="nonZero", clipFillType="nonZero"): pc = pyclipper.Pyclipper() for i, subjectContour in enumerate(subjectContours): try: pc.AddPath(subjectContour, pyclipper.PT_SUBJECT) except pyclipper.ClipperException: # skip invalid paths with no area if pyclipper.Area(subjectContour) != 0: raise InvalidSubjectContourError("contour %d is invalid for clipping" % i) for j, clipContour in enumerate(clipContours): try: pc.AddPath(clipContour, pyclipper.PT_CLIP) except pyclipper.ClipperException: # skip invalid paths with no area if pyclipper.Area(clipContour) == 0: raise InvalidClippingContourError("contour %d is invalid for clipping" % j) bounds = pc.GetBounds() if (bounds.bottom, bounds.left, bounds.top, bounds.right) == (0, 0, 0, 0): # do nothing if there are no paths return [] try: solution = pc.Execute(_operationMap[operation], _fillTypeMap[subjectFillType], _fillTypeMap[clipFillType]) except pyclipper.ClipperException as exc: raise ExecutionError(exc) return [[tuple(p) for p in path] for path in solution] def _performOperation(operation, subjectContours, clipContours, outPen): # prep the contours subjectInputContours = [InputContour(contour) for contour in subjectContours if contour and len(contour) > 1] clipInputContours = [InputContour(contour) for contour in clipContours if contour and len(contour) > 1] inputContours = subjectInputContours + clipInputContours resultContours = clipExecute([subjectInputContour.originalFlat for subjectInputContour in subjectInputContours], [clipInputContour.originalFlat for clipInputContour in clipInputContours], operation, subjectFillType="nonZero", clipFillType="nonZero") # convert to output contours outputContours = [OutputContour(contour) for contour in resultContours] # re-curve entire contour for inputContour in inputContours: for outputContour in outputContours: if outputContour.final: continue if outputContour.reCurveFromEntireInputContour(inputContour): # the input is expired if a match was made, # so stop passing it to the outputs break # curve fit for outputContour in outputContours: outputContour.reCurveSubSegments(inputContours) # output the results for outputContour in outputContours: outputContour.drawPoints(outPen) return outputContours class BooleanOperationManager: @staticmethod def union(contours, outPen): return _performOperation("union", contours, [], outPen) @staticmethod def difference(subjectContours, clipContours, outPen): return _performOperation("difference", subjectContours, clipContours, outPen) @staticmethod def intersection(subjectContours, clipContours, outPen): return _performOperation("intersection", subjectContours, clipContours, outPen) @staticmethod def xor(subjectContours, clipContours, outPen): return _performOperation("xor", subjectContours, clipContours, outPen) @staticmethod def getIntersections(contours): from .flatten import _scalePoints, inverseClipperScale # prep the contours inputContours = [InputContour(contour) for contour in contours if contour and len(contour) > 1] inputFlatPoints = set() for contour in inputContours: inputFlatPoints.update(contour.originalFlat) resultContours = clipExecute( [inputContour.originalFlat for inputContour in inputContours], [], "union", subjectFillType="nonZero", clipFillType="nonZero") resultFlatPoints = set() for contour in resultContours: resultFlatPoints.update(contour) intersections = resultFlatPoints - inputFlatPoints return _scalePoints(intersections, inverseClipperScale)
{ "repo_name": "typemytype/booleanOperations", "path": "Lib/booleanOperations/booleanOperationManager.py", "copies": "1", "size": "5047", "license": "mit", "hash": 4321527657831709700, "line_mean": 36.9473684211, "line_max": 116, "alpha_frac": 0.6865464632, "autogenerated": false, "ratio": 3.983425414364641, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5169971877564641, "avg_score": null, "num_lines": null }
from flatten import * POS_SIZE = 2**23 - 1 NEG_SIZE = -2**23 OPTIMIZE = True OPTIMIZERS = { 'set': 'SET', 'setglobal': 'SET_GLOBAL', 'local': 'SET_LOCAL', 'get': 'GET', 'getglobal': 'GET_GLOBAL', 'return': 'RETURN', 'recurse': 'RECURSE', 'drop': 'DROP', 'dup': 'DUP', '[]': 'NEW_LIST', '{}': 'NEW_DICT', 'swap': 'SWAP', 'rot': 'ROT', 'over': 'OVER', 'pop-from': 'POP_FROM', 'push-to': 'PUSH_TO', 'push-through': 'PUSH_THROUGH', 'has': 'HAS_DICT', 'get-from': 'GET_DICT', 'set-to': 'SET_DICT', 'raise': 'RAISE', 'reraise': 'RERAISE', 'call': 'CALL', } ARGED_OPT = set('SET SET_LOCAL SET_GLOBAL GET GET_GLOBAL'.split()) positional_instructions = set('JMP JMPZ LABDA JMPEQ JMPNE ENTER_ERRHAND'.split()) def convert(filename, flat): bytecode = [SingleInstruction('SOURCE_FILE', String(None, '"' + filename))] for k in flat: if isinstance(k, SingleInstruction): bytecode.append(k) elif isinstance(k, Code): for w in k.words: if isinstance(w, ProperWord): if OPTIMIZE and w.value in OPTIMIZERS: if OPTIMIZERS[w.value] in ARGED_OPT: if bytecode and bytecode[-1].opcode == 'PUSH_LITERAL' and isinstance(bytecode[-1].ref, Ident): s = bytecode.pop().ref else: bytecode.append(SingleInstruction('PUSH_WORD', w)) continue else: s = 0 bytecode.append(SingleInstruction(OPTIMIZERS[w.value], s)) elif w.value == 'for': mstart = Marker() mend = Marker() bytecode.extend([ mstart, SingleInstruction('DUP', 0), SingleInstruction('JMPZ', mend), SingleInstruction('CALL', 0), SingleInstruction('JMP', mstart), mend, SingleInstruction('DROP', 0) ]) elif w.value == '(:split:)': mparent = Marker() mchild = Marker() bytecode.extend([ SingleInstruction('LABDA', mparent), SingleInstruction('JMP', mchild), mparent, SingleInstruction('RETURN', 0), mchild, ]) elif w.value == '\xce\xbb': #U+03BB GREEK SMALL LETTER LAMDA for i in range(len(bytecode) - 1, -1, -1): l = bytecode[i] if isinstance(l, SingleInstruction) and l.opcode == 'PUSH_WORD' and l.ref.value == ';': l.opcode = 'LABDA' l.ref = Marker() bytecode.extend([ SingleInstruction('RETURN', 0), l.ref, ]) break else: raise DejaSyntaxError('Inline lambda without closing semi-colon.') elif '!' in w.value: if w.value.startswith('!'): w.value = 'eva' + w.value if w.value.endswith('!'): w.value = w.value[:-1] args = w.value.split('!') base = args.pop(0) bytecode.extend(SingleInstruction('PUSH_LITERAL', x) for x in reversed(args)) bytecode.extend([ SingleInstruction('PUSH_WORD', base), SingleInstruction('GET_DICT', 0), SingleInstruction('CALL', 0) ]) else: bytecode.append(SingleInstruction('PUSH_WORD', w)) elif isinstance(w, Number) and w.value.is_integer() and w.value <= POS_SIZE and w.value >= NEG_SIZE: bytecode.append(SingleInstruction('PUSH_INTEGER', int(w.value))) else: bytecode.append(SingleInstruction('PUSH_LITERAL', w)) elif isinstance(k, Marker): bytecode.append(k) elif isinstance(k, GoTo): bytecode.append(SingleInstruction('JMP', k.index)) elif isinstance(k, Branch): bytecode.append(SingleInstruction('JMPZ', k.index)) elif isinstance(k, LabdaNode): bytecode.append(SingleInstruction('LABDA', k.index)) bytecode.append(SingleInstruction('RETURN', 0)) return bytecode def is_return(node): return isinstance(node, SingleInstruction) and node.opcode == 'RETURN' def is_jump_to(node, marker): return isinstance(node, SingleInstruction) and node.opcode == 'JMP' and node.ref is marker def is_pass(node): return isinstance(node, SingleInstruction) and node.opcode == 'PUSH_WORD' and (node.ref == 'pass' or (isinstance(node.ref, ProperWord) and node.ref.value == 'pass')) def is_linenr(node): return isinstance(node, SingleInstruction) and node.opcode == 'LINE_NUMBER' def get(l, i): try: return l[i] except IndexError: return None def optimize(flattened): #optimize away superfluous RETURN statements for i, instruction in reversed(list(enumerate(flattened))): if (is_return(instruction) and (is_return(get(flattened, i + 1)) or (isinstance(get(flattened, i + 1), Marker) and is_return(get(flattened, i + 2)))) or isinstance(get(flattened, i + 1), Marker) and is_jump_to(instruction, get(flattened, i + 1)) or isinstance(get(flattened, i + 2), Marker) and isinstance(get(flattened, i + 1), Marker) and is_jump_to(instruction, get(flattened, i + 2)) or is_pass(instruction) or is_linenr(instruction) and is_linenr(get(flattened, i + 1)) ): flattened.pop(i) return flattened def refine(flattened): #removes all markers and replaces them by indices #first pass: fill dictionary memo = {} i = 0 while i < len(flattened): item = flattened[i] if isinstance(item, Marker): memo[item] = i del flattened[i] else: i += 1 #second pass: change all goto and branches for i, item in enumerate(flattened): if item.opcode in positional_instructions: item.ref = memo[item.ref] - i return flattened
{ "repo_name": "gvx/deja", "path": "convert.py", "copies": "1", "size": "5277", "license": "isc", "hash": -1801007816308796200, "line_mean": 31.3742331288, "line_max": 166, "alpha_frac": 0.6391889331, "autogenerated": false, "ratio": 3.089578454332553, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.42287673874325526, "avg_score": null, "num_lines": null }
from flavio.physics.bdecays.formfactors.b_p import bcl, cln, bsz from flavio.classes import AuxiliaryQuantity, Implementation from flavio.config import config processes_H2L = ['B->K', 'B->pi'] # heavy to light processes_H2H = ['B->D', ] # heavy to heavy def ff_function(function, process, **kwargs): return lambda wc_obj, par_dict, q2: function(process, q2, par_dict, **kwargs) for p in processes_H2L + processes_H2H: quantity = p + ' form factor' a = AuxiliaryQuantity(name=quantity, arguments=['q2']) a.set_description('Hadronic form factor for the ' + p + ' transition') iname = p + ' BSZ3' i = Implementation(name=iname, quantity=quantity, function=ff_function(bsz.ff, p, n=3)) i.set_description("3-parameter BSZ parametrization (see arXiv:1811.00983).") iname = p + ' BCL3' i = Implementation(name=iname, quantity=quantity, function=ff_function(bcl.ff, p, n=3)) i.set_description("3-parameter BCL parametrization (see arXiv:0807.2722).") iname = p + ' BCL4' i = Implementation(name=iname, quantity=quantity, function=ff_function(bcl.ff, p, n=4)) i.set_description("4-parameter BCL parametrization (see arXiv:0807.2722).") iname = p + ' BCL3-IW' i = Implementation(name=iname, quantity=quantity, function=ff_function(bcl.ff_isgurwise, p, scale=config['renormalization scale']['bpll'], n=3)) i.set_description("3-parameter BCL parametrization using improved Isgur-Wise relation" " for the tensor form factor") iname = p + ' BCL4-IW' i = Implementation(name=iname, quantity=quantity, function=ff_function(bcl.ff_isgurwise, p, scale=config['renormalization scale']['bpll'], n=4)) i.set_description("4-parameter BCL parametrization using improved Isgur-Wise relation" " for the tensor form factor") iname = p + ' BCL3-IW-t0max' i = Implementation(name=iname, quantity=quantity, function=ff_function(bcl.ff_isgurwise, p, scale=config['renormalization scale']['bpll'], n=3, t0='tm')) i.set_description("3-parameter BCL parametrization using improved Isgur-Wise relation" r" for the tensor form factor and taking $t_0=t_-$ in the $z$ expansion") iname = p + ' BCL4-IW-t0max' i = Implementation(name=iname, quantity=quantity, function=ff_function(bcl.ff_isgurwise, p, scale=config['renormalization scale']['bpll'], n=4, t0='tm')) i.set_description("4-parameter BCL parametrization using improved Isgur-Wise relation" r" for the tensor form factor and taking $t_0=t_-$ in the $z$ expansion") for p in processes_H2H: iname = p + ' CLN' i = Implementation(name=iname, quantity=quantity, function=ff_function(cln.ff, p, scale=config['renormalization scale']['bpll'])) i.set_description("CLN parametrization based on HQET")
{ "repo_name": "flav-io/flavio", "path": "flavio/physics/bdecays/formfactors/b_p/btop.py", "copies": "1", "size": "3081", "license": "mit", "hash": -4805255542879007000, "line_mean": 45.6818181818, "line_max": 95, "alpha_frac": 0.6286919831, "autogenerated": false, "ratio": 3.348913043478261, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4477605026578261, "avg_score": null, "num_lines": null }
from flavio.physics.bdecays.formfactors.b_v import bsz, sse, cln, clnexp from flavio.classes import AuxiliaryQuantity, Implementation from flavio.config import config processes_H2L = ['B->K*', 'B->rho', 'B->omega', 'Bs->phi', 'Bs->K*'] # heavy to light processes_H2H = ['B->D*', ] # heavy to heavy def ff_function(function, process, **kwargs): return lambda wc_obj, par_dict, q2: function(process, q2, par_dict, **kwargs) for p in processes_H2L + processes_H2H: quantity = p + ' form factor' a = AuxiliaryQuantity(name=quantity, arguments=['q2']) a.set_description('Hadronic form factor for the ' + p + ' transition') iname = p + ' BSZ2' i = Implementation(name=iname, quantity=quantity, function=ff_function(bsz.ff, p, n=2)) i.set_description("2-parameter BSZ parametrization (see arXiv:1503.05534)") iname = p + ' BSZ3' i = Implementation(name=iname, quantity=quantity, function=ff_function(bsz.ff, p, n=3)) i.set_description("3-parameter BSZ parametrization (see arXiv:1503.05534)") iname = p + ' SSE' i = Implementation(name=iname, quantity=quantity, function=ff_function(sse.ff, p, n=2)) i.set_description("2-parameter simplified series expansion") for p in processes_H2H: iname = p + ' CLN' i = Implementation(name=iname, quantity=quantity, function=ff_function(cln.ff, p, scale=config['renormalization scale']['bvll'])) i.set_description("CLN parametrization") iname = p + ' CLNexp-IW' i = Implementation(name=iname, quantity=quantity, function=ff_function(clnexp.ff, p, scale=config['renormalization scale']['bvll'])) i.set_description("CLN-like parametrization as used by B factories" " and using improved Isgur-Wise relations" " for the tensor form factors")
{ "repo_name": "flav-io/flavio", "path": "flavio/physics/bdecays/formfactors/b_v/btov.py", "copies": "1", "size": "1898", "license": "mit", "hash": -5037600595039425000, "line_mean": 40.2608695652, "line_max": 101, "alpha_frac": 0.6448893572, "autogenerated": false, "ratio": 3.283737024221453, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9416003466518037, "avg_score": 0.0025245829806831792, "num_lines": 46 }
from flavored_words import can_combine, add_sound_parts def check_can_combine(first, second): assert can_combine(first, second), "unable to combine %s and %s" % (first, second) def check_cannot_combine(first, second): assert can_combine(first, second) == False, "should not be able to combine %s and %s" % (first, second) def test_can_combine(): check_can_combine(('', '', ''), ('', '', '')) check_can_combine(('a', 'd', ''), ('', 'c', 'b')) check_can_combine(('a', 'b'), tuple('b')) def test_cannot_combine(): check_cannot_combine(('a', 'd', ''), ('e', 'c', 'b')) check_cannot_combine(('a', 'b'), ('c', 'd')) check_cannot_combine(('a', 'bae'), ('ac', 'd')) def check_add_sound_parts(base, parts, expected): assert add_sound_parts(base, parts) == expected, "expected %s from %s and %s" % (expected, base, parts) def test_add_sound_parts(): check_add_sound_parts(tuple(''), tuple(''), tuple('')) check_add_sound_parts(('', ''), ('', ''), ('', '', '')) check_add_sound_parts(('a', ''), ('', ''), ('a', '', '')) check_add_sound_parts(('a', ''), ('', 'b'), ('a', '', 'b')) check_add_sound_parts(('a', 'b'), ('b', 'c'), ('a', 'b', 'c')) if __name__ == '__main__': test_can_combine() test_add_sound_parts()
{ "repo_name": "dianarg/conlang-util", "path": "generator/word/test_combine_word.py", "copies": "1", "size": "1279", "license": "mit", "hash": 6269744717044895000, "line_mean": 32.6578947368, "line_max": 107, "alpha_frac": 0.538702111, "autogenerated": false, "ratio": 3.074519230769231, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9108053969315106, "avg_score": 0.001033474490824763, "num_lines": 38 }
from flavored_words import divide_word def check_divide_word(word, expected): pieces = divide_word(word) assert pieces == expected, "divide_word(%s) produced %s, expected %s" % (word, pieces, expected) def test_divide_word(): check_divide_word('', [('', '', '')]) check_divide_word('a', [('a', '', '')]) check_divide_word('ai', [('ai', '', '')]) check_divide_word('x', [('', 'x', '')]) check_divide_word('xx', [('', 'xx', '')]) check_divide_word('ax', [('a', 'x', '')]) check_divide_word('xa', [('', 'x', 'a')]) check_divide_word('axe', [('a', 'x', 'e')]) check_divide_word('xxa', [('', 'xx', 'a')]) check_divide_word('xax', [('', 'x', 'a'), ('a', 'x', '')]) check_divide_word('axaxa', [('a', 'x', 'a'), ('a', 'x', 'a')]) check_divide_word('miniature', [('', 'm', 'i'), ('i', 'n', 'ia'), ('ia', 't', 'u'), ('u', 'r', 'e')]) check_divide_word('school', [('', 'sch', 'oo'), ('oo', 'l', '')]) check_divide_word('alleviate', [('a', 'll', 'e'), ('e', 'v', 'ia'), ('ia', 't', 'e')]) if __name__ == '__main__': test_divide_word()
{ "repo_name": "dianarg/conlang-util", "path": "generator/word/test_divide_word.py", "copies": "1", "size": "1098", "license": "mit", "hash": 7546128454467545000, "line_mean": 38.2142857143, "line_max": 105, "alpha_frac": 0.4626593807, "autogenerated": false, "ratio": 2.772727272727273, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3735386653427273, "avg_score": null, "num_lines": null }
from flavorsync.database import db from flavorsync.model import Flavor, Infrastructure from sqlalchemy.exc import InvalidRequestError, IntegrityError from flavorsync.exceptions import InfrastructureAlreadyExistsError,\ InfrastructureNotFoundError, FlavorAlreadyExistsError,\ FlavorNotFoundExceptionError from sqlalchemy.orm.exc import UnmappedInstanceError class DatabaseManager(): def get_infrastructures(self): return Infrastructure.query.all() def get_infrastructure(self, name): return Infrastructure.query.get(name) def register_infrastructure(self, infrastructure): db.session.add(infrastructure) try: db.session.commit() except IntegrityError: raise InfrastructureAlreadyExistsError(infrastructure.name) def unregister_infrastructure(self, name): infrastructure = Infrastructure.query.get(name) try: db.session.delete(infrastructure) db.session.commit() except UnmappedInstanceError: raise InfrastructureNotFoundError(name) def get_flavors(self, public_, promoted_): if not public_ and not promoted_: flavors = Flavor.query.all() elif public_ and promoted_: flavors = Flavor.query.filter_by(public=public_, promoted=promoted_).all() elif public_: flavors = Flavor.query.filter_by(public=public_).all() elif promoted_: flavors = Flavor.query.filter_by(promoted=promoted_).all() return flavors def create_flavor(self, flavor): db.session.add(flavor) try: db.session.commit() except InvalidRequestError: raise FlavorAlreadyExistsError(flavor.name) except IntegrityError: raise FlavorAlreadyExistsError(flavor.name) return flavor def get_flavor(self, flavor_id): flavor = Flavor.query.get(flavor_id) if flavor is None: raise FlavorNotFoundExceptionError(flavor_id) return flavor def promote_flavor(self, flavor): flavor.promoted = True db.session.commit() def add_node_to_flavor(self, modified_flavor, node): modified_flavor.nodes.extend(node) db.session.commit() def delete_flavor(self, flavor_id): flavor = Flavor.query.get(flavor_id) db.session.delete(flavor) try: db.session.commit() except InvalidRequestError: raise FlavorNotFoundExceptionError(flavor_id) def delete_node_in_flavor(self, flavor, infrastructure): flavor.nodes.remove(infrastructure) try: db.session.commit() except InvalidRequestError: raise FlavorNotFoundExceptionError(flavor.id)
{ "repo_name": "Atos-FiwareOps/flavor-sync", "path": "flavorsync/database_manager.py", "copies": "2", "size": "2856", "license": "apache-2.0", "hash": -2516889939698399000, "line_mean": 33.0119047619, "line_max": 86, "alpha_frac": 0.6488095238, "autogenerated": false, "ratio": 4.533333333333333, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0264832579533124, "num_lines": 84 }
from flavorsync.database import db from flavorsync.parser.parser_factory import ParserFactory import re from flavorsync.exceptions import FlavorInfrastructureNotFoundError class ParseableModel(): @classmethod def deserialize(cls, mimetype, data): parser_factory = ParserFactory() parser = parser_factory.get_parser(mimetype, cls) return parser.to_dict(data) def serialize(self, mimetype): parser_factory = ParserFactory() parser = parser_factory.get_parser(mimetype, self.__class__) return parser.from_model(self) # DB classes class Infrastructure(db.Model, ParseableModel): __tablename__ = 'infrastructure' name = db.Column(db.String(30), primary_key = True) keystone_url = db.Column(db.String(30)) username = db.Column(db.String(20)) password = db.Column(db.String(30)) tenant = db.Column(db.String(20)) def __init__(self, name="", keystone_url="", username="", password="", tenant=""): self.name = name self.keystone_url = keystone_url self.username = username self.password = password self.tenant = tenant def __repr__(self): return '<Infrastructure %r>' % self.name @classmethod def deserialize(cls, mimetype, data): infrastructure_dict = super(Infrastructure, cls).deserialize(mimetype, data) return Infrastructure( infrastructure_dict['name'], infrastructure_dict['keystone_url'], infrastructure_dict['username'], infrastructure_dict['password'], infrastructure_dict['tenant']) def serialize(self, mimetype): return ParseableModel.serialize(self, mimetype) def _to_content_dict(self): return { "id": self.name, "name" : self.name } def to_dict(self): return {"infrastructure": {"name" : self.name}} class InfrastructureCollection(ParseableModel): def __init__(self, infrastructures): self.infrastructures = infrastructures def serialize(self, mimetype): return ParseableModel.serialize(self, mimetype) def extend(self, infrastructure_collection): self.infrastructures.extend(infrastructure_collection.infrastructures) def to_dict(self): infrastructures = [] for infrastructure in self.infrastructures: infrastructure_dict = infrastructure._to_content_dict() infrastructures.append(infrastructure_dict) return {"Infrastructures" : infrastructures} class Flavor(db.Model, ParseableModel): __tablename__ = 'flavor' id = db.Column(db.String(36), primary_key = True) name = db.Column(db.String(30), unique =True) vcpus = db.Column(db.Integer) ram = db.Column(db.Integer) disk = db.Column(db.Integer) swap = db.Column(db.Integer) public = db.Column(db.Boolean) promoted = db.Column(db.Boolean) nodes = db.relationship( 'Infrastructure', secondary = 'flavor_infrastructure_link' ) def __init__(self, flavor_id=None, name=None, vcpus=-1, ram=-1,disk=-1, swap=0, promoted=False, public=False, nodes=[]): self.id = flavor_id self.name = name self.vcpus = vcpus self.ram = ram self.disk = disk self.swap = swap self.promoted = promoted self.public = public self.nodes=nodes def __repr__(self): return '<Flavor %r>' % self.name @classmethod def deserialize(cls, mimetype, data): flavor_dict = super(Flavor, cls).deserialize(mimetype, data) nodes = [] if 'nodes' in flavor_dict.keys(): for node_name in flavor_dict.get('nodes'): try: node = Infrastructure.query.get(node_name) except: raise FlavorInfrastructureNotFoundError(node_name) nodes.append(node) return Flavor( flavor_dict.get('id'), flavor_dict.get('name'), flavor_dict.get('vcpus'), flavor_dict.get('ram'), flavor_dict.get('disk'), flavor_dict.get('swap'), flavor_dict.get('promoted'), flavor_dict.get('public'), nodes) @classmethod def from_openstack_flavor(cls, flavor, infrastructure): number_regex = "[0-9]+" if type(flavor.swap) is str and re.match(number_regex, flavor.swap): swap = int(flavor.swap) else: swap = 0 return (Flavor( flavor.id, flavor.name, flavor.vcpus, flavor.ram, flavor.disk, swap, False, False, [infrastructure] ) ) def serialize(self, mimetype): return ParseableModel.serialize(self, mimetype) def _to_content_dict(self): nodes_dict = [] for node in self.nodes: nodes_dict.append(node._to_content_dict()) return { "id" : self.id, "name" : self.name, "vcpus": self.vcpus, "ram" : self.ram, "disk" : self.disk, "swap" : self.swap, "public": self.public, "promoted" : self.promoted, "nodes" : nodes_dict } def to_dict(self): return {"flavor" : self._to_content_dict()} class FlavorInfrastructureLink(db.Model): __tablename__ = 'flavor_infrastructure_link' flavor_id = db.Column(db.String(36), db.ForeignKey('flavor.id'), primary_key = True) infrastructure_name = db.Column(db.String(30), db.ForeignKey('infrastructure.name'), primary_key = True) class FlavorCollection(ParseableModel): def __init__(self, flavors): self.flavors = flavors @classmethod def from_openstack_flavor_list(cls, flavor_list, infrastructure): flavors = [] for flavor in flavor_list: flavors.append(Flavor.from_openstack_flavor(flavor, infrastructure)) return FlavorCollection(flavors) def serialize(self, mimetype): return ParseableModel.serialize(self, mimetype) def extend(self, flavor_collection): self.flavors.extend(flavor_collection.flavors) def to_dict(self): flavors = [] for flavor in self.flavors: flavor_dict = flavor._to_content_dict() flavors.append(flavor_dict) return {"flavors" : flavors}
{ "repo_name": "Fiware/ops.Flavor-sync", "path": "flavorsync/model.py", "copies": "2", "size": "6804", "license": "apache-2.0", "hash": 6276228813352002000, "line_mean": 33.5431472081, "line_max": 108, "alpha_frac": 0.5706937096, "autogenerated": false, "ratio": 4.268506900878293, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.03320085662977786, "num_lines": 197 }
from flavorsync import app from flask import request from flask import Response from flavorsync.parser.parser_factory import ParserFactory class UnAuthorizedMethodError(Exception): status_code = 405 def __init__(self): Exception.__init__(self, "UnAuthorized method") class UnimplementedMethodError(Exception): def __init__(self): Exception.__init__(self, "Uninplemented method") class FlavorSyncError(Exception): def __init__(self, message, status_code=None, payload=None): Exception.__init__(self) self.message = message if status_code is not None: self.status_code = status_code self.payload = payload def to_dict(self): rv = dict(self.payload or ()) rv['error']= {"message" : self.message} return rv def super_class(self): return self.__class__ class InfrastructureAlreadyExistsError(FlavorSyncError): status_code = 409 def __init__(self, infrastructure_id): message = "The infrastructure {0} already exists".format(infrastructure_id) super(InfrastructureAlreadyExistsError, self).__init__(message, self.status_code) class InfrastructureBadRequestError(FlavorSyncError): status_code = 400 def __init__(self): message = "The infrastructure is not well formed" super(InfrastructureBadRequestError, self).__init__(message, self.status_code) class InfrastructureNotFoundError(FlavorSyncError): status_code = 404 def __init__(self, infrastructure_id): message = "The infrastructure {0} does not exist".format(infrastructure_id) super(InfrastructureNotFoundError, self).__init__(message, self.status_code) class FlavorNotFoundExceptionError(FlavorSyncError): status_code = 404 def __init__(self, flavor_id): message = "The flavor {0} does not exist".format(flavor_id) super(FlavorNotFoundExceptionError, self).__init__(message, self.status_code) class FlavorAlreadyExistsError(FlavorSyncError): status_code = 409 def __init__(self, flavor_name): message = "The there is already a flavor named {0}".format(flavor_name) super(FlavorAlreadyExistsError, self).__init__(message, self.status_code) class FlavorInfrastructureNotFoundError(FlavorSyncError): status_code = 409 def __init__(self, infrastructure_name): message = "The node {0} does not exist".format(infrastructure_name) super(FlavorInfrastructureNotFoundError, self).__init__(message, self.status_code) class UnpublishUnpromotedFlavorError(FlavorSyncError): status_code = 409 def __init__(self): message = "A flavor cannot be unpublished or unpromoted" super(UnpublishUnpromotedFlavorError, self).__init__(message, self.status_code) class FlavorBadRequestError(FlavorSyncError): status_code = 400 def __init__(self): message = "The flavor request is not well formed" super(FlavorBadRequestError, self).__init__(message, self.status_code) class PromotedNotPublicFlavorBadRequestError(FlavorSyncError): status_code = 400 def __init__(self): message = "A flavor cannot be promoted and private" super(PromotedNotPublicFlavorBadRequestError, self).__init__(message, self.status_code) class OpenStackConnectionError(FlavorSyncError): status_code = 502 def __init__(self): message = "Cannot connet to Openstack infrastructure. It could happen " message += "because it is down, it is not reachable or credentials are " message += "wrong. Please check it" super(OpenStackConnectionError, self).__init__(message, self.status_code) class OpenStackEndPointNotFound(FlavorSyncError): status_code = 502 def __init__(self, infrastructure_name): message = "Error publicURL endpoint for compute service in {0} region not found".format(infrastructure_name) super(OpenStackEndPointNotFound, self).__init__(message, self.status_code) class OpenStackForbidden(FlavorSyncError): status_code = 403 def __init__(self, infrastructure_name): message = "Error when managing flavors in the region {0}. Your credentials don't give you access to this resource.".format(infrastructure_name) super(OpenStackForbidden, self).__init__(message, self.status_code) class OpenStackUnauthorizedError(FlavorSyncError): status_code = 401 def __init__(self): message = "Your credentials are wrong and the request requires user authentication" message += " Please check it" super(OpenStackUnauthorizedError, self).__init__(message, self.status_code) class UnsupportedMediaTypeError(FlavorSyncError): status_code = 415 def __init__(self, content_type): if content_type: message = "Unrecognized content type '{0}'.".format(content_type) message += " Mustbe 'application/xml or 'application/json'" else: message = "Unrecognized content type. Mustbe 'application/xml'" message += " or 'application/json'" super(UnsupportedMediaTypeError, self).__init__(message, self.status_code) @app.errorhandler(FlavorSyncError) def handle_invalid_usage(error): mimetype = request.accept_mimetypes parser_factory = ParserFactory() parser = parser_factory.get_parser(mimetype, FlavorSyncError) response_body = parser.from_model(error) return Response(response_body, status=error.status_code, mimetype=mimetype[0][0])
{ "repo_name": "Atos-FiwareOps/flavor-sync", "path": "flavorsync/exceptions.py", "copies": "2", "size": "5592", "license": "apache-2.0", "hash": 6850976996468134000, "line_mean": 36.5369127517, "line_max": 151, "alpha_frac": 0.6850858369, "autogenerated": false, "ratio": 4.229954614220877, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5915040451120878, "avg_score": null, "num_lines": null }
from flavorsync.openstack.openstack_manager import OpenStackManager from flavorsync.database_manager import DatabaseManager from flavorsync.model import FlavorCollection, Flavor, InfrastructureCollection from flavorsync.exceptions import FlavorNotFoundExceptionError,\ PromotedNotPublicFlavorBadRequestError, UnpublishUnpromotedFlavorError from uuid import uuid4 from flask import session class FlavorSynchronizer(): def __init__(self): self.database_manager = DatabaseManager() ############## #Management of the completed lifecycle of the flavors, including private, public and promoted flavors #That should be only possible if all the management is done using this API, if the different regions don't use it, #it will be complicated to maintain the coherence. #Hence, this part is not finished and tested, since we have not centralized this management. ######### def register_infrastructure(self, infrastructure): self.database_manager.register_infrastructure(infrastructure) def unregister_infrastructure(self, name): self.database_manager.unregister_infrastructure(name) def get_flavors(self, public, promoted): flavors = self._get_public_flavors(public, promoted) flavor_collection = FlavorCollection(flavors) if not public and not promoted: private_flavors = self._get_private_flavors() self._remove_duplicated_flavors(flavors, private_flavors) flavor_collection.extend(private_flavors) return flavor_collection def get_flavors_region(self, region): private_flavors = self._get_private_flavors() return flavor_collection def create_flavor(self, flavor): f = self._create_private_flavor(flavor) return f def get_flavor(self, flavor_id): try: flavor = self._get_public_flavor(flavor_id) except FlavorNotFoundExceptionError: flavor = self._get_private_flavor(flavor_id) return flavor def publish_or_promote_flavor(self, flavor_id, modified_flavor): self._check_well_formed_publishing_conditions(modified_flavor) current_flavor = self.get_flavor(flavor_id) self._check_publishing_conditions(current_flavor, modified_flavor) self._publish_or_promote_flavor(current_flavor, modified_flavor) return current_flavor def add_node_to_flavor(self, flavor_id, modified_flavor): current_flavor = self.get_flavor(flavor_id) self._create_private_flavor(current_flavor) self.database_manager.add_node_to_flavor(current_flavor, modified_flavor.nodes) return current_flavor def delete_flavor(self, flavor_id): flavor = self.get_flavor(flavor_id) self._delete_private_flavor(flavor.id) if flavor.public: self._delete_node_in_flavor(flavor) def is_node_included(self, region): return self._exist_node(region) def get_nodes(self): return self._get_nodes() ######### ######### ############## #Management of the promoted flavors, which are not related with the private flavors. #This part has been integrated with the DashFI. ######### def get_public_flavor(self, flavor_id): try: flavor = self._get_public_flavor(flavor_id) except FlavorNotFoundExceptionError: flavor = None return flavor def create_promoted_flavor(self, flavor): #this method only manage the promoted flavors. Hence, it is responsible to force the promoted attribute. flavor.promoted = True flavor.public = True if not flavor.id: flavor.id = str(uuid4()) print (flavor) print (flavor.id) f = self._publish_flavor(flavor) return f def delete_promoted_flavor(self, flavor_id): #If the promoted flavor has nodes associated an error raised, since it is not allowed to remove promote flavors with nodes. #If you only manage promoted flavors, it shouldn't happen, #nevertheless if you are managing the complete life cycle, the flavor cannot be deleted if it has nodes associated. self.database_manager.delete_flavor(flavor_id) ######### ######### ######### #Manage only the private flavors for the different regions. #This part has been integrated with the DashFI. ######### def get_region_flavors(self, region): private_flavors = self._get_private_region_flavors(region) return private_flavors def get_region_flavor(self, region, flavor_id): try: flavor = self._get_private_region_flavor(region, flavor_id) except FlavorNotFoundExceptionError: flavor = None return flavor def create_region_flavor(self, region, flavor): f = self._create_private_region_flavor(region, flavor) return f def delete_region_flavor(self, region, flavor_id): self._delete_private_region_flavor(region, flavor_id) ######## ######## ######## ##Common and private methods ######## def _get_public_flavors(self, public, promoted): return self.database_manager.get_flavors(public, promoted) def _exist_node(self, region): infrastructure = self.database_manager.get_infrastructure(region) if infrastructure is None: return False else: return True def _get_nodes(self): infrastructures = self.database_manager.get_infrastructures() infrastructure_collection = InfrastructureCollection(infrastructures) return infrastructure_collection #with token of KeyStone def _get_private_region_flavors(self, region): token = session['token_keystone'] infrastructure = self.database_manager.get_infrastructure(region) openstack_manager = OpenStackManager(region, token) openstack_flavors = openstack_manager.get_flavors() #TODO review how to manage the infrastructure to be aligned with the data base definition. return FlavorCollection.from_openstack_flavor_list(openstack_flavors, infrastructure) def _get_private_region_flavor(self, region, flavor_id): token = session['token_keystone'] infrastructure = self.database_manager.get_infrastructure(region) openstack_manager = OpenStackManager(region, token) openstack_flavor = openstack_manager.get_flavor(flavor_id) return Flavor.from_openstack_flavor(openstack_flavor, infrastructure) def _create_private_region_flavor(self, region, flavor): token = session['token_keystone'] infrastructure = self.database_manager.get_infrastructure(region) openstack_manager = OpenStackManager(region, token) created_flavor = openstack_manager.create_flavor(flavor) return Flavor.from_openstack_flavor(created_flavor, infrastructure) def _delete_private_region_flavor(self, region, flavor_id): token = session['token_keystone'] infrastructure = self.database_manager.get_infrastructure(region) openstack_manager = OpenStackManager(region, token) openstack_manager.delete_flavor(flavor_id) #without Keystone token def _get_private_flavors(self): infrastructure = self.database_manager.get_infrastructure('Mordor') openstack_manager = OpenStackManager(infrastructure) openstack_flavors = openstack_manager.get_flavors() return FlavorCollection.from_openstack_flavor_list(openstack_flavors, infrastructure) def _create_private_flavor(self, flavor): infrastructure = self.database_manager.get_infrastructure('Mordor') openstack_manager = OpenStackManager(infrastructure) created_flavor = openstack_manager.create_flavor(flavor) return Flavor.from_openstack_flavor(created_flavor, infrastructure) def _publish_flavor(self, flavor): f = self.database_manager.create_flavor(flavor) return f def _get_private_flavor(self, flavor_id): infrastructure = self.database_manager.get_infrastructure('Mordor') openstack_manager = OpenStackManager(infrastructure) openstack_flavor = openstack_manager.get_flavor(flavor_id) return Flavor.from_openstack_flavor(openstack_flavor, infrastructure) def _get_public_flavor(self, flavor_id): return self.database_manager.get_flavor(flavor_id) def _delete_private_flavor(self, flavor_id): infrastructure = self.database_manager.get_infrastructure('Mordor') openstack_manager = OpenStackManager(infrastructure) openstack_manager.delete_flavor(flavor_id) def _delete_node_in_flavor(self, flavor): infrastructure = self.database_manager.get_infrastructure('Mordor') self.database_manager.delete_node_in_flavor(flavor, infrastructure) def _check_well_formed_publishing_conditions(self, flavor): if flavor.promoted and flavor.public is not None and not flavor.public: raise PromotedNotPublicFlavorBadRequestError() def _check_publishing_conditions(self, current_flavor, modified_flavor): if (modified_flavor.public is not None and current_flavor.public and not modified_flavor.public or current_flavor.promoted and not modified_flavor.promoted): raise UnpublishUnpromotedFlavorError() def _publish_or_promote_flavor(self, current_flavor, modified_flavor): if modified_flavor.public: current_flavor.public = modified_flavor.public if modified_flavor.promoted is not None: current_flavor.promoted = modified_flavor.promoted current_flavor = self._publish_flavor(current_flavor) elif modified_flavor.promoted: current_flavor = self.database_manager.promote_flavor(current_flavor) return current_flavor def _is_openstack_flavor(self, flavor): return flavor is None def _remove_duplicated_flavors(self, public_flavors, private_flavors): for public_flavor in public_flavors: for private_flavor in private_flavors.flavors: if private_flavor.id in public_flavor.id: private_flavors.flavors.remove(private_flavor)
{ "repo_name": "Atos-FiwareOps/flavor-sync", "path": "flavorsync/flavor_synchronizer.py", "copies": "2", "size": "10604", "license": "apache-2.0", "hash": 5357107942425000000, "line_mean": 38.8684210526, "line_max": 131, "alpha_frac": 0.6675782724, "autogenerated": false, "ratio": 4.374587458745874, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.025395966600855583, "num_lines": 266 }
from flax.geometry import Blob, Point, Rectangle, Size, Span def test_blob_create(): rect = Rectangle(origin=Point(0, 0), size=Size(5, 5)) blob = Blob.from_rectangle(rect) assert blob.area == rect.area assert blob.height == rect.height def test_blob_math_disjoint(): # These rectangles look like this: # xxx # xxx # xxx xxx # xxx # xxx rect1 = Rectangle(origin=Point(0, 0), size=Size(3, 3)) rect2 = Rectangle(origin=Point(6, 2), size=Size(3, 3)) blob1 = Blob.from_rectangle(rect1) blob2 = Blob.from_rectangle(rect2) union_blob = blob1 + blob2 assert union_blob.area == blob1.area + blob2.area assert union_blob.area == rect1.area + rect2.area assert union_blob.height == 5 left_blob = blob1 - blob2 from pprint import pprint pprint(blob1.spans) pprint(blob2.spans) pprint(left_blob.spans) assert left_blob.area == blob1.area assert left_blob == blob1 right_blob = blob2 - blob1 from pprint import pprint pprint(blob1.spans) pprint(blob2.spans) pprint(right_blob.spans) assert right_blob.area == blob2.area assert right_blob == blob2 def test_blob_math_overlap(): # These rectangles look like this: # xxx # x##x # x##x # xxx rect1 = Rectangle(origin=Point(0, 0), size=Size(3, 3)) rect2 = Rectangle(origin=Point(1, 1), size=Size(3, 3)) blob1 = Blob.from_rectangle(rect1) blob2 = Blob.from_rectangle(rect2) union_blob = blob1 + blob2 assert union_blob.area == 14 left_blob = blob1 - blob2 assert left_blob.area == 5 assert left_blob.height == 3 assert left_blob.spans == { 0: (Span(0, 2),), 1: (Span(0, 0),), 2: (Span(0, 0),), } right_blob = blob2 - blob1 assert right_blob.area == 5 assert right_blob.height == 3 assert right_blob.spans == { 1: (Span(3, 3),), 2: (Span(3, 3),), 3: (Span(1, 3),), } def test_blob_math_contain(): # These rectangles look like this: # xxxxx # x###x # x###x # x###x # xxxxx rect1 = Rectangle(origin=Point(0, 0), size=Size(5, 5)) rect2 = Rectangle(origin=Point(1, 1), size=Size(3, 3)) blob1 = Blob.from_rectangle(rect1) blob2 = Blob.from_rectangle(rect2) union_blob = blob1 + blob2 assert union_blob.area == blob1.area assert union_blob.height == blob1.height left_blob = blob1 - blob2 assert left_blob.area == 16 assert left_blob.height == 5 assert left_blob.spans == { 0: (Span(0, 4),), 1: (Span(0, 0), Span(4, 4)), 2: (Span(0, 0), Span(4, 4)), 3: (Span(0, 0), Span(4, 4)), 4: (Span(0, 4),), } right_blob = blob2 - blob1 assert right_blob.area == 0 assert right_blob.height == 0 assert right_blob.spans == {} def test_blob_math_fuzzer(): pass
{ "repo_name": "eevee/flax", "path": "flax/tests/geometry_test.py", "copies": "1", "size": "2898", "license": "mit", "hash": 5565408903469552000, "line_mean": 24.6460176991, "line_max": 60, "alpha_frac": 0.5862663906, "autogenerated": false, "ratio": 3.066666666666667, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4152933057266667, "avg_score": null, "num_lines": null }
from flee import flee from datamanager import handle_refugee_data from datamanager import DataTable #DataTable.subtract_dates() from flee import InputGeography import numpy as np import outputanalysis.analysis as a import sys import argparse import time def date_to_sim_days(date): return DataTable.subtract_dates(date,"2010-01-01") if __name__ == "__main__": t_exec_start = time.time() end_time = 10 last_physical_day = 10 parser = argparse.ArgumentParser(description='Run a parallel Flee benchmark.') parser.add_argument("-p", "--parallelmode", type=str, default="advanced", help="Parallelization mode (advanced, classic, cl-hilat OR adv-lowlat)") parser.add_argument("-N", "--initialagents", type=int, default=100000, help="Number of agents at the start of the simulation.") parser.add_argument("-d", "--newagentsperstep", type=int, default=1000, help="Number of agents added per time step.") parser.add_argument("-t", "--simulationperiod", type=int, default=10, help="Duration of the simulation in days.") parser.add_argument("-i", "--inputdir", type=str, default="test_data/test_input_csv", help="Directory with parallel test input. Must have locations named 'A','D','E' and 'F'.") args = parser.parse_args() end_time = args.simulationperiod last_physical_day = args.simulationperiod e = flee.Ecosystem() if args.parallelmode is "advanced" or "adv-lowlat": e.parallel_mode = "loc-par" else: e.parallel_mode = "classic" if args.parallelmode is "advanced" or "cl-hilat": e.latency_mode = "high_latency" else: e.latency_mode = "low_latency" print("MODE: ", args, file=sys.stderr) ig = InputGeography.InputGeography() ig.ReadLocationsFromCSV("%s/locations.csv" % args.inputdir) ig.ReadLinksFromCSV("%s/routes.csv" % args.inputdir) ig.ReadClosuresFromCSV("%s/closures.csv" % args.inputdir) e,lm = ig.StoreInputGeographyInEcosystem(e) #print("Network data loaded") #d = handle_refugee_data.RefugeeTable(csvformat="generic", data_directory="test_data/test_input_csv/refugee_data", start_date="2010-01-01", data_layout="data_layout.csv") output_header_string = "Day," camp_locations = e.get_camp_names() ig.AddNewConflictZones(e,0) # All initial refugees start in location A. e.add_agents_to_conflict_zones(args.initialagents) for l in camp_locations: output_header_string += "%s sim,%s data,%s error," % (lm[l].name, lm[l].name, lm[l].name) output_header_string += "Total error,refugees in camps (UNHCR),total refugees (simulation),raw UNHCR refugee count,refugees in camps (simulation),refugee_debt" if e.getRankN(0): print(output_header_string) # Set up a mechanism to incorporate temporary decreases in refugees refugees_raw = 0 #raw (interpolated) data from TOTAL UNHCR refugee count only. t_exec_init = time.time() if e.getRankN(0): my_file = open('perf.log', 'w', encoding='utf-8') print("Init time,{}".format(t_exec_init - t_exec_start), file=my_file) for t in range(0,end_time): if t>0: ig.AddNewConflictZones(e,t) # Determine number of new refugees to insert into the system. new_refs = args.newagentsperstep refugees_raw += new_refs #Insert refugee agents e.add_agents_to_conflict_zones(new_refs) e.refresh_conflict_weights() t_data = t e.enact_border_closures(t) e.evolve() #Calculation of error terms errors = [] abs_errors = [] camps = [] for i in camp_locations: camps += [lm[i]] # calculate retrofitted time. refugees_in_camps_sim = 0 for c in camps: refugees_in_camps_sim += c.numAgents output = "%s" % t for i in range(0,len(camp_locations)): output += ",%s" % (lm[camp_locations[i]].numAgents) if refugees_raw>0: output += ",%s,%s" % (e.numAgents(), refugees_in_camps_sim) else: output += ",0,0" if e.getRankN(t): print(output) t_exec_end = time.time() if e.getRankN(0): my_file = open('perf.log', 'a', encoding='utf-8') print("Time in main loop,{}".format(t_exec_end - t_exec_init), file=my_file)
{ "repo_name": "djgroen/flee-release", "path": "test_par_seq.py", "copies": "1", "size": "4167", "license": "bsd-3-clause", "hash": -3479104499119047000, "line_mean": 28.9784172662, "line_max": 172, "alpha_frac": 0.6705063595, "autogenerated": false, "ratio": 3.1120238984316653, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4282530257931665, "avg_score": null, "num_lines": null }
from flee import flee from datamanager import handle_refugee_data from datamanager import DataTable #DataTable.subtract_dates() import numpy as np import outputanalysis.analysis as a import sys def linkBF(e): # bing based e.linkUp("Douentza","Mentao","487.0") e.linkUp("Mopti","Mentao","360.0") e.linkUp("Mopti","Bobo-Dioulasso","462.0") e.linkUp("Segou","Bobo-Dioulasso","376.3") e.linkUp("Mentao","Bobo-Dioulasso","475.0") def linkNiger(e): # bing based e.linkUp("Menaka","Abala","172.0") e.linkUp("Menaka","Mangaize","305.0") e.linkUp("Ansongo","Tabareybarey","148.4") e.linkUp("Menaka","Tabareybarey","361.0") # All distances here are Bing-based. e.linkUp("Abala","Mangaize","256.0") e.linkUp("Abala","Niamey","253.0") e.linkUp("Abala","Tabareybarey","412.0") e.linkUp("Mangaize","Niamey","159.0") e.linkUp("Mangaize","Tabareybarey","217.0") e.linkUp("Niamey","Tabareybarey","205.0") def AddInitialRefugees(e, d, loc): """ Add the initial refugees to a location, using the location name""" num_refugees = int(d.get_field(loc.name, 0, FullInterpolation=True)) for i in range(0, num_refugees): e.addAgent(location=loc) def date_to_sim_days(date): return DataTable.subtract_dates(date,"2012-02-29") if __name__ == "__main__": if len(sys.argv)>1: if (sys.argv[1]).isnumeric(): end_time = int(sys.argv[1]) last_physical_day = int(sys.argv[1]) else: end_time = 300 last_physical_day = 300 duration = flee.SimulationSettings.SimulationSettings.ReadFromCSV(sys.argv[1]) if duration>0: end_time = duration last_physical_day = end_time else: end_time = 300 last_physical_day = 300 e = flee.Ecosystem() # Refugees reduce population counts. #flee.SimulationSettings.TakeRefugeesFromPopulation = True # Distances are estimated using Bing Maps. # Mali lm = {} lm["Kidal"] = e.addLocation("Kidal", movechance="default", pop=25617) # pop. 25,617. GPS 18.444305 1.401523 lm["Gao"] = e.addLocation("Gao", movechance="default", pop=86633) # pop. 86,633. GPS 16.270910 -0.040210 lm["Timbuktu"] = e.addLocation("Timbuktu", movechance="default", pop=54453) # pop. 54,453. GPS 16.780260 -3.001590 lm["Mopti"] = e.addLocation("Mopti", movechance="default", pop=148456) #108456 from Mopti + 40000 from Sevare, which is 10km southeast to Mopti. # pop. 108,456 (2009 census) lm["Douentza"] = e.addLocation("Douentza", movechance="default", pop=28005) # pop. 28,005 (2009 census), fell on 5th of April 2012. lm["Konna"] = e.addLocation("Konna", movechance="default", pop=36767) # pop. 36,767 (2009 census), captured in January 2013 by the Islamists. lm["Menaka"] = e.addLocation("Menaka", movechance="conflict", pop=20702) # pop. 20,702 (2009 census), captured in January 2012 by the Islamists. lm["Niafounke"] = e.addLocation("Niafounke", movechance="conflict", pop=1000) # pop. negligible. Added because it's a junction point, move chance set to 1.0 for that reason. lm["Bourem"] = e.addLocation("Bourem", movechance="default", pop=27486) # pop. 27,486. GPS 16.968122, -0.358435. No information about capture yet, but it's a sizeable town at a junction point. lm["Bamako"] = e.addLocation("Bamako", movechance="default", pop=1809106) # pop. 1,809,106 capital subject to coup d'etat between March 21st and April 8th 2012. lm["Tenenkou"] = e.addLocation("Tenenkou", movechance="default", pop=11310) # pop. 11310. First Battle on 02-03-2012, 14.5004532,-4.8748448. lm["Segou"] = e.addLocation("Segou", movechance="default", pop=130690) lm["Ansongo"] = e.addLocation("Ansongo", movechance="default", pop=32709) # pop. 32709 lm["Lere"] = e.addLocation("Lere", movechance="default", pop=16072) # pop. 16,072. lm["Dire"] = e.addLocation("Dire", movechance="default", pop=22365) # pop. 22,365. lm["Goundam"] = e.addLocation("Goundam", movechance="default", pop=16253) # pop. 16,253. """ Town merges in Mali, as they are <= 10 km away: ACLED towns -> town in simulation Kati, Kambila, Badalabougo -> Bamako Sevare -> Mopti """ # bing based e.linkUp("Kidal","Bourem", "308.0") e.linkUp("Gao","Bourem","97.0") e.linkUp("Timbuktu","Bourem","314.0") e.linkUp("Timbuktu", "Konna","303.0") #Mopti is literally on the way to Bobo-Dioulasso. e.linkUp("Gao", "Douentza","397.0") #Mopti is literally on the way to Bobo-Dioulasso. e.linkUp("Douentza","Konna","121.0") #Douentza is on the road between Gao and Mopti. e.linkUp("Konna","Mopti","70.0") #Konna is on the road between Gao and Mopti. e.linkUp("Mopti","Segou","401.3") e.linkUp("Ansongo","Menaka","190.7") e.linkUp("Gao","Ansongo","99.6") e.linkUp("Dire","Goundam","42.2") e.linkUp("Goundam","Timbuktu","85.3") e.linkUp("Goundam","Niafounke","77.5") e.linkUp("Niafounke","Konna","153.0") e.linkUp("Niafounke", "Lere", "139.8") e.linkUp("Tenenkou","Niafounke","308.1") e.linkUp("Tenenkou","Lere","294.5") e.linkUp("Tenenkou","Segou","227.5") e.linkUp("Segou","Bamako","239.8") # Mauritania m1 = e.addLocation("Mbera", movechance="camp", capacity=103731, foreign=True) # GPS 15.639012,-5.751422 m2 = e.addLocation("Fassala", movechance=0.08, foreign=True) # bing based e.linkUp("Lere","Fassala","98.1") e.linkUp("Fassala","Mbera","25.0", forced_redirection=True) # Burkina Faso b1 = e.addLocation("Mentao", movechance="camp", capacity=10038, foreign=True) # GPS 13.999700,-1.680371 b2 = e.addLocation("Bobo-Dioulasso", movechance="camp", capacity=1926, foreign=True) # GPS 11.178103,-4.291773 # No linking up yet, as BF border was shut prior to March 21st 2012. # Niger n1 = e.addLocation("Abala", movechance="camp", capacity=18573, foreign=True) # GPS 14.927683 3.433727 n2 = e.addLocation("Mangaize", movechance="camp", capacity=4356, foreign=True) # GPS 14.684030 1.882720 n3 = e.addLocation("Niamey", movechance="camp", capacity=6327, foreign=True) n4 = e.addLocation("Tabareybarey", movechance="camp", capacity=9189, foreign=True) # GPS 14.754761 0.944773 d = handle_refugee_data.RefugeeTable(csvformat="generic", data_directory="source_data/mali2012/") # Correcting for overestimations due to inaccurate level 1 registrations in five of the camps. # These errors led to a perceived large drop in refugee population in all of these camps. # We correct by linearly scaling the values down to make the last level 1 registration match the first level 2 registration value. # To our knowledge, all level 2 registration procedures were put in place by the end of 2012. d.correctLevel1Registrations("Mbera","2012-12-31") m1.capacity = d.getMaxFromData("Mbera", last_physical_day) d.correctLevel1Registrations("Mentao","2012-10-03") b1.capacity = d.getMaxFromData("Mentao", last_physical_day) d.correctLevel1Registrations("Abala","2012-12-21") n1.capacity = d.getMaxFromData("Abala", last_physical_day) d.correctLevel1Registrations("Mangaize","2012-12-21") n2.capacity = d.getMaxFromData("Mangaize", last_physical_day) d.correctLevel1Registrations("Tabareybarey","2012-12-21") n4.capacity = d.getMaxFromData("Tabareybarey", last_physical_day) print("Day,Mbera sim,Mbera data,Mbera error,Mentao sim,Mentao data,Mentao error,Bobo-Dioulasso sim,Bobo-Dioulasso data,Bobo-Dioulasso error,Abala sim,Abala data,Abala error,Mangaize sim,Mangaize data,Mangaize error,Niamey sim,Niamey data,Niamey error,Tabareybarey sim,Tabareybarey data,Tabareybarey error,Total error,refugees in camps (UNHCR),total refugees (simulation),raw UNHCR refugee count,retrofitted time,refugees in camps (simulation),refugee_debt,Total error (retrofitted)") # Set up a mechanism to incorporate temporary decreases in refugees refugee_debt = 0 refugees_raw = 0 #raw (interpolated) data from TOTAL UNHCR refugee count only. # Add initial refugees to the destinations. AddInitialRefugees(e,d,m1) AddInitialRefugees(e,d,m2) AddInitialRefugees(e,d,b1) AddInitialRefugees(e,d,b2) AddInitialRefugees(e,d,n1) AddInitialRefugees(e,d,n2) AddInitialRefugees(e,d,n3) AddInitialRefugees(e,d,n4) e.add_conflict_zone("Menaka") # Start with a refugee debt to account for the mismatch between camp aggregates and total UNHCR data. refugee_debt = e.numAgents() t_retrofitted = 0 for t in range(0,end_time): e.refresh_conflict_weights() t_data = t # Close/open borders here. if t_data == date_to_sim_days("2012-03-19"): #On the 19th of March, Fassala closes altogether, and instead functions as a forward to Mbera (see PDF report 1 and 2). m2.movechance = 1.0 if t_data == date_to_sim_days("2012-03-21"): #On the 21st of March, Burkina Faso opens its borders (see PDF report 3). linkBF(e) if t_data == date_to_sim_days("2012-04-01"): #Starting from April, refugees appear to enter Niger again (on foot, report 4). linkNiger(e) # Determine number of new refugees to insert into the system. new_refs = d.get_daily_difference(t, FullInterpolation=True) - refugee_debt refugees_raw += d.get_daily_difference(t, FullInterpolation=True) if new_refs < 0: refugee_debt = -new_refs new_refs = 0 elif refugee_debt > 0: refugee_debt = 0 # Add conflict zones at the right time. if t_data == date_to_sim_days("2012-02-03"): e.add_conflict_zone("Kidal") if t_data == date_to_sim_days("2012-02-03"): e.add_conflict_zone("Timbuktu") if t_data == date_to_sim_days("2012-03-02"): e.add_conflict_zone("Tenenkou") if t_data == date_to_sim_days("2012-03-23"): e.add_conflict_zone("Gao") if t_data == date_to_sim_days("2012-08-10"): e.add_conflict_zone("Bamako") if t_data == date_to_sim_days("2012-03-30"): e.add_conflict_zone("Bourem") if t_data == date_to_sim_days("2012-09-01"): e.add_conflict_zone("Douentza") if t_data == date_to_sim_days("2012-11-28"): e.add_conflict_zone("Lere") if t_data == date_to_sim_days("2012-03-30"): e.add_conflict_zone("Ansongo") if t_data == date_to_sim_days("2012-03-13"): e.add_conflict_zone("Dire") # Here we use the random choice to make a weighted choice between the source locations. e.add_agents_to_conflict_zones(new_refs) e.evolve() # Validation / data comparison camps = [m1,b1,b2,n1,n2,n3,n4] camp_names = ["Mbera", "Mentao", "Bobo-Dioulasso", "Abala", "Mangaize", "Niamey", "Tabareybarey"] # TODO: refactor camp_names using list comprehension. # calculate retrofitted time. refugees_in_camps_sim = 0 for c in camps: refugees_in_camps_sim += c.numAgents t_retrofitted = d.retrofit_time_to_refugee_count(refugees_in_camps_sim, camp_names) # calculate error terms. camp_pops = [] errors = [] abs_errors = [] camp_pops_retrofitted = [] errors_retrofitted = [] abs_errors_retrofitted = [] for i in range(0, len(camp_names)): # normal 1 step = 1 day errors. camp_pops += [d.get_field(camp_names[i], t, FullInterpolation=True)] errors += [a.rel_error(camps[i].numAgents, camp_pops[-1])] abs_errors += [a.abs_error(camps[i].numAgents, camp_pops[-1])] # errors when using retrofitted time stepping. camp_pops_retrofitted += [d.get_field(camp_names[i], t_retrofitted, FullInterpolation=True)] errors_retrofitted += [a.rel_error(camps[i].numAgents, camp_pops_retrofitted[-1])] abs_errors_retrofitted += [a.abs_error(camps[i].numAgents, camp_pops_retrofitted[-1])] # Total error is calculated using float(np.sum(abs_errors))/float(refugees_raw)) locations = camps loc_data = camp_pops #if e.numAgents()>0: # print "Total error: ", float(np.sum(abs_errors))/float(e.numAgents()) # write output (one line per time step taken. output = "%s" % (t) for i in range(0,len(locations)): output += ",%s,%s,%s" % (locations[i].numAgents, loc_data[i], errors[i]) if float(sum(loc_data))>0: # Reminder: Total error,refugees in camps (UNHCR),total refugees (simulation),raw UNHCR refugee count,retrofitted time,refugees in camps (simulation),Total error (retrofitted) output += ",%s,%s,%s,%s,%s,%s,%s,%s" % (float(np.sum(abs_errors))/float(refugees_raw), int(sum(loc_data)), e.numAgents(), refugees_raw, t_retrofitted, refugees_in_camps_sim, refugee_debt, float(np.sum(abs_errors_retrofitted))/float(refugees_raw)) else: output += ",0,0,0,0,0,0,0" print(output)
{ "repo_name": "djgroen/flee-release", "path": "maliv2.py", "copies": "1", "size": "12526", "license": "bsd-3-clause", "hash": -6329857009168552000, "line_mean": 38.5141955836, "line_max": 485, "alpha_frac": 0.6797062111, "autogenerated": false, "ratio": 2.714781100996966, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3894487312096966, "avg_score": null, "num_lines": null }
from flee import flee from datamanager import handle_refugee_data from datamanager import DataTable import numpy as np import outputanalysis.analysis as a import analyze_graph import sys """ Generation 1 code. Incorporates only distance, travel always takes one day. """ #Central African Republic (CAR) Simulation def date_to_sim_days(date): return DataTable.subtract_dates(date,"2013-12-01") def AddInitialRefugees(e, d, loc): """ Add the initial refugees to a location, using the location name""" num_refugees = int(d.get_field(loc.name, 0, FullInterpolation=True)) for i in range(0, num_refugees): e.addAgent(location=loc) if __name__ == "__main__": if len(sys.argv)>1: if (sys.argv[1]).isnumeric(): end_time = int(sys.argv[1]) last_physical_day = int(sys.argv[1]) else: end_time = 820 last_physical_day = 820 duration = flee.SimulationSettings.SimulationSettings.ReadFromCSV(sys.argv[1]) if duration>0: end_time = duration last_physical_day = end_time else: end_time = 820 last_physical_day = 820 e = flee.Ecosystem() #print("Conflict weight:",flee.SimulationSettings.SimulationSettings.ConflictWeight) #default movechance is 0.3 lm = {} #CAR lm["Bangui"] = e.addLocation("Bangui", pop=734350-400000) #Subtracting the number of IDPs from the population to reflect local shelter. lm["Bimbo"] = e.addLocation("Bimbo", pop=267859) lm["Mbaiki"] = e.addLocation("Mbaiki") lm["Boda"] = e.addLocation("Boda", pop=11688) lm["Nola"] = e.addLocation("Nola", pop=41462) lm["Bossembele"] = e.addLocation("Bossembele", pop=37849) lm["Berberati"] = e.addLocation("Berberati", pop=105155) lm["Gamboula"] = e.addLocation("Gamboula") lm["Carnot"] = e.addLocation("Carnot", pop=54551) lm["Bouar"] = e.addLocation("Bouar", pop=39205) lm["Baboua"] = e.addLocation("Baboua") lm["Bozoum"] = e.addLocation("Bozoum", pop=22284) lm["Paoua"] = e.addLocation("Paoua", pop=17370) lm["Bossangoa"] = e.addLocation("Bossangoa", pop=38451) lm["RN1"] = e.addLocation("RN1", movechance=1.0) #non-city junction, Coordinates = 7.112110, 17.030220 lm["Batangafo"] = e.addLocation("Batangafo", pop=16420) lm["Bouca"] = e.addLocation("Bouca", pop=12280) lm["Kabo"] = e.addLocation("Kabo") lm["Kaga Bandoro"] = e.addLocation("Kaga Bandoro", pop=27797) lm["Sibut"] = e.addLocation("Sibut", pop=24527) lm["Bamingui"] = e.addLocation("Bamingui", pop=6230) lm["Dekoa"] = e.addLocation("Dekoa", pop=12447) lm["Ndele"] = e.addLocation("Ndele", pop=13704) lm["Birao"] = e.addLocation("Birao") lm["Bria"] = e.addLocation("Bria", pop=43322) lm["Bambari"] = e.addLocation("Bambari", pop=41486) lm["Grimari"] = e.addLocation("Grimari", pop=10822) lm["Bangassou"] = e.addLocation("Bangassou", pop=35305) lm["Rafai"] = e.addLocation("Rafai", pop=13962) lm["Obo"] = e.addLocation("Obo", pop=36029) lm["Mobaye"] = e.addLocation("Mobaye") lm["Bohong"] = e.addLocation("Bohong", pop=19700) lm["Mbres"] = e.addLocation("Mbres", pop=20709) lm["Damara"] = e.addLocation("Damara", pop=32321) lm["Bogangolo"] = e.addLocation("Bogangolo", pop=9966) lm["Marali"] = e.addLocation("Marali") lm["Beboura"] = e.addLocation("Beboura") lm["RN8"] = e.addLocation("RN8", movechance=1.0) #non-city junction, Coordinates = 9.560670, 22.140450 lm["Zemio"] = e.addLocation("Zemio") camp_movechance = flee.SimulationSettings.SimulationSettings.CampMoveChance #Chad, Cameroon & Demotratic R.of Congo & R. of Congo camps starting at index locations[39] (at time of writing). lm["Amboko"] = e.addLocation("Amboko", movechance=camp_movechance, capacity=12405, foreign=True) lm["Belom"] = e.addLocation("Belom", movechance=camp_movechance, capacity=28483, foreign=True) lm["Dosseye"] = e.addLocation("Dosseye", movechance=camp_movechance, capacity=22925, foreign=True) lm["Gondje"] = e.addLocation("Gondje", movechance=camp_movechance, capacity=12171, foreign=True) lm["Moyo"] = e.addLocation("Moyo", movechance=camp_movechance, capacity=10903, foreign=True) #strange blip in the data at 14969. lm["Lolo"] = e.addLocation("Lolo", movechance=1.0, foreign=True) #forwarding location (to aggreg. camp) lm["Mbile"] = e.addLocation("Mbile", movechance=1.0, foreign=True) #forwarding location (to aggreg. camp) lm["Batouri"] = e.addLocation("Batouri") #city on junction point lm["Timangolo"] = e.addLocation("Timangolo", movechance=1.0, foreign=True, x=4.628170000, y=14.544500000) #forwarding location (to aggreg. camp) lm["Gado-Badzere"] = e.addLocation("Gado-Badzere", movechance=1.0, foreign=True) #forwarding location (to aggreg. camp) lm["East"] = e.addLocation("East", movechance=camp_movechance, capacity=180485, foreign=True) #regional camp. lm["Borgop"] = e.addLocation("Borgop", movechance=1.0, foreign=True) #forwarding location (to aggreg. camp) lm["Ngam"] = e.addLocation("Ngam", movechance=1.0, foreign=True) #forwarding location (to aggreg. camp) lm["Adamaoua"] = e.addLocation("Adamaoua", movechance=camp_movechance, capacity=71506, foreign=True) lm["Mole"] = e.addLocation("Mole", movechance=camp_movechance, capacity=20454, foreign=True) lm["Gbadolite"] = e.addLocation("Gbadolite") #city on junction point lm["N24"] = e.addLocation("N24", movechance=1.0) #non-city junction, Coordinates = 3.610560, 20.762290 lm["Bili"] = e.addLocation("Bili", movechance=camp_movechance, capacity=10282, foreign=True) #lm["Bossobolo"] = e.addLocation("Bossobolo", movechance=camp_movechance, capacity=18054, foreign=True) # excluded because Bossobolo has no measurable refugee influx. lm["Boyabu"] = e.addLocation("Boyabu", movechance=camp_movechance, capacity=20393, foreign=True) lm["Mboti"] = e.addLocation("Mboti", movechance=camp_movechance, capacity=704, foreign=True) lm["Inke"] = e.addLocation("Inke", movechance=camp_movechance, capacity=20365, foreign=True) lm["Betou"] = e.addLocation("Betou", movechance=camp_movechance, capacity=10232, foreign=True) lm["Brazaville"] = e.addLocation("Brazaville", movechance=camp_movechance, capacity=7221, foreign=True) lm["Gore"] = e.addLocation("Gore", movechance=1.0) #city on junction point, where refugees are actively encouraged to go to nearby camps. #Within CAR e.linkUp("Bangui","Bimbo","26.0") e.linkUp("Bimbo","Mbaiki","92.0") e.linkUp("Bangui","Boda","134.0") e.linkUp("Mbaiki","Boda","82.0") e.linkUp("Boda","Nola","221.0") e.linkUp("Boda","Bossembele","144.0") e.linkUp("Nola","Berberati","137.0") e.linkUp("Berberati","Gamboula","82.0") e.linkUp("Nola","Gamboula","148.0") e.linkUp("Berberati","Carnot","92.0") e.linkUp("Carnot","Bouar","140.0") e.linkUp("Bouar","Baboua","98.0") e.linkUp("Bouar","Bohong","72.0") e.linkUp("Bohong","Bozoum","101.0") e.linkUp("Bouar","Bozoum","109.0") e.linkUp("Bozoum","Carnot","186.0") e.linkUp("Bozoum","Paoua","116.0") e.linkUp("Paoua","Beboura","28.0") e.linkUp("Bozoum","Bossangoa","132.0") e.linkUp("Bossangoa","RN1","98.0") e.linkUp("Batangafo","RN1","154.0") e.linkUp("Beboura","RN1","54.0") e.linkUp("Bozoum","Bossembele","223.0") e.linkUp("Bossangoa","Bossembele","148.0") e.linkUp("Bossembele","Bogangolo","132.0") e.linkUp("Bossembele","Bangui","159.0") e.linkUp("Bossangoa","Bouca","98.0") e.linkUp("Bossangoa","Batangafo","147.0") e.linkUp("Bouca","Batangafo","84.0") e.linkUp("Batangafo","Kabo","60.0") e.linkUp("Kabo","Kaga Bandoro","107.0") e.linkUp("Batangafo","Kaga Bandoro","113.0") e.linkUp("Damara","Bogangolo","93.0") e.linkUp("Bangui","Damara","74.0") e.linkUp("Damara","Sibut","105.0") e.linkUp("Sibut","Bogangolo","127.0") e.linkUp("Bogangolo","Marali","55.0") e.linkUp("Marali","Bouca","58.0") e.linkUp("Marali","Sibut","89.0") e.linkUp("Sibut","Dekoa","69.0") e.linkUp("Dekoa","Kaga Bandoro","80.0") e.linkUp("Kaga Bandoro","Mbres","91.0") e.linkUp("Mbres","Bamingui","112.0") e.linkUp("Bamingui","Ndele","121.0") e.linkUp("Ndele","RN8","239.0") e.linkUp("RN8","Birao","114.0") e.linkUp("Birao","Bria","480.0") e.linkUp("Ndele","Bria","314.0") e.linkUp("Bria","Bambari","202.0") e.linkUp("Bambari","Grimari","77.0") e.linkUp("Grimari","Dekoa","136.0") e.linkUp("Grimari","Sibut","115.0") e.linkUp("Bria","Bangassou","282.0") e.linkUp("Bangassou","Rafai","132.0") e.linkUp("Bria","Rafai","333.0") e.linkUp("Rafai","Zemio","148.0") e.linkUp("Zemio","Obo","199.0") e.linkUp("Bangassou","Mobaye","224.0") e.linkUp("Mobaye","Bambari","213.0") e.linkUp("Mobaye","Gbadolite","146.0") e.linkUp("Gbadolite","Bangui","500.0") #CAR -> Chad e.linkUp("Kabo","Belom","89.0") e.linkUp("Beboura","Gore","87.0") e.linkUp("RN8","Moyo","186.0") # links within Chad e.linkUp("Gore","Amboko","6.0") #e.linkUp("Beboura","Amboko","93.0") e.linkUp("Gore","Gondje","15.0") #e.linkUp("Beboura","Gondje","102.0") #e.linkUp("Amboko","Gondje","7.0") #e.linkUp("Amboko","Dosseye","35.0") e.linkUp("Gore","Dosseye","34.0") #e.linkUp("Beboura","Dosseye","121.0") e.linkUp("Gamboula","Lolo","43.0") e.linkUp("Lolo","Mbile","11.0", forced_redirection=True) e.linkUp("Mbile","Batouri","56.0", forced_redirection=True) e.linkUp("Timangolo","Batouri","24.0", forced_redirection=True) e.linkUp("Batouri","East","27.0", forced_redirection=True) e.linkUp("Baboua","Gado-Badzere","81.0") e.linkUp("Gado-Badzere","Timangolo","211.0", forced_redirection=True) e.linkUp("Gado-Badzere","East","281.0", forced_redirection=True) e.linkUp("Paoua","Borgop","254.0") e.linkUp("Borgop","Ngam","44.0", forced_redirection=True) e.linkUp("Ngam","Adamaoua","272.0", forced_redirection=True) e.linkUp("Gbadolite","N24","93.0") #e.linkUp("N24","Bossobolo","23.0") #Bossobolo has been taken out (see above). e.linkUp("Bangui","Mole","42.0") e.linkUp("Mole","Boyabu","25.0") e.linkUp("Zemio","Mboti","174.0") e.linkUp("Mobaye","Mboti","662.0") e.linkUp("Gbadolite","Inke","42.0") e.linkUp("Mbaiki","Betou","148.0") e.linkUp("Nola","Brazaville","1300.0") #DEBUG: print graph and show it on an image. #vertices, edges = e.export_graph() #analyze_graph.print_graph_nx(vertices, edges, print_dist=True) #sys.exit() d = handle_refugee_data.RefugeeTable(csvformat="generic", data_directory="source_data/car2014/", start_date="2013-12-01", data_layout="data_layout.csv") #Correcting for overestimations due to inaccurate level 1 registrations in five of the camps. #These errors led to a perceived large drop in refugee population in all of these camps. #We correct by linearly scaling the values down to make the last level 1 registration match the first level 2 registration value. #To our knowledge, all level 2 registration procedures were put in place by the end of 2016. d.correctLevel1Registrations("Amboko","2015-09-30") d.correctLevel1Registrations("Belom","2015-08-31") d.correctLevel1Registrations("Dosseye","2015-09-30") d.correctLevel1Registrations("Gondje","2015-09-30") lm["Moyo"].capacity *= d.correctLevel1Registrations("Moyo","2015-06-02") #also "2014-05-11" and "2015-06-02" d.correctLevel1Registrations("East","2014-09-28") d.correctLevel1Registrations("Adamaoua","2014-10-19") #d.correctLevel1Registrations("Mole","2016-02-29") # no clear decrease visible. d.correctLevel1Registrations("Bili","2016-06-30") #d.correctLevel1Registrations("Bossobolo","2016-05-20") #Data is only decreasing over time, so no grounds for a level1 corr. d.correctLevel1Registrations("Boyabu","2016-06-30") d.correctLevel1Registrations("Inke","2014-06-30") d.correctLevel1Registrations("Betou","2014-03-22") #d.correctLevel1Registrations("Brazaville","2016-04-30") lm["Amboko"].capacity = d.getMaxFromData("Amboko", last_physical_day) lm["Belom"].capacity = d.getMaxFromData("Belom", last_physical_day) # set manually. lm["Dosseye"].capacity = d.getMaxFromData("Dosseye", last_physical_day) lm["Gondje"].capacity = d.getMaxFromData("Gondje", last_physical_day) #lm["Moyo"].capacity = d.getMaxFromData("Moyo", last_physical_day ) # blip in the data set, set capacity manually. lm["East"].capacity = d.getMaxFromData("East", last_physical_day) lm["Adamaoua"].capacity = d.getMaxFromData("Adamaoua", last_physical_day) lm["Mole"].capacity = d.getMaxFromData("Mole", last_physical_day) lm["Bili"].capacity = d.getMaxFromData("Bili", last_physical_day) #lm["Bossobolo"].capacity = d.getMaxFromData("Bossobolo", last_physical_day) #camp excluded lm["Boyabu"].capacity = d.getMaxFromData("Boyabu", last_physical_day) lm["Mboti"].capacity = d.getMaxFromData("Mboti", last_physical_day) lm["Inke"].capacity = d.getMaxFromData("Inke", last_physical_day) lm["Betou"].capacity = d.getMaxFromData("Betou", last_physical_day) lm["Brazaville"].capacity = d.getMaxFromData("Brazaville", last_physical_day) camp_locations = ["Amboko","Belom","Dosseye","Gondje","Moyo","East","Adamaoua","Mole","Bili","Boyabu","Mboti","Inke","Betou","Brazaville"] #for c in camp_locations: # print(c, lm[c].capacity, d.getMaxFromData(c, last_physical_day)) # Add initial refugees to the destinations. output_header_string = "Day," for i in camp_locations: l = lm[i] AddInitialRefugees(e,d,l) output_header_string += "%s sim,%s data,%s error," % (l.name, l.name, l.name) output_header_string += "Total error,refugees in camps (UNHCR),total refugees (simulation),raw UNHCR refugee count,retrofitted time,refugees in camps (simulation),refugee_debt,Total error (retrofitted)" print(output_header_string) #Set up a mechanism to incorporate temporary decreases in refugees refugee_debt = 0 refugees_raw = 0 #raw (interpolated) data from TOTAL UNHCR refugee count only #Append conflict_zones and weights to list from ACLED conflict database. #Conflict zones year before the start of simulation period #if t_data == date_to_sim_days("2012-12-10"): e.add_conflict_zone("Ndele") #if t_data == date_to_sim_days("2012-12-15"): e.add_conflict_zone("Bamingui") #if t_data == date_to_sim_days("2012-12-28"): e.add_conflict_zone("Bambari") #if t_data == date_to_sim_days("2013-01-18"): e.add_conflict_zone("Obo") #if t_data == date_to_sim_days("2013-03-11"): e.add_conflict_zone("Bangassou") #if t_data == date_to_sim_days("2013-03-24"): e.add_conflict_zone("Bangui") # Main capital entry. Bangui has 100,000s-500,000 IDPs though. #if t_data == date_to_sim_days("2013-04-17"): e.add_conflict_zone("Mbres") #if t_data == date_to_sim_days("2013-05-03"): e.add_conflict_zone("Bohong") #if t_data == date_to_sim_days("2013-05-17"): e.add_conflict_zone("Bouca") #if t_data == date_to_sim_days("2013-09-07"): e.add_conflict_zone("Bossangoa") #if t_data == date_to_sim_days("2013-09-14"): e.add_conflict_zone("Bossembele") #if t_data == date_to_sim_days("2013-10-10"): e.add_conflict_zone("Bogangolo") #if t_data == date_to_sim_days("2013-10-26"): e.add_conflict_zone("Bouar") #if t_data == date_to_sim_days("2013-11-10"): e.add_conflict_zone("Rafai") #if t_data == date_to_sim_days("2013-11-28"): e.add_conflict_zone("Damara") # Start with a refugee debt to account for the mismatch between camp aggregates and total UNHCR data. refugee_debt = e.numAgents() t_retrofitted = 0 for t in range(0,end_time): e.refresh_conflict_weights() t_data = t # Determine number of new refugees to insert into the system. new_refs = d.get_daily_difference(t, FullInterpolation=True) - refugee_debt refugees_raw += d.get_daily_difference(t, FullInterpolation=True) if new_refs < 0: refugee_debt = -new_refs new_refs = 0 elif refugee_debt > 0: refugee_debt = 0 new_links = [] #CAR/DRC border is closed on the 5th of December 2013. Appears to remain closed until the 30th of June #Source: http://data.unhcr.org/car/download.php if t_data == date_to_sim_days("2013-12-05"): e.remove_link("Bangui","Mole") e.remove_link("Gbadolite","Inke") e.remove_link("Gbadolite","N24") e.remove_link("Zemio","Mboti") e.remove_link("Mobaye","Mboti") if t_data == date_to_sim_days("2014-06-30"): e.linkUp("Bangui","Mole","42.0") e.linkUp("Gbadolite","Inke","42.0") e.linkUp("Gbadolite","N24","93.0") e.linkUp("Zemio","Mboti","174.0") e.linkUp("Mobaye","Mboti","662.0") # 12 Feb. In Mole, refugees who were waiting to be registered and relocated received their food rations from the WFP.   # Source: http://data.unhcr.org/car/download.php?id=22 # 19 Feb: drop of IDPs in Bangui from 400k to 273k. # Close borders here: On the 12th of May 2014, Chad closes border altogether. if t_data == date_to_sim_days("2014-05-12"): e.remove_link("Kabo","Belom") e.remove_link("Beboura","Gore") e.remove_link("RN8","Moyo") #Optional: write graph image for debugging purposes. #vertices, edges = e.export_graph() #analyze_graph.print_graph_nx(vertices, edges, print_dist=True) #sys.exit() # Bili camp opens on April 1st, 2015. if t_data == date_to_sim_days("2015-04-01"): e.linkUp("N24","Bili","20.0") #There is no road after 93km to the camp & the remaining 20km was found by distance calculator (www.movable-type.co.uk/scripts/latlong.html) #Optional: write graph image for debugging purposes. #vertices, edges = e.export_graph() #analyze_graph.print_graph_nx(vertices, edges, print_dist=True) #Conflict zones after the start of simulation period if t_data == date_to_sim_days("2013-12-06"): #A wave of reprisal attacks & escalating cycle of violence between Seleka militia and Anti-Balaka e.add_conflict_zone("Bozoum") #if t_data == date_to_sim_days("2013-12-21"): #MISCA: African-led International Support Mission against Anti-balaka (deaths & thousnads displaced) # e.add_conflict_zone("Bossangoa") if t_data == date_to_sim_days("2014-01-01"): #Violence & death in battles between Seleka militia and Anti-Balaka e.add_conflict_zone("Bimbo") #if t_data == date_to_sim_days("2014-01-19"): #Violence & battles of Seleka militia with Anti-Balaka # e.add_conflict_zone("Bambari") #if t_data == date_to_sim_days("2014-01-20"): # e.add_conflict_zone("Bouar") if t_data == date_to_sim_days("2014-01-28"): #Battles between Seleka militia and Anti-Balaka e.add_conflict_zone("Boda") if t_data == date_to_sim_days("2014-02-06"): #Battles between Seleka militia and Anti-Balaka e.add_conflict_zone("Kaga Bandoro") if t_data == date_to_sim_days("2014-02-11"): ##Battles between Military forces and Anti-Balaka e.add_conflict_zone("Berberati") #if t_data == date_to_sim_days("2014-02-16"): #Battles between Seleka militia and Salanze Communal Militia # e.add_conflict_zone("Bangassou") #if t_data == date_to_sim_days("2014-03-08"): #Battles between Seleka militia and Sangaris (French Mission) # e.add_conflict_zone("Ndele") if t_data == date_to_sim_days("2014-03-11"): #MISCA: African-led International Support Mission against Anti-balaka e.add_conflict_zone("Nola") if t_data == date_to_sim_days("2014-04-08"): #Battles between Seleka militia and Anti-Balaka e.add_conflict_zone("Dekoa") if t_data == date_to_sim_days("2014-04-10"): #Battles of Bria Communal Militia (Seleka Militia) and MISCA (African-led International Support Mission) e.add_conflict_zone("Bria") if t_data == date_to_sim_days("2014-04-14"): #Battles between Anti-Balaka and Seleka militia e.add_conflict_zone("Grimari") #if t_data == date_to_sim_days("2014-04-23"): #Battles between Seleka militia and Anti-Balaka # e.add_conflict_zone("Bouca") if t_data == date_to_sim_days("2014-04-26"): #Battles by unidentified Armed groups e.add_conflict_zone("Paoua") if t_data == date_to_sim_days("2014-05-23"): #MISCA: African-led International Support Mission against Anti-balaka e.add_conflict_zone("Carnot") if t_data == date_to_sim_days("2014-07-30"): #Battles between Anti-Balaka and Seleka militia e.add_conflict_zone("Batangafo") if t_data == date_to_sim_days("2014-10-10"): #MINUSCA: United Nations Multidimensional Integrated Stabilization Mission against Seleka militia (PRGF Faction) e.add_conflict_zone("Sibut") #Insert refugee agents e.add_agents_to_conflict_zones(new_refs) #Propagate the model by one time step. e.evolve() #e.printInfo() #Calculation of error terms errors = [] abs_errors = [] loc_data = [] camps = [] for i in camp_locations: camps += [lm[i]] loc_data += [d.get_field(i, t)] camp_pops_retrofitted = [] errors_retrofitted = [] abs_errors_retrofitted = [] # calculate retrofitted time. refugees_in_camps_sim = 0 for c in camps: refugees_in_camps_sim += c.numAgents t_retrofitted = d.retrofit_time_to_refugee_count(refugees_in_camps_sim, camp_locations) # calculate errors j=0 for i in camp_locations: errors += [a.rel_error(lm[i].numAgents, loc_data[j])] abs_errors += [a.abs_error(lm[i].numAgents, loc_data[j])] # errors when using retrofitted time stepping. camp_pops_retrofitted += [d.get_field(i, t_retrofitted, FullInterpolation=True)] errors_retrofitted += [a.rel_error(lm[i].numAgents, camp_pops_retrofitted[-1])] abs_errors_retrofitted += [a.abs_error(lm[i].numAgents, camp_pops_retrofitted[-1])] j += 1 output = "%s" % t for i in range(0,len(errors)): output += ",%s,%s,%s" % (lm[camp_locations[i]].numAgents, loc_data[i], errors[i]) if refugees_raw>0: #output_string += ",%s,%s,%s,%s" % (float(np.sum(abs_errors))/float(refugees_raw), int(sum(loc_data)), e.numAgents(), refugees_raw) output += ",%s,%s,%s,%s,%s,%s,%s,%s" % (float(np.sum(abs_errors))/float(refugees_raw), int(sum(loc_data)), e.numAgents(), refugees_raw, t_retrofitted, refugees_in_camps_sim, refugee_debt, float(np.sum(abs_errors_retrofitted))/float(refugees_raw)) else: output += ",0,0,0,0,0,0,0" #output_string += ",0" print(output)
{ "repo_name": "djgroen/flee-release", "path": "car.py", "copies": "1", "size": "22283", "license": "bsd-3-clause", "hash": -5844967816829778000, "line_mean": 42.5851272016, "line_max": 252, "alpha_frac": 0.6734913793, "autogenerated": false, "ratio": 2.647961003447866, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.38214523827478664, "avg_score": null, "num_lines": null }
from flee import flee from datamanager import handle_refugee_data from datamanager import DataTable import numpy as np import outputanalysis.analysis as a import sys """ Generation 1 code. Incorporates only distance, travel always takes one day. """ #Burundi Simulation def date_to_sim_days(date): return DataTable.subtract_dates(date,"2015-05-01") if __name__ == "__main__": if len(sys.argv)>1: if (sys.argv[1]).isnumeric(): end_time = int(sys.argv[1]) last_physical_day = int(sys.argv[1]) else: end_time = 396 last_physical_day = 396 duration = flee.SimulationSettings.SimulationSettings.ReadFromCSV(sys.argv[1]) if duration>0: end_time = duration last_physical_day = end_time else: end_time = 396 last_physical_day = 396 e = flee.Ecosystem() locations = [] #Burundi locations.append(e.addLocation("Bujumbura", movechance="conflict", pop=497166)) locations.append(e.addLocation("Bubanza", movechance="default")) locations.append(e.addLocation("Bukinanyana", movechance="default", pop=75750)) locations.append(e.addLocation("Cibitoke", movechance="default", pop=460435)) locations.append(e.addLocation("Isale", movechance="default")) locations.append(e.addLocation("Muramvya", movechance="default")) locations.append(e.addLocation("Kayanza", movechance="default")) locations.append(e.addLocation("Kabarore", movechance="default", pop=62303)) #This resides in Kayanza province in Burundi. Not to be confused with Kabarore, Rwanda. locations.append(e.addLocation("Mwaro", movechance="default", pop=273143)) locations.append(e.addLocation("Rumonge", movechance="default")) locations.append(e.addLocation("Burambi", movechance="default", pop=57167)) locations.append(e.addLocation("Bururi", movechance="default")) locations.append(e.addLocation("Rutana", movechance="default")) locations.append(e.addLocation("Makamba", movechance="default")) locations.append(e.addLocation("Gitega", movechance="default")) locations.append(e.addLocation("Karuzi", movechance="default")) locations.append(e.addLocation("Ruyigi", movechance="default")) locations.append(e.addLocation("Gisuru", movechance="default", pop=99461)) locations.append(e.addLocation("Cankuzo", movechance="default")) locations.append(e.addLocation("Muyinga", movechance="default")) locations.append(e.addLocation("Kirundo", movechance="default")) locations.append(e.addLocation("Ngozi", movechance="default")) locations.append(e.addLocation("Gashoho", movechance="default")) locations.append(e.addLocation("Gitega-Ruyigi", movechance="default")) locations.append(e.addLocation("Makebuko", movechance="default")) locations.append(e.addLocation("Commune of Mabanda", movechance="default")) #Rwanda, Tanzania, Uganda and DRCongo camps locations.append(e.addLocation("Mahama", movechance="camp", capacity=49451, foreign=True)) locations.append(e.addLocation("Nduta", movechance="default", capacity=55320, foreign=True)) # Nduta open on 2015-08-10 locations.append(e.addLocation("Kagunga", movechance=1/21.0, foreign=True)) locations.append(e.addLocation("Nyarugusu", movechance="camp", capacity=100925, foreign=True)) locations.append(e.addLocation("Nakivale", movechance="camp", capacity=18734, foreign=True)) locations.append(e.addLocation("Lusenda", movechance="default", capacity=17210, foreign=True)) #Within Burundi e.linkUp("Bujumbura","Bubanza","48.0") e.linkUp("Bubanza","Bukinanyana","74.0") e.linkUp("Bujumbura","Cibitoke","63.0") e.linkUp("Cibitoke","Bukinanyana","49.0") e.linkUp("Bujumbura","Muramvya","58.0") e.linkUp("Muramvya","Gitega","44.0") e.linkUp("Gitega","Karuzi","54.0") e.linkUp("Gitega","Ruyigi","55.0") e.linkUp("Ruyigi","Karuzi","43.0") e.linkUp("Karuzi","Muyinga","42.0") e.linkUp("Bujumbura","Kayanza","95.0") e.linkUp("Kayanza","Ngozi","31.0") ## e.linkUp("Ngozi","Gashoho","41.0") ## e.linkUp("Kayanza","Kabarore","18.0") e.linkUp("Gashoho","Kirundo","42.0") e.linkUp("Gashoho","Muyinga","34.0") e.linkUp("Bujumbura","Mwaro","67.0") e.linkUp("Mwaro","Gitega","46.0") e.linkUp("Bujumbura","Rumonge","75.0") e.linkUp("Rumonge","Bururi","31.0") e.linkUp("Rumonge","Burambi","22.0") e.linkUp("Rumonge","Commune of Mabanda","73.0") e.linkUp("Commune of Mabanda","Makamba","18.0") # ?? e.linkUp("Bururi","Rutana","65.0") e.linkUp("Makamba","Rutana","50.0") # ?? e.linkUp("Rutana","Makebuko","46.0") # ?? e.linkUp("Makebuko","Gitega","24.0") # ?? e.linkUp("Makebuko","Ruyigi","40.0") e.linkUp("Ruyigi","Cankuzo","51.0") e.linkUp("Ruyigi","Gisuru","31.0") e.linkUp("Cankuzo","Muyinga","63.0") #Camps, starting at index locations[26] (at time of writing). e.linkUp("Muyinga","Mahama","135.0") e.linkUp("Kirundo","Mahama","183.0") #Shorter route than via Gashoho and Muyinga. Goes through Bugesera, where a transit centre is located according to UNHCR reports. e.linkUp("Gisuru","Nduta","60.0") e.linkUp("Commune of Mabanda","Kagunga","36.0") e.linkUp("Commune of Mabanda","Nyarugusu","71.0") #Estimated distance, as exact location of Nyarugusu is uncertain. e.linkUp("Kagunga","Nyarugusu","91.0", forced_redirection=True) #From Kagunga to Kigoma by ship (Kagunga=Kigoma) e.linkUp("Kirundo","Nakivale","318.0") e.linkUp("Kayanza","Nakivale","413.0") e.linkUp("Nduta","Nyarugusu","150.0", forced_redirection=True) #distance needs to be checked. d = handle_refugee_data.RefugeeTable(csvformat="generic", data_directory="source_data/burundi2015", start_date="2015-05-01") # Correcting for overestimations due to inaccurate level 1 registrations in five of the camps. # These errors led to a perceived large drop in refugee population in all of these camps. # We correct by linearly scaling the values down to make the last level 1 registration match the first level 2 registration value. # To our knowledge, all level 2 registration procedures were put in place by the end of 2016. d.correctLevel1Registrations("Mahama","2015-10-04") d.correctLevel1Registrations("Nduta","2016-04-06") d.correctLevel1Registrations("Nyarugusu","2015-11-10") d.correctLevel1Registrations("Nakivale","2015-08-18") d.correctLevel1Registrations("Lusenda","2015-09-30") locations[26].capacity = d.getMaxFromData("Mahama", last_physical_day) locations[27].capacity = d.getMaxFromData("Nduta", last_physical_day) locations[29].capacity = d.getMaxFromData("Nyarugusu", last_physical_day) locations[30].capacity = d.getMaxFromData("Nakivale", last_physical_day) locations[31].capacity = d.getMaxFromData("Lusenda", last_physical_day) list_of_cities = "Time" for l in locations: list_of_cities = "%s,%s" % (list_of_cities, l.name) #print(list_of_cities) #print("Time, campname") print("Day,Mahama sim,Mahama data,Mahama error,Nduta sim,Nduta data,Nduta error,Nyarugusu sim,Nyarugusu data,Nyarugusu error,Nakivale sim,Nakivale data,Nakivale error,Lusenda sim,Lusenda data,Lusenda error,Total error,refugees in camps (UNHCR),total refugees (simulation),raw UNHCR refugee count,retrofitted time,refugees in camps (simulation),refugee_debt,Total error (retrofitted)") #Set up a mechanism to incorporate temporary decreases in refugees refugee_debt = 0 refugees_raw = 0 #raw (interpolated) data from TOTAL UNHCR refugee count only e.add_conflict_zone("Bujumbura") t_retrofitted = 0 for t in range(0,end_time): t_data = t #Lusenda camp open on the 30th of July 2015 if t_data == date_to_sim_days("2015-07-30"): #Open Lusenda locations[31].SetCampMoveChance() locations[31].Camp=True e.linkUp("Bujumbura","Lusenda","53.0") #Only added when the refugee inflow starts at Lusenda, on 30-07-2015 if t_data == date_to_sim_days("2015-08-10"): locations[27].SetCampMoveChance() locations[27].Camp=True e.remove_link("Nduta","Nyarugusu") e.linkUp("Nduta","Nyarugusu","150.0") #Re-add link, but without forced redirection #Append conflict_zone and weight to list. #Conflict zones after the start of simulation period if t_data == date_to_sim_days("2015-07-10"): #Intense fighting between military & multineer military forces e.add_conflict_zone("Kabarore") elif t_data == date_to_sim_days("2015-07-11"): #Intense fighting between military & mulineer military forces e.add_conflict_zone("Bukinanyana") elif t_data == date_to_sim_days("2015-07-15"): #Battles unidentified armed groups coordinately attacked military barracks e.add_conflict_zone("Cibitoke") elif t_data == date_to_sim_days("2015-10-26"): #Clashes and battles police forces e.add_conflict_zone("Mwaro") elif t_data == date_to_sim_days("2015-11-23"): #Battles unidentified armed groups coordinate attacks e.add_conflict_zone("Gisuru") elif t_data == date_to_sim_days("2015-12-08"): #Military forces e.add_conflict_zone("Burambi") #new_refs = d.get_new_refugees(t) new_refs = d.get_new_refugees(t, FullInterpolation=True) - refugee_debt refugees_raw += d.get_new_refugees(t, FullInterpolation=True) if new_refs < 0: refugee_debt = -new_refs new_refs = 0 elif refugee_debt > 0: refugee_debt = 0 # Here we use the random choice to make a weighted choice between the source locations. e.add_agents_to_conflict_zones(new_refs) #Propagate the model by one time step. e.evolve() #e.printInfo() #Validation/data comparison mahama_data = d.get_field("Mahama", t) #- d.get_field("Mahama", 0) nduta_data = d.get_field("Nduta", t) #-d.get_field("Nduta", 0) nyarugusu_data = d.get_field("Nyarugusu", t) #- d.get_field("Nyarugusu", 0) nakivale_data = d.get_field("Nakivale", t) #- d.get_field("Nakivale", 0) lusenda_data = d.get_field("Lusenda", t) #- d.get_field("Lusenda", 0) errors = [] abs_errors = [] loc_data = [mahama_data, nduta_data, nyarugusu_data, nakivale_data, lusenda_data] camp_locations = [26, 27, 29, 30, 31] camps = [] for i in camp_locations: camps += [locations[i]] camp_names = ["Mahama", "Nduta", "Nyarugusu", "Nakivale", "Lusenda"] camp_pops_retrofitted = [] errors_retrofitted = [] abs_errors_retrofitted = [] # calculate retrofitted time. refugees_in_camps_sim = 0 for c in camps: refugees_in_camps_sim += c.numAgents t_retrofitted = d.retrofit_time_to_refugee_count(refugees_in_camps_sim, camp_names) # calculate errors for i in range(0,len(camp_locations)): camp_number = camp_locations[i] errors += [a.rel_error(locations[camp_number].numAgents, loc_data[i])] abs_errors += [a.abs_error(locations[camp_number].numAgents, loc_data[i])] # errors when using retrofitted time stepping. camp_pops_retrofitted += [d.get_field(camp_names[i], t_retrofitted, FullInterpolation=True)] errors_retrofitted += [a.rel_error(camps[i].numAgents, camp_pops_retrofitted[-1])] abs_errors_retrofitted += [a.abs_error(camps[i].numAgents, camp_pops_retrofitted[-1])] output = "%s" % t for i in range(0,len(errors)): camp_number = camp_locations[i] output += ",%s,%s,%s" % (locations[camp_number].numAgents, loc_data[i], errors[i]) if refugees_raw>0: #output_string += ",%s,%s,%s,%s" % (float(np.sum(abs_errors))/float(refugees_raw), int(sum(loc_data)), e.numAgents(), refugees_raw) output += ",%s,%s,%s,%s,%s,%s,%s,%s" % (float(np.sum(abs_errors))/float(refugees_raw), int(sum(loc_data)), e.numAgents(), refugees_raw, t_retrofitted, refugees_in_camps_sim, refugee_debt, float(np.sum(abs_errors_retrofitted))/float(refugees_raw)) else: output += ",0,0,0,0,0,0,0" #output_string += ",0" print(output)
{ "repo_name": "djgroen/flee-release", "path": "burundi.py", "copies": "1", "size": "11810", "license": "bsd-3-clause", "hash": 4251455919482989000, "line_mean": 42.102189781, "line_max": 386, "alpha_frac": 0.6929720576, "autogenerated": false, "ratio": 2.779477524123323, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3972449581723323, "avg_score": null, "num_lines": null }
from flee import pflee from datamanager import handle_refugee_data from datamanager import DataTable #DataTable.subtract_dates() from flee import InputGeography import numpy as np import outputanalysis.analysis as a import sys import argparse import time def date_to_sim_days(date): return DataTable.subtract_dates(date,"2010-01-01") if __name__ == "__main__": t_exec_start = time.time() end_time = 10 last_physical_day = 10 parser = argparse.ArgumentParser(description='Run a parallel Flee benchmark.') parser.add_argument("-p", "--parallelmode", type=str, default="advanced", help="Parallelization mode (advanced, classic, cl-hilat OR adv-lowlat)") parser.add_argument("-N", "--initialagents", type=int, default=100000, help="Number of agents at the start of the simulation.") parser.add_argument("-d", "--newagentsperstep", type=int, default=1000, help="Number of agents added per time step.") parser.add_argument("-t", "--simulationperiod", type=int, default=10, help="Duration of the simulation in days.") parser.add_argument("-i", "--inputdir", type=str, default="test_data/test_input_csv", help="Directory with parallel test input. Must have locations named 'A','D','E' and 'F'.") args = parser.parse_args() end_time = args.simulationperiod last_physical_day = args.simulationperiod e = pflee.Ecosystem() if args.parallelmode is "advanced" or "adv-lowlat": e.parallel_mode = "loc-par" else: e.parallel_mode = "classic" if args.parallelmode is "advanced" or "cl-hilat": e.latency_mode = "high_latency" else: e.latency_mode = "low_latency" print("MODE: ", args, file=sys.stderr) ig = InputGeography.InputGeography() ig.ReadLocationsFromCSV("%s/locations.csv" % args.inputdir) ig.ReadLinksFromCSV("%s/routes.csv" % args.inputdir) ig.ReadClosuresFromCSV("%s/closures.csv" % args.inputdir) e,lm = ig.StoreInputGeographyInEcosystem(e) #print("Network data loaded") #d = handle_refugee_data.RefugeeTable(csvformat="generic", data_directory="test_data/test_input_csv/refugee_data", start_date="2010-01-01", data_layout="data_layout.csv") output_header_string = "Day," camp_locations = e.get_camp_names() ig.AddNewConflictZones(e,0) # All initial refugees start in location A. e.add_agents_to_conflict_zones(args.initialagents) for l in camp_locations: output_header_string += "%s sim,%s data,%s error," % (lm[l].name, lm[l].name, lm[l].name) output_header_string += "Total error,refugees in camps (UNHCR),total refugees (simulation),raw UNHCR refugee count,refugees in camps (simulation),refugee_debt" if e.getRankN(0): print(output_header_string) # Set up a mechanism to incorporate temporary decreases in refugees refugees_raw = 0 #raw (interpolated) data from TOTAL UNHCR refugee count only. t_exec_init = time.time() if e.getRankN(0): my_file = open('perf.log', 'w', encoding='utf-8') print("Init time,{}".format(t_exec_init - t_exec_start), file=my_file) for t in range(0,end_time): if t>0: ig.AddNewConflictZones(e,t) # Determine number of new refugees to insert into the system. new_refs = args.newagentsperstep refugees_raw += new_refs #Insert refugee agents e.add_agents_to_conflict_zones(new_refs) e.refresh_conflict_weights() t_data = t e.enact_border_closures(t) e.evolve() #Calculation of error terms errors = [] abs_errors = [] camps = [] for i in camp_locations: camps += [lm[i]] # calculate retrofitted time. refugees_in_camps_sim = 0 for c in camps: refugees_in_camps_sim += c.numAgents output = "%s" % t for i in range(0,len(camp_locations)): output += ",%s" % (lm[camp_locations[i]].numAgents) if refugees_raw>0: output += ",%s,%s" % (e.numAgents(), refugees_in_camps_sim) else: output += ",0,0" if e.getRankN(t): print(output) t_exec_end = time.time() if e.getRankN(0): my_file = open('perf.log', 'a', encoding='utf-8') print("Time in main loop,{}".format(t_exec_end - t_exec_init), file=my_file)
{ "repo_name": "djgroen/flee-release", "path": "test_par.py", "copies": "1", "size": "4169", "license": "bsd-3-clause", "hash": 5394552411202746000, "line_mean": 28.9928057554, "line_max": 172, "alpha_frac": 0.6706644279, "autogenerated": false, "ratio": 3.113517550410754, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9204952663129813, "avg_score": 0.01584586303618845, "num_lines": 139 }
from flee import pflee #parallel implementation from flee import coupling #coupling interface for multiscale models from datamanager import handle_refugee_data from datamanager import DataTable #DataTable.subtract_dates() from flee import InputGeography import numpy as np import outputanalysis.analysis as a import sys import analyze_graph def AddInitialRefugees(e, loc): """ Add the initial refugees to a location, using the location name""" num_refugees = 10000 for i in range(0, num_refugees): e.addAgent(location=loc) def date_to_sim_days(date): return DataTable.subtract_dates(date,"2010-01-01") if __name__ == "__main__": end_time = 10 last_physical_day = 10 submodel_id = 0 if len(sys.argv)>1: if (sys.argv[1]).isnumeric(): submodel_id = int(sys.argv[1]) #duration = pflee.SimulationSettings.SimulationSettings.ReadFromCSV(sys.argv[1]) #if duration>0: # end_time = duration # last_physical_day = end_time e = pflee.Ecosystem() c = coupling.CouplingInterface(e) c.setCouplingFilenames("in","out") if(submodel_id > 0): c.setCouplingFilenames("out","in") ig = InputGeography.InputGeography() ig.ReadLocationsFromCSV("examples/testmscale/locations-%s.csv" % submodel_id) ig.ReadLinksFromCSV("examples/testmscale/routes-%s.csv" % submodel_id) ig.ReadClosuresFromCSV("examples/testmscale/closures-%s.csv" % submodel_id) e,lm = ig.StoreInputGeographyInEcosystem(e) #DEBUG: print graph and show it on an image. vertices, edges = e.export_graph() #analyze_graph.print_graph_nx(vertices, edges, print_dist=True) #sys.exit() #print("Network data loaded") #d = handle_refugee_data.RefugeeTable(csvformat="generic", data_directory="test_data/test_input_csv/refugee_data", start_date="2010-01-01", data_layout="data_layout.csv") output_header_string = "Day," coupled_locations = ["N","E","S","W"] camp_locations = list(lm.keys()) #print(camp_locations) #camp_locations = ["N","E","S","W"] #if(submodel_id > 0): # camp_locations = ["A","B"] #TODO: Add Camps from CSV based on their location type. if submodel_id == 0: AddInitialRefugees(e,lm["A"]) for l in coupled_locations: c.addCoupledLocation(lm[l], l) for l in camp_locations: output_header_string += "%s sim," % (lm[l].name) if e.getRankN(0): output_header_string += "num agents,num agents in camps" print(output_header_string) # Set up a mechanism to incorporate temporary decreases in refugees refugee_debt = 0 refugees_raw = 0 #raw (interpolated) data from TOTAL UNHCR refugee count only. for t in range(0,end_time): #if t>0: ig.AddNewConflictZones(e,t) # Determine number of new refugees to insert into the system. new_refs = 0 if submodel_id == 0: new_refs = 0 refugees_raw += new_refs #Insert refugee agents if submodel_id == 0: e.add_agents_to_conflict_zones(new_refs) e.refresh_conflict_weights() t_data = t #e.enact_border_closures(t) e.evolve() #Calculation of error terms errors = [] abs_errors = [] camps = [] for i in camp_locations: camps += [lm[i]] # calculate retrofitted time. refugees_in_camps_sim = 0 for camp in camps: refugees_in_camps_sim += camp.numAgents if e.getRankN(t): output = "%s" % t for i in range(0,len(camp_locations)): output += ",%s" % (lm[camp_locations[i]].numAgents) if refugees_raw>0: output += ",%s,%s" % (e.numAgents(), refugees_in_camps_sim) else: output += ",0,0" print(output) #exchange data with other code. c.Couple(t)
{ "repo_name": "djgroen/flee-release", "path": "mscalecity.py", "copies": "1", "size": "3676", "license": "bsd-3-clause", "hash": 6563539744643333000, "line_mean": 25.8321167883, "line_max": 172, "alpha_frac": 0.662132753, "autogenerated": false, "ratio": 3.030502885408079, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4192635638408079, "avg_score": null, "num_lines": null }
from .fleet_object import FleetObject try: # pragma: no cover # python 2 from StringIO import StringIO except ImportError: # pragma: no cover # python 3 from io import StringIO class Unit(FleetObject): """This object represents a Unit in Fleet Create and modify Unit entities to communicate to fleet the desired state of the cluster. This simply declares what should be happening; the backend system still has to react to the changes in this desired state. The actual state of the system is communicated with UnitState entities. Attributes (all are readonly): Always available: options (update with add_option, remove_option): list of UnitOption entities desiredState: (update with set_desired_state): state the user wishes the Unit to be in ("inactive", "loaded", or "launched") Available once units are submitted to fleet: name: unique identifier of entity currentState: state the Unit is currently in (same possible values as desiredState) machineID: ID of machine to which the Unit is scheduled A UnitOption represents a single option in a systemd unit file. section: name of section that contains the option (e.g. "Unit", "Service", "Socket") name: name of option (e.g. "BindsTo", "After", "ExecStart") value: value of option (e.g. "/usr/bin/docker run busybox /bin/sleep 1000") """ _STATES = ['inactive', 'loaded', 'launched'] def __init__(self, client=None, data=None, desired_state=None, options=None, from_file=None, from_string=None): """Create a new unit Args: client (fleet.v1.Client, optional): The fleet client that retrieved this object data (dict, optional): Initialize this object with this data. If this is used you must not specify options, desired_state, from_file, or from_string desired_state (string, optional): The desired_state for this object, defaults to 'launched' if not specified If you do not specify data, You may specify one of the following args to initialize the object: options (list, optional): A list of options to initialize the object with. from_file (str, optional): Initialize this object from the unit file on disk at this path from_string (str, optional): Initialize this object from the unit file in this string If none are specified, an empty unit will be created Raises: IOError: from_file was specified and it does not exist ValueError: Conflicting options, or The unit contents specified in from_string or from_file is not valid """ # make sure if they specify data, then they didn't specify anything else if data and (desired_state or options or from_file or from_string): raise ValueError('If you specify data you can not specify desired_state,' 'options, from_file, or from_string') # count how many of options, from_file, from_string we have given = 0 for thing in [options, from_file, from_string]: if thing: given += 1 # we should only have one, if we have more, yell at them if given > 1: raise ValueError('You must specify only one of options, from_file, from_string') # ensure we have a minimum structure if we aren't passed one if data is None: # we set this here, instead as a default value to the arg # as we want to be able to check it vs data above, it should be None in that case if desired_state is None: desired_state = 'launched' if options is None: options = [] # Minimum structure required by fleet data = { 'desiredState': desired_state, 'options': options } # Call the parent class to configure us super(Unit, self).__init__(client=client, data=data) # If they asked us to load from a file, attemp to slurp it up if from_file: with open(from_file, 'r') as fh: self._set_options_from_file(fh) # If they asked us to load from a string, lie to the loader with StringIO if from_string: self._set_options_from_file(StringIO(from_string)) def __repr__(self): return '<{0}: {1}>'.format( self.__class__.__name__, self.as_dict() ) def __str__(self): """Generate a Unit file representation of this object""" # build our output here output = [] # get a ist of sections sections = set([x['section'] for x in self._data['options']]) for section in sections: # for each section, add it to our output output.append(u'[{0}]'.format(section)) # iterate through the list of options, adding all items to this section for option in self._data['options']: if option['section'] == section: output.append(u'{0}={1}'.format(option['name'], option['value'])) # join and return the output return u"\n".join(output) def _set_options_from_file(self, file_handle): """Parses a unit file and updates self._data['options'] Args: file_handle (file): a file-like object (supporting read()) containing a unit Returns: True: The file was successfuly parsed and options were updated Raises: IOError: from_file was specified and it does not exist ValueError: The unit contents specified in from_string or from_file is not valid """ # TODO: Find a library to handle this unit file parsing # Can't use configparser, it doesn't handle multiple entries for the same key in the same section # This is terribly naive # build our output here options = [] # keep track of line numbers to report when parsing problems happen line_number = 0 # the section we are currently in section = None for line in file_handle.read().splitlines(): line_number += 1 # clear any extra white space orig_line = line line = line.strip() # ignore comments, and blank lines if not line or line.startswith('#'): continue # is this a section header? If so, update our variable and continue # Section headers look like: [Section] if line.startswith('[') and line.endswith(']'): section = line.strip('[]') continue # We encountered a non blank line outside of a section, this is a problem if not section: raise ValueError( 'Unable to parse unit file; ' 'Unexpected line outside of a section: {0} (line: {1}'.format( line, line_number )) # Attempt to parse a line inside a section # Lines should look like: name=value \ # continuation continuation = False try: # if the previous value ends with \ then we are a continuation # so remove the \, and set the flag so we'll append to this below if options[-1]['value'].endswith('\\'): options[-1]['value'] = options[-1]['value'][:-1] continuation = True except IndexError: pass try: # if we are a continuation, then just append our value to the previous line if continuation: options[-1]['value'] += orig_line continue # else we are a normal line, so spit and get our name / value name, value = line.split('=', 1) options.append({ 'section': section, 'name': name, 'value': value }) except ValueError: raise ValueError( 'Unable to parse unit file; ' 'Malformed line in section {0}: {1} (line: {2})'.format( section, line, line_number )) # update our internal structure self._data['options'] = options return True def _is_live(self): """Checks to see if this unit came from fleet, or was created locally Only units with a .name property (set by the server), and _client property are considered 'live' Returns: True: The object is live False: The object is not """ if 'name' in self._data and self._client: return True return False def add_option(self, section, name, value): """Add an option to a section of the unit file Args: section (str): The name of the section, If it doesn't exist it will be created name (str): The name of the option to add value (str): The value of the option Returns: True: The item was added """ # Don't allow updating units we loaded from fleet, it's not supported if self._is_live(): raise RuntimeError('Submitted units cannot update their options') option = { 'section': section, 'name': name, 'value': value } self._data['options'].append(option) return True def remove_option(self, section, name, value=None): """Remove an option from a unit Args: section (str): The section to remove from. name (str): The item to remove. value (str, optional): If specified, only the option matching this value will be removed If not specified, all options with ``name`` in ``section`` will be removed Returns: True: At least one item was removed False: The item requested to remove was not found """ # Don't allow updating units we loaded from fleet, it's not supported if self._is_live(): raise RuntimeError('Submitted units cannot update their options') removed = 0 # iterate through a copy of the options for option in list(self._data['options']): # if it's in our section if option['section'] == section: # and it matches our name if option['name'] == name: # and they didn't give us a value, or it macthes if value is None or option['value'] == value: # nuke it from the source self._data['options'].remove(option) removed += 1 if removed > 0: return True return False def destroy(self): """Remove a unit from the fleet cluster Returns: True: The unit was removed Raises: fleet.v1.errors.APIError: Fleet returned a response code >= 400 """ # if this unit didn't come from fleet, we can't destroy it if not self._is_live(): raise RuntimeError('A unit must be submitted to fleet before it can destroyed.') return self._client.destroy_unit(self.name) def set_desired_state(self, state): """Update the desired state of a unit. Args: state (str): The desired state for the unit, must be one of ``_STATES`` Returns: str: The updated state Raises: fleet.v1.errors.APIError: Fleet returned a response code >= 400 ValueError: An invalid value for ``state`` was provided """ if state not in self._STATES: raise ValueError( 'state must be one of: {0}'.format( self._STATES )) # update our internal structure self._data['desiredState'] = state # if we have a name, then we came from the server # and we have a handle to an active client # Then update our selves on the server if self._is_live(): self._update('_data', self._client.set_unit_desired_state(self.name, self.desiredState)) # Return the state return self._data['desiredState']
{ "repo_name": "cnelson/python-fleet", "path": "fleet/v1/objects/unit.py", "copies": "1", "size": "12802", "license": "apache-2.0", "hash": -6422829983395319000, "line_mean": 35.5771428571, "line_max": 120, "alpha_frac": 0.5612404312, "autogenerated": false, "ratio": 4.796553016110903, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0014755889494490683, "num_lines": 350 }
from FleetStatistics import FleetStatistics import sys, os, random from collections import Counter #from buildings import buildings class Logic: """ The console is merely the game logic. Here includes all main functions including moving, building, the queue handler and perhaps notifications*? *Although notifications will need another class - learn about thread safety - just merely using read only data. """ ErrFile = None ATTACK = 0 DEFENSE = 1 BONUS = 2 def __init__(self, user): self.user = user def updateQueue(self): for fleet in self.user["fleetQueue"]: self.move(fleet, fleet["destination"], True) return True for build in self.user["buildQueue"]: print("") def build(self, building, planet, quantity, time=4, begin=True): """testing """ if begin == True: time = 4 b1 = [building, planet, quantity, time] self.user['buildQueue'].append(b1) self.user['buildQueue'][0][3] -=1 if time==0: buildings.builds(building, quantity, self.user, planet, time) del self.buildQueue[0] # probably one of the best written functions. def move(self,fleet, destination, inQueue = False): if fleet["time"] == 0: fleet["time"] = 5 #This will need to be put in a function for varying planets self.user['fleetQueue'].append(fleet) fleet["destination"] = destination fleet["time"] = fleet["time"]-1 if fleet["time"] == 0: self.user['fleetQueue'].remove(fleet) fleet["origin"] = destination fleet["destination"] = None def invade(self, fleet, enemy, planet): enemyFleet = [fleet for fleet in planet["fleets"] if enemy["name"] == planet["owner"]] if not enemyFleet: print("planet can be invaded.") else: print("planet cannot be invaded") print(" This is because of %s still has:" % enemy["name"] ) print(enemyFleet[0]["fleet"]) #self.build(build[0], build[1], build[2], build[3], False) #def printStatistics(): def printStatistics(self, opponent, defender): print("\n--------------------") print("Your ships") for key, ship in opponent.items(): print("%s: %s" % (key, ship)) print("\nEnemy ships") for key, ship in defender.items(): print("%s: %s" % (key, ship)) print("--------------------") def attackFleet(self, offender, defender): """ Combat should be simultaneous and therefore calculations can't be applied to results in situ. self.build(build[0], build[1], build[2], build[3], False) Our first task is to calculate bonus attack (atk) points (always > 0) and then bonus defense (def) points. """ defenderOld = defender offenderOld = offender self.printStatistics(offender["fleet"], defender["fleet"]) def __attack__(offender, defender): # loops players and ships for ship, dict1 in FleetStatistics.AirAttack.items(): for ship1, statList in dict1.items(): # set up bonus scheme atkBonus = 0 if offender["fleet"][ship] > 0: for i in range(0, offender["fleet"][ship]): if statList[self.ATTACK] == 0: # attack bonus is calculated differently if random.randrange(0,100) <= 5: #statList[self.BONUS]: atkBonus +=1 else: if random.randrange(0,100) <= 5: #statList[self.BONUS]: atkBonus += statList[self.ATTACK] + 1 #let's make things less complicated for testing purposes. #atkBonus = 0 defBonus = 0 #print(offender[offShips]) bonus = (atkBonus - defBonus) print("%d: critical hit on %s from %s" % (bonus ,ship1, ship)) #if bonus > 0: # bonus = 0 shipDamage = defender["fleet"][ship] - defender["fleet"][ship1]# - bonus defender["fleet"][ship] = shipDamage if defender["fleet"][ship] < 0: defender["fleet"][ship] = 0 return defender #self.logErrMsg("Something went wrong. Something will always inevitably go wrong.") offender = __attack__(defender, offender) defender = __attack__(offender, defender) #defender = defenderOld self.printStatistics(offender["fleet"], defender["fleet"]) def logErrMsg(self,msg): print("Err Printed") if os.path.exists('err.log'): ErrFile = open("err.log","a") ErrFile.write(msg) ErrFile.write("\n") ErrFile.close() else: ErrFile = open("err.log", 'w') ErrFile.write(msg) ErrFile.write("\n") ErrFile.close()
{ "repo_name": "hydrius/schwarzschild-radius", "path": "old/logic.py", "copies": "1", "size": "5706", "license": "mit", "hash": 2359624258225477600, "line_mean": 30.8770949721, "line_max": 114, "alpha_frac": 0.4894847529, "autogenerated": false, "ratio": 4.164963503649635, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5154448256549635, "avg_score": null, "num_lines": null }
from FleetStatistics import FleetStatistics class Mechanics(): class start: def start(self): print("load player data") class player: def save(self): print "saving" def load(self): print "loading" class planets: def save(self): print "Saving planets" def load(self): print "loading planets" class Attack(): """ air: fighters 1:1 ratio invade: population population 1:1 ratio military 3:1 ratio military population 3:1 military 1:1 """ def air(self, offender, defender): print "Attackers ships", offender.fighters print "Defenders ships", defender.fighters if offender.fighters > 0 and defender.fighters > 0: defenderShipsLost = (offender.fighters * FleetStatistics.fighter.fighter.attack) offenderShipsLost = (defender.fighters * FleetStatistics.fighter.fighter.attack) defender.fighters -=defenderShipsLost offender.fighters -=offenderShipsLost if defender.fighters < 0: defender.fighters = 0 if offender.fighters < 0: offender.fighters = 0 print "Attacker damage taken", offenderShipsLost print "Defender damage taken", defenderShipsLost print "Ships Remaining" print "Attackers ships", offender.fighters print "Defenders ships", defender.fighters #player 1 is the invader #player 2 is the defender def invade(self, offender, defender): if defender.fighters == 0: defender.population -= offender.population if defender.population <= 0: print "offender has invaded" if offender.population <=0: print "offender has failed" class Player(): #def __init__(self): #Mechanics = Mechanics.player() #Mechanics.load() fighters = 752 population = 1000 player1 = Player() player1.fighters = 500 player2 = Player() attack = Attack() attack.air(player1, player2) if __name__ == "__main__": Mechanics = Mechanics.player() user = Player() #Monday 10 o clock #Malaga oxly 96
{ "repo_name": "hydrius/schwarzschild-radius", "path": "old/SchwarzschildRadius1/AboveTheClouds.py", "copies": "1", "size": "2424", "license": "mit", "hash": 8520887341912068000, "line_mean": 17.0895522388, "line_max": 92, "alpha_frac": 0.5577557756, "autogenerated": false, "ratio": 3.8354430379746836, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48931988135746834, "avg_score": null, "num_lines": null }
from flexbe_core import EventState, Logger from wm_direction_to_point.srv import get_direction, get_directionRequest import rospy class Get_direction_to_point(EventState): ''' Gets the direction to a given point. Receives an input_key: point and has 2 parameters : frame_reference and frame_origin. Returns 2 angles within userdata. -- frame_reference string Name for the frame the targetPoint is compared to -- frame_origin string Name for the frame, who will return an angle ># targetPoint point Position of the point. #> yaw float64 Value of the yaw angle in the origin frame. #> pitch float64 Value of the pitch angle in the origin frame. <= done Indicates completion of the calculation. <= fail Indicates it failed. ''' def __init__(self, frame_origin, frame_reference): ''' Constructor ''' super(Get_direction_to_point, self).__init__(outcomes=['done','fail'], input_keys=['targetPoint'], output_keys=['yaw','pitch']) self.service = get_directionRequest() self.service.reference = frame_reference self.service.origine = frame_origin Logger.loginfo('waiting for service /get_direction') rospy.wait_for_service('/get_direction') #Attend que le service soit disopnible def execute(self, userdata): """Wait for action result and return outcome accordingly""" #rospy.wait_for_service('/get_direction') serv = rospy.ServiceProxy('/get_direction', get_direction) self.service.point = userdata.targetPoint resp = serv(self.service) userdata.yaw = resp.yaw userdata.pitch = resp.pitch Logger.loginfo('Angle retrieved') return 'done'
{ "repo_name": "WalkingMachine/sara_behaviors", "path": "sara_flexbe_states/src/sara_flexbe_states/Get_direction_to_point.py", "copies": "1", "size": "1870", "license": "bsd-3-clause", "hash": 8735026396763222000, "line_mean": 36.42, "line_max": 135, "alpha_frac": 0.6272727273, "autogenerated": false, "ratio": 4.338747099767981, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00422254333043352, "num_lines": 50 }
from flex.constants import ( OBJECT, ARRAY, ) from flex.datastructures import ( ValidationDict, ) from flex.loading.common.format import ( format_validator, ) from .title import ( title_validator, ) from flex.loading.common.default import ( validate_default_is_of_one_of_declared_types, ) from flex.loading.common.external_docs import ( external_docs_validator, ) from .min_properties import ( min_properties_validator, validate_type_for_min_properties, ) from .max_properties import ( max_properties_validator, validate_max_properties_is_greater_than_or_equal_to_min_properties, validate_type_for_max_properties, ) from .required import ( required_validator, ) from .type import ( type_validator, ) from .read_only import ( read_only_validator, ) from flex.loading.common import ( field_validators as common_field_validators, non_field_validators as common_non_field_validators, type_validators as common_type_validators, ) schema_schema = { 'type': OBJECT, 'properties': { 'properties': { 'type': OBJECT, }, } } schema_field_validators = ValidationDict() schema_field_validators.update(common_field_validators) schema_field_validators.add_property_validator('format', format_validator) schema_field_validators.add_property_validator('title', title_validator) schema_field_validators.add_property_validator('minProperties', min_properties_validator) schema_field_validators.add_property_validator('maxProperties', max_properties_validator) schema_field_validators.add_property_validator('required', required_validator) schema_field_validators.add_property_validator('type', type_validator) schema_field_validators.add_property_validator('readOnly', read_only_validator) schema_field_validators.add_property_validator('externalDocs', external_docs_validator) schema_non_field_validators = ValidationDict() schema_non_field_validators.update(common_non_field_validators) schema_non_field_validators.update(common_type_validators) schema_non_field_validators.add_validator( 'default', validate_default_is_of_one_of_declared_types, ) schema_non_field_validators.add_validator( 'maxProperties', validate_max_properties_is_greater_than_or_equal_to_min_properties, ) schema_non_field_validators.add_validator( 'type', validate_type_for_min_properties, ) schema_non_field_validators.add_validator( 'type', validate_type_for_max_properties, ) # # Properties. # properties_schema = { 'type': OBJECT, } # # Items # items_schema = { 'type': [ ARRAY, # Array of schemas OBJECT, # Single Schema ] }
{ "repo_name": "pipermerriam/flex", "path": "flex/loading/common/schema/__init__.py", "copies": "1", "size": "2655", "license": "mit", "hash": 2811208943173993500, "line_mean": 25.2871287129, "line_max": 89, "alpha_frac": 0.7370998117, "autogenerated": false, "ratio": 3.4796854521625162, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.9714566362197069, "avg_score": 0.0004437803330894888, "num_lines": 101 }
from flex.constants import ( OBJECT, ) from flex.datastructures import ( ValidationDict, ) from flex.validation.common import ( generate_object_validator, ) from flex.loading.common.mimetypes import ( mimetype_validator, ) from .info import info_validator from .swagger import swagger_version_validator from .host import host_validator from .base_path import base_path_validator from .schemes import schemes_validator from .paths import paths_validator __ALL__ = [ 'info_validator', 'swagger_schema_validators', 'host_validator', 'base_path_validator', 'schemes_validator', 'mimetype_validator', 'paths_validator', ] swagger_schema = { 'type': OBJECT, 'required': [ 'info', 'paths', 'swagger', ], } non_field_validators = ValidationDict() non_field_validators.add_property_validator('info', info_validator) non_field_validators.add_property_validator('swagger', swagger_version_validator) non_field_validators.add_property_validator('host', host_validator) non_field_validators.add_property_validator('basePath', base_path_validator) non_field_validators.add_property_validator('schemes', schemes_validator) non_field_validators.add_property_validator('produces', mimetype_validator) non_field_validators.add_property_validator('consumes', mimetype_validator) non_field_validators.add_property_validator('paths', paths_validator) swagger_schema_validator = generate_object_validator( schema=swagger_schema, non_field_validators=non_field_validators, )
{ "repo_name": "pipermerriam/flex", "path": "flex/loading/schema/__init__.py", "copies": "1", "size": "1545", "license": "mit", "hash": 7499682902354743000, "line_mean": 28.1509433962, "line_max": 81, "alpha_frac": 0.7430420712, "autogenerated": false, "ratio": 3.7318840579710146, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.49749261291710145, "avg_score": null, "num_lines": null }
from flex.datastructures import ( ValidationDict, ) from flex.error_messages import ( MESSAGES, ) from flex.constants import ( OBJECT, ARRAY, EMPTY, ) from flex.exceptions import ValidationError from flex.utils import ( pluralize, ) from flex.decorators import ( pull_keys_from_obj, suffix_reserved_words, ) from flex.loading.common import ( field_validators as common_field_validators, non_field_validators as common_non_field_validators, type_validators as common_type_validators, ) from flex.loading.common.default import ( validate_default_is_of_one_of_declared_types, ) from flex.validation.common import ( generate_object_validator, ) from flex.loading.common.format import ( format_validator, ) from .description import ( description_validator, ) from .type import ( type_validator, ) from .collection_format import ( collection_format_validator, ) single_header_schema = { 'type': OBJECT, 'required': [ 'type', ] } single_header_field_validators = ValidationDict() single_header_field_validators.update(common_field_validators) single_header_field_validators.add_property_validator('description', description_validator) single_header_field_validators.add_property_validator('type', type_validator) single_header_field_validators.add_property_validator('format', format_validator) single_header_field_validators.add_property_validator( 'collectionFormat', collection_format_validator, ) @pull_keys_from_obj('type', 'items') @suffix_reserved_words def validate_items_required_if_type_arraw(type_, items, **kwargs): types = pluralize(type_) if ARRAY in types and items is EMPTY: raise ValidationError(MESSAGES['required']['required']) single_header_non_field_validators = ValidationDict() single_header_non_field_validators.update(common_non_field_validators) single_header_non_field_validators.update(common_type_validators) single_header_non_field_validators.add_validator( 'default', validate_default_is_of_one_of_declared_types, ) single_header_non_field_validators.add_validator( 'items', validate_items_required_if_type_arraw, ) single_header_validator = generate_object_validator( schema=single_header_schema, field_validators=single_header_field_validators, non_field_validators=single_header_non_field_validators, )
{ "repo_name": "pipermerriam/flex", "path": "flex/loading/common/single_header/__init__.py", "copies": "1", "size": "2366", "license": "mit", "hash": -373448316508540860, "line_mean": 27.1666666667, "line_max": 91, "alpha_frac": 0.7510566357, "autogenerated": false, "ratio": 3.595744680851064, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48468013165510637, "avg_score": null, "num_lines": null }
from flex.datastructures import ( ValidationDict, ) from flex.loading.common.single_parameter import ( single_parameter_schema, single_parameter_field_validators as common_single_parameter_field_validators, single_parameter_non_field_validators as common_single_parameter_non_field_validators, ) from flex.loading.definitions.schema import ( schema_validator, items_validator, ) from flex.validation.common import ( generate_object_validator, ) single_parameter_field_validators = ValidationDict() single_parameter_field_validators.update( common_single_parameter_field_validators ) # schema fields single_parameter_field_validators.add_property_validator('schema', schema_validator) single_parameter_field_validators.add_property_validator('items', items_validator) single_parameter_non_field_validators = ValidationDict() single_parameter_non_field_validators.update( common_single_parameter_non_field_validators ) single_parameter_validator = generate_object_validator( schema=single_parameter_schema, field_validators=single_parameter_field_validators, non_field_validators=single_parameter_non_field_validators, )
{ "repo_name": "pipermerriam/flex", "path": "flex/loading/definitions/parameters/single.py", "copies": "1", "size": "1172", "license": "mit", "hash": 6681623933472713000, "line_mean": 31.5555555556, "line_max": 90, "alpha_frac": 0.7935153584, "autogenerated": false, "ratio": 3.9328859060402683, "config_test": false, "has_no_keywords": true, "few_assignments": false, "quality_score": 0.5226401264440268, "avg_score": null, "num_lines": null }
from flex.datastructures import ( ValidationList, ) from flex.exceptions import ValidationError from flex.constants import ( OBJECT, ) from flex.error_messages import MESSAGES from flex.decorators import ( skip_if_not_of_type, skip_if_empty, ) from flex.validation.common import ( generate_object_validator, ) from flex.context_managers import ( ErrorDict, ) from .path_item import ( path_item_validator, ) @skip_if_empty @skip_if_not_of_type(OBJECT) def validate_path_items(paths, **kwargs): with ErrorDict() as errors: for path, path_definition in paths.items(): # TODO: move this to its own validation function that validates the keys. if not path.startswith('/'): errors.add_error(path, MESSAGES['path']['must_start_with_slash']) try: path_item_validator(path_definition, **kwargs) except ValidationError as err: errors.add_error(path, err.detail) paths_schema = { 'type': OBJECT, } non_field_validators = ValidationList() non_field_validators.add_validator(validate_path_items) paths_validator = generate_object_validator( schema=paths_schema, non_field_validators=non_field_validators, )
{ "repo_name": "pipermerriam/flex", "path": "flex/loading/schema/paths/__init__.py", "copies": "1", "size": "1248", "license": "mit", "hash": 8935458832083121000, "line_mean": 25, "line_max": 85, "alpha_frac": 0.6778846154, "autogenerated": false, "ratio": 3.725373134328358, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9900776184215028, "avg_score": 0.0004963131026659103, "num_lines": 48 }