Example #1
0
    def generate(self, number):
        """
        Generates an MP3 file with tones from a range of low and high
        frequencies.

        Args:
            number (int): A number used in the multiprocessing iterator.

        Returns:
            str: The name of the generated MP3 file.
        """

        lorem = TextLorem()
        title = lorem.sentence()
        handle, qr_filename = mkstemp('.png')
        os.close(handle)

        try:
            qr = qrcode.make(md5(title.encode('utf-8')).hexdigest())
            qr.save(qr_filename)
            wav_filename = generate_wav(self.low_freq, self.high_freq,
                                        self.duration)

            try:
                handle, mp3_filename = mkstemp('.mp3')
                os.close(handle)

                convert_mp3(wav_filename, mp3_filename)
                tag_mp3(mp3_filename, title, qr_filename)
                return mp3_filename
            finally:
                os.remove(wav_filename)
        finally:
            os.remove(qr_filename)
def main(args):
    init()
    lorem = TextLorem(srange=(1, args.length))
    while True:
        print(getColors() + lorem.sentence().lower().replace(".", ""), end="")
        if args.time > 0:
            pause(args.time)
Example #3
0
def seed_tables(cats, prods, opts):
    categories = []

    for i in range(0, cats):
       products = []
       cat_id = str(uuid.uuid4())
       categories.append({
           "CategoryId": cat_id,
           "CategoryName": TextLorem(srange=(1,3)).sentence(),
           "CategoryDescription": lorem.sentence()
       })

       for j in range(0, prods):
           options = []
           prod_id = str(uuid.uuid4())
           products.append({
               "ProductId": prod_id,
               "ProductName": TextLorem(srange=(1,3)).sentence(),
               "ProductDescription": lorem.sentence()
           })

           for k in range(0, opts):
               opt_id = str(uuid.uuid4())
               options.append({
                   "OptionId": opt_id,
                   "OptionName": TextLorem(srange=(1,3)).sentence(),
                   "OptionDescription": lorem.sentence(),
                   "OptionValue": TextLorem(srange=(1,3)).sentence()
               })
           products[j]["Options"] = options
       categories[i]["Products"] = products

    with open('seed_3.txt', 'w') as outfile:
        json.dump(categories, outfile)
Example #4
0
def generate_data(file):
    # opening the csv file to find the amount of lines & seq number
    with open(file, 'r') as infile:
        seq = len(infile.readlines())

    while seq < 1000002:
        # generate guid
        guid = uuid.uuid4()

        # generate fake cc
        cc_len = 16
        ccnumber = ''.join(["%s" % random.randint(0, 9)
                            for num in range(0, cc_len)])

        # generate random date because ???
        date = datetime.date(random.randint(2005, 2025),
                            random.randint(1, 12), random.randint(1, 28)).strftime("%d/%m/%Y")

        # generate sentence filled with gibberish??? okay...
        lorem = TextLorem(wsep=' ', srange=(6, 12))
        sentence = lorem.sentence()

        # now we are writing the data to the csv until we have 1 mil entries
        
        with open(file, 'a') as outfile:
        # seq len is one extra b/c of header, but that works instead of +=
            writer = csv.writer(outfile)
            row = [seq, guid, seq, seq, ccnumber, date, sentence]
            writer.writerow(row)
            seq += 1
Example #5
0
def main():
    # separate words by '-'
    # sentence length should be between 2 and 3
    # choose words from A, B, C and D
    lorem = TextLorem(wsep='-', srange=(2, 3), words="A B C D".split())

    s1 = lorem.sentence()  # 'C-B.'
    s2 = lorem.sentence()  # 'C-A-C.'
    print("This is dummy gm.com text, will hit on this")
Example #6
0
def get_sentence_using_service_2():
    address, port = get_service("service2")

    words = requests.get(f"http://{address}:{port}/words").json()

    words = words["words"]

    lorem = TextLorem(words=words)

    return {"sentence": lorem.sentence()}
Example #7
0
def create_tables_data():

    lorem = TextLorem(srange=(1, 2))
    for i in range(0, 40):

        data = {
            "table_id": i + 1,
            "name": lorem.sentence(),
            "max_line": randint(600, 800)
        }

        table = ModelTable.find_table(data.get("table_id"))

        if not table:
            table = ModelTable(**data)
            table.save_table()
Example #8
0
def create_random_data(count):
    name_generator = TextLorem(srange=(2, 4))
    description_generator = TextLorem(srange=(4, 8))
    registered = True
    for i in range(count):
        device = Device.objects.create(
            name=f'{name_generator.sentence()}_{count}',
            serial_id=''.join(
                random.choices(string.ascii_uppercase + string.digits, k=10)),
            description=description_generator.sentence(),
            address=''.join(
                random.choices(string.ascii_uppercase + string.digits, k=10)),
            registered=registered)
        if registered:
            registered = False
        else:
            registered = True
Example #9
0
def lorem_struct(recurse=0):
    d = dict()
    keys = random.randrange(2, 10)
    for i in range(0, keys):
        key = TextLorem(wsep='-', srange=(1, 2)).sentence().rstrip('.')
        # roll the dice
        options = 5 if recurse else 4
        roll = random.randrange(0, options)
        if roll == 0:  # int
            value = int(random.randrange(1, 10000))
        elif roll == 1:  # word
            value = TextLorem(srange=(1, 1)).sentence().rstrip('.')
        elif roll == 2:  # sentence
            value = TextLorem(srange=(2, 5)).sentence().rstrip('.')
        elif roll == 3:  # paragraph
            value = lorem.paragraph().rstrip('.')
        elif roll == 4:  # struct
            value = lorem_struct(recurse - 1)
        d[key] = value
    return d
Example #10
0
def lorem_preferences():
    prefs = dict()
    nprefs = random.randrange(1, 10)
    for i in range(0, nprefs):
        name = TextLorem(wsep='.',
                         srange=(2,
                                 random.randrange(3,
                                                  5))).sentence().rstrip('.')
        if name not in prefs:
            prefs[name] = lorem_struct(random.randrange(1, 2))
    return prefs
Example #11
0
    def generate(self):
        """Generate."""
        size = self.holder.items["total"]
        iloc_pids = self.holder.pids("internal_locations", "pid")
        doc_pids = self.holder.pids("documents", "pid")
        shelf_lorem = TextLorem(wsep='-',
                                srange=(2, 3),
                                words='Ax Bs Cw 8080'.split())
        objs = [{
            "pid":
            self.create_pid(),
            "document_pid":
            random.choice(doc_pids),
            "internal_location_pid":
            random.choice(iloc_pids),
            "legacy_id":
            "{}".format(randint(100000, 999999)),
            "legacy_library_id":
            "{}".format(randint(5, 50)),
            "barcode":
            "{}".format(randint(10000000, 99999999)),
            "shelf":
            "{}".format(shelf_lorem.sentence()),
            "description":
            "{}".format(lorem.text()),
            "internal_notes":
            "{}".format(lorem.text()),
            "medium":
            random.choice(Item.MEDIUMS),
            "status":
            random.choice(
                random.choices(population=Item.STATUSES,
                               weights=[0.7, 0.1, 0.1, 0.1, 0.05],
                               k=10)),
            "circulation_restriction":
            random.choice(Item.CIRCULATION_RESTRICTIONS),
        } for pid in range(1, size + 1)]

        self.holder.items["objs"] = objs
Example #12
0
def step2_mokc_data():  #using environment variables
    xx = traverse_replace_yaml_tree(yaml_config)
    xx = recurse_replace_yaml(xx, runtime_dict)
    for project in xx:

        incoming = xx[project]['incoming']
        outgoing = xx[project]['outgoing']
        logger = logging.getLogger()
        pio = ProjectIO(project=project,
                        logger=logger,
                        incoming=incoming,
                        outgoing=outgoing)

        os.makedirs(pio.incoming.path, exist_ok=True)
        os.makedirs(pio.outgoing.path, exist_ok=True)
        #print(yaml_reader('/workspace/scripts/switchboard.yaml'))
        lorem = TextLorem(wsep='_', srange=(2, 3))
        for i in range(MOCKSIZE):

            file_name = lorem.sentence() + random.choice(FILE_TYPES)
            with open(os.path.join(pio.incoming.path, file_name), 'a') as f:
                f.write(lorem.paragraph())
            os.chmod(os.path.join(pio.incoming.path, file_name), 0o777)
Example #13
0
    def test_02_make_dirs(self):  #using environment variables

        for project in yaml_config:

            incoming = yaml_config[project]['incoming']
            outgoing = yaml_config[project]['outgoing']
            logger = logging.getLogger()
            pio = ProjectIO(project=project,
                            logger=logger,
                            incoming=incoming,
                            outgoing=outgoing)

            os.makedirs(os.path.abspath(pio.incoming.path), exist_ok=True)
            os.makedirs(os.path.abspath(pio.outgoing.path), exist_ok=True)
            #print(yaml_reader('/workspace/scripts/switchboard.yaml'))
            lorem = TextLorem(wsep='_', srange=(2, 3))
            for i in range(10):

                file_name = lorem.sentence() + random.choice(FILE_TYPES)
                with open(os.path.join(pio.incoming.path, file_name),
                          'a') as f:
                    f.write(lorem.paragraph())
                os.chmod(os.path.join(pio.incoming.path, file_name), 0o777)
Example #14
0
def textToText(text):
    #parameters for the lorem ipsum
    lorem = TextLorem(wsep=' ')

    binaryData = []
    # converting to binary
    for letter in text:
        binaryData.append(format(ord(letter), '08b'))


    sentence = ""
    sentenceList = []

    # sentences based on the number of letters
    for number in range(0, len(binaryData)):
        for element in binaryData[number]:
            word = lorem._word()
            # iterating until we find a word of sufficient length
            if int(element) == 0:
                word = lorem._word()
                # 0 for any word less than 6 letters
                while len(word) > 6:
                    word = lorem._word()

                sentence += word + " "

            # 1 for any word more than 7 letters
            elif int(element) == 1:
                word = lorem._word()
                while len(word) < 7:
                    word = lorem._word()

                sentence += word + " "

        sentence = sentence[0].capitalize() + sentence[1:]
        sentenceList.append(sentence[:-1] + ".")
        sentence = ""

    output = ""
    for text in sentenceList:
        output += text + " "

    print(output)
Example #15
0
def seed_database():
    print('seeding db')
    bcrypt = Bcrypt()
    title_lorem = TextLorem(wsep=" ", srange=(2, 10))
    content_lorem = TextLorem(wsep=" ", srange=(10, 20))
    # current user in database
    password = b'ava_utf8'
    hashed_password = bcrypt.generate_password_hash(password).decode("utf-8")
    ava = User(
        username='******',
        password=hashed_password,
        email='*****@*****.**',
        first_name='Ava',
        last_name='Ava',
        profile_photo=
        'https://images.unsplash.com/photo-1521191809347-74bcae21439c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=60'
    )

    print('adding user')
    db.session.add(ava)
    db.session.commit()

    # seed chirps
    chirps = []
    for _ in range(6):
        chirp = Feedback(title=title_lorem.sentence(),
                         content=content_lorem.paragraph(),
                         username='******')
        chirps.append(chirp)

    # add list of chirps to psql
    print('adding chirps')
    db.session.bulk_save_objects(chirps)
    db.session.commit()

    print('chirps added')
Example #16
0
def test_lorem_ipsum():
    from lorem.text import TextLorem
    generate_lorem = TextLorem(prange=(500, 1000), trange=(500, 1000))
    return perftest('lorem ipsum', generate_lorem.text)
import json
import random
from lorem.text import TextLorem

name_gen = TextLorem(srange=(2,2))
text_gen = TextLorem(srange=(1,30))

types = ["Generic","Share", "Image"]

name1 = name_gen.sentence()[:-1]
name2 = name_gen.sentence()[:-1]

obj = dict()
participants = [{"name":name1},{"name":name2}]
obj['participants'] = participants

n_messages = random.randint(10,1000)
messages = []

day = 0
ms_per_day = 86400000L
useName1 = True
for i in range(n_messages):
    msg_obj = dict()
    msg_obj['sender_name'] = name1 if useName1 else name2
    msg_obj['timestamp_ms'] = day * ms_per_day + i
    messages.append

    type = 'Generic'
    # 10% for share, 10% for image
    msg_type = random.randint(1,10)
Example #18
0
# -*- coding: utf-8 -*-

import os
import sys
import lorem
from lorem.text import TextLorem

APP_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(APP_DIR)

from shopbox.db.session import Session
from shopbox.db_models.project import Project

session = Session()
sd_lorem = TextLorem(prange=(3, 4))


def create_project(index):
    session.add(
        Project(
            id=index,
            name=f"project{index}",
            display_name=f"Project {index}",
            short_description=sd_lorem.paragraph(),
            long_description=lorem.text(),
        ))


def create_projects(num):
    for i in range(num):
        create_project(i)
Example #19
0
from pylatex.utils import bold, escape_latex
from pylatex.position import Center, VerticalSpace, HorizontalSpace
from pylatex.base_classes import Command, Options
from pylatex.package import Package
from datetime import datetime
from lorem.text import TextLorem


def obtain_pagesize(table_info_size):
    from math import floor, sqrt

    return "11in" if table_info_size <= 2 else str(
        11 + floor(sqrt(table_info_size - 2))) + "in"


lorem = lambda x: TextLorem(srange=(x, x)).sentence()

if __name__ == '__main__':

    geometry_options = {"margin": "0.5in", "paperwidth": "11in"}

    doc = Document(indent=False,
                   documentclass="article",
                   document_options="a4paper,landscape",
                   geometry_options=geometry_options,
                   page_numbers=False)

    doc.packages.append(Package("array"))

    # Header
    with doc.create(Center()) as centered:
Example #20
0
from src.Game.game import Game
import random
import numpy as np 
import tensorflow as tf
import copy
import time
from src import shaper
from os import system, name 
from time import sleep 
from lorem.text import TextLorem
import sys
import json
import codecs  
import gc

gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)

gc.enable()
#gc.set_debug(gc.DEBUG_LEAK)

lorem = TextLorem(srange=(1,2))
used_names = []
Example #21
0
import os
from lorem.text import TextLorem
import logging
import time
import random

logging.basicConfig(filename='loggenerator.log',
                    level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s')
logging.info("Started")

lorem = TextLorem(wsep=' ', srange=(5, 20))


def generate():
    s1 = lorem.sentence()
    level = random.randrange(1, 5)
    if level == 1:
        logging.debug(s1)
    elif level == 2:
        logging.info(s1)
    elif level == 3:
        logging.warning(s1)
    else:
        logging.error(s1)


for iter in range(1000000):
    generate()

for iter in range(1000000):
Example #22
0
def get_sentence_using_own_words():
    lorem = TextLorem()

    return {"sentence": lorem.sentence()}
Example #23
0
from random import randint
from lorem.text import TextLorem

import csv

NUM_DIFFERENT_SCHEMAS = 10  # num output tables
NUM_RECORDS = 100

out = csv.writer(open("input.csv", "w"))

for i in range(NUM_RECORDS):
    rnd = randint(1, NUM_DIFFERENT_SCHEMAS)
    lorem = TextLorem(wsep=',', srange=(rnd, rnd))

    out.writerow([str(rnd) + ',' + lorem.sentence()[:-1]])

print 'input.csv file created'
class Command(BaseCommand):
    lorem = TextLorem(
        srange=(1, 3),
        trange=(1, 4),
    )

    def add_arguments(self, parser: 'CommandParser'):
        parser.add_argument(
            '-u',
            '--user',
            dest='username',
            help=('Name of user published generated'
                  'content. If there is no user with'
                  'such name it would be created. If'
                  'name is not provided script takes'
                  'first found user.'),
        )
        parser.add_argument(
            '-p',
            '--posts',
            dest='posts_count',
            type=int,
            default=10,
            help=('Posts count to generate.'),
        )
        parser.add_argument(
            '--max-attachments',
            dest='max_attachments',
            type=int,
            default=10,
            help=('Max number of attachments in post.'),
        )
        parser.add_argument(
            '--min-attachments',
            dest='min_attachments',
            type=int,
            default=2,
            help=('Min number of attachments in post.'),
        )

    def handle(
        self,
        username: Optional[str],
        posts_count: int,
        max_attachments: int,
        min_attachments: int,
        *args,
        **options,
    ):
        user = self._get_user(username=username, )
        self._create_posts(
            posts_count=posts_count,
            publisher=user,
            max_attachments=max_attachments,
            min_attachments=min_attachments,
        )

    @classmethod
    def _get_user(cls, username: Optional[str]) -> User:
        if username is not None:
            user = User.objects.filter(username=username, ).first()

            if user is None:
                user = User(
                    username=username,
                    is_staff=True,
                )
                user.set_password(username)
                user.save()
        else:
            user = User.objects.first()
            if user is None:
                raise ValueError('There is no users in DB! Use'
                                 '`--username` to create one or'
                                 'create it manually.')

        assert isinstance(user, User)
        cls._assign_permissions(user=user, )
        return user

    @staticmethod
    def _assign_permissions(user: User):
        permissions = Permission.objects.filter(
            content_type__app_label='hosting', ).values_list(
                'pk',
                flat=True,
            )

        for permission in permissions:
            user.user_permissions.add(permission, )

    def _create_posts(
        self,
        posts_count: int,
        publisher: User,
        max_attachments: int,
        min_attachments: int,
    ) -> Tuple[Post, ...]:
        created_posts = tuple(
            Post.objects.create(publisher=publisher, )
            for _ in range(posts_count))

        for post in created_posts:
            attachments_count = randint(
                min_attachments,
                max_attachments,
            )
            for position, fabric_name in zip(range(1, 1 + attachments_count),
                                             self.fabric_names):
                PostContent.objects.create(
                    post=post,
                    attachment=self._make_attachment(fabric_name),
                    position=position,
                )

        return created_posts

    @classmethod
    def _make_attachment(cls, fabric_name):
        return getattr(cls,
                       fabric_name)(**cls._make_abstract_content_params(), )

    @classmethod
    def _make_abstract_content_params(cls) -> Dict[str, Any]:
        return dict(title=cls.lorem.sentence(), )

    VIDEO_FILE_EXTENSIONS = (
        'mp4',
        'mkv',
        'avi',
    )
    SUBTITLE_FILE_EXTENSIONS = (
        'vvt',
        'srt',
    )
    AUDIO_FILE_EXTENSIONS = (
        'mp3',
        'm4a',
        'ogg',
    )

    @classmethod
    def _create_file(
        cls,
        filename: str,
        fabric: Type[AbstractFile],
        content: 'AbstractContent',
        **extra,
    ):
        mock_file = open(settings.MEDIA_ROOT / filename, mode='w')
        with mock_file:
            pass
        # create empty mock file

        fabric.objects.create(
            file=filename,
            content=content,
            **extra,
        )

    @classmethod
    def _make_video_content(cls, **abstract_content_params):
        content = VideoContent.objects.create(**abstract_content_params, )
        cls._create_file(
            '{filename}.{ext}'.format(
                filename=get_random_string(),
                ext=choice(cls.VIDEO_FILE_EXTENSIONS),
            ),
            content=content,
            fabric=VideoFile,
        )
        if choice((True, False)):
            cls._create_file(
                '{filename}.{ext}'.format(
                    filename=get_random_string(),
                    ext=choice(cls.SUBTITLE_FILE_EXTENSIONS),
                ),
                content=content,
                fabric=SubtitleFile,
            )

        return content

    @classmethod
    def _make_audio_content(cls, **abstract_content_params):
        content = AudioContent.objects.create(**abstract_content_params, )
        cls._create_file(
            '{filename}.{ext}'.format(
                filename=get_random_string(),
                ext=choice(cls.AUDIO_FILE_EXTENSIONS),
            ),
            content=content,
            fabric=AudioFile,
            bitrate=choice((320, 192, 128)),
        )

        return content

    @classmethod
    def _make_text_content(cls, **abstract_content_params):
        content = TextContent.objects.create(
            content=cls.lorem.text(),
            **abstract_content_params,
        )
        return content

    _specific_content_fabrics = (
        '_make_video_content',
        '_make_audio_content',
        '_make_text_content',
    )

    @property
    @lru_cache(maxsize=None)
    def fabric_names(self):
        return cycle(self._specific_content_fabrics)
Example #25
0
from email.mime.text import MIMEText

# some variables do not change
email_sender = '*****@*****.**'
email_recipients = [
    '*****@*****.**', '*****@*****.**',
    '*****@*****.**'
]
body_recipients = ", ".join(email_recipients)
mail_server = "secure.emailsrvr.com"
email_password = "******"

# loop for all of time
while True:
    # new lorem instance for random text
    lorem = TextLorem()

    # a block of random text to go in the email body
    t1 = lorem.text()

    # set the subject to something unique so we don't end up with
    email_subject = "Hello from {}".format(lorem.sentence())

    email_body = "MIME-Version: 1.0\nContent-type: text/html\nFrom: {efrom}\nTo: {to}\nSubject: {subject}\n\n<b>Hi. This is a randomly-generated message.</b>\n<p>Really, all I'm doing is trying to generate some email for these mailboxes, and keep it continuously flowing.\n<p>This is really just for continuous testing - for before/during/after migration scenarios.\n<p>Here's some random text:\n\n{ipsum}".format(
        efrom=email_sender,
        to=body_recipients,
        subject=email_subject,
        ipsum=lorem.paragraph())

    server = smtplib.SMTP(mail_server)
    server.starttls()
Example #26
0
from pathlib import Path
from zipfile import ZipFile

from lorem.text import TextLorem

from zesje.database import db, Exam, Grader, Scan, Submission, Solution, Page, Copy, ExamLayout
from zesje.scans import _process_scan
from zesje.factory import create_app
import zesje.mysql as mysql


if 'ZESJE_SETTINGS' not in os.environ:
    os.environ['ZESJE_SETTINGS'] = '../zesje_dev_cfg.py'


lorem_name = TextLorem(srange=(1, 3))
lorem_prob = TextLorem(srange=(2, 5))

pil_font = ImageFont.truetype('tests/data/fonts/Hugohandwriting-Regular.ttf', size=28)


def init_app(delete):
    app = create_app()
    app.config['LOGIN_DISABLED'] = True

    mysql_was_running_before_delete = False
    if os.path.exists(app.config['DATA_DIRECTORY']) and delete:
        mysql_was_running_before_delete = mysql.is_running(app.config)
        if mysql_was_running_before_delete:
            mysql.stop(app.config)
            time.sleep(5)
Example #27
0
def random_text():
    with open('data/words.txt', 'r') as words:
        words_list = words.read().split()
    lorem = TextLorem(wsep=' ', srange=(4, 7), words=words_list)
    return lorem.sentence()
nBatches = 20  #<-- number of batches to generate
mux = [random.uniform(-500, 500) for i in range(nBatches)]
sigmax = [random.uniform(20, 30) for i in range(nBatches)]
muy = [random.uniform(-500, 500) for i in range(nBatches)]
sigmay = [random.uniform(10, 40) for i in range(nBatches)]
muz = [random.uniform(-500, 500) for i in range(nBatches)]
sigmaz = [random.uniform(10, 40) for i in range(nBatches)]
nPointsB = [int(random.uniform(20, 50)) for i in range(nBatches)]

## crerate colors for each batch at random
colorDict = {}
for i in range(nBatches):
    r = lambda: random.randint(0, 255)
    colorDict[i] = '#%02X%02X%02X' % (r(), r(), r())

lorem = TextLorem(wsep='', srange=(2, 3))
batchNames = []
for batch in range(nBatches):
    batchNames.append(lorem.sentence())

with open(data_file, 'w') as f:
    f.write("id\tx\ty\tz\tbatch\tcolor\n")
    f.write('0-1\t0\t0\t0\t1\t' + colorDict[1] + '\n')
    f.write('100-2\t100\t100\t100\t1\t' + colorDict[1] + '\n')
    kount = 3
    for batch in range(nBatches):
        print('Cardinality of ', batch, ': ', nPointsB[batch] + 1)
        for kount in range(nPointsB[batch]):
            xval = str(round(random.gauss(mux[batch], sigmax[batch]), 1))
            yval = str(round(random.gauss(muy[batch], sigmay[batch]), 1))
            zval = str(round(random.gauss(muz[batch], sigmaz[batch]), 1))
Example #29
0
from lorem.text import TextLorem

# remove duplicate entries from the list of topics
with open("topics.txt", "w") as topics:
    lines_seen = set()  # holds lines already seen
    for line in open("topics_w_dups.txt", "r"):
        if line not in lines_seen:  # not a duplicate
            topics.write(line)
            lines_seen.add(line)

# make an insert statement for each topic
with open("topics.txt", "r") as topics:
    sql = open("../../sql/insert/topics.sql", "w")
    # 4-16 words/sentence, 2-16 sentences/paragraph
    lorem = TextLorem(srange=(4, 16), prange=(2, 16))
    for topic in topics:
        while True:
            description = lorem.paragraph()
            # ensure the description fits in db
            if len(description) <= 255:
                break
        # remove trailing \n and escape single quotes
        label = topic[:-1].replace("'", "''")
        sql.write("""
insert into topics
	(label, description)
values
	('""" + label + "', '" + description + """');
""")
    sql.close()
Example #30
0
def delivery_data():

    category = [{
        "name": "Caneca",
        "description": ""
    }, {
        "name": "Azulejo",
        "description": ""
    }, {
        "name": "SmartWatch",
        "description": ""
    }, {
        "name": "Fone de Ouvido",
        "description": ""
    }]

    for cat in category:
        cate = ModelCategoryProduct.find_category(cat.get("id"))
        if not cate:
            cat = ModelCategoryProduct(**cat)
            cat.save_category()

    brand = [{
        "name": "Marca 1",
        "description": ""
    }, {
        "name": "Azulejo",
        "description": "Marca 2"
    }, {
        "name": "Marca 3",
        "description": ""
    }, {
        "name": "Marca 4",
        "description": ""
    }]

    for bran in brand:
        cate = ModelBrandProduct.find_brand(bran.get("id"))
        if not cate:
            cat = ModelBrandProduct(**bran)
            cat.save_brand()

    providers = [{
        "enable": True,
        "type_registration": 2,
        "cnpj": "16897733000100",
        "cell_phone": "22997069161",
        "phone": "",
        "company_name": "Azul e Rosa Teste Update",
        "contact_name": "andre",
        "fancy_name": "AZUl e Rosa",
        "municipal_registration": "",
        "state_registration": "",
        "address": "Rua Major Euclides",
        "city": "Campos dos Goytacazes",
        "complement": "",
        "email": "",
        "neighborhood": "Turf",
        "number": "",
        "obs": "",
        "site": "",
        "state": "RJ",
        "zip_code": "28015161"
    }, {
        "enable": True,
        "type_registration": 2,
        "cnpj": "16897733000100",
        "cell_phone": "22997069161",
        "phone": "",
        "company_name": "Azul e Rosa Teste Update",
        "contact_name": "andre",
        "fancy_name": "Fornecedor 2",
        "municipal_registration": "",
        "state_registration": "",
        "address": "Rua Major Euclides",
        "city": "Campos dos Goytacazes",
        "complement": "",
        "email": "",
        "neighborhood": "Turf",
        "number": "",
        "obs": "",
        "site": "",
        "state": "RJ",
        "zip_code": "28015161"
    }]

    for provider in providers:
        prov = ModelProvider.find_provider(provider.get("id"))
        if not prov:
            provider = ModelProvider(**provider)
            provider.save_provider()

    product = {
        "internal_code": "acb123",
        "name": "Produto Teste",
        "brand": randint(1, 4),
        "unit": 1,
        "category": 1,
        "long_description": "Descrição longa do produto",
        "short_description": "Descrição curta do produto",
        "maximum_stock": 30,
        "minimum_stock": 10,
        "sale_price": 10.50,
        "available": True,
        "height": 10,
        "provider": [1],
        "cover": "",
        "images": [],
        "length": 1.5,
        "weight": 0.75,
        "width": 1.25,
        "maximum_discount": 10.00,
        "minimum_sale": 1,
        "subtract": False
    }

    prod = ModelProducts.find_product(product.get("id"))

    if not prod:

        for _ in range(20):
            lorem = TextLorem(srange=(1, 2))
            product["name"] = lorem.sentence()
            ModelProducts(**product).save_product()

    purchase = {
        "provider_id":
        1,
        "value":
        20.10,
        "freight":
        1,
        "discount":
        0,
        "total_value":
        21.1,
        "payment_form":
        1,
        "payment_method":
        2,
        "delivery_status":
        2,
        "parcel":
        1,
        "delivery_time":
        "2017-10-10",
        "obs":
        "",
        "itens": [{
            "id": "",
            "product_id": 1,
            "product_name": "NOme do produto",
            "unit_price": 10.05,
            "qtde": 2,
            "total_price": 20.1,
            "obs": ""
        }]
    }

    for _ in range(1):

        puchase = ModelPurchase(**purchase)

        for item in purchase.get("itens"):
            puchase.itens.append(
                ModelPurchaseItem(**item,
                                  id_purchase=puchase,
                                  provider_id=purchase.get("provider_id")))
        puchase.save_purchase()