Esempio n. 1
0
    def handle(self, *args, **options):
        users = list(User.objects.all())

        for i in range(10):
            t = Topic()
            t.name = u'Topic Name {}'.format(i)
            t.description = u'Topic Description {}'.format(i)
            t.save()
        topics = list(Topic.objects.all())

        for j in range(100):
            q = Question()
            q.author = random.choice(users)
            q.title = u'title {}'.format(j)
            q.text = u'text {}'.format(j)
            q.pub_date = datetime.datetime.now()
            q.is_published = True
            q.save()
            q.topics = random.sample(topics, random.randint(1, 6))
        questions = list(Question.objects.all())

        for k in range(100):
            c = Comment()
            c.author = random.choice(users)
            c.question = random.choice(questions)
            c.text = u'text {}'.format(k)
            c.pub_date = datetime.datetime.now()
            c.save()
Esempio n. 2
0
    def handle(self, *args, **options):
        users = list(User.objects.all())

        for i in range(10):
            t = Topic()
            t.name = u'Topic Name {}'.format(i)
            t.description = u'Topic Description {}'.format(i)
            t.save()
        topics = list(Topic.objects.all())

        for j in range(100):
            q = Question()
            q.author = random.choice(users)
            q.title = u'title {}'.format(j)
            q.text = u'text {}'.format(j)
            q.pub_date = datetime.datetime.now()
            q.is_published = True
            q.save()
            q.topics = random.sample(topics, random.randint(1, 6))
        questions = list(Question.objects.all())

        for k in range(100):
            c = Comment()
            c.author = random.choice(users)
            c.question = random.choice(questions)
            c.text = u'text {}'.format(k)
            c.pub_date = datetime.datetime.now()
            c.save()
Esempio n. 3
0
    def save(self, user):
        model = Topic(title=self.cleaned_data['title'],
                      node=self.cleaned_data['node'],
                      content=self.cleaned_data['content'],
                      creater=user)
        model.save()

        return model
Esempio n. 4
0
    def save(self, user):
        model = Topic(
            title = self.cleaned_data['title'],
            node = self.cleaned_data['node'],
            content = self.cleaned_data['content'],
            creater = user)
        model.save()

        return model
    def create_topic(self, number):
        """Create topic object.

        Args:
            number: Identifier of the topic (int).

        Returns:
            Topic object.
        """
        topic = Topic(
            slug="topic-{}".format(number),
            name="Topic {}".format(number),
            content="<p>Content for topic {}.</p>".format(number),
        )
        topic.save()
        return topic
Esempio n. 6
0
def initialize():
    # init user
    admin = 'cacate'
    if not getuserbyname(admin):
        user = newuser(truename=admin, password='******',
                email='*****@*****.**', description="I am the boss!", avatar=None)
        user.is_staff = True
        user.is_superuser = True
        user.save()
    for i in range(10):
        truename = 'test%d'%i
        if not getuserbyname(truename):
            user = newuser(truename=truename, password='******',
                    email='*****@*****.**'%i, description="%d"%i, avatar=None)
            print('create user %s'%truename)

    # init genres
    glist = ['Quantum Computation', 'Machine Learning',
            'Tensor Network', 'Monte Carlo']
    for g in glist:
        try:
            g = Genre(text=g)
            g.save()
            print('create genre %s'%g)
        except Exception:
            pass

    # init topics
    for i in range(10):
        try:
            t = Topic(text='topic%d'%i, ref = None, url='www.baidu.com',
                    add_date=datetime.now(), genre=random.choice(Genre.objects.all()),
                    user=getuserbyname('test%d'%random.randint(0,9)))
            t.save()
            print('create topic %s'%t)
        except:
            pass

    for t in Topic.objects.all():
        try:
            for j in range(5):
                kind = random.choice([1, 0, -1])
                v = newvote(topic=t, user=getuserbyname('test%d'%j), kind=kind)
                print('create vote %s'%v)
        except Exception:
            print(traceback.format_exc())
Esempio n. 7
0
    def run(self):
        chunks = {}

        chunks['bottom'] = (self.amount * 60) / 100
        chunks['middle'] = (self.amount * 30) / 100
        chunks['top'] = self.amount - (chunks['bottom'] + chunks['middle'])

        bottom_vals = [random.randint(1, 80) for i in range(chunks['bottom'])]
        bottom = []

        print colored.white("Generating topics level 0:")
        for elem in progress.bar(bottom_vals):
            new_topic = Topic()
            bottom.append(new_topic)
            
            new_topic.save()
        middle = []
        transaction.commit()

        print colored.white("Generating topics level 1:")
        for i in progress.bar(range(chunks['middle'])):
            children = random.sample(bottom, random.randint(8, 11))

            new_topic = Topic()
            new_topic.save()

            for child in children:
                new_topic.parent.add(child)

            middle.append(new_topic)
        
        print colored.white("Generating topics level 2:")
        for i in progress.bar(range(chunks['top'])):
            children = random.sample(middle, random.randint(4, 7))

            new_topic = Topic()
            new_topic.save()

            for child in children:
                new_topic.parent.add(child)

        transaction.commit()
Esempio n. 8
0
    def update(self, request):

        meeting = Meeting.objects.get(id = request.data.get('meeting'))

        meeting.title = request.data.get('title')
        meeting.subject_matter = request.data.get('subject_matter')
        meeting.status = request.data.get('status')
        meeting.initial_date = request.data.get('initial_date')
        meeting.final_date = request.data.get('final_date')
        meeting.initial_hour = request.data.get('initial_hour')
        meeting.final_hour = request.data.get('final_hour')
        meeting.save()

        if request.data.get('topics') != None:

            for topic in request.data.get('topics'):

                new_topic = Topic()
                new_topic.title = topic['title']

                if Topic.objects.all().filter(title = new_topic.title) != True:

                    new_topic.save()
                    meeting.topics.add(new_topic)

        if request.data.get('rules') != None:

            for rules in request.data.get('rules'):

                new_rule = Rules()
                new_rule.title = rules['title']

                if Rules.objects.all().filter(title = new_rule.title) != True:

                    new_rule.save()
                    meeting.rules.add(new_rule)

        if request.data.get('users') != None:

            for users in request.data.get('users'):

                new_user = User.objects.get(id = users['id'])
                meeting.users.add(new_user)

        if request.data.get('questtionaire') != None:

            questtionaires = Questionnaire()
            questtionaires.title = request.data.get('questtionaire').get('title')
            questtionaires.save()
            meeting.questtionaire.add(questtionaires)

            order = 1

            for quiz in request.data.get('questtionaire').get('questions'):

                new_quiz = Quiz()
                new_quiz.title = quiz['title']
                new_quiz.order = order
                new_quiz.save()

                for user in meeting.users.all():

                    if user.name == str(meeting.meeting_leader):

                        print('Usuário é o Líder da Reunião')

                    else:

                        new_quiz.users.add(user)

                for choice in quiz.get('choices'):

                    new_choice = Choice()
                    new_choice.title = choice
                    new_choice.save()
                    new_quiz.choices.add(new_choice)

                new_quiz.questtionaire = questtionaires
                new_quiz.save()
                order += 1

        return meeting
Esempio n. 9
0
    text = 'nothing'

Topic.objects.all().delete()
for i in range(100):
    t = Topic()
    day = random.randrange(1, 27)
    month = random.randrange(1, 12)
    year = 2010 + random.randrange(1, 8)
    date = datetime.date(year, month, day)
    time = datetime.time(8, 0, tzinfo=timezone.get_current_timezone())
    t.published_at = datetime.datetime.combine(date, time)
    t.title = 'New Article {}/{}/{}'.format(day, month, year)
    t.slug = 'new-article-{}-{}-{}-{}'.format(i, day, month, year)
    t.content = text
    t.author = users[random.randrange(0, len(users) - 1)]
    Topic.save(t)

topics = Topic.objects.all()
for t in topics:
    for i in range(random.randrange(2, 7)):
        u = users[random.randrange(0, len(users) - 1)]
        upvoted = False
        if i > 0:
            topic_upvotes = Upvote.objects.filter(topic=t)
            for el in topic_upvotes:
                if el.upvoter == u:
                    upvoted = True
        if not upvoted:
            up = Upvote(topic=t, upvoter=u)
            Upvote.save(up)
        if random.random() > .5:  # randomly comment on article
def read_csv(source_csv, dept_name, order='esd'):
    count = 0
    #with codecs.open(source_csv, 'rb', encoding='utf-8') as csvfile:
    with open(source_csv) as csvfile:
        reader = unicode_csv_reader(csvfile)

        #just print the first row:
        print '>, <'.join(reader.next())

        for row in reader:
            count += 1

            if order == 'esd':
                url = row[0]
                alias = row[2]
                #aka status/notes, or topic?
                tag = row[3]
                notes = row[4]
                title = row[5]
                page_views = to_int(row[6])
                page_views_unique = to_int(row[7])
                average_time = row[8]
                entrances = to_int(row[9])
                bounce_rate = row[10]
                exit_percent = row[11]
                section_id = row[12]
                categories = ','.join(row[13:])
            else:
                raise ValueError, "Unknown Order: %s" % order

            dept_options = Department.objects.filter(name=dept_name)
            if len(dept_options):
                department = dept_options[0]
            else:
                print "Be sure to import departments with 'make_departments.py'"
                raise ValueError, "Couldn't find department: %s" % dept_name

            #there is some filtering we can do here...
            tag = re.sub("DAM: keep", '', tag)
            tag = re.sub("DAM: Keep", '', tag)

            tags = []
            items = tag.split('/')
            for item in items:
                current = item.strip()
                if not current in tags:
                    tags.append(current)            

            default_topic = None
            for tag in tags:
                #aka status/notes, or topic?
                #tag = row[3]
                topic_options = Topic.objects.filter(name=tag)
                if len(topic_options):
                    topic = topic_options[0]
                elif tag:
                    topic = Topic()
                    #TODO: associate alias here?
                    topic.name = tag
                    topic.tag = to_tag(tag)
                else:
                    topic = None

                if topic:
                    #doing this again, for updates
                    #topic.name = tag
                    topic.save()
                    #print "Save topic here"
                    if not default_topic:
                        default_topic = topic

            page_options = Page.objects.filter(url=url)
            if len(page_options):
                page = page_options[0]
            elif url:
                #make a new one:
                page = Page()
                page.url = url

                page.alias = alias
                
                page.notes = notes
                page.title = title
                page.page_views = page_views
                page.page_views_unique = page_views_unique
                page.average_time = average_time
                page.entrances = entrances
                page.bounce_rate = bounce_rate
                page.exit_percent = exit_percent
                page.section_id = section_id
                page.categories = categories
                
            else:
                page = None

            if page:
                page.position = count
                page.default_topic = topic
                page.site = "bloomington.in.gov"
                page.save()
                #print "Save page here"

            department_page_options = DepartmentPage.objects.filter(page=page, department=department)
            if len(department_page_options):
                department_page = department_page_options[0]
            elif department and page:
                department_page = DepartmentPage()
                department_page.page = page
                department_page.department = department
            else:
                department_page = None

            if department_page:
                department_page.save()
                #print "Save department_page here"


            page_topic_options = PageTopic.objects.filter(page=page, topic=topic)
            if len(page_topic_options):
                page_topic = page_topic_options[0]
            elif page and topic:
                page_topic = PageTopic()
                page_topic.page = page
                page_topic.topic = topic
            else:
                #print "no page: %s -OR- no topic: %s" % (page, topic)
                page_topic = None

            if page_topic:
                page_topic.save()
Esempio n. 11
0
    def load(self):
        """Load the content for a topic.

        Raise:
            MissingRequiredFieldError: when no object can be found with the matching
                attribute.
        """
        topic_structure = self.load_yaml_file(self.structure_file_path)

        unit_plans = topic_structure.get("unit-plans", None)
        if unit_plans is None:
            raise MissingRequiredFieldError(self.structure_file_path,
                                            ["unit-plans"], "Topic")

        # Convert the content to HTML
        topic_content = self.convert_md_file(
            os.path.join(self.BASE_PATH, "{}.md".format(self.topic_slug)),
            self.structure_file_path)

        # If other resources are given, convert to HTML
        if "other-resources" in topic_structure:
            topic_other_resources_file = topic_structure["other-resources"]
            if topic_other_resources_file is not None:
                other_resources_content = self.convert_md_file(
                    os.path.join(self.BASE_PATH, topic_other_resources_file),
                    self.structure_file_path)
                topic_other_resources_html = other_resources_content.html_string
            else:
                topic_other_resources_html = None
        else:
            topic_other_resources_html = None

        # Check if icon is given
        if "icon" in topic_structure:
            topic_icon = topic_structure["icon"]
            if topic_icon is not None:
                find_image_files([topic_icon], self.structure_file_path)
            else:
                topic_icon = None
        else:
            topic_icon = None

        # Create topic objects and save to the db
        topic = Topic(slug=self.topic_slug,
                      name=topic_content.title,
                      content=topic_content.html_string,
                      other_resources=topic_other_resources_html,
                      icon=topic_icon)
        topic.save()

        self.log("Added Topic: {}".format(topic.name))

        # Load programming challenges
        if "programming-challenges" in topic_structure:
            programming_challenges_structure_file_path = topic_structure[
                "programming-challenges"]
            if programming_challenges_structure_file_path is not None:
                self.factory.create_programming_challenges_loader(
                    programming_challenges_structure_file_path, topic,
                    self.BASE_PATH).load()

        # Load unit plans
        for unit_plan_file_path in unit_plans:
            self.factory.create_unit_plan_loader(unit_plan_file_path, topic,
                                                 self.BASE_PATH).load()

        if "curriculum-integrations" in topic_structure:
            curriculum_integrations_structure_file_path = topic_structure[
                "curriculum-integrations"]
            if curriculum_integrations_structure_file_path is not None:
                self.factory.create_curriculum_integrations_loader(
                    curriculum_integrations_structure_file_path, topic,
                    self.BASE_PATH).load()

        self.log("")