def save_state(session, state_id): """Save state to database""" state = State() state.id = state_id session.add(state) session.commit() return state
def setUp(self): TestFactory.setUp(self) data = [] data.append(State(descripcion="abierto")) data.append(State(descripcion="cerrado")) data.append(Priority(descripcion="baja")) data.append(Priority(descripcion="Alta")) data.append(Department(descripcion="default")) data.append(Client(nombre="default")) db.session.add_all(data) db.session.commit() data = Ticket( titulo="prueba", content= """My money's in that office, right? If she start giving me some bullshit about it ain't there, and we got to go someplace else and get it, I'm gonna shoot you in the head then and there. Then I'm gonna shoot that bitch in the kneecaps, find out where my goddamn money is. She gonna tell me too. Hey, look at me when I'm talking to you, m**********r. You listen: we go in there, and that n***a Winston or anybody else is in there, you the first m**********r to get shot. You understand?""", email="*****@*****.**", client_id=1, department_id=1, priority_id=1, state_id=1, user_id=1) db.session.add(data) db.session.commit() self.path = '/tickets'
def deploy(): # 初始化数据库 db.drop_all() db.create_all() # 初始化基础数据 Role.insert_roles() State.insert_state() User.insert_admin()
def test_state_repr(self): """ Test state representation representation """ state = State() self.assertEqual( state.__repr__(), '{"State" : {"name": None, "capital": None, "population": None, "governor": None, "abbrev": None}}' )
def update_state(new_value): old_state = State.query.get(0) if old_state: on_state_change(State.query.get(0).value, new_value) else: old_state = State(id=0) old_state.value = new_value old_state.start_time = datetime.datetime.now(pytz.utc) db.session.commit() return True
def populate_choices(self): """Populate choices for sector and category drop downs.""" self.sector.choices = Sector.list() cat_sector = 1 if self.sector.data is None else self.sector.data self.category.choices = Category.list(cat_sector) self.address.state.choices = State.list() return self
def seed_states(): for state_tup in states: location = State(state=state_tup[0], abbr=state_tup[1]) db.session.add(location) db.session.commit()
def move_commence(game_privacy, duration): auth = auth_auth('commence') if auth['success']: app.logger.info(auth) player_id = auth['user_id'] else: app.logger.info('player guest') player_id = auth_guest() try: app.logger.info('trying') if game_privacy == 'public': app.logger.info('we are game privacy') offer = Offer.query.filter_by(public=True).filter_by( time_limit=duration).first() if offer: app.logger.info('we are offer') new_game = Game(player_one=offer.player_one, player_two=player_id, time_limit=duration, offer_id=offer.id) Game.insert(new_game) game = new_game.id offer.delete() current_state = State(game_id=new_game.id, move_number=1, move='white', position=calculate_moves(), time_limit=duration, white_timer=duration, black_timer=duration) State.insert(current_state) db.session.close() return json.dumps({'status': 'redirect', 'id': game}) app.logger.info('we are here') offer = Offer(player_one=player_id, time_limit=duration) Offer.insert(offer) offer_id = offer.id db.session.close() return json.dumps({'status': 'waiting', 'offerId': offer_id}) except: app.logger.info(sys.exc_info()) error = True db.session.rollback() finally: db.session.close() if error: return json.dumps({'status': 'error'})
def init_state(): l = ["在职:管理人员", "在职:专技人员", "在职:一般管理人员", "协理", "调离", "退休", "去世"] for temp in l: res = State.query.filter_by(name=temp).first() if res is None: state = State(name=temp) db.session.add(state) print("状态写入完毕!")
def get_department(session, state_id, department_type): """Get department from database""" department = session.query(Department).filter( Department.state_id == state_id).filter( Department.department_type == department_type).first() if department is None: department = Department() state = session.query(State).get(state_id) if not state: state = State() state.id = state_id session.add(state) department.state_id = state.id department.department_type = department_type session.add(department) session.commit() return department
def state(): """ add a new event """ form = StateForm() events = State.query.all() days = '' event = None if form.validate_on_submit(): if form.mon.data == True: days += 'mon,' if form.tue.data == True: days += 'tue,' if form.wed.data == True: days += 'wed,' if form.thu.data == True: days += 'thu,' if form.fri.data == True: days += 'fri,' if form.sat.data == True: days += 'sat,' if form.sun.data == True: days += 'sun,' if days != "": days = days[ 0:len(days) - 1] # strip "," comma off of end of last day entry (so it is in usable data format) event_duplicate = State.query.filter_by( event_days=days, event_hour=form.hour.data, event_min=form.minute.data).first() if not event_duplicate: event = State(event_days=days, event_hour=form.hour.data, event_min=form.minute.data) db.session.add(event) db.session.commit() sched.add_job(runKettle, 'cron', id=str(event.id), day_of_week=str(days), hour=str(form.hour.data), minute=str(form.minute.data)) sched.print_jobs() print(sched.get_jobs()) flash('Event added!', 'success') return redirect(url_for('state')) else: flash("Event Already Exists, Please revise!", 'danger') else: flash("Error with request please check that it is valid", 'danger') return render_template('state.html', title='State', form=form, event=event, events=events)
def demo(): # 初始化数据库 db.drop_all() db.create_all() # 初始化基础数据 User.insert_admin() Role.insert_roles() State.insert_state() # 插入演示数据 Demo.insert_users() Demo.insert_products() Demo.insert_projects() Demo.insert_orders() Demo.insert_logs() Demo.insert_product_list() Demo.insert_skills()
def post(self): """User move * if no existing state """ state = State() db.session.add(state) db.session.commit() return {"msg": "state created", "state": schema.dump(state)}, 201
def create_state(json_data): state = json_data['state'] stateCode = json_data['state_code'] avgData = json_data['avg_loan'] stateGeojson = create_geojsonfeature(json_data['geojson']) state = State(state, stateCode, stateGeojson, avgData) db.session.add(state) db.session.commit() create_counties(state, json_data['counties'])
def create_states(session): """Yields states""" states_created = 0 for filename in os.listdir(DK.SS_FOLDER): state_abbr = os.path.splitext(filename)[0] session.add(State(abbr=state_abbr)) states_created += 1 print("State records created: %d" % states_created, end="\r") print() session.commit()
def single(): user = current_user.username if request.method == 'POST': # reset the tictactoe board to the original state # the TicTacToe's object is stored in players[user] variable players[user].reset() # get the mark for the current player # replace None player_mark = None # get the mark for the computer player # replace None with your code computer_mark = None # update database # the 'cell' should be the state of the board # which can be obtained from the tictactoe object # replace None data = State(user_id=None, time=datetime.now(), cell=None, mark=None) # add the data to the session pass # commit the session to the database pass return render_template('single.html', title='Single Player', player=player_mark, computer=computer_mark) else: if user not in players: # set player mark randomly player_mark = random.choice(marks) # create the object instant TicTacToe using # the player's mark players[user] = TicTacToe(mark=player_mark) # set the computer mark # replace None with your code computer_mark = None else: # if user is already in the dictionary, use the mark there # the TicTacToe object is stored inside players[user] variable player_mark = players[user].mark # set the computer mark # replace None with your code computer_mark = None return render_template('single.html', title='Single Player', player=player_mark, computer=computer_mark)
def handle_connect(message): print("Connected") mark = message["mark"] all_data = State.query.filter_by(user_id=current_user.id).all() if len(all_data) < 1: data = State(user_id=current_user.id, time=datetime.now(), cell='_________', mark=mark) db.session.add(data) db.session.commit() last_data = State.query.filter_by(user_id=current_user.id).all()[-1] players[current_user.username] = TicTacToe(last_data.cell, last_data.mark) emit('afterconnect', {'data': last_data.cell})
def add_country(): filename = os.path.join(os.getcwd(), 'misc/nigeria.json') file_content = '' with open(filename, 'r') as rb: for line in rb: file_content += line obj = json.loads(file_content) country = Country(name='Nigeria') for i in obj: state = State(name=i) for k in obj[i]: city = City(name=k) state.cities.append(city) country.states.append(state) db.session.add(country) db.session.commit()
def post(self): """Create new game""" schema = GameSchema() game = schema.load(request.json) settings = SettingsService.initialize(Settings()) settings.game = game state = StateService.generate_state(State()) game.states.append(state) db.session.add(game) db.session.add(settings) db.session.add(state) db.session.commit() return {"msg": "game created", "game": schema.dump(game)}, 201
class AddressField(FlaskForm): """Form to capture user or business address. Fields: line1 (str): street address line 1 (i.e. 100 Main St) line2 (str): optional, 2nd line of street address (i.e. apt 3b) city (str): address city state (select): address state zip (str): 5 digit zip code Methods: validate_zip: check zip code, verifies 5 digits and only numbers in zip code """ line1 = StringField( "Street Address", default='', validators=[InputRequired(message="Street address is required.")]) line2 = StringField("Address Line 2", default='', validators=[Optional()]) city = StringField("City", default='', validators=[InputRequired(message="City is required.")]) state = SelectField( "State", choices=State.list(), coerce=int, default=0, validators=[InputRequired(message="State is required.")]) zip = StringField( "Zip", default='', validators=[InputRequired(message="Zip code is required.")]) def validate_zip(form, field): if len(field.data) != 5: raise ValidationError('Please enter a 5 digit zip code.') elif not field.data.isdigit(): raise ValidationError('Only include numbers in zip code.') def populate_choices(self): self.state.choices = State.list() return self
def process_winning(winner=None, status='lose'): user = current_user.username # if there is a winner, # emit signal 'winning' and pass on the winner as the data if winner != None: emit('winning', {'data': winner}) # if the status is not lose, update the score if status != 'lose': update_score(status) # reset the TicTacToe's board players[user].reset() # update DB with a clean board data = State(user_id=current_user.id, time=datetime.now(), cell=players[user].board_to_str, mark=players[user].mark) db.session.add(data) db.session.commit()
def dbinit(): data = [] data.append(File(filename="default.png")) data.append(Rol(descripcion="administrador")) data.append(Rol(descripcion="supervisor")) data.append(Rol(descripcion="agente")) data.append(Rol(descripcion="cliente")) data.append(State(descripcion="New")) data.append(State(descripcion="Proccess")) data.append(State(descripcion="Pending")) data.append(State(descripcion="Close")) data.append(State(descripcion="Re-Open")) data.append(State(descripcion="Abandoned")) data.append(Department(descripcion="IT")) data.append(Priority(descripcion="standar", respuesta = 8, resuelto = 72)) data.append(Priority(descripcion="High", respuesta = 4, resuelto = 24, escalable = 1)) data.append(Priority(descripcion="Critical", respuesta = 1, resuelto = 4 )) data.append(Priority(descripcion="Scheduled or Low", respuesta = 3, resuelto = 7)) data.append(Client(nombre="Default")) db.session.add_all(data) db.session.commit() rolAdm = Rol.query.filter_by(descripcion="administrador").first() sys = User( username="******", nombre = "COMPUTER", apellido = "SYS", email = "*****@*****.**", rol_id = rolAdm.id ) administrador = User( username="******", nombre = "Super", apellido = "admin", email = "*****@*****.**", rol_id = rolAdm.id ) administrador.set_password("admin") sys.set_password(''.join(random.choices(string.ascii_uppercase + string.digits, k = N))) db.session.add(sys) db.session.add(administrador) db.session.commit()
def test_db(app): db.drop_all() db.create_all() # define categories State.create(id=1, name="North Carolina", state_short="NC") State.create(id=2, name="New York", state_short="NY") Sector.create(id=1, name="Home Services") Sector.create(id=2, name="Food & Drink") c1 = Category.create(id=1, name="Electrician", sector_id=1) c2 = Category.create(id=2, name="Plumber", sector_id=1) Category.create(id=3, name="Mexican Restaurant", sector_id=2) a1 = Address.create( line1="13 Brook St", city="Lakewood", zip="14750", state_id=2, latitude=42.100201, longitude=-79.340303 ) # add test users u1 = User.create( id=1, username="******", first_name="Sarah", last_name="Smith", email="*****@*****.**", address=a1 ) u2 = User.create( id=2, username="******", first_name="John", last_name="Jones", email="*****@*****.**", address=Address( line1="7708 covey chase Dr", line2='', city="Charlotte", zip="28210", state_id=1, latitude=35.123949, longitude=-80.864783 ) ) u3 = User.create( id=3, username="******", first_name="Mark", last_name="Johnson", email="*****@*****.**", address=Address( line1="7718 Covey Chase Dr", line2='', city="Charlotte", zip="28210", state_id=1, latitude=35.123681, longitude=-80.865045 ) ) User.create( id=4, username="******", first_name="Hyman", last_name="Rickover", email="*****@*****.**", address=Address( line1="7920 Covey Chase Dr", line2='', city="Charlotte", zip="28210", state_id=1, latitude=35.120759, longitude=-80.865781 ) ) # add test providers p1 = Provider.create( id=1, name="Douthit Electrical", telephone="704-726-3329", email="*****@*****.**", website='https://www.douthitelectrical.com/', categories=[c1, c2], address=Address( line1="6000 Fairview Rd", line2="suite 1200", city="Charlotte", zip="28210", state_id=1, latitude=35.150495, longitude=-80.838958 ) ) Provider.create( id=2, name="Evers Electric", telephone="7048431910", email='', website='http://www.everselectric.com/', categories=[c1], address=Address( line1="3924 Cassidy Drive", line2="", city="Waxhaw", zip="28173", state_id=1, latitude=34.938645, longitude=-80.760691 ) ) p3 = Provider.create( id=3, name="Preferred Electric Co", telephone="7043470446", email="*****@*****.**", categories=[c1], address=Address( line1="4113 Yancey Rd", line2='', city="charlotte", zip="28217", state_id=1, latitude=35.186947, longitude=-80.880459 ) ) p4 = Provider.create( id=4, name="Basic Electric Co", telephone="7044070077", email="*****@*****.**", is_active=False, categories=[c1], address=Address( line1="7708 Covey Chase Dr", line2='', city="Charlotte", zip="28217", state_id=1, latitude=35.123949, longitude=-80.865781 ) ) # add test groups g1 = Group.create( id=1, name="QHIV HOA", description="Hoa for the neighborhood", admin_id=2 ) Group.create( id=2, name="Shannon's Bees", description="Insects that like to make honey", admin_id=2 ) Group.create( id=3, name="Shawshank Redemption Fans", description="test", admin_id=3 ) # add test reviews Review.create( id=1, user=u2, provider=p1, category=c1, rating=3, cost=3, description="fixed a light bulb", comments="satisfactory work.", pictures=[ Picture( path=os.path.join( app.config['MEDIA_FOLDER'], '2', 'test1.jpg' ), name='test1.jpg' ) ] ) Review.create( id=2, user=u3, provider=p1, category=c1, rating=5, cost=5, price_paid="", description="installed breaker box", comments="very clean" ) Review.create( id=3, user=u1, provider=p1, category=c1, rating=1, cost=5, price_paid="", description="test", comments="Test" ) Review.create( id=4, user=u2, provider=p3, category=c1, rating=5, cost=2, price_paid="", description="test", comments="Test123", service_date=date(2019, 5, 1) ) Review.create( id=5, user=u2, provider=p3, category=c1, rating=4, cost=3, price_paid="", description="moretest", comments="Test123456", service_date=date(2019, 5, 1) ) Review.create( id=6, user=u1, provider=p1, category=c1, rating=1, cost=5, price_paid="", description="yetanothertest", comments="Testing" ) Review.create( id=7, user=u2, provider=p4, category=c1, rating=1, cost=1, price_paid=100, description="getting electrocuted", comments="terrible" ) # add test relationships u2.add(u1) u2.add(g1) u3.add(g1) # set user passwords u1.set_password("password1234") u2.set_password("password") u3.set_password("password5678") # set starting messages Message.send_new( dict(user_id=1), dict(user_id=2), "test subject", "test body" ) time.sleep(1) Message.send_new( dict(user_id=2), dict(full_name="admin"), "test admin subject", "test adminbody", msg_type="admin" ) Message.send_new( dict(user_id=1), dict(user_id=2), "yet another test subject", " yet another test body" ) yield db db.session.remove() db.drop_all()
def make_form(self, formDict): """Override FormTest make form to populate choices""" super().make_form(formDict) self.form.state.choices = State.list()
def move_maker(figure, move_number, game_id, promote, move): error = False authorized = auth_auth(game_id) if figure: if authorized: state = State.query.filter_by(game_id=game_id).order_by( State.move_number.desc()).first() app.logger.info('state: %s' % state) check = legal(state, figure, move) try: if check == 1: app.logger.info('check 1') legal_move = reffery(state, figure, move, promote) next_state = State(game_id=state.game_id, move_number=state.move_number + 1, move=legal_move['next_move'], position=legal_move['new_position'], white_timer=legal_move['time']['white'], black_timer=legal_move['time']['black'], time_limit=state.time_limit) State.insert(next_state) data = next_state.format() cash_put(state.game_id, state.move_number + 1) if check == 'WKing': app.logger.info('check white') game = Game.query.filter_by(id=game_id).first() game.winner = game.player_one position = state.position position['WKing']['surrender'] = True next_state = State(game_id=state.game_id, move_number=state.move_number + 1, move='none', position=position, white_timer='0', black_timer=state.black_timer, time_limit=state.time_limit) data = next_state.format() State.insert(next_state) if check == 'BKing': app.logger.info('check black') game = Game.query.filter_by(id=game_id).first() game.winner = game.player_two position = state.position position['BKing']['surrender'] = True next_state = State(game_id=state.game_id, move_number=state.move_number + 1, move='none', position=position, white_timer=state.white_timer, black_timer='0', time_limit=state.time_limit) data = next_state.format() State.insert(next_state) except: error = True db.session.rollback() app.logger.info(sys.exc_info()) app.logger.info(sys.argv[1]) finally: db.session.close() if error: return json.dumps({'error': True}) return json.dumps(data) if move_number: app.logger.info('move_number') if authorized: cashed = cash_get(game_id, move_number) if cashed: return json.dumps(None) #state = State.query.join(Game).filter(or_(Game.player_one==authorized, Game.player_two==authorized).order_by(State.move_number.desc()).first() state = State.query.filter_by(game_id=game_id).order_by( State.move_number.desc()).first() new_state = state.format() db.session.close() if move_number < new_state['move_number']: return json.dumps(new_state) else: return json.dumps(None) else: app.logger.info('no_move_number') state = State.query.filter_by(game_id=game_id).order_by( State.move_number.desc()).first() check = legal(state, None, None) if check == 'BKing': game = Game.query.filter_by(id=game_id).first() game.winner = game.player_two position = state.position position['BKing']['surrender'] = True next_state = State(game_id=state.game_id, move_number=state.move_number + 1, move='none', position=position, white_timer=state.white_timer, black_timer='0', time_limit=state.time_limit) data = next_state.format() State.insert(next_state) elif check == 'WKing': app.logger.info('check white') game = Game.query.filter_by(id=game_id).first() game.winner = game.player_one position = state.position position['WKing']['surrender'] = True next_state = State(game_id=state.game_id, move_number=state.move_number + 1, move='none', position=position, white_timer='0', black_timer=state.black_timer, time_limit=state.time_limit) data = next_state.format() State.insert(next_state) else: data = state.format() db.session.close() return json.dumps(data)
def post(self): args = post_parser.parse_args() newData = State(descripcion=args.descripcion, ) db.session.add(newData) db.session.commit() return newData, 201
graph.push(zipcode) # add edge comm.CMTE_ZIP.add(zipcode) city = City.select(graph, data.CMTE_CITY).first() if not city: city = City() city.CITY = data.CMTE_CITY graph.push(city) # add edge comm.CMTE_CITY.add(city) party = Party.select(graph, data.CMTE_PTY_AFFILIATION).first() if not party: party = Party() party.PARTY = data.CMTE_PTY_AFFILIATION graph.push(party) # add edge comm.CMTE_PTY_AFFILIATION.add(party) state = State.select(graph, data.CMTE_ST).first() if not state: state = State() state.STATE = data.CMTE_ST graph.push(state) # add edge comm.CMTE_ST.add(state) # Commit it all graph.push(comm)
basedir = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(basedir, 'state_lga.json'), 'r') as json_file: content = json_file.read() my_collection = json.loads(content) state_names = [re.sub(' State', '', x['state']['name']) for x in my_collection] all_lga_object = [x['state']['locals'] for x in my_collection] all_lga_list = list() for lga_object in all_lga_object: all_lga_list.append([x['name'] for x in lga_object]) state_lga_dict = dict(zip(state_names, all_lga_list)) # creating the application app = create_app() # Making a db query inside the application context with app.app_context(): for state, lgas in state_lga_dict.items(): s = State(state) s.lgas = [Lga(lga) for lga in lgas] db.session.add(s) db.session.commit() sleep(2) print("Done with the Population")
def populate_choices(self): """Populate state drop down list for address field.""" self.address.state.choices = State.list() return self
def populate_choices(self): self.state.choices = State.list() return self