import random from faker import Faker #faker framework'unu pip ile indirip import ettik #Faker modulunu calistirmak icin degiskene atiyoruz fake_data = Faker() #olusturacagimiz fake ogrencileri kaydetmek icin bir liste yaratiyoruz classroom = list() #10 defa calisacak bir donguyle fake ogrenciler yaratalim ##fake_data.name() her turda bir fake isim dondurecek for name in range(10): classroom.append(fake_data.name()) #notlari tutacagimiz sozlugu yaratalim st = dict() for student in classroom: st[student] = dict() st[student]['not1'] = random.randrange(0, 100) st[student]['not2'] = random.randrange(0, 100) st[student]['not3'] = random.randrange(0, 100) print('*' * 30) print( student, "=", int((st[student]['not1'] + st[student]['not2'] + st[student]['not3']) / 3))
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','CRUISE.settings') import django django.setup() import random from cruiseWeb.models import Tweet from faker import Faker from django.utils import timezone fakegen = Faker() def populate(): with open('tweet.txt') as f: for eachline in f: tweet = eachline.lstrip() cDate = timezone.now() iData = Tweet.objects.get_or_create(tweetText = tweet, createdDate = cDate)[0] if __name__ == '__main__': print('Populating Script!') populate() print('Populating Complete')
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'studentdb_proj.settings') import django django.setup() from student_db.models import Student from faker import Faker from random import * fake = Faker() def phonenumbergen(): d1 = randint(6, 9) num = '' + str(d1) for i in range(9): num = num + str(randint(0, 9)) return int(num) def populate(n): for i in range(n): frollno = fake.random_int(min=1, max=999) fname = fake.name() fdob = fake.date() fmarks = fake.random_int(min=1, max=100) femail = fake.email() fphonenumber = phonenumbergen() faddress = fake.address() student_record = Student.objects.get_or_create(
def setUp(self): self.factory = Faker('sv_SE')
def setUp(self): self.factory = Faker('ar')
def create_fake_record(): """Create records for demo purposes.""" fake = Faker() data_to_use = { "access": { "record": "public", "files": "public", }, "files": { "enabled": False, }, "pids": { }, "metadata": { "resource_type": CachedVocabularies.fake_resource_type(), "creators": [{ "person_or_org": { "family_name": fake.last_name(), "given_name": fake.first_name(), "type": "personal", "identifiers": [{ "scheme": "orcid", "identifier": "0000-0002-1825-0097", }], }, "role": CachedVocabularies.fake_creatibutor_role(), "affiliations": [] } for i in range(4)], "title": fake.company() + "'s gallery", "additional_titles": [{ "title": "a research data management platform", "type": CachedVocabularies.fake_title_type(), "lang": {"id": "eng"} }, { "title": fake.company() + "'s gallery", "type": {"id": "alternative-title"}, "lang": CachedVocabularies.fake_language() }], "publisher": "InvenioRDM", "publication_date": fake_edtf_level_0(), "subjects": [], # Too complex to generate for now "contributors": [{ "person_or_org": { "family_name": fake.last_name(), "given_name": fake.first_name(), "type": "personal", }, "role": CachedVocabularies.fake_creatibutor_role(), "affiliations": [], } for i in range(3)], # "dates": [{ # # No end date to avoid computations based on start # "date": fake.date(pattern='%Y-%m-%d'), # "description": "Random test date", # "type": "other" # }], "languages": [CachedVocabularies.fake_language()], "related_identifiers": [{ "identifier": "10.9999/rdm.9999988", "scheme": "doi", "relation_type": CachedVocabularies.fake_relation_type(), "resource_type": CachedVocabularies.fake_resource_type() }], "sizes": [ "11 pages" ], "formats": [ "application/pdf" ], "version": "v0.0.1", # "rights": [{ # "rights": "Berkeley Software Distribution 3", # "uri": "https://opensource.org/licenses/BSD-3-Clause", # "identifier": "03yrm5c26", # "scheme": "ror", # }], "description": fake.text(max_nb_chars=3000), "additional_descriptions": [{ "description": fake.text(max_nb_chars=200), "type": CachedVocabularies.fake_description_type(), "lang": "eng" } for i in range(2)], "funding": [{ "funder": { "name": "European Commission", "identifier": "03yrm5c26", "scheme": "ror" }, "award": { "title": "OpenAIRE", "number": "246686", "identifier": "0000-0002-1825-0097", "scheme": "orcid" } }], # "locations": [{ # 'geometry': { # 'type': 'Point', # 'coordinates': [ # float(fake.latitude()), float(fake.longitude()) # ] # }, # "place": fake.location_on_land()[2], # "description": "Random place on land...", # 'identifiers': [{ # 'scheme': 'ror', # 'identifier': '03yrm5c26', # }, { # 'scheme': 'orcid', # 'identifier': '0000-0002-1825-0097', # }] # }, { # 'geometry': { # 'type': 'MultiPoint', # 'coordinates': [ # [float(fake.latitude()), float(fake.longitude())], # [float(fake.latitude()), float(fake.longitude())] # ] # }, # "place": fake.location_on_land()[2], # } # ], "references": [{ "reference": "Reference to something et al.", "identifier": "0000000114559647", "scheme": "isni" }], "identifiers": [{ "identifier": "ark:/123/456", "scheme": "ark" }], } } return json.loads(json.dumps(data_to_use))
from faker import Faker from models.models import Base, Prepod, Student from mysql_orm_client.mysql_orm_client import MysqlOrmConnection fake = Faker(locale='ru_RU') class MysqlOrmBuilder(object): def __init__(self, connection: MysqlOrmConnection): self.connection = connection self.engine = self.connection.connection.engine self.create_prepods() self.create_students() def create_prepods(self): if not self.engine.dialect.has_table(self.engine, 'prepods'): Base.metadata.tables['prepods'].create(self.engine) def create_students(self): if not self.engine.dialect.has_table(self.engine, 'students'): Base.metadata.tables['students'].create(self.engine) def add_prepod(self): # Создаем запись в таблице 'prepods' через класс Prepod prepod = Prepod( name=fake.first_name(), surname=fake.last_name(), start_teaching=fake.date() )
import factory import factory.fuzzy import random from web.domains.office.models import Office from faker import Faker fake = Faker('en_GB') class OfficeFactory(factory.django.DjangoModelFactory): class Meta: model = Office is_active = random.choice([True, False]) address = fake.address()
from faker import Faker from ondewo.nlu.client import Client from ondewo.nlu.client_config import ClientConfig from ondewo.nlu.session_pb2 import DetectIntentResponse, DetectIntentRequest, QueryInput, TextInput if __name__ == '__main__': parent: str = '<PUT_YOUR_AGENT_PARENT_HERE>' config: ClientConfig = ClientConfig(host='<host>', port='<port>', http_token='<http/root token>', user_name='<e-mail of user>', password='******') client: Client = Client(config=config, use_secure_channel=False) f: Faker = Faker() session_name: str = f.name() request: DetectIntentRequest = DetectIntentRequest( session=f'{parent}/sessions/{session_name}', query_input=QueryInput(text=TextInput(text='<Some text>'))) response: DetectIntentResponse = client.services.sessions.detect_intent( request=request) print(f'Text received by the server: {response.query_result.query_text}') print(f'Intent detected: {response.query_result.intent.display_name}') print( f'Text response: {response.query_result.fulfillment_messages[0].text.text[0]}' )
from flask import Flask, render_template, request from faker import Faker import random import requests from bs4 import BeautifulSoup fake = Faker('ko_KR') app = Flask(__name__) # task1 : fakesearch @app.route('/') def home(): return render_template('home.html') # task2 : 전생 @app.route('/pastlife') def pastlife(): return render_template('pastlife.html') DicFake = {} #밖으로 빼줘야 매번 실행마다 딕셔너리 초기화 안함 @app.route('/result') def result(): name = request.args.get('name') # 1. 우리 데이터에 해당하는 이름이 있는지 없는지 확인 if name in DicFake: # 3. 있다면 => DicFake에 저장된 직업 보여줌
import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project1.settings") import django django.setup() from faker import Faker from newApp.models import User fakergen = Faker() def populate(N=10): for i in range(N): name = fakergen.name() fake_first = name.split(' ')[0] fake_last = name.split(' ')[0] fake_email = fakergen.email() usr = User.objects.get_or_create(FirstName=fake_first, LastName=fake_last, Email=fake_email)[0] if __name__ == '__main__': print("Create user.") populate(50) print("user creation completed.")
from kafka import KafkaProducer #for producing data from kafka.errors import KafkaError import json #to change dict to json from faker import Faker #to create random arbitary names import random #to create random age from random import randint import logging fake = Faker('en_US') producer = KafkaProducer(value_serializer=lambda m: json.dumps(m).encode( 'ascii')) #set kafkaProducer for json for _ in range(10): my_dict = { 'first_name': fake.first_name(), 'last_name': fake.last_name(), 'age': randint(0, 100) } print(str(my_dict)) print("\n") future = producer.send( 'asamasach_3', my_dict) #send json data to kafka topic named 'asamasach_3' try: record_metadata = future.get(timeout=10) #to chech metadata of sending except KafkaError: # Decide what to do if produce request failed... log.exception() pass
from app import db, Employee from faker import Faker import random categories = ["first", "second", "third"] if __name__ == '__main__': fake = Faker('ru_RU') db.create_all() for e in range(50): f_name = fake.name().split() f_date = fake.date() f_summ = random.randint(1000, 50000) emp = Employee(name=f_name[1], surname=f_name[0], date=f_date, summ=f_summ) db.session.add(emp) db.session.commit() print("Database populated")
def __init__(self, driver, database, server, user, password): self._connection = pyodbc.connect( f"DRIVER={driver};DATABASE={database};SERVER={server};UID={user};PWD={password}" ) self._cursor = self._connection.cursor() self._faker = Faker()
def fake_data(): from faker import Faker fake = Faker() name, surname = fake.name().split() return BaseContact(name=name, surname=surname, private_mail=fake.email())
from faker import Faker fake = Faker('pl_PL') fake.first_name() fake.last_name() fake.address() fake.company() fake.job() fake.phone_number() fake.email() class Card: card_list = [] def __init__(self, name, surname, address, company, occupation, phone_number, e_mail): self.name = name self.surname = surname self.address = address self.company = company self.occupation = occupation self.phone_number = phone_number self.e_mail = e_mail self.card_list.append(self) class Basecontact(Card): basecontact_list = [] def __init__(self, name, surname, address, phone_number, e_mail):
def fake_data2(): from faker import Faker fake = Faker() name, surname = fake.name().split() return BusinessContact(name=name, surname=surname, private_mail=fake.email(), company=fake.company(), job_title=fake.job(), company_phone=fake.ssn())
def test_InviteAdminUser(self): f = Faker() driver = self.driver driver.get(self.base_url + "/#/page/login") driver.find_element_by_id("exampleInputEmail1").clear() driver.find_element_by_id("exampleInputEmail1").send_keys( "*****@*****.**") driver.find_element_by_id("exampleInputPassword1").clear() driver.find_element_by_id("exampleInputPassword1").send_keys("test123") time.sleep(2) driver.find_element_by_xpath("//button[@type='submit']").click() time.sleep(2) driver.find_element_by_xpath("//li[5]/a/span").click() time.sleep(2) driver.find_element_by_xpath( "html/body/div[2]/section/div/div/button[1]").click() time.sleep(2) ####### write organization name cname = f.company() driver.find_element_by_xpath( "//input[contains(@orgname,'orgname')]").send_keys(cname) print(cname) time.sleep(2) ####### enter zipcode driver.find_element_by_xpath("//div[2]/input").send_keys("94086") time.sleep(2) ####### enter address #add =f.street_address #driver.find_element_by_xpath("//div[2]/div[1]/div[3]/input").send_keys(add) #print(add) # time.sleep(2) driver.find_element_by_xpath("//div[3]/input").send_keys("123 cbbnbn") ####### enter country driver.find_element_by_xpath("//input[@name='country']").send_keys( "USA") ####### enter state #state = f.state() #driver.find_element_by_xpath("//input[contains(@name,'state')]").send_keys(state) #print(state) #driver.find_element_by_xpath("//input[contains(@name,'state')]").send_keys("CA") ####### select state from drop down driver.find_element_by_xpath( "//select[contains(@ng-show,'ctrl.showStatesDropDown')]").click() driver.find_element_by_xpath("//option[contains(.,'Kansas')]").click() driver.find_element_by_xpath("//option[contains(.,'Kansas')]").click() #driver.find_element_by_xpath("//a/div/b").click() #driver.find_element_by_xpath("//li[@class='active-result'][text()='Kansas - KS']").click() ####### enter city # city = f.city # driver.find_element_by_xpath("//input[contains(@name,'city')]").send_keys(city) # print(city) # time.sleep(2) driver.find_element_by_xpath( "//input[contains(@name,'city')]").send_keys("santa clara") ####### click NextStep driver.find_element_by_xpath( "//div[2]/section/div/div/div[2]/button[2]").click() print("regular user page") time.sleep(2) ####### click next step driver.find_element_by_xpath("//button[2]").click() time.sleep(2) print("Onadmin user page") driver.save_screenshot("C:\Users\UNI\Desktop\QAUber") ####### add email id for admin user print("enter email id") driver.find_element_by_xpath("(//input[@type='text'])[12]").send_keys( "*****@*****.**") driver.find_element_by_xpath("(//input[@type='text'])[12]").click() driver.find_element_by_xpath("//button[2]").click() #driver.find_element_by_xpath("//button[@class='btn btn-primary']").is_enabled() ####### click on Invite button #driver.find_element_by_xpath("html/body/div[2]/section/div/div/div[1]/div[3]/form/div/div/span/button").click() time.sleep(15) print("Invitation sent to admin user") driver.find_element_by_xpath("//button[contains(.,'Done')]").click() print("done") driver.find_element_by_link_text("Logout").click()
class Command(BaseCommand): """Create a manage.py command""" help = "Fills the database with randomized data for testing" fake = Faker() def add_arguments(self, parser): """Arguments for comment""" parser.add_argument('-f', '--fridges', type=int, help="Number of fridges") parser.add_argument('-u', '--users', type=int, help="Number of users") parser.add_argument('-i', '--items', type=int, help="Number of items") parser.add_argument('-fc', '--fridgecontent', type=int, help="Max amount of items in fridge") parser.add_argument('-fcmin', '--fridgecontentmin', type=int, help="Min amount of items in fridge") parser.add_argument('-upf', '--userpfridge', type=int, help="Amount of users per fridge") def handle(self, *_, **options): """Handle the executed command""" p_fridges = 3 if options["fridges"] is None else options["fridges"] p_users = 5 if options["users"] is None else options["users"] p_items = 10 if options["items"] is None else options["items"] p_upf = 2 if options["userpfridge"] is None else options["userpfridge"] p_fc = 25 if options["fridgecontent"] is None else options[ "fridgecontent"] p_fcm = 10 if options["fridgecontentmin"] is None else options[ "fridgecontentmin"] self.stdout.write( f"Fill database with: \n" + f"Fridges: {p_fridges}, Users: {p_users+1}, User per Fridge: {p_upf}," f"Items: {p_items}, Max. Items per fridge: {p_fc}, Min. Items per Fridge: {p_fcm}" ) self.fake.add_provider(internet) self.fake.add_provider(person) self.fake.add_provider(date_time) self.fake.add_provider(lorem) self.fake.add_provider(barcode) self.create_users(p_users) self.create_fridge(p_fridges) self.connect_uf(p_users, p_upf) self.create_store() self.create_item(p_items) self.fill_fridges(p_fcm, p_fc) self.stdout.write(f"Database was filled successfully...") def create_users(self, count): """Create users""" pw = bcrypt.hashpw("password".encode("utf-8"), bcrypt.gensalt()).decode("utf-8") for _ in range(count): _ = models.Users.objects.create( username=self.fake.user_name(), name=self.fake.last_name(), surname=self.fake.first_name(), email=self.fake.email(), password=pw, birth_date=self.fake.date_of_birth().strftime("%Y-%m-%d")) models.Users.objects.create( username="******", name="Fridgify", surname="Test", email="*****@*****.**", password=pw, birth_date=self.fake.date_of_birth().strftime("%Y-%m-%d")) self.users = models.Users.objects.all() def create_fridge(self, count): """Create fridges""" for _ in range(count): fridge = models.Fridges(name=self.fake.word(), description=self.fake.text()) fridge.save() self.fridges = models.Fridges.objects.all() def connect_uf(self, user_count, upf=1): """Connect user with fridges""" ufs = [] for fridge in self.fridges: exclude = [] ufs.append( models.UserFridge( user=models.Users.objects.get(username="******"), fridge=fridge, role=0)) for _ in range(upf): rand = random.randint(0, user_count - 1) while rand in exclude: rand = random.randint(0, user_count - 1) ufs.append( models.UserFridge(user=self.users[rand], fridge=fridge, role=random.randint(1, 2))) exclude.append(rand) models.UserFridge.objects.bulk_create(ufs) def create_store(self): """Create stores""" models.Stores.objects.bulk_create([ models.Stores(name="Rewe"), models.Stores(name="Aldi Süd"), models.Stores(name="Penny"), models.Stores(name="Lidl"), models.Stores(name="Nahkauf"), ]) self.stores = models.Stores.objects.all() def create_item(self, count): """Create Items""" for _ in range(count): models.Items.objects.create(barcode=self.fake.ean(), name=self.fake.word(), description=self.fake.sentence(), store=self.stores[random.randint( 0, (len(self.stores) - 1))]) self.items = models.Items.objects.all() def fill_fridges(self, min_amount, max_items): """Fill fridges with dummy data""" fc = [] units = ["kg", "g", "l", "ml"] for fridge in self.fridges: for _ in range(random.randint(min_amount, max_items)): dates = [ self.fake.future_date().strftime("%Y-%m-%d"), self.fake.date_time_between(start_date='-20d') ] amount = random.randint(0, 1000) item = self.items[random.randint(0, (len(self.items) - 1))] fc.append( models.FridgeContent( fridge=fridge, item=item, amount=amount, max_amount=amount, unit=units[random.randint(0, 3)], expiration_date=dates[random.randint(0, 1)], )) models.FridgeContent.objects.bulk_create(fc)
# Commonly used test case functions. import json from faker import Faker def register_user(self, data): return self.client.post( "/auth/register", data=json.dumps(data), content_type="application/json", ) def login_user(self, email, password): return self.client.post( "/auth/login", data=json.dumps(dict( email=email, password=password, )), content_type="application/json", ) # Create a fake profile. profile = Faker().profile()
def setUp(self): self.factory = Faker('ne_NP')
def fake(): return Faker()
def setUp(self): self.factory = Faker('pl_PL')
from faker import Faker from faker.providers import BaseProvider import random import csv gen = Faker() class MedicalProvider(BaseProvider): def age(self): return random.randint(1, 85) def gender(self): options = ['M', 'F'] return options[random.randrange(len(options))] def race(self): options = [ "White", "White", "White", "White", "Black or African American", "Black or African American", "Black or African American", "Asian", "Asian", "Native American or Alaska Native", "Native Hawaiians or Other Pacific Islander", "Two or more races", "Some other race" ] return options[random.randrange(len(options))] def blood(self): options = [ "A+", "B+", "AB+", "O+", "A+", "B+", "AB+", "O+", "A+", "B+", "AB+", "O+", "A-", "B-", "AB-", "O-" ] return options[random.randrange(len(options))]
def setUp(self): self.factory = Faker('ja')
#!/usr/bin/env python # coding: utf-8 # # My Sources Generation # In[5]: from faker import Faker fake = Faker(["en_AU", "en_US", "en_UK"]) # In[6]: import os from dataclasses import dataclass, field from typing import List from pathlib import Path from datetime import datetime import random import json from pprint import pprint from transformers import pipeline from textblob import TextBlob from dotenv import load_dotenv import pymongo import requests import matplotlib.pyplot as plt from tqdm import tqdm load_dotenv()
], [ sg.Button('Gerar Cartão de Crédito', size=(20, 0)), sg.Input(key='cartao_credito', size=(60, 0)) ], [sg.Output(size=(85, 20))], [ sg.Button('Imprimir Perfil Completo'), sg.Button('Salvar Perfil em Arquivo') ]] #criando a janela, usando o layout que foi definido janela = sg.Window('Faker - Gerador de Dados para Testes', layout=layout) # Lendo os eventos da tela e gerar os dados fakes fake = Faker('pt_BR') Faker.seed(0) while True: event, valores = janela.read() if event == sg.WIN_CLOSED: break if event == 'Gerar Nome': janela['nome'].update(fake.name()) elif event == 'Gerar Profissão': janela['profissao'].update(fake.job()) elif event == 'Gerar Endereços': janela['endereco'].update(fake.address()) elif event == 'Gerar Placa': janela['placa'].update(fake.license_plate()) elif event == 'Gerar Cartão de Crédito': janela['cartao_credito'].update(fake.credit_card_full())
from random import randint, choice from faker import Faker from common.models import LoginStats, SystemAdmin, MerchantAdmin, Marketer, Client, City, Area, MerchantCategory, \ PaymentQRCode, Merchant, CouponRule, Coupon, Account, Payment, Refund, Withdraw, Transaction, \ MerchantMarketerShip, TransferRecord, Settlement from common.model_manager.utils import set_amount from config import MERCHANT_STATUS, MARKETER_TYPES, MERCHANT_ADMIN_TYPES, VALID_STRATEGY, COUPON_STATUS, \ WITHDRAW_STATUS, PAYMENT_STATUS, REFUND_STATUS, PAY_CHANNELS, TRANSACTION_TYPE, SYSTEM_USER_STATUS, \ WITHDRAW_TYPE, TRANSFER_STATUS, SETTLEMENT_STATUS fake = Faker('zh_CN') class Config: default_number = 1 many_to_many_num = 5 merchant_categories = ('美食', '饮品', '足浴', '珠宝', '健身运动', '电影', '酒店住宿', '密室逃脱', '酒吧', 'KTV', '手机维修', '开锁', '宠物', '超市/生鲜', '鲜花') image_urls = ( 'https://ss1.mvpalpha.muchbo.com//tmp/wxde4cd9477fb1b7cc.o6zAJs_2J1MEva4MSZJ3mD_HZxGs.GFOwACkadFdDe15e3b97da58527dc8aee94f917354a3.png', 'https://ss1.mvpalpha.muchbo.com//tmp/wxde4cd9477fb1b7cc.o6zAJs_2J1MEva4MSZJ3mD_HZxGs.vXbifX6t4GBJ12b9f3ceaa2b26674b022d4148a894b3.png', 'https://ss1.mvpalpha.muchbo.com//tmp/wxde4cd9477fb1b7cc.o6zAJs_2J1MEva4MSZJ3mD_HZxGs.66AMmUizMaOYcc06e6e74ba8b05925979ce561b0e7ed.png', 'https://ss1.mvpalpha.muchbo.com//tmp/wxde4cd9477fb1b7cc.o6zAJs_2J1MEva4MSZJ3mD_HZxGs.nvTz6UJsNa5K3690ad76c046f3192363a782eda7fae4.png', ) discount = (5, 10, 12, 15, 20, 30, 40, 50, 55, 59) min_charge = (60, 66, 88, 80, 99, 100, 101, 110, 120, 300)
import os os.environ.setdefault('DJANGO_SETTINGS_MODULE','restapi2.settings') import django django.setup() from testapp.models import Student from faker import Faker from random import * faker=Faker() def populate(n): for i in range(n): srno=randint(100,999) sname=faker.name() saddr=faker.city() # smarks=choice([,60000,1000,55000,43000,25000]) smarks=randint(50,99) emp_record=Student.objects.get_or_create(srno=srno,sname=sname,saddr=saddr,smarks=smarks) populate(5)
from faker import Faker import random f = Faker("ru_RU") users = [] #10 пользователей -> users.json, users.csv products = [] #10 товаров -> products.json, products.csv sales = [ ] #0-10 случайных продаж случайного товара каждому пользователю ->sales.json, sales.csv user = {'name': "...", 'mail': "...", 'phone': "..."} product = {'name': "...", 'price': random.randomint(10000) / 100} sale = { 'user': "******", 'product': "name/id", 'date': randomDate((2017, 01, 01), (2018, 12, 31)), 'count': random.randomint(10) } #https://stackoverflow.com/questions/553303/generate-a-random-date-between-two-other-dates