Example #1
0
  def __init__(self):
    self.data = {}

    translations = glob.glob('coursedata/texts/*.yaml')
    for trans_file in translations:
      lang = path.splitext(path.basename(trans_file))[0]
      self.data[lang] = YamlFile.for_file(trans_file)
Example #2
0
def quiz_data_file_for(lang, level):
    quiz_file = YamlFile.for_file(f'coursedata/quizzes/{lang}.yaml')
    if not quiz_file.exists():
        return None
    if level not in quiz_file['levels'].keys():
        return None
    return quiz_file['levels'][level]
Example #3
0
 def __init__(self, course_name, language, defaults):
   self.course_name = course_name
   self.language = language
   self.defaults = defaults
   self._validated = False
   self.course_file = YamlFile.for_file(f'coursedata/course/{self.course_name}/{self.language}.yaml')
   self.custom = self.course_file.get('custom', False)
   self.adventures = self.course_file.get('adventures', False)
Example #4
0
def collect_snippets(path):
    Hedy_snippets = []
    files = [
        f for f in os.listdir(path)
        if os.path.isfile(os.path.join(path, f)) and f.endswith('.yaml')
    ]
    for file in files:
        file = os.path.join(path, file)
        yaml = YamlFile.for_file(file)

        for level in yaml:
            try:
                level_number = int(level)
            except:
                continue  #level nummer geen int -> dan is het oude content, bijv 10-old en is ok
            if level_number > hedy.HEDY_MAX_LEVEL:
                print('content above max level!')
            else:
                # start_code
                Hedy_snippets.append(
                    Snippet(filename=file,
                            level=level,
                            field_name='start_code',
                            code=yaml[level]['start_code']))

                # commands.k.demo_code
                for k, command in enumerate(yaml[level]['commands']):
                    # todo: at one point all commands should have names again!

                    command_text_short = command[
                        'name'] if 'name' in command.keys(
                        ) else command['explanation'][0:10]
                    Hedy_snippets.append(
                        Snippet(filename=file,
                                level=level,
                                field_name='command ' + command_text_short +
                                ' demo_code',
                                code=command['demo_code']))

                # code snippets inside intro_text
                code_snippet_counter = 0
                for tag in utils.markdown_to_html_tags(
                        yaml[level]['intro_text']):
                    if tag.name != 'pre' or not tag.contents[0]:
                        continue
                    code_snippet_counter += 1
                    Hedy_snippets.append(
                        Snippet(filename=file,
                                level=level,
                                field_name='intro_text snippet #' +
                                str(code_snippet_counter),
                                code=tag.contents[0].contents[0]))
    return Hedy_snippets
Example #5
0
    def test_load_yaml_equivalent(self):
        """Test that when we load a YAML file uncached and cached, it produces the same data.

    Also get a gauge for the speedup we get from loading a pickled file,
    although we're not going to fail the test on the numbers we get from that.
    """
        n = 50

        # Pick a file with unicode in it so we're sure it gets handled properly
        file = YamlFile(os.path.join(os.path.dirname(__file__), '..',
                                     'coursedata/adventures/hu.yaml'),
                        try_pickle=True)

        # Remove pickled version of this file if it exists, it may
        # influence the tests
        if os.path.isfile(file.pickle_filename):
            os.unlink(file.pickle_filename)

        start = time.time()
        for _ in range(n):
            original_data = file.load_uncached()
        original_seconds = time.time() - start

        # Generate the pickle file
        file.access()

        start = time.time()
        for _ in range(n):
            cached_data = file.load_pickle()
        cached_seconds = time.time() - start

        self.assertEqual(original_data, cached_data)
        print(
            f'YAML loading takes {original_seconds / n} seconds, unpickling takes {cached_seconds / n} ({original_seconds / cached_seconds:.1f}x faster)'
        )
Example #6
0
def collect_snippets(path):
    Hedy_snippets = []
    files = [
        f for f in os.listdir(path)
        if os.path.isfile(os.path.join(path, f)) and f.endswith('.yaml')
    ]
    for f in files:
        f = os.path.join(path, f)
        yaml = YamlFile.for_file(f)

        for name, adventure in yaml['adventures'].items():
            if name != 'next':
                for level_number in adventure['levels']:
                    if level_number > hedy.HEDY_MAX_LEVEL:
                        print('content above max level!')
                    else:
                        level = adventure['levels'][level_number]
                        adventure_name = adventure['name']

                        code_snippet_counter = 0
                        # code snippets inside story_text
                        for tag in utils.markdown_to_html_tags(
                                level['story_text']):
                            if tag.name != 'pre' or not tag.contents[0]:
                                continue
                            code_snippet_counter += 1
                            code = tag.contents[0].contents[0]

                            Hedy_snippets.append(
                                Snippet(
                                    f, level_number,
                                    'story_text code snippet #' +
                                    str(code_snippet_counter), code,
                                    adventure_name))

                        # start_code
                        try:
                            start_code = level['start_code']
                            Hedy_snippets.append(
                                Snippet(f, level_number, 'start_code',
                                        start_code, adventure_name))

                        except KeyError:
                            #TODO: create startcode not found error
                            pass

    return Hedy_snippets
Example #7
0
    def test_level_defaults_snippets(self):
        level_default_fails = []

        for file in files:
            file = os.path.join(path, file)
            yaml = YamlFile.for_file(file)

            for level in yaml:
                # start_code
                result = check_code(file, level, 'start_code',
                                    yaml[level]['start_code'])
                if result != True:
                    level_default_fails.append(result)
                # commands.k.demo_code
                for k, command in enumerate(yaml[level]['commands']):
                    command_text_short = command['explanation'][0:10]
                    result = check_code(
                        file, level,
                        'command ' + command_text_short + ' demo_code',
                        command['demo_code'])
                    if result != True:
                        level_default_fails.append(result)

                # code snippets inside intro_text
                code_snippet_counter = 0
                for tag in utils.markdown_to_html_tags(
                        yaml[level]['intro_text']):
                    if tag.name != 'pre' or not tag.contents[0]:
                        continue
                    code_snippet_counter += 1
                    result = check_code(
                        file, level,
                        'intro_text snippet #' + str(code_snippet_counter),
                        tag.contents[0].contents[0])
                    if result != True:
                        level_default_fails.append(result)

        self.assertEqual(0, len(level_default_fails))
Example #8
0
    def test_adventure_snippets(self):
        adventure_fails = []

        for f in files:
            f = os.path.join(path, f)
            yaml = YamlFile.for_file(f)

            for adventure in yaml['adventures'].values ():
                for level_number in adventure['levels']:
                    level = adventure['levels'][level_number]
                    adventure_name = adventure['name']

                    code_snippet_counter = 0
                    # code snippets inside story_text
                    for tag in utils.markdown_to_html_tags(level['story_text']):
                        if tag.name != 'pre' or not tag.contents[0]:
                            continue
                        code_snippet_counter += 1
                        code = tag.contents[0].contents[0]

                        result = check_code(f, level_number, 'story_text code snippet #' + str (code_snippet_counter), code, adventure_name)
                        if result != True:
                            adventure_fails.append(result)

                    # start_code
                    try:
                        start_code = level['start_code']
                        result = check_code(f, level_number, 'start_code', start_code, adventure_name)
                        if result != True:
                            adventure_fails.append(result)
                    except KeyError:
                        #create startcode not found error
                        message = f'Adventure {adventure_name} misses start_code at level {level_number}'
                        adventure_fails.append(message)
                        print(message)

        self.assertEqual(0, len(adventure_fails))
Example #9
0
def translate_fromto(source, target):
    # FIXME: right now loading source file on demand. We might need to cache this...
    source_adventures = YamlFile.for_file(
        f'coursedata/adventures/{source}.yaml')
    source_levels = YamlFile.for_file(
        f'coursedata/level-defaults/{source}.yaml')
    source_texts = YamlFile.for_file(f'coursedata/texts/{source}.yaml')

    target_adventures = YamlFile.for_file(
        f'coursedata/adventures/{target}.yaml')
    target_levels = YamlFile.for_file(
        f'coursedata/level-defaults/{target}.yaml')
    target_texts = YamlFile.for_file(f'coursedata/texts/{target}.yaml')

    files = []

    files.append(
        translating.TranslatableFile(
            'Levels', f'level-defaults/{target}.yaml',
            translating.struct_to_sections(source_levels, target_levels)))

    files.append(
        translating.TranslatableFile(
            'Messages', f'texts/{target}.yaml',
            translating.struct_to_sections(source_texts, target_texts)))

    files.append(
        translating.TranslatableFile(
            'Adventures', f'adventures/{target}.yaml',
            translating.struct_to_sections(source_adventures,
                                           target_adventures)))

    return render_template('translate-fromto.html',
                           source_lang=source,
                           target_lang=target,
                           files=files)
Example #10
0
def is_admin(request):
    user = current_user(request)
    return user['username'] == os.getenv(
        'ADMIN_USER') or user['email'] == os.getenv('ADMIN_USER')


def is_teacher(request):
    user = current_user(request)
    return bool('is_teacher' in user and user['is_teacher'])


# The translations are imported here because current_user above is used by hedyweb.py and we need to avoid circular dependencies
import hedyweb
TRANSLATIONS = hedyweb.Translations()
EMAILS = YamlFile.for_file('website/emails.yaml')


# Thanks to https://stackoverflow.com/a/34499643
def requires_login(f):
    @wraps(f)
    def inner(*args, **kws):
        user = None
        if request.cookies.get(cookie_name):
            token = DATABASE.get_token(request.cookies.get(cookie_name))
            if not token:
                return 'unauthorized', 403
            user = DATABASE.user_by_username(token['username'])
            if not user:
                return 'unauthorized', 403
        else:
Example #11
0
def load_adventures_in_all_languages():
    adventures = {}
    for lang in ALL_LANGUAGES.keys():
        adventures[lang] = YamlFile.for_file(
            f'coursedata/adventures/{lang}.yaml')
    return adventures
Example #12
0
def quiz_data_file_for(level):
    return YamlFile.for_file(f'coursedata/quiz/quiz_questions_lvl{level}.yaml')
Example #13
0
 def __init__(self, language):
   self.language = language
   self.levels = YamlFile.for_file(f'coursedata/level-defaults/{self.language}.yaml')
Example #14
0
 def __init__(self, language):
     self.language = language
     self.adventures_file = YamlFile.for_file(
         f'coursedata/adventures/{self.language}.yaml')
Example #15
0
 def __init__(self, page):
   self.data = {}
   translations = glob.glob('coursedata/pages/' + page + '/*.yaml')
   for file in translations:
     lang = path.splitext(path.basename(file))[0]
     self.data[lang] = YamlFile.for_file(file)