mathmaker.lib.tools package

Submodules

mathmaker.lib.tools.database module

class mathmaker.lib.tools.database.IntspansProduct(cartesianpower_spans, elt_nb=None)[source]

Bases: object

Handle intspan-like ranges, possibly concatenated by ×

random_draw(return_all=False, do_shuffle=True, **kwargs)[source]
turn_to_query_conditions(nb_list=None, nb_modifiers=None)[source]

Turn self to a SQLite query condition.

mathmaker.lib.tools.database.classify_tag(tag)[source]
mathmaker.lib.tools.database.db_table(tag)[source]

Table’s name possibly associated to tag.

mathmaker.lib.tools.database.generate_random_decimal_nb(position=None, width='random', generation_type=None, pos_matches_invisible_zero=False, unique_figures=True, grow_left=False, numberof=False, digits_positions=None, **unused)[source]
mathmaker.lib.tools.database.generate_values(source_id)[source]
class mathmaker.lib.tools.database.mc_source[source]

Bases: object

next(source_id, qkw=None, **kwargs)[source]
mathmaker.lib.tools.database.parse_sql_creation_query(qr)[source]

Retrieve table’s name and columns’ names from sql query.

mathmaker.lib.tools.database.postprocess_decimalfractionssums_query(qr, qkw=None, **kwargs)[source]

Create two decimal fractions from the drawn decimal number.

Parameters:qr (tuple) – the result of the query (containing the decimal number)
Return type:tuple
mathmaker.lib.tools.database.postprocess_int_triplesforprop_query(qr)[source]
mathmaker.lib.tools.database.postprocess_percentage_query(qr, source_id, qkw=None, **kwargs)[source]

Create the two numbers from the query result, depending on source_id.

Parameters:
  • qr (tuple) – the result of the query (containing the number(s))
  • source_id (str) – the original source id
  • qkw (dict) – the question’s keywords (attributes)
Return type:

tuple

mathmaker.lib.tools.database.preprocess_deci_int_triplesforprop_tag(tag, qkw=None)[source]
mathmaker.lib.tools.database.preprocess_decimalfractions_pairs_tag(qkw=None, **kwargs)[source]

Create the SQL query according to possible qkw’s overlap value.

Parameters:qkw (dict) – keywords provided by the question
Return type:dict
mathmaker.lib.tools.database.preprocess_decimals_query(qkw=None)[source]

Create the SQL query according to possible qkw.

mathmaker.lib.tools.database.preprocess_divisibles(intsp, reason='no reason')[source]

Called to help to choose special numbers divisible by intsp (e.g. 3 or 9).

Parameters:intsp – the possible divisor
mathmaker.lib.tools.database.preprocess_extdecimals_query(qkw=None)[source]

Create the SQL query according to possible qkw.

mathmaker.lib.tools.database.preprocess_int_pairs_tag(tag, qkw=None)[source]
mathmaker.lib.tools.database.preprocess_int_quintuples_tag(tag, qkw=None)[source]
mathmaker.lib.tools.database.preprocess_int_triplesforprop_tag(tag, not_in=None)[source]
mathmaker.lib.tools.database.preprocess_percentage_tag(tag, qkw=None)[source]

Deal with quarters, halves… numbers’ sources.

As the initial tag (source_id) may be modified, it is returned along the tag to use, in first position, so all return statements are of the form return tag, …

mathmaker.lib.tools.database.preprocess_polygons_sides_lengths_query(polygon_data=None, qkw=None)[source]

Query’s keywords depending on polygon’s type and expected kind of numbers.

mathmaker.lib.tools.database.preprocess_qkw(table_name, qkw=None)[source]

Add relevant questions keywords to build the query.

mathmaker.lib.tools.database.preprocess_single_nb_tag(tag)[source]

From single…_mintomax, get and return min and max in a dictionary.

mathmaker.lib.tools.database.preprocess_units_pairs_tag(tag, last_draw=None, qkw=None)[source]

Create the SQL query according to last_draw content and possible qkw.

class mathmaker.lib.tools.database.source(table_name, cols, **kwargs)[source]

Bases: object

next(**kwargs)[source]
class mathmaker.lib.tools.database.sub_source(source_id, **kwargs)[source]

Bases: object

next(qkw=None, **kwargs)[source]

mathmaker.lib.tools.distcode module

mathmaker.lib.tools.distcode.distcode(*numbers)[source]

Identifies a tuple of numbers depending on its composition.

mathmaker.lib.tools.distcode.expanddist(nndist)[source]

Perform the opposite of nndist().

Examples:
>>> expanddist([(1, 3), (2, 4)])
[3, 4, 4]
>>> expanddist([(1, 2), (2, 8), (3, 5)])
[2, 5, 5, 5, 8, 8]
mathmaker.lib.tools.distcode.matchdist(nndist, distcode)[source]

Tell whether the natural numbers’ distribution matches the distcode.

Take care, the order of numbers in the distribution is the contrary of the one in the distcode.

Examples:
>>> matchdist([(1, 3), (2, 4)], '2_1')
True
>>> matchdist([(1, 2), (2, 8), (3, 5)], '3_2_1')
True
>>> matchdist([(2, 2), (2, 6), (3, 4)], '3_3_2')
False
mathmaker.lib.tools.distcode.nndist(nn_tuple)[source]

Return a list of pairs (nb of times number shows up, number).

Examples:
>>> nndist((3, 4, 4))
[(1, 3), (2, 4)]
>>> nndist((2, 5, 5, 5, 8, 8))
[(1, 2), (2, 8), (3, 5)]

mathmaker.lib.tools.frameworks module

mathmaker.lib.tools.frameworks.build_exercises_list(data)[source]

Return the list of exercises from a sheet.

Parameters:data (dict) – the sheet’s data, as read from YAML file
Return type:list
mathmaker.lib.tools.frameworks.build_index()[source]

Create the index of all (YAML) sheets available.

mathmaker.lib.tools.frameworks.build_questions_list(data)[source]

Return the list of questions from an exercise.

Parameters:data (dict) – the exercise’s data, as read from YAML file (extract from the complete sheet’s data)
Return type:list
mathmaker.lib.tools.frameworks.get_attributes(filename, tag)[source]

Gathers the “attributes” of all filename’s keys matching tag.

Parameters:
  • filename (str) – The YAML file name.
  • tag (str) – The tag we’re looking for.
Return type:

list

mathmaker.lib.tools.frameworks.get_q_modifier(q_type, nb_source)[source]
mathmaker.lib.tools.frameworks.list_all_sheets()[source]

Creates the list of all available mathmaker’s sheets.

The list is displayed as a tabular.

Returns:The list as str
mathmaker.lib.tools.frameworks.load_sheet(theme, subtheme, sheet_name)[source]

Retrieve sheet data from yaml file.

Parameters:
  • theme (str) – the theme where to find the sheet
  • subtheme (str) – the subtheme where to find the sheet
  • sheet_name (str) – the name of the sheet
Return type:

OrderedDict

mathmaker.lib.tools.frameworks.parse_qid(qid)[source]

Return question’s kind and subkind from question’s attribute “id”.

mathmaker.lib.tools.frameworks.read_index()[source]

Read the index of all (YAML) sheets available.

mathmaker.lib.tools.frameworks.read_layout(data)[source]

Create the layout dictionary from the raw data.

Parameters:data (dict or list) – the dictionary loaded from YAML file (might be list of dict)
Return type:dict

mathmaker.lib.tools.ignition module

This module gathers functions that should be run at startup.

These functions check dependencies, settings consistency and setup the language for gettext translations.

mathmaker.lib.tools.ignition.check_dependencies(euktoeps='euktoeps', xmllint='xmllint', lualatex='lualatex', luaotfload_tool='luaotfload-tool') → bool[source]

Will check all mathmaker’s dependencies.

mathmaker.lib.tools.ignition.check_dependency(name: str, goal: str, path_to: str, required_version_nb: str) → bool[source]

Will check if a dependency is installed plus its version number.

The version number is supposed to be displayed at the end of the line containing ‘version’ when calling executable –version (or the equivalent).

Parameters:
  • name (str) – the dependency’s name.
  • goal (str) – tells shortly why mathmaker needs it for
  • path_to (str) – the path to the executable to test
  • required_version_nb (str) – well, the required version number
Return type:

bool

mathmaker.lib.tools.ignition.check_font() → bool[source]

Will check if settings.font belongs to data/fonts_list.txt.

It will first check if the exact name is in the list, then if one line of the list starts with the exact name.

mathmaker.lib.tools.ignition.check_settings_consistency(language=None, od=None)[source]

Will check the consistency of several settings values.

The checked values are: whether the language is supported as a LaTeX package that mathmaker uses, the output directory (is it an existing directory?) and whether the chosen font is usable by lualatex.

mathmaker.lib.tools.ignition.install_gettext_translations(**kwargs)[source]

Will install output’s language (gettext functions).

mathmaker.lib.tools.ignition.retrieve_fonts(fonts_list_file='mathmaker/data/fonts_list.txt', datadir='mathmaker/data', force=False) → tuple[source]

Store in a file the list of the fonts available for lualatex.

mathmaker.lib.tools.ignition.warning_msg(name: str, path_to: str, c_out: str, c_err: str, gkw: str, g_out: str, g_err: str)[source]

Return the formatted warning message.

Parameters:
  • name – name of the software
  • path_to – the path to the software
  • c_out – output of the call to software –version
  • c_err – error output of the call to software –version
  • gkw – keyword used to grep the version from output
  • g_out – output of the call to grep…
  • g_err – error output of the call to grep…

mathmaker.lib.tools.maths module

mathmaker.lib.tools.maths.barycenter(points_list, barycenter_name, weights=None)[source]
mathmaker.lib.tools.maths.coprime_generator(n)[source]
mathmaker.lib.tools.maths.coprimes_to(n, span)[source]

List numbers coprime to n inside provided span.

Parameters:
  • n (int) – integer number
  • span (list) – a list of integer numbers
Return type:

list

mathmaker.lib.tools.maths.gcd(a, b)[source]
mathmaker.lib.tools.maths.generate_decimal(width, places_scale, start_place)[source]
mathmaker.lib.tools.maths.is_even(objct)[source]
mathmaker.lib.tools.maths.is_uneven(objct)[source]
mathmaker.lib.tools.maths.lcm(a, b)[source]
mathmaker.lib.tools.maths.lcm_of_the_list(l)[source]
mathmaker.lib.tools.maths.mean(numberList, weights=None)[source]
mathmaker.lib.tools.maths.not_coprimes_to(n, span, exclude=None)[source]

List numbers NOT coprime to n inside provided span.

Parameters:
  • n (int) – integer number
  • span (list) – a list of integer numbers
  • exclude (list) – a list of number to always exclude from the results
Return type:

list

mathmaker.lib.tools.maths.prime_factors(n)[source]

Return all the prime factors of a positive integer

Taken from https://stackoverflow.com/a/412942/3926735.

mathmaker.lib.tools.maths.pupil_gcd(a, b)[source]
mathmaker.lib.tools.maths.sign_of_product(signed_objctlist)[source]
mathmaker.lib.tools.maths.ten_power_gcd(a, b)[source]

mathmaker.lib.tools.request_handler module

class mathmaker.lib.tools.request_handler.MathmakerHTTPRequestHandler(request, client_address, server)[source]

Bases: http.server.BaseHTTPRequestHandler

do_GET()[source]

mathmaker.lib.tools.wording module

Use these functions to process sentences or objects containing a wording.

mathmaker.lib.tools.wording.cut_off_hint_from(sentence: str) → tuple[source]

Return the sentence and the possible hint separated.

Only one hint will be taken into account.

Parameters:sentence (str) – the sentence to inspect
Return type:tuple
Examples:
>>> cut_off_hint_from("This sentence has no hint.")
('This sentence has no hint.', '')
>>> cut_off_hint_from("This sentence has a hint: |hint:length_unit|")
('This sentence has a hint:', 'length_unit')
>>> cut_off_hint_from("Malformed hint:|hint:length_unit|")
('Malformed hint:|hint:length_unit|', '')
>>> cut_off_hint_from("Malformed hint: |hint0:length_unit|")
('Malformed hint: |hint0:length_unit|', '')
>>> cut_off_hint_from("Two hints: |hint:unit| |hint:something_else|")
('Two hints: |hint:unit|', 'something_else')
mathmaker.lib.tools.wording.extract_formatting_tags_from(s: str)[source]

Return all tags found wrapped in {}. Punctuation has no effect.

Parameters:s – the sentence where to look for {tags}.
mathmaker.lib.tools.wording.handle_valueless_names_tags(arg: object, sentence: str)[source]

Each {name} tag found triggers an arg.name attribute to be randomly set.

All concerned tags are: {name}, {nameN}, {masculine_name}, {masculine_nameN}, {feminine_name}, {feminine_nameN}.

If the tag embbeds a value, like in {name=John}, then it’s ignored by this function. If arg already has an attribute matching the tag, then it’s also ignored by this function.

Now, say arg has no attributes like name, name1, etc. then, if sentence contains:

  • “{name}” then arg.name will receive a random name.
  • “{name1}”, then arg.name1 will receive a random name.
  • “{name=Michael}”, then this function ignores it.
  • “{feminine_name}”, then arg.feminine_name will get a random feminine name.
Parameters:
  • arg – the object that attributes must be checked and possibly set
  • sentence – the sentence where to look for “name” tags.
mathmaker.lib.tools.wording.handle_valueless_unit_tags(arg: object, sentence: str)[source]

Each {*_unit} tag triggers an arg.*_unit attribute to be randomly set.

For instance, if {length_unit} is found, then arg.length_unit will get a random length unit. Moreover, if {area_unit} or {volume_unit} are found, arg.length_unit is set accordingly too. If arg.length_unit does already exist, then arg.area_unit will be set accordingly (and not randomly any more).

{*_unitN}, <*_unit> and <*_unitN> tags will be handled the same way by this function.

If the tag embbeds a value, like in {capacity_unit=dL}, then it’s ignored by this function. If arg already has an attribute matching the tag, then it’s also ignored by this function.

Parameters:
  • arg (object) – the object that attributes must be checked and possibly set
  • sentence (str) – the sentence where to look for “unit” tags.
Return type:

None

mathmaker.lib.tools.wording.insert_nonbreaking_spaces(sentence: str)[source]

Replace spaces by nonbreaking ones between a number and the next word.

Parameters:sentence – the sentence to process
mathmaker.lib.tools.wording.is_unit(word: str) → bool[source]

Return True if word is a “unit” tag (e.g. ends with _unit}).

Punctuation has no effect.

Parameters:word – the word to inspect
mathmaker.lib.tools.wording.is_unitN(word)[source]

Return True if word is a “unitN” tag (e.g. ends with _unitN}).

Punctuation has no effect.

Parameters:word – the word to inspect
mathmaker.lib.tools.wording.is_wrapped(word: str, braces='{}', extra_braces='') → bool[source]

Return True if word is wrapped between braces.

Parameters:
  • word – the word to inspect
  • braces – to change the default {} braces to something else,

like [] or <> :param extra_braces: to add extra braces around the usual ones. Like in ({tag}) or [{tag}] :Examples:

>>> is_wrapped('{word}')
True
>>> is_wrapped('{word},')
False
>>> is_wrapped('<word>')
False
>>> is_wrapped('<word>', braces='<>')
True
>>> is_wrapped('({word})')
False
>>> is_wrapped('({word})', extra_braces='()')
True
>>> is_wrapped('[{word}]', extra_braces='()')
False
mathmaker.lib.tools.wording.is_wrapped_P(word: str, braces='{}', extra_braces='') → bool[source]

Return True if word is wrapped between braces & followed by a punctuation.

Parameters:
  • word – the word to inspect
  • braces – to change the default {} braces to something else,

like [] or <> :param extra_braces: to add extra braces around the usual ones. Like in ({tag}) or [{tag}]

Examples:
>>> is_wrapped_P('{word}')
False
>>> is_wrapped_P('{word},')
True
>>> is_wrapped_P('<word>')
False
>>> is_wrapped_P('<word>', braces='<>')
False
>>> is_wrapped_P('<word>:', braces='<>')
True
>>> is_wrapped_P('({word})', extra_braces='()')
False
>>> is_wrapped_P('({word}).', extra_braces='()')
True
>>> is_wrapped_P('[{word}]?', extra_braces='[]')
True
mathmaker.lib.tools.wording.is_wrapped_p(word: str, braces='{}', extra_braces='') → bool[source]

Return True if word is wrapped between braces. Punctuation has no effect.

Parameters:
  • word – the word to inspect
  • braces – to change the default {} braces to something else,

like [] or <> :param extra_braces: to add extra braces around the usual ones. Like in ({tag}) or [{tag}]

Examples:
>>> is_wrapped_p('{word}')
True
>>> is_wrapped_p('{word},')
True
>>> is_wrapped_p('<word>')
False
>>> is_wrapped_p('<word>', braces='<>')
True
>>> is_wrapped_p('<word>:', braces='<>')
True
>>> is_wrapped_p('({word}).')
False
>>> is_wrapped_p('({word}).', extra_braces='()')
True
>>> is_wrapped_p('[{word}]?', extra_braces='[]')
True
mathmaker.lib.tools.wording.merge_nb_unit_pairs(arg: object, w_prefix='')[source]

Merge all occurences of {nbN} {*_unit} in arg.wording into {nbN_*_unit}.

In the same time, the matching attribute arg.nbN_*_unit is set to Number(nbN, unit=Unit(arg.*_unit)) (the possible exponent is taken into account too).

Parameters:arg (object) – the object whose attribute wording will be processed. It must have a wording attribute as well as nbN and *_unit attributes.
Return type:None
Example:
>>> class Object(object): pass
...
>>> arg = Object()
>>> arg.wording = 'I have {nb1} {capacity_unit} of water.'
>>> arg.nb1 = 2
>>> arg.capacity_unit = 'L'
>>> merge_nb_unit_pairs(arg)
>>> arg.wording
'I have {nb1_capacity_unit} of water.'
>>> arg.nb1_capacity_unit
'\\SI{2}{L}'
mathmaker.lib.tools.wording.post_process(sentence: str)[source]

Apply all desired post processes to a sentence without {tags}.

So far, this is only the replacement of spaces following a number and preceding a word by nonbreaking spaces.

Parameters:sentence – the sentence to post process
mathmaker.lib.tools.wording.process_attr_values(sentence: str) → tuple[source]

Build a dict with all {key=val} occurrences in sentence. Update such tags.

All {key=val} occurrences will be replaced by {key}.

Parameters:sentence – the sentence to process
Returns:this couple: (transformed_sentence, {key:val, …})
mathmaker.lib.tools.wording.setup_wording_format_of(w_object: object, w_prefix='')[source]

Set w_object’s attributes according to the tags found in w_object.wording.

This is the complete process of the wording. w_object.wording will also be modified in the process.

For instance, if w_object.wording is: “Here are one {name}, {nb1} {length_unit1} of roads, and a cube of {nb2} {volume_unit=cm}. What is the side’s length of the cube? |hint:length_unit|”

Then w_object.wording becomes: “Here are one {name}, {nb1_length_unit1} of roads, and a cube of {nb2_volume_unit}. What is the side’s length of the cube?”

w_object.name will be set with a random name,

w_object.nb1_length_unit1 will be set with: ‘\SI{<value of nb1>}{<random length unit>}’

w_object.length_unit will be set to centimeters

w_object.nb2_volume_unit will be set with: ‘\SI{<value of nb2>}{cm^{3}}’

w_object.hint will be set with: ‘\si{cm}’

If w_prefix is set, the “wording” processed attributes will be w_object.<prefix>wording and w_object.<prefix>wording_format. This allows to process several different wordings.

Parameters:
  • w_object – The object having a ‘wording’ attribute to process.
  • w_prefix – The possible prefix of the “wording” attributes to

process.

mathmaker.lib.tools.wording.wrap(word: str, braces='{}', o_str=None, e_str=None) → str[source]

Return the word wrapped between the two given strings.

Using o_str and e_str (e.g. opening str and ending str) will override braces content. It’s interesting when one want to wrap the word with something longer than a char.

Parameters:
  • word (str) – the chunk of text to be wrapped
  • braces (str) – the pair of braces that will wrap the word
  • o_str (str) – prefix the word.
  • e_str (str) – suffix the word
Return type:

str

Examples:
>>> wrap('wonderful')
'{wonderful}'
>>> wrap('wonderful', braces='<>')
'<wonderful>'
>>> wrap('wonderful', o_str='<<', e_str='>>')
'<<wonderful>>'
>>> wrap('wonderful', e_str='}*')
'{wonderful}*'
mathmaker.lib.tools.wording.wrap_latex_keywords(s: str) → str[source]

Replace some {kw} by {{kw}}, to prevent format() from using them as keys.

mathmaker.lib.tools.xml module

mathmaker.lib.tools.xml.check_q_consistency(q_attrib, sources)[source]

(Unfinished) Check the consistency of question’s kind, subkind and source.

mathmaker.lib.tools.xml.get_exercises_list(file_name)[source]

Retrieves the exercises’ list from file_name.

Parameters:file_name (str) – The XML file name.
Return type:list
mathmaker.lib.tools.xml.get_sheet_config(file_name)[source]

Retrieves the sheet configuration values from file_name.

Parameters:file_name (str) – The XML file name.
Return type:tuple
mathmaker.lib.tools.xml.get_xml_schema_path()[source]
mathmaker.lib.tools.xml.get_xml_sheets_paths()[source]

Returns all paths to default xml frameworks.

They are returned as a dictionary like: {id: path_to_matching_file.xml, …} the id being the filename without its extension.

Return type:dict

Module contents

Various auxiliary functions.

mathmaker.lib.tools.check_unique_letters_words(words_list, n)[source]

Check if each word of the list contains exactly n letters, all unique.

class mathmaker.lib.tools.ext_dict[source]

Bases: dict

A dict with more methods.

flat(sep='.')[source]

Return a recursively flattened dict.

If the dictionary contains nested dictionaries, this function will return a one-level (“flat”) dictionary.

Example:
>>> d = ext_dict({'a': {'a1': 3, 'a2': {'z': 5}}, 'b': 'data'})
>>> d.flat() == {'a.a1': 3, 'a.a2.z': 5, 'b': 'data'}
True
recursive_update(d2)[source]

Update self with d2 key/values, recursively update nested dicts.

Example:
>>> d = ext_dict({'a': 1, 'b': {'a': 7, 'c': 10}})
>>> d.recursive_update({'a': 24, 'd': 13, 'b': {'c': 100}})
>>> print(d == {'a': 24, 'd': 13, 'b': {'a': 7, 'c': 100}})
True
mathmaker.lib.tools.fix_math_style2_fontsize(text)[source]

Turn all frac to dfrac.

Return type:str
mathmaker.lib.tools.generate_preamble_comment(document_format, comment_symbol='% ')[source]

Return the preamble comment for output text files.

mathmaker.lib.tools.load_config(file_tag, settingsdir)[source]

Will load the values from the yaml config file, named file_tag.yaml.

The default configuration values are loaded from mathmaker/settings/default/.yaml, then load_config will update with values found successively in /etc/mathmaker/.yaml, then in ~/.config/mathmaker/.yaml, finally in mathmaker/settings/dev/.yaml.

mathmaker.lib.tools.parse_layout_descriptor(d, sep=None, special_row_chars=None, min_row=0, min_col=0)[source]

Parse a “layout” string, e.g. ‘3×4’. Return number of rows, number of cols.

Parameters:
  • d (str) – the “layout” string
  • sep (None or str or a list of str) – the separator’s list. Default to ‘×’
  • special_row_chars (None or list) – a list of special characters allowed instead of natural numbers. Defaults to []
  • min_row (positive int) – a minimal value that the number of rows must respect. It is not checked is nrow is a special char
  • min_col (positive int) – a minimal value that the number of columns must respect
Return type:

tuple

mathmaker.lib.tools.po_file_get_list_of(what, language, arg)[source]
mathmaker.lib.tools.rotate(l, n)[source]

Rotate list l of n places, to the right if n > 0; else to the left.