id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
sequence
docstring
stringlengths
3
17.3k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
87
242
248,800
UCL-INGI/INGInious
inginious/frontend/session_mongodb.py
MongoStore.cleanup
def cleanup(self, timeout): ''' Removes all sessions older than ``timeout`` seconds. Called automatically on every session access. ''' cutoff = time() - timeout self.collection.remove({_atime: {'$lt': cutoff}})
python
def cleanup(self, timeout): ''' Removes all sessions older than ``timeout`` seconds. Called automatically on every session access. ''' cutoff = time() - timeout self.collection.remove({_atime: {'$lt': cutoff}})
[ "def", "cleanup", "(", "self", ",", "timeout", ")", ":", "cutoff", "=", "time", "(", ")", "-", "timeout", "self", ".", "collection", ".", "remove", "(", "{", "_atime", ":", "{", "'$lt'", ":", "cutoff", "}", "}", ")" ]
Removes all sessions older than ``timeout`` seconds. Called automatically on every session access.
[ "Removes", "all", "sessions", "older", "than", "timeout", "seconds", ".", "Called", "automatically", "on", "every", "session", "access", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/session_mongodb.py#L114-L120
248,801
UCL-INGI/INGInious
inginious/frontend/plugin_manager.py
PluginManager.load
def load(self, client, webpy_app, course_factory, task_factory, database, user_manager, submission_manager, config): """ Loads the plugin manager. Must be done after the initialisation of the client """ self._app = webpy_app self._task_factory = task_factory self._database = database self._user_manager = user_manager self._submission_manager = submission_manager self._loaded = True for entry in config: module = importlib.import_module(entry["plugin_module"]) module.init(self, course_factory, client, entry)
python
def load(self, client, webpy_app, course_factory, task_factory, database, user_manager, submission_manager, config): self._app = webpy_app self._task_factory = task_factory self._database = database self._user_manager = user_manager self._submission_manager = submission_manager self._loaded = True for entry in config: module = importlib.import_module(entry["plugin_module"]) module.init(self, course_factory, client, entry)
[ "def", "load", "(", "self", ",", "client", ",", "webpy_app", ",", "course_factory", ",", "task_factory", ",", "database", ",", "user_manager", ",", "submission_manager", ",", "config", ")", ":", "self", ".", "_app", "=", "webpy_app", "self", ".", "_task_factory", "=", "task_factory", "self", ".", "_database", "=", "database", "self", ".", "_user_manager", "=", "user_manager", "self", ".", "_submission_manager", "=", "submission_manager", "self", ".", "_loaded", "=", "True", "for", "entry", "in", "config", ":", "module", "=", "importlib", ".", "import_module", "(", "entry", "[", "\"plugin_module\"", "]", ")", "module", ".", "init", "(", "self", ",", "course_factory", ",", "client", ",", "entry", ")" ]
Loads the plugin manager. Must be done after the initialisation of the client
[ "Loads", "the", "plugin", "manager", ".", "Must", "be", "done", "after", "the", "initialisation", "of", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugin_manager.py#L28-L38
248,802
UCL-INGI/INGInious
inginious/frontend/plugin_manager.py
PluginManager.add_page
def add_page(self, pattern, classname): """ Add a new page to the web application. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._app.add_mapping(pattern, classname)
python
def add_page(self, pattern, classname): if not self._loaded: raise PluginManagerNotLoadedException() self._app.add_mapping(pattern, classname)
[ "def", "add_page", "(", "self", ",", "pattern", ",", "classname", ")", ":", "if", "not", "self", ".", "_loaded", ":", "raise", "PluginManagerNotLoadedException", "(", ")", "self", ".", "_app", ".", "add_mapping", "(", "pattern", ",", "classname", ")" ]
Add a new page to the web application. Only available after that the Plugin Manager is loaded
[ "Add", "a", "new", "page", "to", "the", "web", "application", ".", "Only", "available", "after", "that", "the", "Plugin", "Manager", "is", "loaded" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugin_manager.py#L40-L44
248,803
UCL-INGI/INGInious
inginious/frontend/plugin_manager.py
PluginManager.add_task_file_manager
def add_task_file_manager(self, task_file_manager): """ Add a task file manager. Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._task_factory.add_custom_task_file_manager(task_file_manager)
python
def add_task_file_manager(self, task_file_manager): if not self._loaded: raise PluginManagerNotLoadedException() self._task_factory.add_custom_task_file_manager(task_file_manager)
[ "def", "add_task_file_manager", "(", "self", ",", "task_file_manager", ")", ":", "if", "not", "self", ".", "_loaded", ":", "raise", "PluginManagerNotLoadedException", "(", ")", "self", ".", "_task_factory", ".", "add_custom_task_file_manager", "(", "task_file_manager", ")" ]
Add a task file manager. Only available after that the Plugin Manager is loaded
[ "Add", "a", "task", "file", "manager", ".", "Only", "available", "after", "that", "the", "Plugin", "Manager", "is", "loaded" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugin_manager.py#L46-L50
248,804
UCL-INGI/INGInious
inginious/frontend/plugin_manager.py
PluginManager.register_auth_method
def register_auth_method(self, auth_method): """ Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded """ if not self._loaded: raise PluginManagerNotLoadedException() self._user_manager.register_auth_method(auth_method)
python
def register_auth_method(self, auth_method): if not self._loaded: raise PluginManagerNotLoadedException() self._user_manager.register_auth_method(auth_method)
[ "def", "register_auth_method", "(", "self", ",", "auth_method", ")", ":", "if", "not", "self", ".", "_loaded", ":", "raise", "PluginManagerNotLoadedException", "(", ")", "self", ".", "_user_manager", ".", "register_auth_method", "(", "auth_method", ")" ]
Register a new authentication method name the name of the authentication method, typically displayed by the webapp input_to_display Only available after that the Plugin Manager is loaded
[ "Register", "a", "new", "authentication", "method" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugin_manager.py#L52-L65
248,805
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/danger_zone.py
CourseDangerZonePage.dump_course
def dump_course(self, courseid): """ Create a zip file containing all information about a given course in database and then remove it from db""" filepath = os.path.join(self.backup_dir, courseid, datetime.datetime.now().strftime("%Y%m%d.%H%M%S") + ".zip") if not os.path.exists(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath)) with zipfile.ZipFile(filepath, "w", allowZip64=True) as zipf: aggregations = self.database.aggregations.find({"courseid": courseid}) zipf.writestr("aggregations.json", bson.json_util.dumps(aggregations), zipfile.ZIP_DEFLATED) user_tasks = self.database.user_tasks.find({"courseid": courseid}) zipf.writestr("user_tasks.json", bson.json_util.dumps(user_tasks), zipfile.ZIP_DEFLATED) submissions = self.database.submissions.find({"courseid": courseid}) zipf.writestr("submissions.json", bson.json_util.dumps(submissions), zipfile.ZIP_DEFLATED) submissions.rewind() for submission in submissions: for key in ["input", "archive"]: if key in submission and type(submission[key]) == bson.objectid.ObjectId: infile = self.submission_manager.get_gridfs().get(submission[key]) zipf.writestr(key + "/" + str(submission[key]) + ".data", infile.read(), zipfile.ZIP_DEFLATED) self._logger.info("Course %s dumped to backup directory.", courseid) self.wipe_course(courseid)
python
def dump_course(self, courseid): filepath = os.path.join(self.backup_dir, courseid, datetime.datetime.now().strftime("%Y%m%d.%H%M%S") + ".zip") if not os.path.exists(os.path.dirname(filepath)): os.makedirs(os.path.dirname(filepath)) with zipfile.ZipFile(filepath, "w", allowZip64=True) as zipf: aggregations = self.database.aggregations.find({"courseid": courseid}) zipf.writestr("aggregations.json", bson.json_util.dumps(aggregations), zipfile.ZIP_DEFLATED) user_tasks = self.database.user_tasks.find({"courseid": courseid}) zipf.writestr("user_tasks.json", bson.json_util.dumps(user_tasks), zipfile.ZIP_DEFLATED) submissions = self.database.submissions.find({"courseid": courseid}) zipf.writestr("submissions.json", bson.json_util.dumps(submissions), zipfile.ZIP_DEFLATED) submissions.rewind() for submission in submissions: for key in ["input", "archive"]: if key in submission and type(submission[key]) == bson.objectid.ObjectId: infile = self.submission_manager.get_gridfs().get(submission[key]) zipf.writestr(key + "/" + str(submission[key]) + ".data", infile.read(), zipfile.ZIP_DEFLATED) self._logger.info("Course %s dumped to backup directory.", courseid) self.wipe_course(courseid)
[ "def", "dump_course", "(", "self", ",", "courseid", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "backup_dir", ",", "courseid", ",", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "\"%Y%m%d.%H%M%S\"", ")", "+", "\".zip\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "filepath", ")", ")", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "filepath", ")", ")", "with", "zipfile", ".", "ZipFile", "(", "filepath", ",", "\"w\"", ",", "allowZip64", "=", "True", ")", "as", "zipf", ":", "aggregations", "=", "self", ".", "database", ".", "aggregations", ".", "find", "(", "{", "\"courseid\"", ":", "courseid", "}", ")", "zipf", ".", "writestr", "(", "\"aggregations.json\"", ",", "bson", ".", "json_util", ".", "dumps", "(", "aggregations", ")", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "user_tasks", "=", "self", ".", "database", ".", "user_tasks", ".", "find", "(", "{", "\"courseid\"", ":", "courseid", "}", ")", "zipf", ".", "writestr", "(", "\"user_tasks.json\"", ",", "bson", ".", "json_util", ".", "dumps", "(", "user_tasks", ")", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "submissions", "=", "self", ".", "database", ".", "submissions", ".", "find", "(", "{", "\"courseid\"", ":", "courseid", "}", ")", "zipf", ".", "writestr", "(", "\"submissions.json\"", ",", "bson", ".", "json_util", ".", "dumps", "(", "submissions", ")", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "submissions", ".", "rewind", "(", ")", "for", "submission", "in", "submissions", ":", "for", "key", "in", "[", "\"input\"", ",", "\"archive\"", "]", ":", "if", "key", "in", "submission", "and", "type", "(", "submission", "[", "key", "]", ")", "==", "bson", ".", "objectid", ".", "ObjectId", ":", "infile", "=", "self", ".", "submission_manager", ".", "get_gridfs", "(", ")", ".", "get", "(", "submission", "[", "key", "]", ")", "zipf", ".", "writestr", "(", "key", "+", "\"/\"", "+", "str", "(", "submission", "[", "key", "]", ")", "+", "\".data\"", ",", "infile", ".", "read", "(", ")", ",", "zipfile", ".", "ZIP_DEFLATED", ")", "self", ".", "_logger", ".", "info", "(", "\"Course %s dumped to backup directory.\"", ",", "courseid", ")", "self", ".", "wipe_course", "(", "courseid", ")" ]
Create a zip file containing all information about a given course in database and then remove it from db
[ "Create", "a", "zip", "file", "containing", "all", "information", "about", "a", "given", "course", "in", "database", "and", "then", "remove", "it", "from", "db" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/danger_zone.py#L39-L65
248,806
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/danger_zone.py
CourseDangerZonePage.delete_course
def delete_course(self, courseid): """ Erase all course data """ # Wipes the course (delete database) self.wipe_course(courseid) # Deletes the course from the factory (entire folder) self.course_factory.delete_course(courseid) # Removes backup filepath = os.path.join(self.backup_dir, courseid) if os.path.exists(os.path.dirname(filepath)): for backup in glob.glob(os.path.join(filepath, '*.zip')): os.remove(backup) self._logger.info("Course %s files erased.", courseid)
python
def delete_course(self, courseid): # Wipes the course (delete database) self.wipe_course(courseid) # Deletes the course from the factory (entire folder) self.course_factory.delete_course(courseid) # Removes backup filepath = os.path.join(self.backup_dir, courseid) if os.path.exists(os.path.dirname(filepath)): for backup in glob.glob(os.path.join(filepath, '*.zip')): os.remove(backup) self._logger.info("Course %s files erased.", courseid)
[ "def", "delete_course", "(", "self", ",", "courseid", ")", ":", "# Wipes the course (delete database)", "self", ".", "wipe_course", "(", "courseid", ")", "# Deletes the course from the factory (entire folder)", "self", ".", "course_factory", ".", "delete_course", "(", "courseid", ")", "# Removes backup", "filepath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "backup_dir", ",", "courseid", ")", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "dirname", "(", "filepath", ")", ")", ":", "for", "backup", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "filepath", ",", "'*.zip'", ")", ")", ":", "os", ".", "remove", "(", "backup", ")", "self", ".", "_logger", ".", "info", "(", "\"Course %s files erased.\"", ",", "courseid", ")" ]
Erase all course data
[ "Erase", "all", "course", "data" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/danger_zone.py#L93-L107
248,807
UCL-INGI/INGInious
inginious/frontend/task_problems.py
DisplayableCodeProblem.show_input
def show_input(self, template_helper, language, seed): """ Show BasicCodeProblem and derivatives """ header = ParsableText(self.gettext(language,self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableCodeProblem.get_renderer(template_helper).tasks.code(self.get_id(), header, 8, 0, self._language, self._optional, self._default))
python
def show_input(self, template_helper, language, seed): header = ParsableText(self.gettext(language,self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableCodeProblem.get_renderer(template_helper).tasks.code(self.get_id(), header, 8, 0, self._language, self._optional, self._default))
[ "def", "show_input", "(", "self", ",", "template_helper", ",", "language", ",", "seed", ")", ":", "header", "=", "ParsableText", "(", "self", ".", "gettext", "(", "language", ",", "self", ".", "_header", ")", ",", "\"rst\"", ",", "translation", "=", "self", ".", "_translations", ".", "get", "(", "language", ",", "gettext", ".", "NullTranslations", "(", ")", ")", ")", "return", "str", "(", "DisplayableCodeProblem", ".", "get_renderer", "(", "template_helper", ")", ".", "tasks", ".", "code", "(", "self", ".", "get_id", "(", ")", ",", "header", ",", "8", ",", "0", ",", "self", ".", "_language", ",", "self", ".", "_optional", ",", "self", ".", "_default", ")", ")" ]
Show BasicCodeProblem and derivatives
[ "Show", "BasicCodeProblem", "and", "derivatives" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/task_problems.py#L66-L70
248,808
UCL-INGI/INGInious
inginious/frontend/task_problems.py
DisplayableMultipleChoiceProblem.show_input
def show_input(self, template_helper, language, seed): """ Show multiple choice problems """ choices = [] limit = self._limit if limit == 0: limit = len(self._choices) # no limit rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed)) # Ensure that the choices are random # we *do* need to copy the choices here random_order_choices = list(self._choices) rand.shuffle(random_order_choices) if self._multiple: # take only the valid choices in the first pass for entry in random_order_choices: if entry['valid']: choices.append(entry) limit = limit - 1 # take everything else in a second pass for entry in random_order_choices: if limit == 0: break if not entry['valid']: choices.append(entry) limit = limit - 1 else: # need to have ONE valid entry for entry in random_order_choices: if not entry['valid'] and limit > 1: choices.append(entry) limit = limit - 1 for entry in random_order_choices: if entry['valid'] and limit > 0: choices.append(entry) limit = limit - 1 rand.shuffle(choices) header = ParsableText(self.gettext(language, self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableMultipleChoiceProblem.get_renderer(template_helper).tasks.multiple_choice( self.get_id(), header, self._multiple, choices, lambda text: ParsableText(self.gettext(language, text) if text else "", "rst", translation=self._translations.get(language, gettext.NullTranslations()))))
python
def show_input(self, template_helper, language, seed): choices = [] limit = self._limit if limit == 0: limit = len(self._choices) # no limit rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed)) # Ensure that the choices are random # we *do* need to copy the choices here random_order_choices = list(self._choices) rand.shuffle(random_order_choices) if self._multiple: # take only the valid choices in the first pass for entry in random_order_choices: if entry['valid']: choices.append(entry) limit = limit - 1 # take everything else in a second pass for entry in random_order_choices: if limit == 0: break if not entry['valid']: choices.append(entry) limit = limit - 1 else: # need to have ONE valid entry for entry in random_order_choices: if not entry['valid'] and limit > 1: choices.append(entry) limit = limit - 1 for entry in random_order_choices: if entry['valid'] and limit > 0: choices.append(entry) limit = limit - 1 rand.shuffle(choices) header = ParsableText(self.gettext(language, self._header), "rst", translation=self._translations.get(language, gettext.NullTranslations())) return str(DisplayableMultipleChoiceProblem.get_renderer(template_helper).tasks.multiple_choice( self.get_id(), header, self._multiple, choices, lambda text: ParsableText(self.gettext(language, text) if text else "", "rst", translation=self._translations.get(language, gettext.NullTranslations()))))
[ "def", "show_input", "(", "self", ",", "template_helper", ",", "language", ",", "seed", ")", ":", "choices", "=", "[", "]", "limit", "=", "self", ".", "_limit", "if", "limit", "==", "0", ":", "limit", "=", "len", "(", "self", ".", "_choices", ")", "# no limit", "rand", "=", "Random", "(", "\"{}#{}#{}\"", ".", "format", "(", "self", ".", "get_task", "(", ")", ".", "get_id", "(", ")", ",", "self", ".", "get_id", "(", ")", ",", "seed", ")", ")", "# Ensure that the choices are random", "# we *do* need to copy the choices here", "random_order_choices", "=", "list", "(", "self", ".", "_choices", ")", "rand", ".", "shuffle", "(", "random_order_choices", ")", "if", "self", ".", "_multiple", ":", "# take only the valid choices in the first pass", "for", "entry", "in", "random_order_choices", ":", "if", "entry", "[", "'valid'", "]", ":", "choices", ".", "append", "(", "entry", ")", "limit", "=", "limit", "-", "1", "# take everything else in a second pass", "for", "entry", "in", "random_order_choices", ":", "if", "limit", "==", "0", ":", "break", "if", "not", "entry", "[", "'valid'", "]", ":", "choices", ".", "append", "(", "entry", ")", "limit", "=", "limit", "-", "1", "else", ":", "# need to have ONE valid entry", "for", "entry", "in", "random_order_choices", ":", "if", "not", "entry", "[", "'valid'", "]", "and", "limit", ">", "1", ":", "choices", ".", "append", "(", "entry", ")", "limit", "=", "limit", "-", "1", "for", "entry", "in", "random_order_choices", ":", "if", "entry", "[", "'valid'", "]", "and", "limit", ">", "0", ":", "choices", ".", "append", "(", "entry", ")", "limit", "=", "limit", "-", "1", "rand", ".", "shuffle", "(", "choices", ")", "header", "=", "ParsableText", "(", "self", ".", "gettext", "(", "language", ",", "self", ".", "_header", ")", ",", "\"rst\"", ",", "translation", "=", "self", ".", "_translations", ".", "get", "(", "language", ",", "gettext", ".", "NullTranslations", "(", ")", ")", ")", "return", "str", "(", "DisplayableMultipleChoiceProblem", ".", "get_renderer", "(", "template_helper", ")", ".", "tasks", ".", "multiple_choice", "(", "self", ".", "get_id", "(", ")", ",", "header", ",", "self", ".", "_multiple", ",", "choices", ",", "lambda", "text", ":", "ParsableText", "(", "self", ".", "gettext", "(", "language", ",", "text", ")", "if", "text", "else", "\"\"", ",", "\"rst\"", ",", "translation", "=", "self", ".", "_translations", ".", "get", "(", "language", ",", "gettext", ".", "NullTranslations", "(", ")", ")", ")", ")", ")" ]
Show multiple choice problems
[ "Show", "multiple", "choice", "problems" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/task_problems.py#L153-L199
248,809
UCL-INGI/INGInious
inginious/frontend/pages/lti.py
LTILaunchPage._parse_lti_data
def _parse_lti_data(self, courseid, taskid): """ Verify and parse the data for the LTI basic launch """ post_input = web.webapi.rawinput("POST") self.logger.debug('_parse_lti_data:' + str(post_input)) try: course = self.course_factory.get_course(courseid) except exceptions.CourseNotFoundException as ex: raise web.notfound(str(ex)) try: test = LTIWebPyToolProvider.from_webpy_request() validator = LTIValidator(self.database.nonce, course.lti_keys()) verified = test.is_valid_request(validator) except Exception: self.logger.exception("...") self.logger.info("Error while validating LTI request for %s", str(post_input)) raise web.forbidden(_("Error while validating LTI request")) if verified: self.logger.debug('parse_lit_data for %s', str(post_input)) user_id = post_input["user_id"] roles = post_input.get("roles", "Student").split(",") realname = self._find_realname(post_input) email = post_input.get("lis_person_contact_email_primary", "") lis_outcome_service_url = post_input.get("lis_outcome_service_url", None) outcome_result_id = post_input.get("lis_result_sourcedid", None) consumer_key = post_input["oauth_consumer_key"] if course.lti_send_back_grade(): if lis_outcome_service_url is None or outcome_result_id is None: self.logger.info('Error: lis_outcome_service_url is None but lti_send_back_grade is True') raise web.forbidden(_("In order to send grade back to the TC, INGInious needs the parameters lis_outcome_service_url and " "lis_outcome_result_id in the LTI basic-launch-request. Please contact your administrator.")) else: lis_outcome_service_url = None outcome_result_id = None tool_name = post_input.get('tool_consumer_instance_name', 'N/A') tool_desc = post_input.get('tool_consumer_instance_description', 'N/A') tool_url = post_input.get('tool_consumer_instance_url', 'N/A') context_title = post_input.get('context_title', 'N/A') context_label = post_input.get('context_label', 'N/A') session_id = self.user_manager.create_lti_session(user_id, roles, realname, email, courseid, taskid, consumer_key, lis_outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label) loggedin = self.user_manager.attempt_lti_login() return session_id, loggedin else: self.logger.info("Couldn't validate LTI request") raise web.forbidden(_("Couldn't validate LTI request"))
python
def _parse_lti_data(self, courseid, taskid): post_input = web.webapi.rawinput("POST") self.logger.debug('_parse_lti_data:' + str(post_input)) try: course = self.course_factory.get_course(courseid) except exceptions.CourseNotFoundException as ex: raise web.notfound(str(ex)) try: test = LTIWebPyToolProvider.from_webpy_request() validator = LTIValidator(self.database.nonce, course.lti_keys()) verified = test.is_valid_request(validator) except Exception: self.logger.exception("...") self.logger.info("Error while validating LTI request for %s", str(post_input)) raise web.forbidden(_("Error while validating LTI request")) if verified: self.logger.debug('parse_lit_data for %s', str(post_input)) user_id = post_input["user_id"] roles = post_input.get("roles", "Student").split(",") realname = self._find_realname(post_input) email = post_input.get("lis_person_contact_email_primary", "") lis_outcome_service_url = post_input.get("lis_outcome_service_url", None) outcome_result_id = post_input.get("lis_result_sourcedid", None) consumer_key = post_input["oauth_consumer_key"] if course.lti_send_back_grade(): if lis_outcome_service_url is None or outcome_result_id is None: self.logger.info('Error: lis_outcome_service_url is None but lti_send_back_grade is True') raise web.forbidden(_("In order to send grade back to the TC, INGInious needs the parameters lis_outcome_service_url and " "lis_outcome_result_id in the LTI basic-launch-request. Please contact your administrator.")) else: lis_outcome_service_url = None outcome_result_id = None tool_name = post_input.get('tool_consumer_instance_name', 'N/A') tool_desc = post_input.get('tool_consumer_instance_description', 'N/A') tool_url = post_input.get('tool_consumer_instance_url', 'N/A') context_title = post_input.get('context_title', 'N/A') context_label = post_input.get('context_label', 'N/A') session_id = self.user_manager.create_lti_session(user_id, roles, realname, email, courseid, taskid, consumer_key, lis_outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label) loggedin = self.user_manager.attempt_lti_login() return session_id, loggedin else: self.logger.info("Couldn't validate LTI request") raise web.forbidden(_("Couldn't validate LTI request"))
[ "def", "_parse_lti_data", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "post_input", "=", "web", ".", "webapi", ".", "rawinput", "(", "\"POST\"", ")", "self", ".", "logger", ".", "debug", "(", "'_parse_lti_data:'", "+", "str", "(", "post_input", ")", ")", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", "except", "exceptions", ".", "CourseNotFoundException", "as", "ex", ":", "raise", "web", ".", "notfound", "(", "str", "(", "ex", ")", ")", "try", ":", "test", "=", "LTIWebPyToolProvider", ".", "from_webpy_request", "(", ")", "validator", "=", "LTIValidator", "(", "self", ".", "database", ".", "nonce", ",", "course", ".", "lti_keys", "(", ")", ")", "verified", "=", "test", ".", "is_valid_request", "(", "validator", ")", "except", "Exception", ":", "self", ".", "logger", ".", "exception", "(", "\"...\"", ")", "self", ".", "logger", ".", "info", "(", "\"Error while validating LTI request for %s\"", ",", "str", "(", "post_input", ")", ")", "raise", "web", ".", "forbidden", "(", "_", "(", "\"Error while validating LTI request\"", ")", ")", "if", "verified", ":", "self", ".", "logger", ".", "debug", "(", "'parse_lit_data for %s'", ",", "str", "(", "post_input", ")", ")", "user_id", "=", "post_input", "[", "\"user_id\"", "]", "roles", "=", "post_input", ".", "get", "(", "\"roles\"", ",", "\"Student\"", ")", ".", "split", "(", "\",\"", ")", "realname", "=", "self", ".", "_find_realname", "(", "post_input", ")", "email", "=", "post_input", ".", "get", "(", "\"lis_person_contact_email_primary\"", ",", "\"\"", ")", "lis_outcome_service_url", "=", "post_input", ".", "get", "(", "\"lis_outcome_service_url\"", ",", "None", ")", "outcome_result_id", "=", "post_input", ".", "get", "(", "\"lis_result_sourcedid\"", ",", "None", ")", "consumer_key", "=", "post_input", "[", "\"oauth_consumer_key\"", "]", "if", "course", ".", "lti_send_back_grade", "(", ")", ":", "if", "lis_outcome_service_url", "is", "None", "or", "outcome_result_id", "is", "None", ":", "self", ".", "logger", ".", "info", "(", "'Error: lis_outcome_service_url is None but lti_send_back_grade is True'", ")", "raise", "web", ".", "forbidden", "(", "_", "(", "\"In order to send grade back to the TC, INGInious needs the parameters lis_outcome_service_url and \"", "\"lis_outcome_result_id in the LTI basic-launch-request. Please contact your administrator.\"", ")", ")", "else", ":", "lis_outcome_service_url", "=", "None", "outcome_result_id", "=", "None", "tool_name", "=", "post_input", ".", "get", "(", "'tool_consumer_instance_name'", ",", "'N/A'", ")", "tool_desc", "=", "post_input", ".", "get", "(", "'tool_consumer_instance_description'", ",", "'N/A'", ")", "tool_url", "=", "post_input", ".", "get", "(", "'tool_consumer_instance_url'", ",", "'N/A'", ")", "context_title", "=", "post_input", ".", "get", "(", "'context_title'", ",", "'N/A'", ")", "context_label", "=", "post_input", ".", "get", "(", "'context_label'", ",", "'N/A'", ")", "session_id", "=", "self", ".", "user_manager", ".", "create_lti_session", "(", "user_id", ",", "roles", ",", "realname", ",", "email", ",", "courseid", ",", "taskid", ",", "consumer_key", ",", "lis_outcome_service_url", ",", "outcome_result_id", ",", "tool_name", ",", "tool_desc", ",", "tool_url", ",", "context_title", ",", "context_label", ")", "loggedin", "=", "self", ".", "user_manager", ".", "attempt_lti_login", "(", ")", "return", "session_id", ",", "loggedin", "else", ":", "self", ".", "logger", ".", "info", "(", "\"Couldn't validate LTI request\"", ")", "raise", "web", ".", "forbidden", "(", "_", "(", "\"Couldn't validate LTI request\"", ")", ")" ]
Verify and parse the data for the LTI basic launch
[ "Verify", "and", "parse", "the", "data", "for", "the", "LTI", "basic", "launch" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/lti.py#L145-L197
248,810
UCL-INGI/INGInious
inginious/frontend/pages/lti.py
LTILaunchPage._find_realname
def _find_realname(self, post_input): """ Returns the most appropriate name to identify the user """ # First, try the full name if "lis_person_name_full" in post_input: return post_input["lis_person_name_full"] if "lis_person_name_given" in post_input and "lis_person_name_family" in post_input: return post_input["lis_person_name_given"] + post_input["lis_person_name_family"] # Then the email if "lis_person_contact_email_primary" in post_input: return post_input["lis_person_contact_email_primary"] # Then only part of the full name if "lis_person_name_family" in post_input: return post_input["lis_person_name_family"] if "lis_person_name_given" in post_input: return post_input["lis_person_name_given"] return post_input["user_id"]
python
def _find_realname(self, post_input): # First, try the full name if "lis_person_name_full" in post_input: return post_input["lis_person_name_full"] if "lis_person_name_given" in post_input and "lis_person_name_family" in post_input: return post_input["lis_person_name_given"] + post_input["lis_person_name_family"] # Then the email if "lis_person_contact_email_primary" in post_input: return post_input["lis_person_contact_email_primary"] # Then only part of the full name if "lis_person_name_family" in post_input: return post_input["lis_person_name_family"] if "lis_person_name_given" in post_input: return post_input["lis_person_name_given"] return post_input["user_id"]
[ "def", "_find_realname", "(", "self", ",", "post_input", ")", ":", "# First, try the full name", "if", "\"lis_person_name_full\"", "in", "post_input", ":", "return", "post_input", "[", "\"lis_person_name_full\"", "]", "if", "\"lis_person_name_given\"", "in", "post_input", "and", "\"lis_person_name_family\"", "in", "post_input", ":", "return", "post_input", "[", "\"lis_person_name_given\"", "]", "+", "post_input", "[", "\"lis_person_name_family\"", "]", "# Then the email", "if", "\"lis_person_contact_email_primary\"", "in", "post_input", ":", "return", "post_input", "[", "\"lis_person_contact_email_primary\"", "]", "# Then only part of the full name", "if", "\"lis_person_name_family\"", "in", "post_input", ":", "return", "post_input", "[", "\"lis_person_name_family\"", "]", "if", "\"lis_person_name_given\"", "in", "post_input", ":", "return", "post_input", "[", "\"lis_person_name_given\"", "]", "return", "post_input", "[", "\"user_id\"", "]" ]
Returns the most appropriate name to identify the user
[ "Returns", "the", "most", "appropriate", "name", "to", "identify", "the", "user" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/lti.py#L199-L218
248,811
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/statistics.py
fast_stats
def fast_stats(data): """ Compute base statistics about submissions """ total_submission = len(data) total_submission_best = 0 total_submission_best_succeeded = 0 for submission in data: if "best" in submission and submission["best"]: total_submission_best = total_submission_best + 1 if "result" in submission and submission["result"] == "success": total_submission_best_succeeded += 1 statistics = [ (_("Number of submissions"), total_submission), (_("Evaluation submissions (Total)"), total_submission_best), (_("Evaluation submissions (Succeeded)"), total_submission_best_succeeded), (_("Evaluation submissions (Failed)"), total_submission_best - total_submission_best_succeeded), # add here new common statistics ] return statistics
python
def fast_stats(data): total_submission = len(data) total_submission_best = 0 total_submission_best_succeeded = 0 for submission in data: if "best" in submission and submission["best"]: total_submission_best = total_submission_best + 1 if "result" in submission and submission["result"] == "success": total_submission_best_succeeded += 1 statistics = [ (_("Number of submissions"), total_submission), (_("Evaluation submissions (Total)"), total_submission_best), (_("Evaluation submissions (Succeeded)"), total_submission_best_succeeded), (_("Evaluation submissions (Failed)"), total_submission_best - total_submission_best_succeeded), # add here new common statistics ] return statistics
[ "def", "fast_stats", "(", "data", ")", ":", "total_submission", "=", "len", "(", "data", ")", "total_submission_best", "=", "0", "total_submission_best_succeeded", "=", "0", "for", "submission", "in", "data", ":", "if", "\"best\"", "in", "submission", "and", "submission", "[", "\"best\"", "]", ":", "total_submission_best", "=", "total_submission_best", "+", "1", "if", "\"result\"", "in", "submission", "and", "submission", "[", "\"result\"", "]", "==", "\"success\"", ":", "total_submission_best_succeeded", "+=", "1", "statistics", "=", "[", "(", "_", "(", "\"Number of submissions\"", ")", ",", "total_submission", ")", ",", "(", "_", "(", "\"Evaluation submissions (Total)\"", ")", ",", "total_submission_best", ")", ",", "(", "_", "(", "\"Evaluation submissions (Succeeded)\"", ")", ",", "total_submission_best_succeeded", ")", ",", "(", "_", "(", "\"Evaluation submissions (Failed)\"", ")", ",", "total_submission_best", "-", "total_submission_best_succeeded", ")", ",", "# add here new common statistics", "]", "return", "statistics" ]
Compute base statistics about submissions
[ "Compute", "base", "statistics", "about", "submissions" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/statistics.py#L172-L193
248,812
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
BetterParanoidPirateClient._register_transaction
def _register_transaction(self, send_msg, recv_msg, coroutine_recv, coroutine_abrt, get_key=None, inter_msg=None): """ Register a type of message to be sent. After this message has been sent, if the answer is received, callback_recv is called. If the remote server becomes dones, calls callback_abrt. :param send_msg: class of message to be sent :param recv_msg: message that the server should send in response :param get_key: receive a `send_msg` or `recv_msg` as input, and returns the "key" (global identifier) of the message :param coroutine_recv: callback called (on the event loop) when the transaction succeed, with, as input, `recv_msg` and eventually other args given to .send :param coroutine_abrt: callback called (on the event loop) when the transaction fails, with, as input, `recv_msg` and eventually other args given to .send :param inter_msg: a list of `(message_class, coroutine_recv)`, that can be received during the resolution of the transaction but will not finalize it. `get_key` is used on these `message_class` to get the key of the transaction. """ if get_key is None: get_key = lambda x: None if inter_msg is None: inter_msg = [] # format is (other_msg, get_key, recv_handler, abrt_handler,responsible_for) # where responsible_for is the list of classes whose transaction will be killed when this message is received. self._msgs_registered[send_msg.__msgtype__] = ([recv_msg.__msgtype__] + [x.__msgtype__ for x, _ in inter_msg], get_key, None, None, []) self._msgs_registered[recv_msg.__msgtype__] = ( [], get_key, coroutine_recv, coroutine_abrt, [recv_msg.__msgtype__] + [x.__msgtype__ for x, _ in inter_msg]) self._transactions[recv_msg.__msgtype__] = {} for msg_class, handler in inter_msg: self._msgs_registered[msg_class.__msgtype__] = ([], get_key, handler, None, []) self._transactions[msg_class.__msgtype__] = {}
python
def _register_transaction(self, send_msg, recv_msg, coroutine_recv, coroutine_abrt, get_key=None, inter_msg=None): if get_key is None: get_key = lambda x: None if inter_msg is None: inter_msg = [] # format is (other_msg, get_key, recv_handler, abrt_handler,responsible_for) # where responsible_for is the list of classes whose transaction will be killed when this message is received. self._msgs_registered[send_msg.__msgtype__] = ([recv_msg.__msgtype__] + [x.__msgtype__ for x, _ in inter_msg], get_key, None, None, []) self._msgs_registered[recv_msg.__msgtype__] = ( [], get_key, coroutine_recv, coroutine_abrt, [recv_msg.__msgtype__] + [x.__msgtype__ for x, _ in inter_msg]) self._transactions[recv_msg.__msgtype__] = {} for msg_class, handler in inter_msg: self._msgs_registered[msg_class.__msgtype__] = ([], get_key, handler, None, []) self._transactions[msg_class.__msgtype__] = {}
[ "def", "_register_transaction", "(", "self", ",", "send_msg", ",", "recv_msg", ",", "coroutine_recv", ",", "coroutine_abrt", ",", "get_key", "=", "None", ",", "inter_msg", "=", "None", ")", ":", "if", "get_key", "is", "None", ":", "get_key", "=", "lambda", "x", ":", "None", "if", "inter_msg", "is", "None", ":", "inter_msg", "=", "[", "]", "# format is (other_msg, get_key, recv_handler, abrt_handler,responsible_for)", "# where responsible_for is the list of classes whose transaction will be killed when this message is received.", "self", ".", "_msgs_registered", "[", "send_msg", ".", "__msgtype__", "]", "=", "(", "[", "recv_msg", ".", "__msgtype__", "]", "+", "[", "x", ".", "__msgtype__", "for", "x", ",", "_", "in", "inter_msg", "]", ",", "get_key", ",", "None", ",", "None", ",", "[", "]", ")", "self", ".", "_msgs_registered", "[", "recv_msg", ".", "__msgtype__", "]", "=", "(", "[", "]", ",", "get_key", ",", "coroutine_recv", ",", "coroutine_abrt", ",", "[", "recv_msg", ".", "__msgtype__", "]", "+", "[", "x", ".", "__msgtype__", "for", "x", ",", "_", "in", "inter_msg", "]", ")", "self", ".", "_transactions", "[", "recv_msg", ".", "__msgtype__", "]", "=", "{", "}", "for", "msg_class", ",", "handler", "in", "inter_msg", ":", "self", ".", "_msgs_registered", "[", "msg_class", ".", "__msgtype__", "]", "=", "(", "[", "]", ",", "get_key", ",", "handler", ",", "None", ",", "[", "]", ")", "self", ".", "_transactions", "[", "msg_class", ".", "__msgtype__", "]", "=", "{", "}" ]
Register a type of message to be sent. After this message has been sent, if the answer is received, callback_recv is called. If the remote server becomes dones, calls callback_abrt. :param send_msg: class of message to be sent :param recv_msg: message that the server should send in response :param get_key: receive a `send_msg` or `recv_msg` as input, and returns the "key" (global identifier) of the message :param coroutine_recv: callback called (on the event loop) when the transaction succeed, with, as input, `recv_msg` and eventually other args given to .send :param coroutine_abrt: callback called (on the event loop) when the transaction fails, with, as input, `recv_msg` and eventually other args given to .send :param inter_msg: a list of `(message_class, coroutine_recv)`, that can be received during the resolution of the transaction but will not finalize it. `get_key` is used on these `message_class` to get the key of the transaction.
[ "Register", "a", "type", "of", "message", "to", "be", "sent", ".", "After", "this", "message", "has", "been", "sent", "if", "the", "answer", "is", "received", "callback_recv", "is", "called", ".", "If", "the", "remote", "server", "becomes", "dones", "calls", "callback_abrt", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L49-L79
248,813
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
BetterParanoidPirateClient._reconnect
async def _reconnect(self): """ Called when the remote server is innacessible and the connection has to be restarted """ # 1. Close all transactions for msg_class in self._transactions: _1, _2, _3, coroutine_abrt, _4 = self._msgs_registered[msg_class] if coroutine_abrt is not None: for key in self._transactions[msg_class]: for args, kwargs in self._transactions[msg_class][key]: self._loop.create_task(coroutine_abrt(key, *args, **kwargs)) self._transactions[msg_class] = {} # 2. Call on_disconnect await self._on_disconnect() # 3. Stop tasks for task in self._restartable_tasks: task.cancel() self._restartable_tasks = [] # 4. Restart socket self._socket.disconnect(self._router_addr) # 5. Re-do start sequence await self.client_start()
python
async def _reconnect(self): # 1. Close all transactions for msg_class in self._transactions: _1, _2, _3, coroutine_abrt, _4 = self._msgs_registered[msg_class] if coroutine_abrt is not None: for key in self._transactions[msg_class]: for args, kwargs in self._transactions[msg_class][key]: self._loop.create_task(coroutine_abrt(key, *args, **kwargs)) self._transactions[msg_class] = {} # 2. Call on_disconnect await self._on_disconnect() # 3. Stop tasks for task in self._restartable_tasks: task.cancel() self._restartable_tasks = [] # 4. Restart socket self._socket.disconnect(self._router_addr) # 5. Re-do start sequence await self.client_start()
[ "async", "def", "_reconnect", "(", "self", ")", ":", "# 1. Close all transactions", "for", "msg_class", "in", "self", ".", "_transactions", ":", "_1", ",", "_2", ",", "_3", ",", "coroutine_abrt", ",", "_4", "=", "self", ".", "_msgs_registered", "[", "msg_class", "]", "if", "coroutine_abrt", "is", "not", "None", ":", "for", "key", "in", "self", ".", "_transactions", "[", "msg_class", "]", ":", "for", "args", ",", "kwargs", "in", "self", ".", "_transactions", "[", "msg_class", "]", "[", "key", "]", ":", "self", ".", "_loop", ".", "create_task", "(", "coroutine_abrt", "(", "key", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_transactions", "[", "msg_class", "]", "=", "{", "}", "# 2. Call on_disconnect", "await", "self", ".", "_on_disconnect", "(", ")", "# 3. Stop tasks", "for", "task", "in", "self", ".", "_restartable_tasks", ":", "task", ".", "cancel", "(", ")", "self", ".", "_restartable_tasks", "=", "[", "]", "# 4. Restart socket", "self", ".", "_socket", ".", "disconnect", "(", "self", ".", "_router_addr", ")", "# 5. Re-do start sequence", "await", "self", ".", "client_start", "(", ")" ]
Called when the remote server is innacessible and the connection has to be restarted
[ "Called", "when", "the", "remote", "server", "is", "innacessible", "and", "the", "connection", "has", "to", "be", "restarted" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L152-L178
248,814
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
BetterParanoidPirateClient.client_start
async def client_start(self): """ Starts the client """ await self._start_socket() await self._on_connect() self._ping_count = 0 # Start the loops, and don't forget to add them to the list of asyncio task to close when the client restarts task_socket = self._loop.create_task(self._run_socket()) task_ping = self._loop.create_task(self._do_ping()) self._restartable_tasks.append(task_ping) self._restartable_tasks.append(task_socket)
python
async def client_start(self): await self._start_socket() await self._on_connect() self._ping_count = 0 # Start the loops, and don't forget to add them to the list of asyncio task to close when the client restarts task_socket = self._loop.create_task(self._run_socket()) task_ping = self._loop.create_task(self._do_ping()) self._restartable_tasks.append(task_ping) self._restartable_tasks.append(task_socket)
[ "async", "def", "client_start", "(", "self", ")", ":", "await", "self", ".", "_start_socket", "(", ")", "await", "self", ".", "_on_connect", "(", ")", "self", ".", "_ping_count", "=", "0", "# Start the loops, and don't forget to add them to the list of asyncio task to close when the client restarts", "task_socket", "=", "self", ".", "_loop", ".", "create_task", "(", "self", ".", "_run_socket", "(", ")", ")", "task_ping", "=", "self", ".", "_loop", ".", "create_task", "(", "self", ".", "_do_ping", "(", ")", ")", "self", ".", "_restartable_tasks", ".", "append", "(", "task_ping", ")", "self", ".", "_restartable_tasks", ".", "append", "(", "task_socket", ")" ]
Starts the client
[ "Starts", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L180-L194
248,815
UCL-INGI/INGInious
inginious/client/_zeromq_client.py
BetterParanoidPirateClient._run_socket
async def _run_socket(self): """ Task that runs this client. """ try: while True: message = await ZMQUtils.recv(self._socket) msg_class = message.__msgtype__ if msg_class in self._handlers_registered: # If a handler is registered, give the message to it self._loop.create_task(self._handlers_registered[msg_class](message)) elif msg_class in self._transactions: # If there are transaction associated, check if the key is ok _1, get_key, coroutine_recv, _2, responsible = self._msgs_registered[msg_class] key = get_key(message) if key in self._transactions[msg_class]: # key exists; call all the coroutines for args, kwargs in self._transactions[msg_class][key]: self._loop.create_task(coroutine_recv(message, *args, **kwargs)) # remove all transaction parts for key2 in responsible: del self._transactions[key2][key] else: # key does not exist raise Exception("Received message %s for an unknown transaction %s", msg_class, key) else: raise Exception("Received unknown message %s", msg_class) except asyncio.CancelledError: return except KeyboardInterrupt: return
python
async def _run_socket(self): try: while True: message = await ZMQUtils.recv(self._socket) msg_class = message.__msgtype__ if msg_class in self._handlers_registered: # If a handler is registered, give the message to it self._loop.create_task(self._handlers_registered[msg_class](message)) elif msg_class in self._transactions: # If there are transaction associated, check if the key is ok _1, get_key, coroutine_recv, _2, responsible = self._msgs_registered[msg_class] key = get_key(message) if key in self._transactions[msg_class]: # key exists; call all the coroutines for args, kwargs in self._transactions[msg_class][key]: self._loop.create_task(coroutine_recv(message, *args, **kwargs)) # remove all transaction parts for key2 in responsible: del self._transactions[key2][key] else: # key does not exist raise Exception("Received message %s for an unknown transaction %s", msg_class, key) else: raise Exception("Received unknown message %s", msg_class) except asyncio.CancelledError: return except KeyboardInterrupt: return
[ "async", "def", "_run_socket", "(", "self", ")", ":", "try", ":", "while", "True", ":", "message", "=", "await", "ZMQUtils", ".", "recv", "(", "self", ".", "_socket", ")", "msg_class", "=", "message", ".", "__msgtype__", "if", "msg_class", "in", "self", ".", "_handlers_registered", ":", "# If a handler is registered, give the message to it", "self", ".", "_loop", ".", "create_task", "(", "self", ".", "_handlers_registered", "[", "msg_class", "]", "(", "message", ")", ")", "elif", "msg_class", "in", "self", ".", "_transactions", ":", "# If there are transaction associated, check if the key is ok", "_1", ",", "get_key", ",", "coroutine_recv", ",", "_2", ",", "responsible", "=", "self", ".", "_msgs_registered", "[", "msg_class", "]", "key", "=", "get_key", "(", "message", ")", "if", "key", "in", "self", ".", "_transactions", "[", "msg_class", "]", ":", "# key exists; call all the coroutines", "for", "args", ",", "kwargs", "in", "self", ".", "_transactions", "[", "msg_class", "]", "[", "key", "]", ":", "self", ".", "_loop", ".", "create_task", "(", "coroutine_recv", "(", "message", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", "# remove all transaction parts", "for", "key2", "in", "responsible", ":", "del", "self", ".", "_transactions", "[", "key2", "]", "[", "key", "]", "else", ":", "# key does not exist", "raise", "Exception", "(", "\"Received message %s for an unknown transaction %s\"", ",", "msg_class", ",", "key", ")", "else", ":", "raise", "Exception", "(", "\"Received unknown message %s\"", ",", "msg_class", ")", "except", "asyncio", ".", "CancelledError", ":", "return", "except", "KeyboardInterrupt", ":", "return" ]
Task that runs this client.
[ "Task", "that", "runs", "this", "client", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/_zeromq_client.py#L202-L232
248,816
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
load_feedback
def load_feedback(): """ Open existing feedback file """ result = {} if os.path.exists(_feedback_file): f = open(_feedback_file, 'r') cont = f.read() f.close() else: cont = '{}' try: result = json.loads(cont) if cont else {} except ValueError as e: result = {"result":"crash", "text":"Feedback file has been modified by user !"} return result
python
def load_feedback(): result = {} if os.path.exists(_feedback_file): f = open(_feedback_file, 'r') cont = f.read() f.close() else: cont = '{}' try: result = json.loads(cont) if cont else {} except ValueError as e: result = {"result":"crash", "text":"Feedback file has been modified by user !"} return result
[ "def", "load_feedback", "(", ")", ":", "result", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "_feedback_file", ")", ":", "f", "=", "open", "(", "_feedback_file", ",", "'r'", ")", "cont", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "else", ":", "cont", "=", "'{}'", "try", ":", "result", "=", "json", ".", "loads", "(", "cont", ")", "if", "cont", "else", "{", "}", "except", "ValueError", "as", "e", ":", "result", "=", "{", "\"result\"", ":", "\"crash\"", ",", "\"text\"", ":", "\"Feedback file has been modified by user !\"", "}", "return", "result" ]
Open existing feedback file
[ "Open", "existing", "feedback", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L18-L32
248,817
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
save_feedback
def save_feedback(rdict): """ Save feedback file """ # Check for output folder if not os.path.exists(_feedback_dir): os.makedirs(_feedback_dir) jcont = json.dumps(rdict) f = open(_feedback_file, 'w') f.write(jcont) f.close()
python
def save_feedback(rdict): # Check for output folder if not os.path.exists(_feedback_dir): os.makedirs(_feedback_dir) jcont = json.dumps(rdict) f = open(_feedback_file, 'w') f.write(jcont) f.close()
[ "def", "save_feedback", "(", "rdict", ")", ":", "# Check for output folder", "if", "not", "os", ".", "path", ".", "exists", "(", "_feedback_dir", ")", ":", "os", ".", "makedirs", "(", "_feedback_dir", ")", "jcont", "=", "json", ".", "dumps", "(", "rdict", ")", "f", "=", "open", "(", "_feedback_file", ",", "'w'", ")", "f", ".", "write", "(", "jcont", ")", "f", ".", "close", "(", ")" ]
Save feedback file
[ "Save", "feedback", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L35-L44
248,818
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
set_problem_result
def set_problem_result(result, problem_id): """ Set problem specific result value """ rdict = load_feedback() if not 'problems' in rdict: rdict['problems'] = {} cur_val = rdict['problems'].get(problem_id, '') rdict['problems'][problem_id] = [result, cur_val] if type(cur_val) == str else [result, cur_val[1]] save_feedback(rdict)
python
def set_problem_result(result, problem_id): rdict = load_feedback() if not 'problems' in rdict: rdict['problems'] = {} cur_val = rdict['problems'].get(problem_id, '') rdict['problems'][problem_id] = [result, cur_val] if type(cur_val) == str else [result, cur_val[1]] save_feedback(rdict)
[ "def", "set_problem_result", "(", "result", ",", "problem_id", ")", ":", "rdict", "=", "load_feedback", "(", ")", "if", "not", "'problems'", "in", "rdict", ":", "rdict", "[", "'problems'", "]", "=", "{", "}", "cur_val", "=", "rdict", "[", "'problems'", "]", ".", "get", "(", "problem_id", ",", "''", ")", "rdict", "[", "'problems'", "]", "[", "problem_id", "]", "=", "[", "result", ",", "cur_val", "]", "if", "type", "(", "cur_val", ")", "==", "str", "else", "[", "result", ",", "cur_val", "[", "1", "]", "]", "save_feedback", "(", "rdict", ")" ]
Set problem specific result value
[ "Set", "problem", "specific", "result", "value" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L55-L62
248,819
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
set_global_feedback
def set_global_feedback(feedback, append=False): """ Set global feedback in case of error """ rdict = load_feedback() rdict['text'] = rdict.get('text', '') + feedback if append else feedback save_feedback(rdict)
python
def set_global_feedback(feedback, append=False): rdict = load_feedback() rdict['text'] = rdict.get('text', '') + feedback if append else feedback save_feedback(rdict)
[ "def", "set_global_feedback", "(", "feedback", ",", "append", "=", "False", ")", ":", "rdict", "=", "load_feedback", "(", ")", "rdict", "[", "'text'", "]", "=", "rdict", ".", "get", "(", "'text'", ",", "''", ")", "+", "feedback", "if", "append", "else", "feedback", "save_feedback", "(", "rdict", ")" ]
Set global feedback in case of error
[ "Set", "global", "feedback", "in", "case", "of", "error" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L72-L76
248,820
UCL-INGI/INGInious
base-containers/base/inginious/feedback.py
set_problem_feedback
def set_problem_feedback(feedback, problem_id, append=False): """ Set problem specific feedback """ rdict = load_feedback() if not 'problems' in rdict: rdict['problems'] = {} cur_val = rdict['problems'].get(problem_id, '') rdict['problems'][problem_id] = (cur_val + feedback if append else feedback) if type(cur_val) == str else [cur_val[0], (cur_val[1] + feedback if append else feedback)] save_feedback(rdict)
python
def set_problem_feedback(feedback, problem_id, append=False): rdict = load_feedback() if not 'problems' in rdict: rdict['problems'] = {} cur_val = rdict['problems'].get(problem_id, '') rdict['problems'][problem_id] = (cur_val + feedback if append else feedback) if type(cur_val) == str else [cur_val[0], (cur_val[1] + feedback if append else feedback)] save_feedback(rdict)
[ "def", "set_problem_feedback", "(", "feedback", ",", "problem_id", ",", "append", "=", "False", ")", ":", "rdict", "=", "load_feedback", "(", ")", "if", "not", "'problems'", "in", "rdict", ":", "rdict", "[", "'problems'", "]", "=", "{", "}", "cur_val", "=", "rdict", "[", "'problems'", "]", ".", "get", "(", "problem_id", ",", "''", ")", "rdict", "[", "'problems'", "]", "[", "problem_id", "]", "=", "(", "cur_val", "+", "feedback", "if", "append", "else", "feedback", ")", "if", "type", "(", "cur_val", ")", "==", "str", "else", "[", "cur_val", "[", "0", "]", ",", "(", "cur_val", "[", "1", "]", "+", "feedback", "if", "append", "else", "feedback", ")", "]", "save_feedback", "(", "rdict", ")" ]
Set problem specific feedback
[ "Set", "problem", "specific", "feedback" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/feedback.py#L79-L86
248,821
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer._display_big_warning
def _display_big_warning(self, content): """ Displays a BIG warning """ print("") print(BOLD + WARNING + "--- WARNING ---" + ENDC) print(WARNING + content + ENDC) print("")
python
def _display_big_warning(self, content): print("") print(BOLD + WARNING + "--- WARNING ---" + ENDC) print(WARNING + content + ENDC) print("")
[ "def", "_display_big_warning", "(", "self", ",", "content", ")", ":", "print", "(", "\"\"", ")", "print", "(", "BOLD", "+", "WARNING", "+", "\"--- WARNING ---\"", "+", "ENDC", ")", "print", "(", "WARNING", "+", "content", "+", "ENDC", ")", "print", "(", "\"\"", ")" ]
Displays a BIG warning
[ "Displays", "a", "BIG", "warning" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L64-L69
248,822
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer._ask_local_config
def _ask_local_config(self): """ Ask some parameters about the local configuration """ options = {"backend": "local", "local-config": {}} # Concurrency while True: concurrency = self._ask_with_default( "Maximum concurrency (number of tasks running simultaneously). Leave it empty to use the number of " "CPU of your host.", "") if concurrency == "": break try: concurrency = int(concurrency) except: self._display_error("Invalid number") continue if concurrency <= 0: self._display_error("Invalid number") continue options["local-config"]["concurrency"] = concurrency break # Debug hostname hostname = self._ask_with_default( "What is the external hostname/address of your machine? You can leave this empty and let INGInious " "autodetect it.", "") if hostname != "": options["local-config"]["debug_host"] = hostname self._display_info( "You can now enter the port range for the remote debugging feature of INGInious. Please verify that these " "ports are open in your firewall. You can leave this parameters empty, the default is 64100-64200") # Debug port range port_range = None while True: start_port = self._ask_with_default("Beginning of the range", "") if start_port != "": try: start_port = int(start_port) except: self._display_error("Invalid number") continue end_port = self._ask_with_default("End of the range", str(start_port + 100)) try: end_port = int(end_port) except: self._display_error("Invalid number") continue if start_port > end_port: self._display_error("Invalid range") continue port_range = str(start_port) + "-" + str(end_port) else: break if port_range != None: options["local-config"]["debug_ports"] = port_range return options
python
def _ask_local_config(self): options = {"backend": "local", "local-config": {}} # Concurrency while True: concurrency = self._ask_with_default( "Maximum concurrency (number of tasks running simultaneously). Leave it empty to use the number of " "CPU of your host.", "") if concurrency == "": break try: concurrency = int(concurrency) except: self._display_error("Invalid number") continue if concurrency <= 0: self._display_error("Invalid number") continue options["local-config"]["concurrency"] = concurrency break # Debug hostname hostname = self._ask_with_default( "What is the external hostname/address of your machine? You can leave this empty and let INGInious " "autodetect it.", "") if hostname != "": options["local-config"]["debug_host"] = hostname self._display_info( "You can now enter the port range for the remote debugging feature of INGInious. Please verify that these " "ports are open in your firewall. You can leave this parameters empty, the default is 64100-64200") # Debug port range port_range = None while True: start_port = self._ask_with_default("Beginning of the range", "") if start_port != "": try: start_port = int(start_port) except: self._display_error("Invalid number") continue end_port = self._ask_with_default("End of the range", str(start_port + 100)) try: end_port = int(end_port) except: self._display_error("Invalid number") continue if start_port > end_port: self._display_error("Invalid range") continue port_range = str(start_port) + "-" + str(end_port) else: break if port_range != None: options["local-config"]["debug_ports"] = port_range return options
[ "def", "_ask_local_config", "(", "self", ")", ":", "options", "=", "{", "\"backend\"", ":", "\"local\"", ",", "\"local-config\"", ":", "{", "}", "}", "# Concurrency", "while", "True", ":", "concurrency", "=", "self", ".", "_ask_with_default", "(", "\"Maximum concurrency (number of tasks running simultaneously). Leave it empty to use the number of \"", "\"CPU of your host.\"", ",", "\"\"", ")", "if", "concurrency", "==", "\"\"", ":", "break", "try", ":", "concurrency", "=", "int", "(", "concurrency", ")", "except", ":", "self", ".", "_display_error", "(", "\"Invalid number\"", ")", "continue", "if", "concurrency", "<=", "0", ":", "self", ".", "_display_error", "(", "\"Invalid number\"", ")", "continue", "options", "[", "\"local-config\"", "]", "[", "\"concurrency\"", "]", "=", "concurrency", "break", "# Debug hostname", "hostname", "=", "self", ".", "_ask_with_default", "(", "\"What is the external hostname/address of your machine? You can leave this empty and let INGInious \"", "\"autodetect it.\"", ",", "\"\"", ")", "if", "hostname", "!=", "\"\"", ":", "options", "[", "\"local-config\"", "]", "[", "\"debug_host\"", "]", "=", "hostname", "self", ".", "_display_info", "(", "\"You can now enter the port range for the remote debugging feature of INGInious. Please verify that these \"", "\"ports are open in your firewall. You can leave this parameters empty, the default is 64100-64200\"", ")", "# Debug port range", "port_range", "=", "None", "while", "True", ":", "start_port", "=", "self", ".", "_ask_with_default", "(", "\"Beginning of the range\"", ",", "\"\"", ")", "if", "start_port", "!=", "\"\"", ":", "try", ":", "start_port", "=", "int", "(", "start_port", ")", "except", ":", "self", ".", "_display_error", "(", "\"Invalid number\"", ")", "continue", "end_port", "=", "self", ".", "_ask_with_default", "(", "\"End of the range\"", ",", "str", "(", "start_port", "+", "100", ")", ")", "try", ":", "end_port", "=", "int", "(", "end_port", ")", "except", ":", "self", ".", "_display_error", "(", "\"Invalid number\"", ")", "continue", "if", "start_port", ">", "end_port", ":", "self", ".", "_display_error", "(", "\"Invalid range\"", ")", "continue", "port_range", "=", "str", "(", "start_port", ")", "+", "\"-\"", "+", "str", "(", "end_port", ")", "else", ":", "break", "if", "port_range", "!=", "None", ":", "options", "[", "\"local-config\"", "]", "[", "\"debug_ports\"", "]", "=", "port_range", "return", "options" ]
Ask some parameters about the local configuration
[ "Ask", "some", "parameters", "about", "the", "local", "configuration" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L170-L230
248,823
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.ask_backend
def ask_backend(self): """ Ask the user to choose the backend """ response = self._ask_boolean( "Do you have a local docker daemon (on Linux), do you use docker-machine via a local machine, or do you use " "Docker for macOS?", True) if (response): self._display_info("If you use docker-machine on macOS, please see " "http://inginious.readthedocs.io/en/latest/install_doc/troubleshooting.html") return "local" else: self._display_info( "You will have to run inginious-backend and inginious-agent yourself. Please run the commands without argument " "and/or read the documentation for more info") return self._display_question("Please enter the address of your backend")
python
def ask_backend(self): response = self._ask_boolean( "Do you have a local docker daemon (on Linux), do you use docker-machine via a local machine, or do you use " "Docker for macOS?", True) if (response): self._display_info("If you use docker-machine on macOS, please see " "http://inginious.readthedocs.io/en/latest/install_doc/troubleshooting.html") return "local" else: self._display_info( "You will have to run inginious-backend and inginious-agent yourself. Please run the commands without argument " "and/or read the documentation for more info") return self._display_question("Please enter the address of your backend")
[ "def", "ask_backend", "(", "self", ")", ":", "response", "=", "self", ".", "_ask_boolean", "(", "\"Do you have a local docker daemon (on Linux), do you use docker-machine via a local machine, or do you use \"", "\"Docker for macOS?\"", ",", "True", ")", "if", "(", "response", ")", ":", "self", ".", "_display_info", "(", "\"If you use docker-machine on macOS, please see \"", "\"http://inginious.readthedocs.io/en/latest/install_doc/troubleshooting.html\"", ")", "return", "\"local\"", "else", ":", "self", ".", "_display_info", "(", "\"You will have to run inginious-backend and inginious-agent yourself. Please run the commands without argument \"", "\"and/or read the documentation for more info\"", ")", "return", "self", ".", "_display_question", "(", "\"Please enter the address of your backend\"", ")" ]
Ask the user to choose the backend
[ "Ask", "the", "user", "to", "choose", "the", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L252-L265
248,824
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.try_mongodb_opts
def try_mongodb_opts(self, host="localhost", database_name='INGInious'): """ Try MongoDB configuration """ try: mongo_client = MongoClient(host=host) except Exception as e: self._display_warning("Cannot connect to MongoDB on host %s: %s" % (host, str(e))) return None try: database = mongo_client[database_name] except Exception as e: self._display_warning("Cannot access database %s: %s" % (database_name, str(e))) return None try: GridFS(database) except Exception as e: self._display_warning("Cannot access gridfs %s: %s" % (database_name, str(e))) return None return database
python
def try_mongodb_opts(self, host="localhost", database_name='INGInious'): try: mongo_client = MongoClient(host=host) except Exception as e: self._display_warning("Cannot connect to MongoDB on host %s: %s" % (host, str(e))) return None try: database = mongo_client[database_name] except Exception as e: self._display_warning("Cannot access database %s: %s" % (database_name, str(e))) return None try: GridFS(database) except Exception as e: self._display_warning("Cannot access gridfs %s: %s" % (database_name, str(e))) return None return database
[ "def", "try_mongodb_opts", "(", "self", ",", "host", "=", "\"localhost\"", ",", "database_name", "=", "'INGInious'", ")", ":", "try", ":", "mongo_client", "=", "MongoClient", "(", "host", "=", "host", ")", "except", "Exception", "as", "e", ":", "self", ".", "_display_warning", "(", "\"Cannot connect to MongoDB on host %s: %s\"", "%", "(", "host", ",", "str", "(", "e", ")", ")", ")", "return", "None", "try", ":", "database", "=", "mongo_client", "[", "database_name", "]", "except", "Exception", "as", "e", ":", "self", ".", "_display_warning", "(", "\"Cannot access database %s: %s\"", "%", "(", "database_name", ",", "str", "(", "e", ")", ")", ")", "return", "None", "try", ":", "GridFS", "(", "database", ")", "except", "Exception", "as", "e", ":", "self", ".", "_display_warning", "(", "\"Cannot access gridfs %s: %s\"", "%", "(", "database_name", ",", "str", "(", "e", ")", ")", ")", "return", "None", "return", "database" ]
Try MongoDB configuration
[ "Try", "MongoDB", "configuration" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L271-L291
248,825
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.configure_task_directory
def configure_task_directory(self): """ Configure task directory """ self._display_question( "Please choose a directory in which to store the course/task files. By default, the tool will put them in the current " "directory") task_directory = None while task_directory is None: task_directory = self._ask_with_default("Task directory", ".") if not os.path.exists(task_directory): self._display_error("Path does not exists") if self._ask_boolean("Would you like to retry?", True): task_directory = None if os.path.exists(task_directory): self._display_question("Demonstration tasks can be downloaded to let you discover INGInious.") if self._ask_boolean("Would you like to download them ?", True): try: filename, _ = urllib.request.urlretrieve( "https://api.github.com/repos/UCL-INGI/INGInious-demo-tasks/tarball") with tarfile.open(filename, mode="r:gz") as thetarfile: members = thetarfile.getmembers() commonpath = os.path.commonpath([tarinfo.name for tarinfo in members]) for member in members: member.name = member.name[len(commonpath) + 1:] if member.name: thetarfile.extract(member, task_directory) self._display_info("Successfully downloaded and copied demonstration tasks.") except Exception as e: self._display_error("An error occurred while copying the directory: %s" % str(e)) else: self._display_warning("Skipping copying the 'test' course because the task dir does not exists") return {"tasks_directory": task_directory}
python
def configure_task_directory(self): self._display_question( "Please choose a directory in which to store the course/task files. By default, the tool will put them in the current " "directory") task_directory = None while task_directory is None: task_directory = self._ask_with_default("Task directory", ".") if not os.path.exists(task_directory): self._display_error("Path does not exists") if self._ask_boolean("Would you like to retry?", True): task_directory = None if os.path.exists(task_directory): self._display_question("Demonstration tasks can be downloaded to let you discover INGInious.") if self._ask_boolean("Would you like to download them ?", True): try: filename, _ = urllib.request.urlretrieve( "https://api.github.com/repos/UCL-INGI/INGInious-demo-tasks/tarball") with tarfile.open(filename, mode="r:gz") as thetarfile: members = thetarfile.getmembers() commonpath = os.path.commonpath([tarinfo.name for tarinfo in members]) for member in members: member.name = member.name[len(commonpath) + 1:] if member.name: thetarfile.extract(member, task_directory) self._display_info("Successfully downloaded and copied demonstration tasks.") except Exception as e: self._display_error("An error occurred while copying the directory: %s" % str(e)) else: self._display_warning("Skipping copying the 'test' course because the task dir does not exists") return {"tasks_directory": task_directory}
[ "def", "configure_task_directory", "(", "self", ")", ":", "self", ".", "_display_question", "(", "\"Please choose a directory in which to store the course/task files. By default, the tool will put them in the current \"", "\"directory\"", ")", "task_directory", "=", "None", "while", "task_directory", "is", "None", ":", "task_directory", "=", "self", ".", "_ask_with_default", "(", "\"Task directory\"", ",", "\".\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "task_directory", ")", ":", "self", ".", "_display_error", "(", "\"Path does not exists\"", ")", "if", "self", ".", "_ask_boolean", "(", "\"Would you like to retry?\"", ",", "True", ")", ":", "task_directory", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "task_directory", ")", ":", "self", ".", "_display_question", "(", "\"Demonstration tasks can be downloaded to let you discover INGInious.\"", ")", "if", "self", ".", "_ask_boolean", "(", "\"Would you like to download them ?\"", ",", "True", ")", ":", "try", ":", "filename", ",", "_", "=", "urllib", ".", "request", ".", "urlretrieve", "(", "\"https://api.github.com/repos/UCL-INGI/INGInious-demo-tasks/tarball\"", ")", "with", "tarfile", ".", "open", "(", "filename", ",", "mode", "=", "\"r:gz\"", ")", "as", "thetarfile", ":", "members", "=", "thetarfile", ".", "getmembers", "(", ")", "commonpath", "=", "os", ".", "path", ".", "commonpath", "(", "[", "tarinfo", ".", "name", "for", "tarinfo", "in", "members", "]", ")", "for", "member", "in", "members", ":", "member", ".", "name", "=", "member", ".", "name", "[", "len", "(", "commonpath", ")", "+", "1", ":", "]", "if", "member", ".", "name", ":", "thetarfile", ".", "extract", "(", "member", ",", "task_directory", ")", "self", ".", "_display_info", "(", "\"Successfully downloaded and copied demonstration tasks.\"", ")", "except", "Exception", "as", "e", ":", "self", ".", "_display_error", "(", "\"An error occurred while copying the directory: %s\"", "%", "str", "(", "e", ")", ")", "else", ":", "self", ".", "_display_warning", "(", "\"Skipping copying the 'test' course because the task dir does not exists\"", ")", "return", "{", "\"tasks_directory\"", ":", "task_directory", "}" ]
Configure task directory
[ "Configure", "task", "directory" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L326-L360
248,826
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.download_containers
def download_containers(self, to_download, current_options): """ Download the chosen containers on all the agents """ if current_options["backend"] == "local": self._display_info("Connecting to the local Docker daemon...") try: docker_connection = docker.from_env() except: self._display_error("Cannot connect to local Docker daemon. Skipping download.") return for image in to_download: try: self._display_info("Downloading image %s. This can take some time." % image) docker_connection.images.pull(image + ":latest") except Exception as e: self._display_error("An error occurred while pulling the image: %s." % str(e)) else: self._display_warning( "This installation tool does not support the backend configuration directly, if it's not local. You will have to " "pull the images by yourself. Here is the list: %s" % str(to_download))
python
def download_containers(self, to_download, current_options): if current_options["backend"] == "local": self._display_info("Connecting to the local Docker daemon...") try: docker_connection = docker.from_env() except: self._display_error("Cannot connect to local Docker daemon. Skipping download.") return for image in to_download: try: self._display_info("Downloading image %s. This can take some time." % image) docker_connection.images.pull(image + ":latest") except Exception as e: self._display_error("An error occurred while pulling the image: %s." % str(e)) else: self._display_warning( "This installation tool does not support the backend configuration directly, if it's not local. You will have to " "pull the images by yourself. Here is the list: %s" % str(to_download))
[ "def", "download_containers", "(", "self", ",", "to_download", ",", "current_options", ")", ":", "if", "current_options", "[", "\"backend\"", "]", "==", "\"local\"", ":", "self", ".", "_display_info", "(", "\"Connecting to the local Docker daemon...\"", ")", "try", ":", "docker_connection", "=", "docker", ".", "from_env", "(", ")", "except", ":", "self", ".", "_display_error", "(", "\"Cannot connect to local Docker daemon. Skipping download.\"", ")", "return", "for", "image", "in", "to_download", ":", "try", ":", "self", ".", "_display_info", "(", "\"Downloading image %s. This can take some time.\"", "%", "image", ")", "docker_connection", ".", "images", ".", "pull", "(", "image", "+", "\":latest\"", ")", "except", "Exception", "as", "e", ":", "self", ".", "_display_error", "(", "\"An error occurred while pulling the image: %s.\"", "%", "str", "(", "e", ")", ")", "else", ":", "self", ".", "_display_warning", "(", "\"This installation tool does not support the backend configuration directly, if it's not local. You will have to \"", "\"pull the images by yourself. Here is the list: %s\"", "%", "str", "(", "to_download", ")", ")" ]
Download the chosen containers on all the agents
[ "Download", "the", "chosen", "containers", "on", "all", "the", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L366-L385
248,827
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.configure_containers
def configure_containers(self, current_options): """ Configures the container dict """ containers = [ ("default", "Default container. For Bash and Python 2 tasks"), ("cpp", "Contains gcc and g++ for compiling C++"), ("java7", "Contains Java 7"), ("java8scala", "Contains Java 8 and Scala"), ("mono", "Contains Mono, which allows to run C#, F# and many other languages"), ("oz", "Contains Mozart 2, an implementation of the Oz multi-paradigm language, made for education"), ("php", "Contains PHP 5"), ("pythia0compat", "Compatibility container for Pythia 0"), ("pythia1compat", "Compatibility container for Pythia 1"), ("r", "Can run R scripts"), ("sekexe", "Can run an user-mode-linux for advanced tasks") ] default_download = ["default"] self._display_question( "The tool will now propose to download some base container image for multiple languages.") self._display_question( "Please note that the download of these images can take a lot of time, so choose only the images you need") to_download = [] for container_name, description in containers: if self._ask_boolean("Download %s (%s) ?" % (container_name, description), container_name in default_download): to_download.append("ingi/inginious-c-%s" % container_name) self.download_containers(to_download, current_options) wants = self._ask_boolean("Do you want to manually add some images?", False) while wants: image = self._ask_with_default("Container image name (leave this field empty to skip)", "") if image == "": break self._display_info("Configuration of the containers done.")
python
def configure_containers(self, current_options): containers = [ ("default", "Default container. For Bash and Python 2 tasks"), ("cpp", "Contains gcc and g++ for compiling C++"), ("java7", "Contains Java 7"), ("java8scala", "Contains Java 8 and Scala"), ("mono", "Contains Mono, which allows to run C#, F# and many other languages"), ("oz", "Contains Mozart 2, an implementation of the Oz multi-paradigm language, made for education"), ("php", "Contains PHP 5"), ("pythia0compat", "Compatibility container for Pythia 0"), ("pythia1compat", "Compatibility container for Pythia 1"), ("r", "Can run R scripts"), ("sekexe", "Can run an user-mode-linux for advanced tasks") ] default_download = ["default"] self._display_question( "The tool will now propose to download some base container image for multiple languages.") self._display_question( "Please note that the download of these images can take a lot of time, so choose only the images you need") to_download = [] for container_name, description in containers: if self._ask_boolean("Download %s (%s) ?" % (container_name, description), container_name in default_download): to_download.append("ingi/inginious-c-%s" % container_name) self.download_containers(to_download, current_options) wants = self._ask_boolean("Do you want to manually add some images?", False) while wants: image = self._ask_with_default("Container image name (leave this field empty to skip)", "") if image == "": break self._display_info("Configuration of the containers done.")
[ "def", "configure_containers", "(", "self", ",", "current_options", ")", ":", "containers", "=", "[", "(", "\"default\"", ",", "\"Default container. For Bash and Python 2 tasks\"", ")", ",", "(", "\"cpp\"", ",", "\"Contains gcc and g++ for compiling C++\"", ")", ",", "(", "\"java7\"", ",", "\"Contains Java 7\"", ")", ",", "(", "\"java8scala\"", ",", "\"Contains Java 8 and Scala\"", ")", ",", "(", "\"mono\"", ",", "\"Contains Mono, which allows to run C#, F# and many other languages\"", ")", ",", "(", "\"oz\"", ",", "\"Contains Mozart 2, an implementation of the Oz multi-paradigm language, made for education\"", ")", ",", "(", "\"php\"", ",", "\"Contains PHP 5\"", ")", ",", "(", "\"pythia0compat\"", ",", "\"Compatibility container for Pythia 0\"", ")", ",", "(", "\"pythia1compat\"", ",", "\"Compatibility container for Pythia 1\"", ")", ",", "(", "\"r\"", ",", "\"Can run R scripts\"", ")", ",", "(", "\"sekexe\"", ",", "\"Can run an user-mode-linux for advanced tasks\"", ")", "]", "default_download", "=", "[", "\"default\"", "]", "self", ".", "_display_question", "(", "\"The tool will now propose to download some base container image for multiple languages.\"", ")", "self", ".", "_display_question", "(", "\"Please note that the download of these images can take a lot of time, so choose only the images you need\"", ")", "to_download", "=", "[", "]", "for", "container_name", ",", "description", "in", "containers", ":", "if", "self", ".", "_ask_boolean", "(", "\"Download %s (%s) ?\"", "%", "(", "container_name", ",", "description", ")", ",", "container_name", "in", "default_download", ")", ":", "to_download", ".", "append", "(", "\"ingi/inginious-c-%s\"", "%", "container_name", ")", "self", ".", "download_containers", "(", "to_download", ",", "current_options", ")", "wants", "=", "self", ".", "_ask_boolean", "(", "\"Do you want to manually add some images?\"", ",", "False", ")", "while", "wants", ":", "image", "=", "self", ".", "_ask_with_default", "(", "\"Container image name (leave this field empty to skip)\"", ",", "\"\"", ")", "if", "image", "==", "\"\"", ":", "break", "self", ".", "_display_info", "(", "\"Configuration of the containers done.\"", ")" ]
Configures the container dict
[ "Configures", "the", "container", "dict" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L387-L424
248,828
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.configure_backup_directory
def configure_backup_directory(self): """ Configure backup directory """ self._display_question("Please choose a directory in which to store the backup files. By default, the tool will them in the current " "directory") backup_directory = None while backup_directory is None: backup_directory = self._ask_with_default("Backup directory", ".") if not os.path.exists(backup_directory): self._display_error("Path does not exists") if self._ask_boolean("Would you like to retry?", True): backup_directory = None return {"backup_directory": backup_directory}
python
def configure_backup_directory(self): self._display_question("Please choose a directory in which to store the backup files. By default, the tool will them in the current " "directory") backup_directory = None while backup_directory is None: backup_directory = self._ask_with_default("Backup directory", ".") if not os.path.exists(backup_directory): self._display_error("Path does not exists") if self._ask_boolean("Would you like to retry?", True): backup_directory = None return {"backup_directory": backup_directory}
[ "def", "configure_backup_directory", "(", "self", ")", ":", "self", ".", "_display_question", "(", "\"Please choose a directory in which to store the backup files. By default, the tool will them in the current \"", "\"directory\"", ")", "backup_directory", "=", "None", "while", "backup_directory", "is", "None", ":", "backup_directory", "=", "self", ".", "_ask_with_default", "(", "\"Backup directory\"", ",", "\".\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "backup_directory", ")", ":", "self", ".", "_display_error", "(", "\"Path does not exists\"", ")", "if", "self", ".", "_ask_boolean", "(", "\"Would you like to retry?\"", ",", "True", ")", ":", "backup_directory", "=", "None", "return", "{", "\"backup_directory\"", ":", "backup_directory", "}" ]
Configure backup directory
[ "Configure", "backup", "directory" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L439-L451
248,829
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.ldap_plugin
def ldap_plugin(self): """ Configures the LDAP plugin """ name = self._ask_with_default("Authentication method name (will be displayed on the login page)", "LDAP") prefix = self._ask_with_default("Prefix to append to the username before db storage. Usefull when you have more than one auth method with " "common usernames.", "") ldap_host = self._ask_with_default("LDAP Host", "ldap.your.domain.com") encryption = 'none' while True: encryption = self._ask_with_default("Encryption (either 'ssl', 'tls', or 'none')", 'none') if encryption not in ['none', 'ssl', 'tls']: self._display_error("Invalid value") else: break base_dn = self._ask_with_default("Base DN", "ou=people,c=com") request = self._ask_with_default("Request to find a user. '{}' will be replaced by the username", "uid={}") require_cert = self._ask_boolean("Require certificate validation?", encryption is not None) return { "plugin_module": "inginious.frontend.plugins.auth.ldap_auth", "host": ldap_host, "encryption": encryption, "base_dn": base_dn, "request": request, "prefix": prefix, "name": name, "require_cert": require_cert }
python
def ldap_plugin(self): name = self._ask_with_default("Authentication method name (will be displayed on the login page)", "LDAP") prefix = self._ask_with_default("Prefix to append to the username before db storage. Usefull when you have more than one auth method with " "common usernames.", "") ldap_host = self._ask_with_default("LDAP Host", "ldap.your.domain.com") encryption = 'none' while True: encryption = self._ask_with_default("Encryption (either 'ssl', 'tls', or 'none')", 'none') if encryption not in ['none', 'ssl', 'tls']: self._display_error("Invalid value") else: break base_dn = self._ask_with_default("Base DN", "ou=people,c=com") request = self._ask_with_default("Request to find a user. '{}' will be replaced by the username", "uid={}") require_cert = self._ask_boolean("Require certificate validation?", encryption is not None) return { "plugin_module": "inginious.frontend.plugins.auth.ldap_auth", "host": ldap_host, "encryption": encryption, "base_dn": base_dn, "request": request, "prefix": prefix, "name": name, "require_cert": require_cert }
[ "def", "ldap_plugin", "(", "self", ")", ":", "name", "=", "self", ".", "_ask_with_default", "(", "\"Authentication method name (will be displayed on the login page)\"", ",", "\"LDAP\"", ")", "prefix", "=", "self", ".", "_ask_with_default", "(", "\"Prefix to append to the username before db storage. Usefull when you have more than one auth method with \"", "\"common usernames.\"", ",", "\"\"", ")", "ldap_host", "=", "self", ".", "_ask_with_default", "(", "\"LDAP Host\"", ",", "\"ldap.your.domain.com\"", ")", "encryption", "=", "'none'", "while", "True", ":", "encryption", "=", "self", ".", "_ask_with_default", "(", "\"Encryption (either 'ssl', 'tls', or 'none')\"", ",", "'none'", ")", "if", "encryption", "not", "in", "[", "'none'", ",", "'ssl'", ",", "'tls'", "]", ":", "self", ".", "_display_error", "(", "\"Invalid value\"", ")", "else", ":", "break", "base_dn", "=", "self", ".", "_ask_with_default", "(", "\"Base DN\"", ",", "\"ou=people,c=com\"", ")", "request", "=", "self", ".", "_ask_with_default", "(", "\"Request to find a user. '{}' will be replaced by the username\"", ",", "\"uid={}\"", ")", "require_cert", "=", "self", ".", "_ask_boolean", "(", "\"Require certificate validation?\"", ",", "encryption", "is", "not", "None", ")", "return", "{", "\"plugin_module\"", ":", "\"inginious.frontend.plugins.auth.ldap_auth\"", ",", "\"host\"", ":", "ldap_host", ",", "\"encryption\"", ":", "encryption", ",", "\"base_dn\"", ":", "base_dn", ",", "\"request\"", ":", "request", ",", "\"prefix\"", ":", "prefix", ",", "\"name\"", ":", "name", ",", "\"require_cert\"", ":", "require_cert", "}" ]
Configures the LDAP plugin
[ "Configures", "the", "LDAP", "plugin" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L453-L481
248,830
UCL-INGI/INGInious
inginious/frontend/installer.py
Installer.configure_authentication
def configure_authentication(self, database): """ Configure the authentication """ options = {"plugins": [], "superadmins": []} self._display_info("We will now create the first user.") username = self._ask_with_default("Enter the login of the superadmin", "superadmin") realname = self._ask_with_default("Enter the name of the superadmin", "INGInious SuperAdmin") email = self._ask_with_default("Enter the email address of the superadmin", "[email protected]") password = self._ask_with_default("Enter the password of the superadmin", "superadmin") database.users.insert({"username": username, "realname": realname, "email": email, "password": hashlib.sha512(password.encode("utf-8")).hexdigest(), "bindings": {}, "language": "en"}) options["superadmins"].append(username) while True: if not self._ask_boolean("Would you like to add another auth method?", False): break self._display_info("You can choose an authentication plugin between:") self._display_info("- 1. LDAP auth plugin. This plugin allows to connect to a distant LDAP host.") plugin = self._ask_with_default("Enter the corresponding number to your choice", '1') if plugin not in ['1']: continue elif plugin == '1': options["plugins"].append(self.ldap_plugin()) return options
python
def configure_authentication(self, database): options = {"plugins": [], "superadmins": []} self._display_info("We will now create the first user.") username = self._ask_with_default("Enter the login of the superadmin", "superadmin") realname = self._ask_with_default("Enter the name of the superadmin", "INGInious SuperAdmin") email = self._ask_with_default("Enter the email address of the superadmin", "[email protected]") password = self._ask_with_default("Enter the password of the superadmin", "superadmin") database.users.insert({"username": username, "realname": realname, "email": email, "password": hashlib.sha512(password.encode("utf-8")).hexdigest(), "bindings": {}, "language": "en"}) options["superadmins"].append(username) while True: if not self._ask_boolean("Would you like to add another auth method?", False): break self._display_info("You can choose an authentication plugin between:") self._display_info("- 1. LDAP auth plugin. This plugin allows to connect to a distant LDAP host.") plugin = self._ask_with_default("Enter the corresponding number to your choice", '1') if plugin not in ['1']: continue elif plugin == '1': options["plugins"].append(self.ldap_plugin()) return options
[ "def", "configure_authentication", "(", "self", ",", "database", ")", ":", "options", "=", "{", "\"plugins\"", ":", "[", "]", ",", "\"superadmins\"", ":", "[", "]", "}", "self", ".", "_display_info", "(", "\"We will now create the first user.\"", ")", "username", "=", "self", ".", "_ask_with_default", "(", "\"Enter the login of the superadmin\"", ",", "\"superadmin\"", ")", "realname", "=", "self", ".", "_ask_with_default", "(", "\"Enter the name of the superadmin\"", ",", "\"INGInious SuperAdmin\"", ")", "email", "=", "self", ".", "_ask_with_default", "(", "\"Enter the email address of the superadmin\"", ",", "\"[email protected]\"", ")", "password", "=", "self", ".", "_ask_with_default", "(", "\"Enter the password of the superadmin\"", ",", "\"superadmin\"", ")", "database", ".", "users", ".", "insert", "(", "{", "\"username\"", ":", "username", ",", "\"realname\"", ":", "realname", ",", "\"email\"", ":", "email", ",", "\"password\"", ":", "hashlib", ".", "sha512", "(", "password", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ")", ",", "\"bindings\"", ":", "{", "}", ",", "\"language\"", ":", "\"en\"", "}", ")", "options", "[", "\"superadmins\"", "]", ".", "append", "(", "username", ")", "while", "True", ":", "if", "not", "self", ".", "_ask_boolean", "(", "\"Would you like to add another auth method?\"", ",", "False", ")", ":", "break", "self", ".", "_display_info", "(", "\"You can choose an authentication plugin between:\"", ")", "self", ".", "_display_info", "(", "\"- 1. LDAP auth plugin. This plugin allows to connect to a distant LDAP host.\"", ")", "plugin", "=", "self", ".", "_ask_with_default", "(", "\"Enter the corresponding number to your choice\"", ",", "'1'", ")", "if", "plugin", "not", "in", "[", "'1'", "]", ":", "continue", "elif", "plugin", "==", "'1'", ":", "options", "[", "\"plugins\"", "]", ".", "append", "(", "self", ".", "ldap_plugin", "(", ")", ")", "return", "options" ]
Configure the authentication
[ "Configure", "the", "authentication" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/installer.py#L483-L515
248,831
UCL-INGI/INGInious
inginious/frontend/app.py
_close_app
def _close_app(app, mongo_client, client): """ Ensures that the app is properly closed """ app.stop() client.close() mongo_client.close()
python
def _close_app(app, mongo_client, client): app.stop() client.close() mongo_client.close()
[ "def", "_close_app", "(", "app", ",", "mongo_client", ",", "client", ")", ":", "app", ".", "stop", "(", ")", "client", ".", "close", "(", ")", "mongo_client", ".", "close", "(", ")" ]
Ensures that the app is properly closed
[ "Ensures", "that", "the", "app", "is", "properly", "closed" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/app.py#L113-L117
248,832
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent._init_clean
async def _init_clean(self): """ Must be called when the agent is starting """ # Data about running containers self._containers_running = {} self._container_for_job = {} self._student_containers_running = {} self._student_containers_for_job = {} self._containers_killed = dict() # Delete tmp_dir, and recreate-it again try: await self._ashutil.rmtree(self._tmp_dir) except OSError: pass try: await self._aos.mkdir(self._tmp_dir) except OSError: pass # Docker self._docker = AsyncProxy(DockerInterface()) # Auto discover containers self._logger.info("Discovering containers") self._containers = await self._docker.get_containers() self._assigned_external_ports = {} # container_id : [external_ports] if self._address_host is None and len(self._containers) != 0: self._logger.info("Guessing external host IP") self._address_host = await self._docker.get_host_ip(next(iter(self._containers.values()))["id"]) if self._address_host is None: self._logger.warning( "Cannot find external host IP. Please indicate it in the configuration. Remote SSH debug has been deactivated.") self._external_ports = None else: self._logger.info("External address for SSH remote debug is %s", self._address_host) # Watchers self._timeout_watcher = TimeoutWatcher(self._docker)
python
async def _init_clean(self): # Data about running containers self._containers_running = {} self._container_for_job = {} self._student_containers_running = {} self._student_containers_for_job = {} self._containers_killed = dict() # Delete tmp_dir, and recreate-it again try: await self._ashutil.rmtree(self._tmp_dir) except OSError: pass try: await self._aos.mkdir(self._tmp_dir) except OSError: pass # Docker self._docker = AsyncProxy(DockerInterface()) # Auto discover containers self._logger.info("Discovering containers") self._containers = await self._docker.get_containers() self._assigned_external_ports = {} # container_id : [external_ports] if self._address_host is None and len(self._containers) != 0: self._logger.info("Guessing external host IP") self._address_host = await self._docker.get_host_ip(next(iter(self._containers.values()))["id"]) if self._address_host is None: self._logger.warning( "Cannot find external host IP. Please indicate it in the configuration. Remote SSH debug has been deactivated.") self._external_ports = None else: self._logger.info("External address for SSH remote debug is %s", self._address_host) # Watchers self._timeout_watcher = TimeoutWatcher(self._docker)
[ "async", "def", "_init_clean", "(", "self", ")", ":", "# Data about running containers", "self", ".", "_containers_running", "=", "{", "}", "self", ".", "_container_for_job", "=", "{", "}", "self", ".", "_student_containers_running", "=", "{", "}", "self", ".", "_student_containers_for_job", "=", "{", "}", "self", ".", "_containers_killed", "=", "dict", "(", ")", "# Delete tmp_dir, and recreate-it again", "try", ":", "await", "self", ".", "_ashutil", ".", "rmtree", "(", "self", ".", "_tmp_dir", ")", "except", "OSError", ":", "pass", "try", ":", "await", "self", ".", "_aos", ".", "mkdir", "(", "self", ".", "_tmp_dir", ")", "except", "OSError", ":", "pass", "# Docker", "self", ".", "_docker", "=", "AsyncProxy", "(", "DockerInterface", "(", ")", ")", "# Auto discover containers", "self", ".", "_logger", ".", "info", "(", "\"Discovering containers\"", ")", "self", ".", "_containers", "=", "await", "self", ".", "_docker", ".", "get_containers", "(", ")", "self", ".", "_assigned_external_ports", "=", "{", "}", "# container_id : [external_ports]", "if", "self", ".", "_address_host", "is", "None", "and", "len", "(", "self", ".", "_containers", ")", "!=", "0", ":", "self", ".", "_logger", ".", "info", "(", "\"Guessing external host IP\"", ")", "self", ".", "_address_host", "=", "await", "self", ".", "_docker", ".", "get_host_ip", "(", "next", "(", "iter", "(", "self", ".", "_containers", ".", "values", "(", ")", ")", ")", "[", "\"id\"", "]", ")", "if", "self", ".", "_address_host", "is", "None", ":", "self", ".", "_logger", ".", "warning", "(", "\"Cannot find external host IP. Please indicate it in the configuration. Remote SSH debug has been deactivated.\"", ")", "self", ".", "_external_ports", "=", "None", "else", ":", "self", ".", "_logger", ".", "info", "(", "\"External address for SSH remote debug is %s\"", ",", "self", ".", "_address_host", ")", "# Watchers", "self", ".", "_timeout_watcher", "=", "TimeoutWatcher", "(", "self", ".", "_docker", ")" ]
Must be called when the agent is starting
[ "Must", "be", "called", "when", "the", "agent", "is", "starting" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L57-L99
248,833
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent._end_clean
async def _end_clean(self): """ Must be called when the agent is closing """ await self._timeout_watcher.clean() async def close_and_delete(container_id): try: await self._docker.remove_container(container_id) except: pass for container_id in self._containers_running: await close_and_delete(container_id) for container_id in self._student_containers_running: await close_and_delete(container_id)
python
async def _end_clean(self): await self._timeout_watcher.clean() async def close_and_delete(container_id): try: await self._docker.remove_container(container_id) except: pass for container_id in self._containers_running: await close_and_delete(container_id) for container_id in self._student_containers_running: await close_and_delete(container_id)
[ "async", "def", "_end_clean", "(", "self", ")", ":", "await", "self", ".", "_timeout_watcher", ".", "clean", "(", ")", "async", "def", "close_and_delete", "(", "container_id", ")", ":", "try", ":", "await", "self", ".", "_docker", ".", "remove_container", "(", "container_id", ")", "except", ":", "pass", "for", "container_id", "in", "self", ".", "_containers_running", ":", "await", "close_and_delete", "(", "container_id", ")", "for", "container_id", "in", "self", ".", "_student_containers_running", ":", "await", "close_and_delete", "(", "container_id", ")" ]
Must be called when the agent is closing
[ "Must", "be", "called", "when", "the", "agent", "is", "closing" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L101-L114
248,834
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent._watch_docker_events
async def _watch_docker_events(self): """ Get raw docker events and convert them to more readable objects, and then give them to self._docker_events_subscriber """ try: source = AsyncIteratorWrapper(self._docker.sync.event_stream(filters={"event": ["die", "oom"]})) async for i in source: if i["Type"] == "container" and i["status"] == "die": container_id = i["id"] try: retval = int(i["Actor"]["Attributes"]["exitCode"]) except asyncio.CancelledError: raise except: self._logger.exception("Cannot parse exitCode for container %s", container_id) retval = -1 if container_id in self._containers_running: self._create_safe_task(self.handle_job_closing(container_id, retval)) elif container_id in self._student_containers_running: self._create_safe_task(self.handle_student_job_closing(container_id, retval)) elif i["Type"] == "container" and i["status"] == "oom": container_id = i["id"] if container_id in self._containers_running or container_id in self._student_containers_running: self._logger.info("Container %s did OOM, killing it", container_id) self._containers_killed[container_id] = "overflow" try: self._create_safe_task(self._docker.kill_container(container_id)) except asyncio.CancelledError: raise except: # this call can sometimes fail, and that is normal. pass else: raise TypeError(str(i)) except asyncio.CancelledError: pass except: self._logger.exception("Exception in _watch_docker_events")
python
async def _watch_docker_events(self): try: source = AsyncIteratorWrapper(self._docker.sync.event_stream(filters={"event": ["die", "oom"]})) async for i in source: if i["Type"] == "container" and i["status"] == "die": container_id = i["id"] try: retval = int(i["Actor"]["Attributes"]["exitCode"]) except asyncio.CancelledError: raise except: self._logger.exception("Cannot parse exitCode for container %s", container_id) retval = -1 if container_id in self._containers_running: self._create_safe_task(self.handle_job_closing(container_id, retval)) elif container_id in self._student_containers_running: self._create_safe_task(self.handle_student_job_closing(container_id, retval)) elif i["Type"] == "container" and i["status"] == "oom": container_id = i["id"] if container_id in self._containers_running or container_id in self._student_containers_running: self._logger.info("Container %s did OOM, killing it", container_id) self._containers_killed[container_id] = "overflow" try: self._create_safe_task(self._docker.kill_container(container_id)) except asyncio.CancelledError: raise except: # this call can sometimes fail, and that is normal. pass else: raise TypeError(str(i)) except asyncio.CancelledError: pass except: self._logger.exception("Exception in _watch_docker_events")
[ "async", "def", "_watch_docker_events", "(", "self", ")", ":", "try", ":", "source", "=", "AsyncIteratorWrapper", "(", "self", ".", "_docker", ".", "sync", ".", "event_stream", "(", "filters", "=", "{", "\"event\"", ":", "[", "\"die\"", ",", "\"oom\"", "]", "}", ")", ")", "async", "for", "i", "in", "source", ":", "if", "i", "[", "\"Type\"", "]", "==", "\"container\"", "and", "i", "[", "\"status\"", "]", "==", "\"die\"", ":", "container_id", "=", "i", "[", "\"id\"", "]", "try", ":", "retval", "=", "int", "(", "i", "[", "\"Actor\"", "]", "[", "\"Attributes\"", "]", "[", "\"exitCode\"", "]", ")", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", ":", "self", ".", "_logger", ".", "exception", "(", "\"Cannot parse exitCode for container %s\"", ",", "container_id", ")", "retval", "=", "-", "1", "if", "container_id", "in", "self", ".", "_containers_running", ":", "self", ".", "_create_safe_task", "(", "self", ".", "handle_job_closing", "(", "container_id", ",", "retval", ")", ")", "elif", "container_id", "in", "self", ".", "_student_containers_running", ":", "self", ".", "_create_safe_task", "(", "self", ".", "handle_student_job_closing", "(", "container_id", ",", "retval", ")", ")", "elif", "i", "[", "\"Type\"", "]", "==", "\"container\"", "and", "i", "[", "\"status\"", "]", "==", "\"oom\"", ":", "container_id", "=", "i", "[", "\"id\"", "]", "if", "container_id", "in", "self", ".", "_containers_running", "or", "container_id", "in", "self", ".", "_student_containers_running", ":", "self", ".", "_logger", ".", "info", "(", "\"Container %s did OOM, killing it\"", ",", "container_id", ")", "self", ".", "_containers_killed", "[", "container_id", "]", "=", "\"overflow\"", "try", ":", "self", ".", "_create_safe_task", "(", "self", ".", "_docker", ".", "kill_container", "(", "container_id", ")", ")", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", ":", "# this call can sometimes fail, and that is normal.", "pass", "else", ":", "raise", "TypeError", "(", "str", "(", "i", ")", ")", "except", "asyncio", ".", "CancelledError", ":", "pass", "except", ":", "self", ".", "_logger", ".", "exception", "(", "\"Exception in _watch_docker_events\"", ")" ]
Get raw docker events and convert them to more readable objects, and then give them to self._docker_events_subscriber
[ "Get", "raw", "docker", "events", "and", "convert", "them", "to", "more", "readable", "objects", "and", "then", "give", "them", "to", "self", ".", "_docker_events_subscriber" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L120-L155
248,835
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent.handle_student_job_closing
async def handle_student_job_closing(self, container_id, retval): """ Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the associated grading container """ try: self._logger.debug("Closing student %s", container_id) try: job_id, parent_container_id, socket_id, write_stream = self._student_containers_running[container_id] del self._student_containers_running[container_id] except asyncio.CancelledError: raise except: self._logger.warning("Student container %s that has finished(p1) was not launched by this agent", str(container_id), exc_info=True) return # Delete remaining student containers if job_id in self._student_containers_for_job: # if it does not exists, then the parent container has closed self._student_containers_for_job[job_id].remove(container_id) killed = await self._timeout_watcher.was_killed(container_id) if container_id in self._containers_killed: killed = self._containers_killed[container_id] del self._containers_killed[container_id] if killed == "timeout": retval = 253 elif killed == "overflow": retval = 252 try: await self._write_to_container_stdin(write_stream, {"type": "run_student_retval", "retval": retval, "socket_id": socket_id}) except asyncio.CancelledError: raise except: pass # parent container closed # Do not forget to remove the container try: await self._docker.remove_container(container_id) except asyncio.CancelledError: raise except: pass # ignore except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_student_job_closing")
python
async def handle_student_job_closing(self, container_id, retval): try: self._logger.debug("Closing student %s", container_id) try: job_id, parent_container_id, socket_id, write_stream = self._student_containers_running[container_id] del self._student_containers_running[container_id] except asyncio.CancelledError: raise except: self._logger.warning("Student container %s that has finished(p1) was not launched by this agent", str(container_id), exc_info=True) return # Delete remaining student containers if job_id in self._student_containers_for_job: # if it does not exists, then the parent container has closed self._student_containers_for_job[job_id].remove(container_id) killed = await self._timeout_watcher.was_killed(container_id) if container_id in self._containers_killed: killed = self._containers_killed[container_id] del self._containers_killed[container_id] if killed == "timeout": retval = 253 elif killed == "overflow": retval = 252 try: await self._write_to_container_stdin(write_stream, {"type": "run_student_retval", "retval": retval, "socket_id": socket_id}) except asyncio.CancelledError: raise except: pass # parent container closed # Do not forget to remove the container try: await self._docker.remove_container(container_id) except asyncio.CancelledError: raise except: pass # ignore except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_student_job_closing")
[ "async", "def", "handle_student_job_closing", "(", "self", ",", "container_id", ",", "retval", ")", ":", "try", ":", "self", ".", "_logger", ".", "debug", "(", "\"Closing student %s\"", ",", "container_id", ")", "try", ":", "job_id", ",", "parent_container_id", ",", "socket_id", ",", "write_stream", "=", "self", ".", "_student_containers_running", "[", "container_id", "]", "del", "self", ".", "_student_containers_running", "[", "container_id", "]", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", ":", "self", ".", "_logger", ".", "warning", "(", "\"Student container %s that has finished(p1) was not launched by this agent\"", ",", "str", "(", "container_id", ")", ",", "exc_info", "=", "True", ")", "return", "# Delete remaining student containers", "if", "job_id", "in", "self", ".", "_student_containers_for_job", ":", "# if it does not exists, then the parent container has closed", "self", ".", "_student_containers_for_job", "[", "job_id", "]", ".", "remove", "(", "container_id", ")", "killed", "=", "await", "self", ".", "_timeout_watcher", ".", "was_killed", "(", "container_id", ")", "if", "container_id", "in", "self", ".", "_containers_killed", ":", "killed", "=", "self", ".", "_containers_killed", "[", "container_id", "]", "del", "self", ".", "_containers_killed", "[", "container_id", "]", "if", "killed", "==", "\"timeout\"", ":", "retval", "=", "253", "elif", "killed", "==", "\"overflow\"", ":", "retval", "=", "252", "try", ":", "await", "self", ".", "_write_to_container_stdin", "(", "write_stream", ",", "{", "\"type\"", ":", "\"run_student_retval\"", ",", "\"retval\"", ":", "retval", ",", "\"socket_id\"", ":", "socket_id", "}", ")", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", ":", "pass", "# parent container closed", "# Do not forget to remove the container", "try", ":", "await", "self", ".", "_docker", ".", "remove_container", "(", "container_id", ")", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", ":", "pass", "# ignore", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", ":", "self", ".", "_logger", ".", "exception", "(", "\"Exception in handle_student_job_closing\"", ")" ]
Handle a closing student container. Do some cleaning, verify memory limits, timeouts, ... and returns data to the associated grading container
[ "Handle", "a", "closing", "student", "container", ".", "Do", "some", "cleaning", "verify", "memory", "limits", "timeouts", "...", "and", "returns", "data", "to", "the", "associated", "grading", "container" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L452-L499
248,836
UCL-INGI/INGInious
inginious/agent/docker_agent/__init__.py
DockerAgent.kill_job
async def kill_job(self, message: BackendKillJob): """ Handles `kill` messages. Kill things. """ try: if message.job_id in self._container_for_job: self._containers_killed[self._container_for_job[message.job_id]] = "killed" await self._docker.kill_container(self._container_for_job[message.job_id]) else: self._logger.warning("Cannot kill container for job %s because it is not running", str(message.job_id)) except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_kill_job")
python
async def kill_job(self, message: BackendKillJob): try: if message.job_id in self._container_for_job: self._containers_killed[self._container_for_job[message.job_id]] = "killed" await self._docker.kill_container(self._container_for_job[message.job_id]) else: self._logger.warning("Cannot kill container for job %s because it is not running", str(message.job_id)) except asyncio.CancelledError: raise except: self._logger.exception("Exception in handle_kill_job")
[ "async", "def", "kill_job", "(", "self", ",", "message", ":", "BackendKillJob", ")", ":", "try", ":", "if", "message", ".", "job_id", "in", "self", ".", "_container_for_job", ":", "self", ".", "_containers_killed", "[", "self", ".", "_container_for_job", "[", "message", ".", "job_id", "]", "]", "=", "\"killed\"", "await", "self", ".", "_docker", ".", "kill_container", "(", "self", ".", "_container_for_job", "[", "message", ".", "job_id", "]", ")", "else", ":", "self", ".", "_logger", ".", "warning", "(", "\"Cannot kill container for job %s because it is not running\"", ",", "str", "(", "message", ".", "job_id", ")", ")", "except", "asyncio", ".", "CancelledError", ":", "raise", "except", ":", "self", ".", "_logger", ".", "exception", "(", "\"Exception in handle_kill_job\"", ")" ]
Handles `kill` messages. Kill things.
[ "Handles", "kill", "messages", ".", "Kill", "things", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/__init__.py#L629-L640
248,837
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/aggregation_edit.py
CourseEditAggregation.get_user_lists
def get_user_lists(self, course, aggregationid=''): """ Get the available student and tutor lists for aggregation edition""" tutor_list = course.get_staff() # Determine student list and if they are grouped student_list = list(self.database.aggregations.aggregate([ {"$match": {"courseid": course.get_id()}}, {"$unwind": "$students"}, {"$project": { "classroom": "$_id", "students": 1, "grouped": { "$anyElementTrue": { "$map": { "input": "$groups.students", "as": "group", "in": { "$anyElementTrue": { "$map": { "input": "$$group", "as": "groupmember", "in": {"$eq": ["$$groupmember", "$students"]} } } } } } } }} ])) student_list = dict([(student["students"], student) for student in student_list]) users_info = self.user_manager.get_users_info(list(student_list.keys()) + tutor_list) if aggregationid: # Order the non-registered students other_students = [student_list[entry]['students'] for entry in student_list.keys() if not student_list[entry]['classroom'] == ObjectId(aggregationid)] other_students = sorted(other_students, key=lambda val: (("0"+users_info[val][0]) if users_info[val] else ("1"+val))) return student_list, tutor_list, other_students, users_info else: return student_list, tutor_list, users_info
python
def get_user_lists(self, course, aggregationid=''): tutor_list = course.get_staff() # Determine student list and if they are grouped student_list = list(self.database.aggregations.aggregate([ {"$match": {"courseid": course.get_id()}}, {"$unwind": "$students"}, {"$project": { "classroom": "$_id", "students": 1, "grouped": { "$anyElementTrue": { "$map": { "input": "$groups.students", "as": "group", "in": { "$anyElementTrue": { "$map": { "input": "$$group", "as": "groupmember", "in": {"$eq": ["$$groupmember", "$students"]} } } } } } } }} ])) student_list = dict([(student["students"], student) for student in student_list]) users_info = self.user_manager.get_users_info(list(student_list.keys()) + tutor_list) if aggregationid: # Order the non-registered students other_students = [student_list[entry]['students'] for entry in student_list.keys() if not student_list[entry]['classroom'] == ObjectId(aggregationid)] other_students = sorted(other_students, key=lambda val: (("0"+users_info[val][0]) if users_info[val] else ("1"+val))) return student_list, tutor_list, other_students, users_info else: return student_list, tutor_list, users_info
[ "def", "get_user_lists", "(", "self", ",", "course", ",", "aggregationid", "=", "''", ")", ":", "tutor_list", "=", "course", ".", "get_staff", "(", ")", "# Determine student list and if they are grouped", "student_list", "=", "list", "(", "self", ".", "database", ".", "aggregations", ".", "aggregate", "(", "[", "{", "\"$match\"", ":", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", "}", "}", ",", "{", "\"$unwind\"", ":", "\"$students\"", "}", ",", "{", "\"$project\"", ":", "{", "\"classroom\"", ":", "\"$_id\"", ",", "\"students\"", ":", "1", ",", "\"grouped\"", ":", "{", "\"$anyElementTrue\"", ":", "{", "\"$map\"", ":", "{", "\"input\"", ":", "\"$groups.students\"", ",", "\"as\"", ":", "\"group\"", ",", "\"in\"", ":", "{", "\"$anyElementTrue\"", ":", "{", "\"$map\"", ":", "{", "\"input\"", ":", "\"$$group\"", ",", "\"as\"", ":", "\"groupmember\"", ",", "\"in\"", ":", "{", "\"$eq\"", ":", "[", "\"$$groupmember\"", ",", "\"$students\"", "]", "}", "}", "}", "}", "}", "}", "}", "}", "}", "]", ")", ")", "student_list", "=", "dict", "(", "[", "(", "student", "[", "\"students\"", "]", ",", "student", ")", "for", "student", "in", "student_list", "]", ")", "users_info", "=", "self", ".", "user_manager", ".", "get_users_info", "(", "list", "(", "student_list", ".", "keys", "(", ")", ")", "+", "tutor_list", ")", "if", "aggregationid", ":", "# Order the non-registered students", "other_students", "=", "[", "student_list", "[", "entry", "]", "[", "'students'", "]", "for", "entry", "in", "student_list", ".", "keys", "(", ")", "if", "not", "student_list", "[", "entry", "]", "[", "'classroom'", "]", "==", "ObjectId", "(", "aggregationid", ")", "]", "other_students", "=", "sorted", "(", "other_students", ",", "key", "=", "lambda", "val", ":", "(", "(", "\"0\"", "+", "users_info", "[", "val", "]", "[", "0", "]", ")", "if", "users_info", "[", "val", "]", "else", "(", "\"1\"", "+", "val", ")", ")", ")", "return", "student_list", ",", "tutor_list", ",", "other_students", ",", "users_info", "else", ":", "return", "student_list", ",", "tutor_list", ",", "users_info" ]
Get the available student and tutor lists for aggregation edition
[ "Get", "the", "available", "student", "and", "tutor", "lists", "for", "aggregation", "edition" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/aggregation_edit.py#L21-L63
248,838
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/aggregation_edit.py
CourseEditAggregation.update_aggregation
def update_aggregation(self, course, aggregationid, new_data): """ Update aggregation and returns a list of errored students""" student_list = self.user_manager.get_course_registered_users(course, False) # If aggregation is new if aggregationid == 'None': # Remove _id for correct insertion del new_data['_id'] new_data["courseid"] = course.get_id() # Insert the new aggregation result = self.database.aggregations.insert_one(new_data) # Retrieve new aggregation id aggregationid = result.inserted_id new_data['_id'] = result.inserted_id aggregation = new_data else: aggregation = self.database.aggregations.find_one({"_id": ObjectId(aggregationid), "courseid": course.get_id()}) # Check tutors new_data["tutors"] = [tutor for tutor in new_data["tutors"] if tutor in course.get_staff()] students, groups, errored_students = [], [], [] # Check the students for student in new_data["students"]: if student in student_list: # Remove user from the other aggregation self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "groups.students": student}, {"$pull": {"groups.$.students": student, "students": student}}) self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "students": student}, {"$pull": {"students": student}}) students.append(student) else: # Check if user can be registered user_info = self.user_manager.get_user_info(student) if user_info is None or student in aggregation["tutors"]: errored_students.append(student) else: students.append(student) removed_students = [student for student in aggregation["students"] if student not in new_data["students"]] self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$push": {"students": {"$each": removed_students}}}) new_data["students"] = students # Check the groups for group in new_data["groups"]: group["students"] = [student for student in group["students"] if student in new_data["students"]] if len(group["students"]) <= group["size"]: groups.append(group) new_data["groups"] = groups # Check for default aggregation if new_data['default']: self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$set": {"default": False}}) aggregation = self.database.aggregations.find_one_and_update( {"_id": ObjectId(aggregationid)}, {"$set": {"description": new_data["description"], "students": students, "tutors": new_data["tutors"], "groups": groups, "default": new_data['default']}}, return_document=ReturnDocument.AFTER) return aggregation, errored_students
python
def update_aggregation(self, course, aggregationid, new_data): student_list = self.user_manager.get_course_registered_users(course, False) # If aggregation is new if aggregationid == 'None': # Remove _id for correct insertion del new_data['_id'] new_data["courseid"] = course.get_id() # Insert the new aggregation result = self.database.aggregations.insert_one(new_data) # Retrieve new aggregation id aggregationid = result.inserted_id new_data['_id'] = result.inserted_id aggregation = new_data else: aggregation = self.database.aggregations.find_one({"_id": ObjectId(aggregationid), "courseid": course.get_id()}) # Check tutors new_data["tutors"] = [tutor for tutor in new_data["tutors"] if tutor in course.get_staff()] students, groups, errored_students = [], [], [] # Check the students for student in new_data["students"]: if student in student_list: # Remove user from the other aggregation self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "groups.students": student}, {"$pull": {"groups.$.students": student, "students": student}}) self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "students": student}, {"$pull": {"students": student}}) students.append(student) else: # Check if user can be registered user_info = self.user_manager.get_user_info(student) if user_info is None or student in aggregation["tutors"]: errored_students.append(student) else: students.append(student) removed_students = [student for student in aggregation["students"] if student not in new_data["students"]] self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$push": {"students": {"$each": removed_students}}}) new_data["students"] = students # Check the groups for group in new_data["groups"]: group["students"] = [student for student in group["students"] if student in new_data["students"]] if len(group["students"]) <= group["size"]: groups.append(group) new_data["groups"] = groups # Check for default aggregation if new_data['default']: self.database.aggregations.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$set": {"default": False}}) aggregation = self.database.aggregations.find_one_and_update( {"_id": ObjectId(aggregationid)}, {"$set": {"description": new_data["description"], "students": students, "tutors": new_data["tutors"], "groups": groups, "default": new_data['default']}}, return_document=ReturnDocument.AFTER) return aggregation, errored_students
[ "def", "update_aggregation", "(", "self", ",", "course", ",", "aggregationid", ",", "new_data", ")", ":", "student_list", "=", "self", ".", "user_manager", ".", "get_course_registered_users", "(", "course", ",", "False", ")", "# If aggregation is new", "if", "aggregationid", "==", "'None'", ":", "# Remove _id for correct insertion", "del", "new_data", "[", "'_id'", "]", "new_data", "[", "\"courseid\"", "]", "=", "course", ".", "get_id", "(", ")", "# Insert the new aggregation", "result", "=", "self", ".", "database", ".", "aggregations", ".", "insert_one", "(", "new_data", ")", "# Retrieve new aggregation id", "aggregationid", "=", "result", ".", "inserted_id", "new_data", "[", "'_id'", "]", "=", "result", ".", "inserted_id", "aggregation", "=", "new_data", "else", ":", "aggregation", "=", "self", ".", "database", ".", "aggregations", ".", "find_one", "(", "{", "\"_id\"", ":", "ObjectId", "(", "aggregationid", ")", ",", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", "}", ")", "# Check tutors", "new_data", "[", "\"tutors\"", "]", "=", "[", "tutor", "for", "tutor", "in", "new_data", "[", "\"tutors\"", "]", "if", "tutor", "in", "course", ".", "get_staff", "(", ")", "]", "students", ",", "groups", ",", "errored_students", "=", "[", "]", ",", "[", "]", ",", "[", "]", "# Check the students", "for", "student", "in", "new_data", "[", "\"students\"", "]", ":", "if", "student", "in", "student_list", ":", "# Remove user from the other aggregation", "self", ".", "database", ".", "aggregations", ".", "find_one_and_update", "(", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"groups.students\"", ":", "student", "}", ",", "{", "\"$pull\"", ":", "{", "\"groups.$.students\"", ":", "student", ",", "\"students\"", ":", "student", "}", "}", ")", "self", ".", "database", ".", "aggregations", ".", "find_one_and_update", "(", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"students\"", ":", "student", "}", ",", "{", "\"$pull\"", ":", "{", "\"students\"", ":", "student", "}", "}", ")", "students", ".", "append", "(", "student", ")", "else", ":", "# Check if user can be registered", "user_info", "=", "self", ".", "user_manager", ".", "get_user_info", "(", "student", ")", "if", "user_info", "is", "None", "or", "student", "in", "aggregation", "[", "\"tutors\"", "]", ":", "errored_students", ".", "append", "(", "student", ")", "else", ":", "students", ".", "append", "(", "student", ")", "removed_students", "=", "[", "student", "for", "student", "in", "aggregation", "[", "\"students\"", "]", "if", "student", "not", "in", "new_data", "[", "\"students\"", "]", "]", "self", ".", "database", ".", "aggregations", ".", "find_one_and_update", "(", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"default\"", ":", "True", "}", ",", "{", "\"$push\"", ":", "{", "\"students\"", ":", "{", "\"$each\"", ":", "removed_students", "}", "}", "}", ")", "new_data", "[", "\"students\"", "]", "=", "students", "# Check the groups", "for", "group", "in", "new_data", "[", "\"groups\"", "]", ":", "group", "[", "\"students\"", "]", "=", "[", "student", "for", "student", "in", "group", "[", "\"students\"", "]", "if", "student", "in", "new_data", "[", "\"students\"", "]", "]", "if", "len", "(", "group", "[", "\"students\"", "]", ")", "<=", "group", "[", "\"size\"", "]", ":", "groups", ".", "append", "(", "group", ")", "new_data", "[", "\"groups\"", "]", "=", "groups", "# Check for default aggregation", "if", "new_data", "[", "'default'", "]", ":", "self", ".", "database", ".", "aggregations", ".", "find_one_and_update", "(", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"default\"", ":", "True", "}", ",", "{", "\"$set\"", ":", "{", "\"default\"", ":", "False", "}", "}", ")", "aggregation", "=", "self", ".", "database", ".", "aggregations", ".", "find_one_and_update", "(", "{", "\"_id\"", ":", "ObjectId", "(", "aggregationid", ")", "}", ",", "{", "\"$set\"", ":", "{", "\"description\"", ":", "new_data", "[", "\"description\"", "]", ",", "\"students\"", ":", "students", ",", "\"tutors\"", ":", "new_data", "[", "\"tutors\"", "]", ",", "\"groups\"", ":", "groups", ",", "\"default\"", ":", "new_data", "[", "'default'", "]", "}", "}", ",", "return_document", "=", "ReturnDocument", ".", "AFTER", ")", "return", "aggregation", ",", "errored_students" ]
Update aggregation and returns a list of errored students
[ "Update", "aggregation", "and", "returns", "a", "list", "of", "errored", "students" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/aggregation_edit.py#L65-L132
248,839
UCL-INGI/INGInious
inginious/frontend/pages/mycourses.py
MyCoursesPage.POST_AUTH
def POST_AUTH(self): # pylint: disable=arguments-differ """ Parse course registration or course creation and display the course list page """ username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) user_input = web.input() success = None # Handle registration to a course if "register_courseid" in user_input and user_input["register_courseid"] != "": try: course = self.course_factory.get_course(user_input["register_courseid"]) if not course.is_registration_possible(user_info): success = False else: success = self.user_manager.course_register_user(course, username, user_input.get("register_password", None)) except: success = False elif "new_courseid" in user_input and self.user_manager.user_is_superadmin(): try: courseid = user_input["new_courseid"] self.course_factory.create_course(courseid, {"name": courseid, "accessible": False}) success = True except: success = False return self.show_page(success)
python
def POST_AUTH(self): # pylint: disable=arguments-differ username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) user_input = web.input() success = None # Handle registration to a course if "register_courseid" in user_input and user_input["register_courseid"] != "": try: course = self.course_factory.get_course(user_input["register_courseid"]) if not course.is_registration_possible(user_info): success = False else: success = self.user_manager.course_register_user(course, username, user_input.get("register_password", None)) except: success = False elif "new_courseid" in user_input and self.user_manager.user_is_superadmin(): try: courseid = user_input["new_courseid"] self.course_factory.create_course(courseid, {"name": courseid, "accessible": False}) success = True except: success = False return self.show_page(success)
[ "def", "POST_AUTH", "(", "self", ")", ":", "# pylint: disable=arguments-differ", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "user_info", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"username\"", ":", "username", "}", ")", "user_input", "=", "web", ".", "input", "(", ")", "success", "=", "None", "# Handle registration to a course", "if", "\"register_courseid\"", "in", "user_input", "and", "user_input", "[", "\"register_courseid\"", "]", "!=", "\"\"", ":", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "user_input", "[", "\"register_courseid\"", "]", ")", "if", "not", "course", ".", "is_registration_possible", "(", "user_info", ")", ":", "success", "=", "False", "else", ":", "success", "=", "self", ".", "user_manager", ".", "course_register_user", "(", "course", ",", "username", ",", "user_input", ".", "get", "(", "\"register_password\"", ",", "None", ")", ")", "except", ":", "success", "=", "False", "elif", "\"new_courseid\"", "in", "user_input", "and", "self", ".", "user_manager", ".", "user_is_superadmin", "(", ")", ":", "try", ":", "courseid", "=", "user_input", "[", "\"new_courseid\"", "]", "self", ".", "course_factory", ".", "create_course", "(", "courseid", ",", "{", "\"name\"", ":", "courseid", ",", "\"accessible\"", ":", "False", "}", ")", "success", "=", "True", "except", ":", "success", "=", "False", "return", "self", ".", "show_page", "(", "success", ")" ]
Parse course registration or course creation and display the course list page
[ "Parse", "course", "registration", "or", "course", "creation", "and", "display", "the", "course", "list", "page" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/mycourses.py#L21-L47
248,840
UCL-INGI/INGInious
inginious/frontend/arch_helper.py
_restart_on_cancel
async def _restart_on_cancel(logger, agent): """ Restarts an agent when it is cancelled """ while True: try: await agent.run() except asyncio.CancelledError: logger.exception("Restarting agent") pass
python
async def _restart_on_cancel(logger, agent): while True: try: await agent.run() except asyncio.CancelledError: logger.exception("Restarting agent") pass
[ "async", "def", "_restart_on_cancel", "(", "logger", ",", "agent", ")", ":", "while", "True", ":", "try", ":", "await", "agent", ".", "run", "(", ")", "except", "asyncio", ".", "CancelledError", ":", "logger", ".", "exception", "(", "\"Restarting agent\"", ")", "pass" ]
Restarts an agent when it is cancelled
[ "Restarts", "an", "agent", "when", "it", "is", "cancelled" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/arch_helper.py#L49-L56
248,841
UCL-INGI/INGInious
inginious/frontend/pages/utils.py
INGIniousAuthPage.GET
def GET(self, *args, **kwargs): """ Checks if user is authenticated and calls GET_AUTH or performs logout. Otherwise, returns the login template. """ if self.user_manager.session_logged_in(): if not self.user_manager.session_username() and not self.__class__.__name__ == "ProfilePage": raise web.seeother("/preferences/profile") if not self.is_lti_page and self.user_manager.session_lti_info() is not None: #lti session self.user_manager.disconnect_user() return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False) return self.GET_AUTH(*args, **kwargs) else: return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False)
python
def GET(self, *args, **kwargs): if self.user_manager.session_logged_in(): if not self.user_manager.session_username() and not self.__class__.__name__ == "ProfilePage": raise web.seeother("/preferences/profile") if not self.is_lti_page and self.user_manager.session_lti_info() is not None: #lti session self.user_manager.disconnect_user() return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False) return self.GET_AUTH(*args, **kwargs) else: return self.template_helper.get_renderer().auth(self.user_manager.get_auth_methods(), False)
[ "def", "GET", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", ":", "if", "not", "self", ".", "user_manager", ".", "session_username", "(", ")", "and", "not", "self", ".", "__class__", ".", "__name__", "==", "\"ProfilePage\"", ":", "raise", "web", ".", "seeother", "(", "\"/preferences/profile\"", ")", "if", "not", "self", ".", "is_lti_page", "and", "self", ".", "user_manager", ".", "session_lti_info", "(", ")", "is", "not", "None", ":", "#lti session", "self", ".", "user_manager", ".", "disconnect_user", "(", ")", "return", "self", ".", "template_helper", ".", "get_renderer", "(", ")", ".", "auth", "(", "self", ".", "user_manager", ".", "get_auth_methods", "(", ")", ",", "False", ")", "return", "self", ".", "GET_AUTH", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "self", ".", "template_helper", ".", "get_renderer", "(", ")", ".", "auth", "(", "self", ".", "user_manager", ".", "get_auth_methods", "(", ")", ",", "False", ")" ]
Checks if user is authenticated and calls GET_AUTH or performs logout. Otherwise, returns the login template.
[ "Checks", "if", "user", "is", "authenticated", "and", "calls", "GET_AUTH", "or", "performs", "logout", ".", "Otherwise", "returns", "the", "login", "template", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/utils.py#L135-L150
248,842
UCL-INGI/INGInious
inginious/frontend/static_middleware.py
StaticMiddleware.normpath
def normpath(self, path): """ Normalize the path """ path2 = posixpath.normpath(urllib.parse.unquote(path)) if path.endswith("/"): path2 += "/" return path2
python
def normpath(self, path): path2 = posixpath.normpath(urllib.parse.unquote(path)) if path.endswith("/"): path2 += "/" return path2
[ "def", "normpath", "(", "self", ",", "path", ")", ":", "path2", "=", "posixpath", ".", "normpath", "(", "urllib", ".", "parse", ".", "unquote", "(", "path", ")", ")", "if", "path", ".", "endswith", "(", "\"/\"", ")", ":", "path2", "+=", "\"/\"", "return", "path2" ]
Normalize the path
[ "Normalize", "the", "path" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/static_middleware.py#L66-L71
248,843
UCL-INGI/INGInious
inginious/frontend/pages/api/submissions.py
_get_submissions
def _get_submissions(course_factory, submission_manager, user_manager, translations, courseid, taskid, with_input, submissionid=None): """ Helper for the GET methods of the two following classes """ try: course = course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not user_manager.course_is_open_to_user(course, lti=False): raise APIForbidden("You are not registered to this course") try: task = course.get_task(taskid) except: raise APINotFound("Task not found") if submissionid is None: submissions = submission_manager.get_user_submissions(task) else: try: submissions = [submission_manager.get_submission(submissionid)] except: raise APINotFound("Submission not found") if submissions[0]["taskid"] != task.get_id() or submissions[0]["courseid"] != course.get_id(): raise APINotFound("Submission not found") output = [] for submission in submissions: submission = submission_manager.get_feedback_from_submission( submission, show_everything=user_manager.has_staff_rights_on_course(course, user_manager.session_username()), translation=translations.get(user_manager.session_language(), gettext.NullTranslations()) ) data = { "id": str(submission["_id"]), "submitted_on": str(submission["submitted_on"]), "status": submission["status"] } if with_input: data["input"] = submission_manager.get_input_from_submission(submission, True) # base64 encode file to allow JSON encoding for d in data["input"]: if isinstance(d, dict) and d.keys() == {"filename", "value"}: d["value"] = base64.b64encode(d["value"]).decode("utf8") if submission["status"] == "done": data["grade"] = submission.get("grade", 0) data["result"] = submission.get("result", "crash") data["feedback"] = submission.get("text", "") data["problems_feedback"] = submission.get("problems", {}) output.append(data) return 200, output
python
def _get_submissions(course_factory, submission_manager, user_manager, translations, courseid, taskid, with_input, submissionid=None): try: course = course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not user_manager.course_is_open_to_user(course, lti=False): raise APIForbidden("You are not registered to this course") try: task = course.get_task(taskid) except: raise APINotFound("Task not found") if submissionid is None: submissions = submission_manager.get_user_submissions(task) else: try: submissions = [submission_manager.get_submission(submissionid)] except: raise APINotFound("Submission not found") if submissions[0]["taskid"] != task.get_id() or submissions[0]["courseid"] != course.get_id(): raise APINotFound("Submission not found") output = [] for submission in submissions: submission = submission_manager.get_feedback_from_submission( submission, show_everything=user_manager.has_staff_rights_on_course(course, user_manager.session_username()), translation=translations.get(user_manager.session_language(), gettext.NullTranslations()) ) data = { "id": str(submission["_id"]), "submitted_on": str(submission["submitted_on"]), "status": submission["status"] } if with_input: data["input"] = submission_manager.get_input_from_submission(submission, True) # base64 encode file to allow JSON encoding for d in data["input"]: if isinstance(d, dict) and d.keys() == {"filename", "value"}: d["value"] = base64.b64encode(d["value"]).decode("utf8") if submission["status"] == "done": data["grade"] = submission.get("grade", 0) data["result"] = submission.get("result", "crash") data["feedback"] = submission.get("text", "") data["problems_feedback"] = submission.get("problems", {}) output.append(data) return 200, output
[ "def", "_get_submissions", "(", "course_factory", ",", "submission_manager", ",", "user_manager", ",", "translations", ",", "courseid", ",", "taskid", ",", "with_input", ",", "submissionid", "=", "None", ")", ":", "try", ":", "course", "=", "course_factory", ".", "get_course", "(", "courseid", ")", "except", ":", "raise", "APINotFound", "(", "\"Course not found\"", ")", "if", "not", "user_manager", ".", "course_is_open_to_user", "(", "course", ",", "lti", "=", "False", ")", ":", "raise", "APIForbidden", "(", "\"You are not registered to this course\"", ")", "try", ":", "task", "=", "course", ".", "get_task", "(", "taskid", ")", "except", ":", "raise", "APINotFound", "(", "\"Task not found\"", ")", "if", "submissionid", "is", "None", ":", "submissions", "=", "submission_manager", ".", "get_user_submissions", "(", "task", ")", "else", ":", "try", ":", "submissions", "=", "[", "submission_manager", ".", "get_submission", "(", "submissionid", ")", "]", "except", ":", "raise", "APINotFound", "(", "\"Submission not found\"", ")", "if", "submissions", "[", "0", "]", "[", "\"taskid\"", "]", "!=", "task", ".", "get_id", "(", ")", "or", "submissions", "[", "0", "]", "[", "\"courseid\"", "]", "!=", "course", ".", "get_id", "(", ")", ":", "raise", "APINotFound", "(", "\"Submission not found\"", ")", "output", "=", "[", "]", "for", "submission", "in", "submissions", ":", "submission", "=", "submission_manager", ".", "get_feedback_from_submission", "(", "submission", ",", "show_everything", "=", "user_manager", ".", "has_staff_rights_on_course", "(", "course", ",", "user_manager", ".", "session_username", "(", ")", ")", ",", "translation", "=", "translations", ".", "get", "(", "user_manager", ".", "session_language", "(", ")", ",", "gettext", ".", "NullTranslations", "(", ")", ")", ")", "data", "=", "{", "\"id\"", ":", "str", "(", "submission", "[", "\"_id\"", "]", ")", ",", "\"submitted_on\"", ":", "str", "(", "submission", "[", "\"submitted_on\"", "]", ")", ",", "\"status\"", ":", "submission", "[", "\"status\"", "]", "}", "if", "with_input", ":", "data", "[", "\"input\"", "]", "=", "submission_manager", ".", "get_input_from_submission", "(", "submission", ",", "True", ")", "# base64 encode file to allow JSON encoding", "for", "d", "in", "data", "[", "\"input\"", "]", ":", "if", "isinstance", "(", "d", ",", "dict", ")", "and", "d", ".", "keys", "(", ")", "==", "{", "\"filename\"", ",", "\"value\"", "}", ":", "d", "[", "\"value\"", "]", "=", "base64", ".", "b64encode", "(", "d", "[", "\"value\"", "]", ")", ".", "decode", "(", "\"utf8\"", ")", "if", "submission", "[", "\"status\"", "]", "==", "\"done\"", ":", "data", "[", "\"grade\"", "]", "=", "submission", ".", "get", "(", "\"grade\"", ",", "0", ")", "data", "[", "\"result\"", "]", "=", "submission", ".", "get", "(", "\"result\"", ",", "\"crash\"", ")", "data", "[", "\"feedback\"", "]", "=", "submission", ".", "get", "(", "\"text\"", ",", "\"\"", ")", "data", "[", "\"problems_feedback\"", "]", "=", "submission", ".", "get", "(", "\"problems\"", ",", "{", "}", ")", "output", ".", "append", "(", "data", ")", "return", "200", ",", "output" ]
Helper for the GET methods of the two following classes
[ "Helper", "for", "the", "GET", "methods", "of", "the", "two", "following", "classes" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/submissions.py#L15-L73
248,844
UCL-INGI/INGInious
inginious/frontend/pages/api/submissions.py
APISubmissionSingle.API_GET
def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ """ List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", "submitted_on": "date", "status" : "done", #can be "done", "waiting", "error" (execution status of the task). "grade": 0.0, "input": {}, #the input data. File are base64 encoded. "result" : "success" #only if status=done. Result of the execution. "feedback": "" #only if status=done. the HTML global feedback for the task "problems_feedback": #only if status=done. HTML feedback per problem. Some pid may be absent. { "pid1": "feedback1", #... } } #... ] If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id/submissions/submissionid, this dict will contain one entry or the page will return 404 Not Found. """ with_input = "input" in web.input() return _get_submissions(self.course_factory, self.submission_manager, self.user_manager, self.app._translations, courseid, taskid, with_input, submissionid)
python
def API_GET(self, courseid, taskid, submissionid): # pylint: disable=arguments-differ with_input = "input" in web.input() return _get_submissions(self.course_factory, self.submission_manager, self.user_manager, self.app._translations, courseid, taskid, with_input, submissionid)
[ "def", "API_GET", "(", "self", ",", "courseid", ",", "taskid", ",", "submissionid", ")", ":", "# pylint: disable=arguments-differ", "with_input", "=", "\"input\"", "in", "web", ".", "input", "(", ")", "return", "_get_submissions", "(", "self", ".", "course_factory", ",", "self", ".", "submission_manager", ",", "self", ".", "user_manager", ",", "self", ".", "app", ".", "_translations", ",", "courseid", ",", "taskid", ",", "with_input", ",", "submissionid", ")" ]
List all the submissions that the connected user made. Returns list of the form :: [ { "id": "submission_id1", "submitted_on": "date", "status" : "done", #can be "done", "waiting", "error" (execution status of the task). "grade": 0.0, "input": {}, #the input data. File are base64 encoded. "result" : "success" #only if status=done. Result of the execution. "feedback": "" #only if status=done. the HTML global feedback for the task "problems_feedback": #only if status=done. HTML feedback per problem. Some pid may be absent. { "pid1": "feedback1", #... } } #... ] If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id/submissions/submissionid, this dict will contain one entry or the page will return 404 Not Found.
[ "List", "all", "the", "submissions", "that", "the", "connected", "user", "made", ".", "Returns", "list", "of", "the", "form" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/submissions.py#L81-L110
248,845
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.is_registration_possible
def is_registration_possible(self, user_info): """ Returns true if users can register for this course """ return self.get_accessibility().is_open() and self._registration.is_open() and self.is_user_accepted_by_access_control(user_info)
python
def is_registration_possible(self, user_info): return self.get_accessibility().is_open() and self._registration.is_open() and self.is_user_accepted_by_access_control(user_info)
[ "def", "is_registration_possible", "(", "self", ",", "user_info", ")", ":", "return", "self", ".", "get_accessibility", "(", ")", ".", "is_open", "(", ")", "and", "self", ".", "_registration", ".", "is_open", "(", ")", "and", "self", ".", "is_user_accepted_by_access_control", "(", "user_info", ")" ]
Returns true if users can register for this course
[ "Returns", "true", "if", "users", "can", "register", "for", "this", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L88-L90
248,846
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.get_accessibility
def get_accessibility(self, plugin_override=True): """ Return the AccessibleTime object associated with the accessibility of this course """ vals = self._hook_manager.call_hook('course_accessibility', course=self, default=self._accessible) return vals[0] if len(vals) and plugin_override else self._accessible
python
def get_accessibility(self, plugin_override=True): vals = self._hook_manager.call_hook('course_accessibility', course=self, default=self._accessible) return vals[0] if len(vals) and plugin_override else self._accessible
[ "def", "get_accessibility", "(", "self", ",", "plugin_override", "=", "True", ")", ":", "vals", "=", "self", ".", "_hook_manager", ".", "call_hook", "(", "'course_accessibility'", ",", "course", "=", "self", ",", "default", "=", "self", ".", "_accessible", ")", "return", "vals", "[", "0", "]", "if", "len", "(", "vals", ")", "and", "plugin_override", "else", "self", ".", "_accessible" ]
Return the AccessibleTime object associated with the accessibility of this course
[ "Return", "the", "AccessibleTime", "object", "associated", "with", "the", "accessibility", "of", "this", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L100-L103
248,847
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.is_user_accepted_by_access_control
def is_user_accepted_by_access_control(self, user_info): """ Returns True if the user is allowed by the ACL """ if self.get_access_control_method() is None: return True elif not user_info: return False elif self.get_access_control_method() == "username": return user_info["username"] in self.get_access_control_list() elif self.get_access_control_method() == "email": return user_info["email"] in self.get_access_control_list() elif self.get_access_control_method() == "binding": return set(user_info["bindings"].keys()).intersection(set(self.get_access_control_list())) return False
python
def is_user_accepted_by_access_control(self, user_info): if self.get_access_control_method() is None: return True elif not user_info: return False elif self.get_access_control_method() == "username": return user_info["username"] in self.get_access_control_list() elif self.get_access_control_method() == "email": return user_info["email"] in self.get_access_control_list() elif self.get_access_control_method() == "binding": return set(user_info["bindings"].keys()).intersection(set(self.get_access_control_list())) return False
[ "def", "is_user_accepted_by_access_control", "(", "self", ",", "user_info", ")", ":", "if", "self", ".", "get_access_control_method", "(", ")", "is", "None", ":", "return", "True", "elif", "not", "user_info", ":", "return", "False", "elif", "self", ".", "get_access_control_method", "(", ")", "==", "\"username\"", ":", "return", "user_info", "[", "\"username\"", "]", "in", "self", ".", "get_access_control_list", "(", ")", "elif", "self", ".", "get_access_control_method", "(", ")", "==", "\"email\"", ":", "return", "user_info", "[", "\"email\"", "]", "in", "self", ".", "get_access_control_list", "(", ")", "elif", "self", ".", "get_access_control_method", "(", ")", "==", "\"binding\"", ":", "return", "set", "(", "user_info", "[", "\"bindings\"", "]", ".", "keys", "(", ")", ")", ".", "intersection", "(", "set", "(", "self", ".", "get_access_control_list", "(", ")", ")", ")", "return", "False" ]
Returns True if the user is allowed by the ACL
[ "Returns", "True", "if", "the", "user", "is", "allowed", "by", "the", "ACL" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L140-L152
248,848
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.allow_unregister
def allow_unregister(self, plugin_override=True): """ Returns True if students can unregister from course """ vals = self._hook_manager.call_hook('course_allow_unregister', course=self, default=self._allow_unregister) return vals[0] if len(vals) and plugin_override else self._allow_unregister
python
def allow_unregister(self, plugin_override=True): vals = self._hook_manager.call_hook('course_allow_unregister', course=self, default=self._allow_unregister) return vals[0] if len(vals) and plugin_override else self._allow_unregister
[ "def", "allow_unregister", "(", "self", ",", "plugin_override", "=", "True", ")", ":", "vals", "=", "self", ".", "_hook_manager", ".", "call_hook", "(", "'course_allow_unregister'", ",", "course", "=", "self", ",", "default", "=", "self", ".", "_allow_unregister", ")", "return", "vals", "[", "0", "]", "if", "len", "(", "vals", ")", "and", "plugin_override", "else", "self", ".", "_allow_unregister" ]
Returns True if students can unregister from course
[ "Returns", "True", "if", "students", "can", "unregister", "from", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L157-L160
248,849
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.get_name
def get_name(self, language): """ Return the name of this course """ return self.gettext(language, self._name) if self._name else ""
python
def get_name(self, language): return self.gettext(language, self._name) if self._name else ""
[ "def", "get_name", "(", "self", ",", "language", ")", ":", "return", "self", ".", "gettext", "(", "language", ",", "self", ".", "_name", ")", "if", "self", ".", "_name", "else", "\"\"" ]
Return the name of this course
[ "Return", "the", "name", "of", "this", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L162-L164
248,850
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.get_description
def get_description(self, language): """Returns the course description """ description = self.gettext(language, self._description) if self._description else '' return ParsableText(description, "rst", self._translations.get(language, gettext.NullTranslations()))
python
def get_description(self, language): description = self.gettext(language, self._description) if self._description else '' return ParsableText(description, "rst", self._translations.get(language, gettext.NullTranslations()))
[ "def", "get_description", "(", "self", ",", "language", ")", ":", "description", "=", "self", ".", "gettext", "(", "language", ",", "self", ".", "_description", ")", "if", "self", ".", "_description", "else", "''", "return", "ParsableText", "(", "description", ",", "\"rst\"", ",", "self", ".", "_translations", ".", "get", "(", "language", ",", "gettext", ".", "NullTranslations", "(", ")", ")", ")" ]
Returns the course description
[ "Returns", "the", "course", "description" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L166-L169
248,851
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.get_all_tags_names_as_list
def get_all_tags_names_as_list(self, admin=False, language="en"): """ Computes and cache two list containing all tags name sorted by natural order on name """ if admin: if self._all_tags_cache_list_admin != {} and language in self._all_tags_cache_list_admin: return self._all_tags_cache_list_admin[language] #Cache hit else: if self._all_tags_cache_list != {} and language in self._all_tags_cache_list: return self._all_tags_cache_list[language] #Cache hit #Cache miss, computes everything s_stud = set() s_admin = set() (common, _, org) = self.get_all_tags() for tag in common + org: # Is tag_name_with_translation correct by doing that like that ? tag_name_with_translation = self.gettext(language, tag.get_name()) if tag.get_name() else "" s_admin.add(tag_name_with_translation) if tag.is_visible_for_student(): s_stud.add(tag_name_with_translation) self._all_tags_cache_list_admin[language] = natsorted(s_admin, key=lambda y: y.lower()) self._all_tags_cache_list[language] = natsorted(s_stud, key=lambda y: y.lower()) if admin: return self._all_tags_cache_list_admin[language] return self._all_tags_cache_list[language]
python
def get_all_tags_names_as_list(self, admin=False, language="en"): if admin: if self._all_tags_cache_list_admin != {} and language in self._all_tags_cache_list_admin: return self._all_tags_cache_list_admin[language] #Cache hit else: if self._all_tags_cache_list != {} and language in self._all_tags_cache_list: return self._all_tags_cache_list[language] #Cache hit #Cache miss, computes everything s_stud = set() s_admin = set() (common, _, org) = self.get_all_tags() for tag in common + org: # Is tag_name_with_translation correct by doing that like that ? tag_name_with_translation = self.gettext(language, tag.get_name()) if tag.get_name() else "" s_admin.add(tag_name_with_translation) if tag.is_visible_for_student(): s_stud.add(tag_name_with_translation) self._all_tags_cache_list_admin[language] = natsorted(s_admin, key=lambda y: y.lower()) self._all_tags_cache_list[language] = natsorted(s_stud, key=lambda y: y.lower()) if admin: return self._all_tags_cache_list_admin[language] return self._all_tags_cache_list[language]
[ "def", "get_all_tags_names_as_list", "(", "self", ",", "admin", "=", "False", ",", "language", "=", "\"en\"", ")", ":", "if", "admin", ":", "if", "self", ".", "_all_tags_cache_list_admin", "!=", "{", "}", "and", "language", "in", "self", ".", "_all_tags_cache_list_admin", ":", "return", "self", ".", "_all_tags_cache_list_admin", "[", "language", "]", "#Cache hit", "else", ":", "if", "self", ".", "_all_tags_cache_list", "!=", "{", "}", "and", "language", "in", "self", ".", "_all_tags_cache_list", ":", "return", "self", ".", "_all_tags_cache_list", "[", "language", "]", "#Cache hit", "#Cache miss, computes everything", "s_stud", "=", "set", "(", ")", "s_admin", "=", "set", "(", ")", "(", "common", ",", "_", ",", "org", ")", "=", "self", ".", "get_all_tags", "(", ")", "for", "tag", "in", "common", "+", "org", ":", "# Is tag_name_with_translation correct by doing that like that ?", "tag_name_with_translation", "=", "self", ".", "gettext", "(", "language", ",", "tag", ".", "get_name", "(", ")", ")", "if", "tag", ".", "get_name", "(", ")", "else", "\"\"", "s_admin", ".", "add", "(", "tag_name_with_translation", ")", "if", "tag", ".", "is_visible_for_student", "(", ")", ":", "s_stud", ".", "add", "(", "tag_name_with_translation", ")", "self", ".", "_all_tags_cache_list_admin", "[", "language", "]", "=", "natsorted", "(", "s_admin", ",", "key", "=", "lambda", "y", ":", "y", ".", "lower", "(", ")", ")", "self", ".", "_all_tags_cache_list", "[", "language", "]", "=", "natsorted", "(", "s_stud", ",", "key", "=", "lambda", "y", ":", "y", ".", "lower", "(", ")", ")", "if", "admin", ":", "return", "self", ".", "_all_tags_cache_list_admin", "[", "language", "]", "return", "self", ".", "_all_tags_cache_list", "[", "language", "]" ]
Computes and cache two list containing all tags name sorted by natural order on name
[ "Computes", "and", "cache", "two", "list", "containing", "all", "tags", "name", "sorted", "by", "natural", "order", "on", "name" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L200-L225
248,852
UCL-INGI/INGInious
inginious/frontend/courses.py
WebAppCourse.update_all_tags_cache
def update_all_tags_cache(self): """ Force the cache refreshing """ self._all_tags_cache = None self._all_tags_cache_list = {} self._all_tags_cache_list_admin = {} self._organisational_tags_to_task = {} self.get_all_tags() self.get_all_tags_names_as_list() self.get_organisational_tags_to_task()
python
def update_all_tags_cache(self): self._all_tags_cache = None self._all_tags_cache_list = {} self._all_tags_cache_list_admin = {} self._organisational_tags_to_task = {} self.get_all_tags() self.get_all_tags_names_as_list() self.get_organisational_tags_to_task()
[ "def", "update_all_tags_cache", "(", "self", ")", ":", "self", ".", "_all_tags_cache", "=", "None", "self", ".", "_all_tags_cache_list", "=", "{", "}", "self", ".", "_all_tags_cache_list_admin", "=", "{", "}", "self", ".", "_organisational_tags_to_task", "=", "{", "}", "self", ".", "get_all_tags", "(", ")", "self", ".", "get_all_tags_names_as_list", "(", ")", "self", ".", "get_organisational_tags_to_task", "(", ")" ]
Force the cache refreshing
[ "Force", "the", "cache", "refreshing" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/courses.py#L243-L253
248,853
UCL-INGI/INGInious
inginious/frontend/webdav.py
get_app
def get_app(config): """ Init the webdav app """ mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost')) database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')] # Create the FS provider if "tasks_directory" not in config: raise RuntimeError("WebDav access is only supported if INGInious is using a local filesystem to access tasks") fs_provider = LocalFSProvider(config["tasks_directory"]) course_factory, task_factory = create_factories(fs_provider, {}, None, WebAppCourse, WebAppTask) user_manager = UserManager(MongoStore(database, 'sessions'), database, config.get('superadmins', [])) config = dict(wsgidav_app.DEFAULT_CONFIG) config["provider_mapping"] = {"/": INGIniousFilesystemProvider(course_factory, task_factory)} config["domaincontroller"] = INGIniousDAVDomainController(user_manager, course_factory) config["verbose"] = 0 app = wsgidav_app.WsgiDAVApp(config) return app
python
def get_app(config): mongo_client = MongoClient(host=config.get('mongo_opt', {}).get('host', 'localhost')) database = mongo_client[config.get('mongo_opt', {}).get('database', 'INGInious')] # Create the FS provider if "tasks_directory" not in config: raise RuntimeError("WebDav access is only supported if INGInious is using a local filesystem to access tasks") fs_provider = LocalFSProvider(config["tasks_directory"]) course_factory, task_factory = create_factories(fs_provider, {}, None, WebAppCourse, WebAppTask) user_manager = UserManager(MongoStore(database, 'sessions'), database, config.get('superadmins', [])) config = dict(wsgidav_app.DEFAULT_CONFIG) config["provider_mapping"] = {"/": INGIniousFilesystemProvider(course_factory, task_factory)} config["domaincontroller"] = INGIniousDAVDomainController(user_manager, course_factory) config["verbose"] = 0 app = wsgidav_app.WsgiDAVApp(config) return app
[ "def", "get_app", "(", "config", ")", ":", "mongo_client", "=", "MongoClient", "(", "host", "=", "config", ".", "get", "(", "'mongo_opt'", ",", "{", "}", ")", ".", "get", "(", "'host'", ",", "'localhost'", ")", ")", "database", "=", "mongo_client", "[", "config", ".", "get", "(", "'mongo_opt'", ",", "{", "}", ")", ".", "get", "(", "'database'", ",", "'INGInious'", ")", "]", "# Create the FS provider", "if", "\"tasks_directory\"", "not", "in", "config", ":", "raise", "RuntimeError", "(", "\"WebDav access is only supported if INGInious is using a local filesystem to access tasks\"", ")", "fs_provider", "=", "LocalFSProvider", "(", "config", "[", "\"tasks_directory\"", "]", ")", "course_factory", ",", "task_factory", "=", "create_factories", "(", "fs_provider", ",", "{", "}", ",", "None", ",", "WebAppCourse", ",", "WebAppTask", ")", "user_manager", "=", "UserManager", "(", "MongoStore", "(", "database", ",", "'sessions'", ")", ",", "database", ",", "config", ".", "get", "(", "'superadmins'", ",", "[", "]", ")", ")", "config", "=", "dict", "(", "wsgidav_app", ".", "DEFAULT_CONFIG", ")", "config", "[", "\"provider_mapping\"", "]", "=", "{", "\"/\"", ":", "INGIniousFilesystemProvider", "(", "course_factory", ",", "task_factory", ")", "}", "config", "[", "\"domaincontroller\"", "]", "=", "INGIniousDAVDomainController", "(", "user_manager", ",", "course_factory", ")", "config", "[", "\"verbose\"", "]", "=", "0", "app", "=", "wsgidav_app", ".", "WsgiDAVApp", "(", "config", ")", "return", "app" ]
Init the webdav app
[ "Init", "the", "webdav", "app" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L120-L140
248,854
UCL-INGI/INGInious
inginious/frontend/webdav.py
INGIniousDAVDomainController.getDomainRealm
def getDomainRealm(self, inputURL, environ): """Resolve a relative url to the appropriate realm name.""" # we don't get the realm here, its already been resolved in # request_resolver if inputURL.startswith("/"): inputURL = inputURL[1:] parts = inputURL.split("/") return parts[0]
python
def getDomainRealm(self, inputURL, environ): # we don't get the realm here, its already been resolved in # request_resolver if inputURL.startswith("/"): inputURL = inputURL[1:] parts = inputURL.split("/") return parts[0]
[ "def", "getDomainRealm", "(", "self", ",", "inputURL", ",", "environ", ")", ":", "# we don't get the realm here, its already been resolved in", "# request_resolver", "if", "inputURL", ".", "startswith", "(", "\"/\"", ")", ":", "inputURL", "=", "inputURL", "[", "1", ":", "]", "parts", "=", "inputURL", ".", "split", "(", "\"/\"", ")", "return", "parts", "[", "0", "]" ]
Resolve a relative url to the appropriate realm name.
[ "Resolve", "a", "relative", "url", "to", "the", "appropriate", "realm", "name", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L30-L37
248,855
UCL-INGI/INGInious
inginious/frontend/webdav.py
INGIniousDAVDomainController.isRealmUser
def isRealmUser(self, realmname, username, environ): """Returns True if this username is valid for the realm, False otherwise.""" try: course = self.course_factory.get_course(realmname) ok = self.user_manager.has_admin_rights_on_course(course, username=username) return ok except: return False
python
def isRealmUser(self, realmname, username, environ): try: course = self.course_factory.get_course(realmname) ok = self.user_manager.has_admin_rights_on_course(course, username=username) return ok except: return False
[ "def", "isRealmUser", "(", "self", ",", "realmname", ",", "username", ",", "environ", ")", ":", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "realmname", ")", "ok", "=", "self", ".", "user_manager", ".", "has_admin_rights_on_course", "(", "course", ",", "username", "=", "username", ")", "return", "ok", "except", ":", "return", "False" ]
Returns True if this username is valid for the realm, False otherwise.
[ "Returns", "True", "if", "this", "username", "is", "valid", "for", "the", "realm", "False", "otherwise", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L44-L51
248,856
UCL-INGI/INGInious
inginious/frontend/webdav.py
INGIniousDAVDomainController.getRealmUserPassword
def getRealmUserPassword(self, realmname, username, environ): """Return the password for the given username for the realm. Used for digest authentication. """ return self.user_manager.get_user_api_key(username, create=True)
python
def getRealmUserPassword(self, realmname, username, environ): return self.user_manager.get_user_api_key(username, create=True)
[ "def", "getRealmUserPassword", "(", "self", ",", "realmname", ",", "username", ",", "environ", ")", ":", "return", "self", ".", "user_manager", ".", "get_user_api_key", "(", "username", ",", "create", "=", "True", ")" ]
Return the password for the given username for the realm. Used for digest authentication.
[ "Return", "the", "password", "for", "the", "given", "username", "for", "the", "realm", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L53-L58
248,857
UCL-INGI/INGInious
inginious/frontend/webdav.py
INGIniousFilesystemProvider.getResourceInst
def getResourceInst(self, path, environ): """Return info dictionary for path. See DAVProvider.getResourceInst() """ self._count_getResourceInst += 1 fp = self._locToFilePath(path) if not os.path.exists(fp): return None if os.path.isdir(fp): return FolderResource(path, environ, fp) return FileResource(path, environ, fp)
python
def getResourceInst(self, path, environ): self._count_getResourceInst += 1 fp = self._locToFilePath(path) if not os.path.exists(fp): return None if os.path.isdir(fp): return FolderResource(path, environ, fp) return FileResource(path, environ, fp)
[ "def", "getResourceInst", "(", "self", ",", "path", ",", "environ", ")", ":", "self", ".", "_count_getResourceInst", "+=", "1", "fp", "=", "self", ".", "_locToFilePath", "(", "path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "fp", ")", ":", "return", "None", "if", "os", ".", "path", ".", "isdir", "(", "fp", ")", ":", "return", "FolderResource", "(", "path", ",", "environ", ",", "fp", ")", "return", "FileResource", "(", "path", ",", "environ", ",", "fp", ")" ]
Return info dictionary for path. See DAVProvider.getResourceInst()
[ "Return", "info", "dictionary", "for", "path", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/webdav.py#L105-L117
248,858
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit.py
CourseEditTask.contains_is_html
def contains_is_html(cls, data): """ Detect if the problem has at least one "xyzIsHTML" key """ for key, val in data.items(): if isinstance(key, str) and key.endswith("IsHTML"): return True if isinstance(val, (OrderedDict, dict)) and cls.contains_is_html(val): return True return False
python
def contains_is_html(cls, data): for key, val in data.items(): if isinstance(key, str) and key.endswith("IsHTML"): return True if isinstance(val, (OrderedDict, dict)) and cls.contains_is_html(val): return True return False
[ "def", "contains_is_html", "(", "cls", ",", "data", ")", ":", "for", "key", ",", "val", "in", "data", ".", "items", "(", ")", ":", "if", "isinstance", "(", "key", ",", "str", ")", "and", "key", ".", "endswith", "(", "\"IsHTML\"", ")", ":", "return", "True", "if", "isinstance", "(", "val", ",", "(", "OrderedDict", ",", "dict", ")", ")", "and", "cls", ".", "contains_is_html", "(", "val", ")", ":", "return", "True", "return", "False" ]
Detect if the problem has at least one "xyzIsHTML" key
[ "Detect", "if", "the", "problem", "has", "at", "least", "one", "xyzIsHTML", "key" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit.py#L73-L80
248,859
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit.py
CourseEditTask.parse_problem
def parse_problem(self, problem_content): """ Parses a problem, modifying some data """ del problem_content["@order"] return self.task_factory.get_problem_types().get(problem_content["type"]).parse_problem(problem_content)
python
def parse_problem(self, problem_content): del problem_content["@order"] return self.task_factory.get_problem_types().get(problem_content["type"]).parse_problem(problem_content)
[ "def", "parse_problem", "(", "self", ",", "problem_content", ")", ":", "del", "problem_content", "[", "\"@order\"", "]", "return", "self", ".", "task_factory", ".", "get_problem_types", "(", ")", ".", "get", "(", "problem_content", "[", "\"type\"", "]", ")", ".", "parse_problem", "(", "problem_content", ")" ]
Parses a problem, modifying some data
[ "Parses", "a", "problem", "modifying", "some", "data" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit.py#L113-L116
248,860
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit.py
CourseEditTask.wipe_task
def wipe_task(self, courseid, taskid): """ Wipe the data associated to the taskid from DB""" submissions = self.database.submissions.find({"courseid": courseid, "taskid": taskid}) for submission in submissions: for key in ["input", "archive"]: if key in submission and type(submission[key]) == bson.objectid.ObjectId: self.submission_manager.get_gridfs().delete(submission[key]) self.database.aggregations.remove({"courseid": courseid, "taskid": taskid}) self.database.user_tasks.remove({"courseid": courseid, "taskid": taskid}) self.database.submissions.remove({"courseid": courseid, "taskid": taskid}) self._logger.info("Task %s/%s wiped.", courseid, taskid)
python
def wipe_task(self, courseid, taskid): submissions = self.database.submissions.find({"courseid": courseid, "taskid": taskid}) for submission in submissions: for key in ["input", "archive"]: if key in submission and type(submission[key]) == bson.objectid.ObjectId: self.submission_manager.get_gridfs().delete(submission[key]) self.database.aggregations.remove({"courseid": courseid, "taskid": taskid}) self.database.user_tasks.remove({"courseid": courseid, "taskid": taskid}) self.database.submissions.remove({"courseid": courseid, "taskid": taskid}) self._logger.info("Task %s/%s wiped.", courseid, taskid)
[ "def", "wipe_task", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "submissions", "=", "self", ".", "database", ".", "submissions", ".", "find", "(", "{", "\"courseid\"", ":", "courseid", ",", "\"taskid\"", ":", "taskid", "}", ")", "for", "submission", "in", "submissions", ":", "for", "key", "in", "[", "\"input\"", ",", "\"archive\"", "]", ":", "if", "key", "in", "submission", "and", "type", "(", "submission", "[", "key", "]", ")", "==", "bson", ".", "objectid", ".", "ObjectId", ":", "self", ".", "submission_manager", ".", "get_gridfs", "(", ")", ".", "delete", "(", "submission", "[", "key", "]", ")", "self", ".", "database", ".", "aggregations", ".", "remove", "(", "{", "\"courseid\"", ":", "courseid", ",", "\"taskid\"", ":", "taskid", "}", ")", "self", ".", "database", ".", "user_tasks", ".", "remove", "(", "{", "\"courseid\"", ":", "courseid", ",", "\"taskid\"", ":", "taskid", "}", ")", "self", ".", "database", ".", "submissions", ".", "remove", "(", "{", "\"courseid\"", ":", "courseid", ",", "\"taskid\"", ":", "taskid", "}", ")", "self", ".", "_logger", ".", "info", "(", "\"Task %s/%s wiped.\"", ",", "courseid", ",", "taskid", ")" ]
Wipe the data associated to the taskid from DB
[ "Wipe", "the", "data", "associated", "to", "the", "taskid", "from", "DB" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit.py#L118-L130
248,861
UCL-INGI/INGInious
inginious/common/hook_manager.py
HookManager._exception_free_callback
def _exception_free_callback(self, callback, *args, **kwargs): """ A wrapper that remove all exceptions raised from hooks """ try: return callback(*args, **kwargs) except Exception: self._logger.exception("An exception occurred while calling a hook! ",exc_info=True) return None
python
def _exception_free_callback(self, callback, *args, **kwargs): try: return callback(*args, **kwargs) except Exception: self._logger.exception("An exception occurred while calling a hook! ",exc_info=True) return None
[ "def", "_exception_free_callback", "(", "self", ",", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "callback", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "self", ".", "_logger", ".", "exception", "(", "\"An exception occurred while calling a hook! \"", ",", "exc_info", "=", "True", ")", "return", "None" ]
A wrapper that remove all exceptions raised from hooks
[ "A", "wrapper", "that", "remove", "all", "exceptions", "raised", "from", "hooks" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/hook_manager.py#L18-L24
248,862
UCL-INGI/INGInious
inginious/common/hook_manager.py
HookManager.add_hook
def add_hook(self, name, callback, prio=0): """ Add a new hook that can be called with the call_hook function. `prio` is the priority. Higher priority hooks are called before lower priority ones. This function does not enforce a particular order between hooks with the same priorities. """ hook_list = self._hooks.get(name, []) add = (lambda *args, **kwargs: self._exception_free_callback(callback, *args, **kwargs)), -prio pos = bisect.bisect_right(list(x[1] for x in hook_list), -prio) hook_list[pos:pos] = [add] self._hooks[name] = hook_list
python
def add_hook(self, name, callback, prio=0): hook_list = self._hooks.get(name, []) add = (lambda *args, **kwargs: self._exception_free_callback(callback, *args, **kwargs)), -prio pos = bisect.bisect_right(list(x[1] for x in hook_list), -prio) hook_list[pos:pos] = [add] self._hooks[name] = hook_list
[ "def", "add_hook", "(", "self", ",", "name", ",", "callback", ",", "prio", "=", "0", ")", ":", "hook_list", "=", "self", ".", "_hooks", ".", "get", "(", "name", ",", "[", "]", ")", "add", "=", "(", "lambda", "*", "args", ",", "*", "*", "kwargs", ":", "self", ".", "_exception_free_callback", "(", "callback", ",", "*", "args", ",", "*", "*", "kwargs", ")", ")", ",", "-", "prio", "pos", "=", "bisect", ".", "bisect_right", "(", "list", "(", "x", "[", "1", "]", "for", "x", "in", "hook_list", ")", ",", "-", "prio", ")", "hook_list", "[", "pos", ":", "pos", "]", "=", "[", "add", "]", "self", ".", "_hooks", "[", "name", "]", "=", "hook_list" ]
Add a new hook that can be called with the call_hook function. `prio` is the priority. Higher priority hooks are called before lower priority ones. This function does not enforce a particular order between hooks with the same priorities.
[ "Add", "a", "new", "hook", "that", "can", "be", "called", "with", "the", "call_hook", "function", ".", "prio", "is", "the", "priority", ".", "Higher", "priority", "hooks", "are", "called", "before", "lower", "priority", "ones", ".", "This", "function", "does", "not", "enforce", "a", "particular", "order", "between", "hooks", "with", "the", "same", "priorities", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/hook_manager.py#L26-L37
248,863
UCL-INGI/INGInious
inginious/common/tasks.py
Task.input_is_consistent
def input_is_consistent(self, task_input, default_allowed_extension, default_max_size): """ Check if an input for a task is consistent. Return true if this is case, false else """ for problem in self._problems: if not problem.input_is_consistent(task_input, default_allowed_extension, default_max_size): return False return True
python
def input_is_consistent(self, task_input, default_allowed_extension, default_max_size): for problem in self._problems: if not problem.input_is_consistent(task_input, default_allowed_extension, default_max_size): return False return True
[ "def", "input_is_consistent", "(", "self", ",", "task_input", ",", "default_allowed_extension", ",", "default_max_size", ")", ":", "for", "problem", "in", "self", ".", "_problems", ":", "if", "not", "problem", ".", "input_is_consistent", "(", "task_input", ",", "default_allowed_extension", ",", "default_max_size", ")", ":", "return", "False", "return", "True" ]
Check if an input for a task is consistent. Return true if this is case, false else
[ "Check", "if", "an", "input", "for", "a", "task", "is", "consistent", ".", "Return", "true", "if", "this", "is", "case", "false", "else" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tasks.py#L75-L80
248,864
UCL-INGI/INGInious
inginious/common/tasks.py
Task.get_limits
def get_limits(self): """ Return the limits of this task """ vals = self._hook_manager.call_hook('task_limits', course=self.get_course(), task=self, default=self._limits) return vals[0] if len(vals) else self._limits
python
def get_limits(self): vals = self._hook_manager.call_hook('task_limits', course=self.get_course(), task=self, default=self._limits) return vals[0] if len(vals) else self._limits
[ "def", "get_limits", "(", "self", ")", ":", "vals", "=", "self", ".", "_hook_manager", ".", "call_hook", "(", "'task_limits'", ",", "course", "=", "self", ".", "get_course", "(", ")", ",", "task", "=", "self", ",", "default", "=", "self", ".", "_limits", ")", "return", "vals", "[", "0", "]", "if", "len", "(", "vals", ")", "else", "self", ".", "_limits" ]
Return the limits of this task
[ "Return", "the", "limits", "of", "this", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tasks.py#L106-L109
248,865
UCL-INGI/INGInious
inginious/common/tasks.py
Task.allow_network_access_grading
def allow_network_access_grading(self): """ Return True if the grading container should have access to the network """ vals = self._hook_manager.call_hook('task_network_grading', course=self.get_course(), task=self, default=self._network_grading) return vals[0] if len(vals) else self._network_grading
python
def allow_network_access_grading(self): vals = self._hook_manager.call_hook('task_network_grading', course=self.get_course(), task=self, default=self._network_grading) return vals[0] if len(vals) else self._network_grading
[ "def", "allow_network_access_grading", "(", "self", ")", ":", "vals", "=", "self", ".", "_hook_manager", ".", "call_hook", "(", "'task_network_grading'", ",", "course", "=", "self", ".", "get_course", "(", ")", ",", "task", "=", "self", ",", "default", "=", "self", ".", "_network_grading", ")", "return", "vals", "[", "0", "]", "if", "len", "(", "vals", ")", "else", "self", ".", "_network_grading" ]
Return True if the grading container should have access to the network
[ "Return", "True", "if", "the", "grading", "container", "should", "have", "access", "to", "the", "network" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tasks.py#L111-L114
248,866
UCL-INGI/INGInious
inginious/common/tasks.py
Task._create_task_problem
def _create_task_problem(self, problemid, problem_content, task_problem_types): """Creates a new instance of the right class for a given problem.""" # Basic checks if not id_checker(problemid): raise Exception("Invalid problem _id: " + problemid) if problem_content.get('type', "") not in task_problem_types: raise Exception("Invalid type for problem " + problemid) return task_problem_types.get(problem_content.get('type', ""))(self, problemid, problem_content, self._translations)
python
def _create_task_problem(self, problemid, problem_content, task_problem_types): # Basic checks if not id_checker(problemid): raise Exception("Invalid problem _id: " + problemid) if problem_content.get('type', "") not in task_problem_types: raise Exception("Invalid type for problem " + problemid) return task_problem_types.get(problem_content.get('type', ""))(self, problemid, problem_content, self._translations)
[ "def", "_create_task_problem", "(", "self", ",", "problemid", ",", "problem_content", ",", "task_problem_types", ")", ":", "# Basic checks", "if", "not", "id_checker", "(", "problemid", ")", ":", "raise", "Exception", "(", "\"Invalid problem _id: \"", "+", "problemid", ")", "if", "problem_content", ".", "get", "(", "'type'", ",", "\"\"", ")", "not", "in", "task_problem_types", ":", "raise", "Exception", "(", "\"Invalid type for problem \"", "+", "problemid", ")", "return", "task_problem_types", ".", "get", "(", "problem_content", ".", "get", "(", "'type'", ",", "\"\"", ")", ")", "(", "self", ",", "problemid", ",", "problem_content", ",", "self", ".", "_translations", ")" ]
Creates a new instance of the right class for a given problem.
[ "Creates", "a", "new", "instance", "of", "the", "right", "class", "for", "a", "given", "problem", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tasks.py#L162-L170
248,867
UCL-INGI/INGInious
inginious/frontend/plugins/scoreboard/__init__.py
course_menu
def course_menu(course, template_helper): """ Displays the link to the scoreboards on the course page, if the plugin is activated for this course """ scoreboards = course.get_descriptor().get('scoreboard', []) if scoreboards != []: return str(template_helper.get_custom_renderer('frontend/plugins/scoreboard', layout=False).course_menu(course)) else: return None
python
def course_menu(course, template_helper): scoreboards = course.get_descriptor().get('scoreboard', []) if scoreboards != []: return str(template_helper.get_custom_renderer('frontend/plugins/scoreboard', layout=False).course_menu(course)) else: return None
[ "def", "course_menu", "(", "course", ",", "template_helper", ")", ":", "scoreboards", "=", "course", ".", "get_descriptor", "(", ")", ".", "get", "(", "'scoreboard'", ",", "[", "]", ")", "if", "scoreboards", "!=", "[", "]", ":", "return", "str", "(", "template_helper", ".", "get_custom_renderer", "(", "'frontend/plugins/scoreboard'", ",", "layout", "=", "False", ")", ".", "course_menu", "(", "course", ")", ")", "else", ":", "return", "None" ]
Displays the link to the scoreboards on the course page, if the plugin is activated for this course
[ "Displays", "the", "link", "to", "the", "scoreboards", "on", "the", "course", "page", "if", "the", "plugin", "is", "activated", "for", "this", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/scoreboard/__init__.py#L172-L179
248,868
UCL-INGI/INGInious
inginious/frontend/plugins/scoreboard/__init__.py
task_menu
def task_menu(course, task, template_helper): """ Displays the link to the scoreboards on the task page, if the plugin is activated for this course and the task is used in scoreboards """ scoreboards = course.get_descriptor().get('scoreboard', []) try: tolink = [] for sid, scoreboard in enumerate(scoreboards): if task.get_id() in scoreboard["content"]: tolink.append((sid, scoreboard["name"])) if tolink: return str(template_helper.get_custom_renderer('frontend/plugins/scoreboard', layout=False).task_menu(course, tolink)) return None except: return None
python
def task_menu(course, task, template_helper): scoreboards = course.get_descriptor().get('scoreboard', []) try: tolink = [] for sid, scoreboard in enumerate(scoreboards): if task.get_id() in scoreboard["content"]: tolink.append((sid, scoreboard["name"])) if tolink: return str(template_helper.get_custom_renderer('frontend/plugins/scoreboard', layout=False).task_menu(course, tolink)) return None except: return None
[ "def", "task_menu", "(", "course", ",", "task", ",", "template_helper", ")", ":", "scoreboards", "=", "course", ".", "get_descriptor", "(", ")", ".", "get", "(", "'scoreboard'", ",", "[", "]", ")", "try", ":", "tolink", "=", "[", "]", "for", "sid", ",", "scoreboard", "in", "enumerate", "(", "scoreboards", ")", ":", "if", "task", ".", "get_id", "(", ")", "in", "scoreboard", "[", "\"content\"", "]", ":", "tolink", ".", "append", "(", "(", "sid", ",", "scoreboard", "[", "\"name\"", "]", ")", ")", "if", "tolink", ":", "return", "str", "(", "template_helper", ".", "get_custom_renderer", "(", "'frontend/plugins/scoreboard'", ",", "layout", "=", "False", ")", ".", "task_menu", "(", "course", ",", "tolink", ")", ")", "return", "None", "except", ":", "return", "None" ]
Displays the link to the scoreboards on the task page, if the plugin is activated for this course and the task is used in scoreboards
[ "Displays", "the", "link", "to", "the", "scoreboards", "on", "the", "task", "page", "if", "the", "plugin", "is", "activated", "for", "this", "course", "and", "the", "task", "is", "used", "in", "scoreboards" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/scoreboard/__init__.py#L182-L195
248,869
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/classroom_edit.py
CourseEditClassroom.get_user_lists
def get_user_lists(self, course, classroomid): """ Get the available student and tutor lists for classroom edition""" tutor_list = course.get_staff() # Determine if user is grouped or not in the classroom student_list = list(self.database.classrooms.aggregate([ {"$match": {"_id": ObjectId(classroomid)}}, {"$unwind": "$students"}, {"$project": { "students": 1, "grouped": { "$anyElementTrue": { "$map": { "input": "$groups.students", "as": "group", "in": { "$anyElementTrue": { "$map": { "input": "$$group", "as": "groupmember", "in": {"$eq": ["$$groupmember", "$students"]} } } } } } } }} ])) student_list = dict([(student["students"], student) for student in student_list]) other_students = [entry['students'] for entry in list(self.database.classrooms.aggregate([ {"$match": {"courseid": course.get_id(), "_id": {"$ne": ObjectId(classroomid)}}}, {"$unwind": "$students"}, {"$project": {"_id": 0, "students": 1}} ]))] users_info = self.user_manager.get_users_info(other_students + list(student_list.keys()) + tutor_list) # Order the non-registered students other_students = sorted(other_students, key=lambda val: (("0"+users_info[val][0]) if users_info[val] else ("1"+val))) return student_list, tutor_list, other_students, users_info
python
def get_user_lists(self, course, classroomid): tutor_list = course.get_staff() # Determine if user is grouped or not in the classroom student_list = list(self.database.classrooms.aggregate([ {"$match": {"_id": ObjectId(classroomid)}}, {"$unwind": "$students"}, {"$project": { "students": 1, "grouped": { "$anyElementTrue": { "$map": { "input": "$groups.students", "as": "group", "in": { "$anyElementTrue": { "$map": { "input": "$$group", "as": "groupmember", "in": {"$eq": ["$$groupmember", "$students"]} } } } } } } }} ])) student_list = dict([(student["students"], student) for student in student_list]) other_students = [entry['students'] for entry in list(self.database.classrooms.aggregate([ {"$match": {"courseid": course.get_id(), "_id": {"$ne": ObjectId(classroomid)}}}, {"$unwind": "$students"}, {"$project": {"_id": 0, "students": 1}} ]))] users_info = self.user_manager.get_users_info(other_students + list(student_list.keys()) + tutor_list) # Order the non-registered students other_students = sorted(other_students, key=lambda val: (("0"+users_info[val][0]) if users_info[val] else ("1"+val))) return student_list, tutor_list, other_students, users_info
[ "def", "get_user_lists", "(", "self", ",", "course", ",", "classroomid", ")", ":", "tutor_list", "=", "course", ".", "get_staff", "(", ")", "# Determine if user is grouped or not in the classroom", "student_list", "=", "list", "(", "self", ".", "database", ".", "classrooms", ".", "aggregate", "(", "[", "{", "\"$match\"", ":", "{", "\"_id\"", ":", "ObjectId", "(", "classroomid", ")", "}", "}", ",", "{", "\"$unwind\"", ":", "\"$students\"", "}", ",", "{", "\"$project\"", ":", "{", "\"students\"", ":", "1", ",", "\"grouped\"", ":", "{", "\"$anyElementTrue\"", ":", "{", "\"$map\"", ":", "{", "\"input\"", ":", "\"$groups.students\"", ",", "\"as\"", ":", "\"group\"", ",", "\"in\"", ":", "{", "\"$anyElementTrue\"", ":", "{", "\"$map\"", ":", "{", "\"input\"", ":", "\"$$group\"", ",", "\"as\"", ":", "\"groupmember\"", ",", "\"in\"", ":", "{", "\"$eq\"", ":", "[", "\"$$groupmember\"", ",", "\"$students\"", "]", "}", "}", "}", "}", "}", "}", "}", "}", "}", "]", ")", ")", "student_list", "=", "dict", "(", "[", "(", "student", "[", "\"students\"", "]", ",", "student", ")", "for", "student", "in", "student_list", "]", ")", "other_students", "=", "[", "entry", "[", "'students'", "]", "for", "entry", "in", "list", "(", "self", ".", "database", ".", "classrooms", ".", "aggregate", "(", "[", "{", "\"$match\"", ":", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"_id\"", ":", "{", "\"$ne\"", ":", "ObjectId", "(", "classroomid", ")", "}", "}", "}", ",", "{", "\"$unwind\"", ":", "\"$students\"", "}", ",", "{", "\"$project\"", ":", "{", "\"_id\"", ":", "0", ",", "\"students\"", ":", "1", "}", "}", "]", ")", ")", "]", "users_info", "=", "self", ".", "user_manager", ".", "get_users_info", "(", "other_students", "+", "list", "(", "student_list", ".", "keys", "(", ")", ")", "+", "tutor_list", ")", "# Order the non-registered students", "other_students", "=", "sorted", "(", "other_students", ",", "key", "=", "lambda", "val", ":", "(", "(", "\"0\"", "+", "users_info", "[", "val", "]", "[", "0", "]", ")", "if", "users_info", "[", "val", "]", "else", "(", "\"1\"", "+", "val", ")", ")", ")", "return", "student_list", ",", "tutor_list", ",", "other_students", ",", "users_info" ]
Get the available student and tutor lists for classroom edition
[ "Get", "the", "available", "student", "and", "tutor", "lists", "for", "classroom", "edition" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/classroom_edit.py#L21-L64
248,870
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/classroom_edit.py
CourseEditClassroom.update_classroom
def update_classroom(self, course, classroomid, new_data): """ Update classroom and returns a list of errored students""" student_list, tutor_list, other_students, _ = self.get_user_lists(course, classroomid) # Check tutors new_data["tutors"] = [tutor for tutor in map(str.strip, new_data["tutors"]) if tutor in tutor_list] students, groups, errored_students = [], [], [] new_data["students"] = map(str.strip, new_data["students"]) # Check the students for student in new_data["students"]: if student in student_list: students.append(student) else: if student in other_students: # Remove user from the other classroom self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "groups.students": student}, {"$pull": {"groups.$.students": student, "students": student}}) self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "students": student}, {"$pull": {"students": student}}) students.append(student) else: # Check if user can be registered user_info = self.user_manager.get_user_info(student) if user_info is None or student in tutor_list: errored_students.append(student) else: students.append(student) removed_students = [student for student in student_list if student not in new_data["students"]] self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$push": {"students": {"$each": removed_students}}}) new_data["students"] = students # Check the groups for group in new_data["groups"]: group["students"] = [student for student in map(str.strip, group["students"]) if student in new_data["students"]] if len(group["students"]) <= group["size"]: groups.append(group) new_data["groups"] = groups classroom = self.database.classrooms.find_one_and_update( {"_id": ObjectId(classroomid)}, {"$set": {"description": new_data["description"], "students": students, "tutors": new_data["tutors"], "groups": groups}}, return_document=ReturnDocument.AFTER) return classroom, errored_students
python
def update_classroom(self, course, classroomid, new_data): student_list, tutor_list, other_students, _ = self.get_user_lists(course, classroomid) # Check tutors new_data["tutors"] = [tutor for tutor in map(str.strip, new_data["tutors"]) if tutor in tutor_list] students, groups, errored_students = [], [], [] new_data["students"] = map(str.strip, new_data["students"]) # Check the students for student in new_data["students"]: if student in student_list: students.append(student) else: if student in other_students: # Remove user from the other classroom self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "groups.students": student}, {"$pull": {"groups.$.students": student, "students": student}}) self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "students": student}, {"$pull": {"students": student}}) students.append(student) else: # Check if user can be registered user_info = self.user_manager.get_user_info(student) if user_info is None or student in tutor_list: errored_students.append(student) else: students.append(student) removed_students = [student for student in student_list if student not in new_data["students"]] self.database.classrooms.find_one_and_update({"courseid": course.get_id(), "default": True}, {"$push": {"students": {"$each": removed_students}}}) new_data["students"] = students # Check the groups for group in new_data["groups"]: group["students"] = [student for student in map(str.strip, group["students"]) if student in new_data["students"]] if len(group["students"]) <= group["size"]: groups.append(group) new_data["groups"] = groups classroom = self.database.classrooms.find_one_and_update( {"_id": ObjectId(classroomid)}, {"$set": {"description": new_data["description"], "students": students, "tutors": new_data["tutors"], "groups": groups}}, return_document=ReturnDocument.AFTER) return classroom, errored_students
[ "def", "update_classroom", "(", "self", ",", "course", ",", "classroomid", ",", "new_data", ")", ":", "student_list", ",", "tutor_list", ",", "other_students", ",", "_", "=", "self", ".", "get_user_lists", "(", "course", ",", "classroomid", ")", "# Check tutors", "new_data", "[", "\"tutors\"", "]", "=", "[", "tutor", "for", "tutor", "in", "map", "(", "str", ".", "strip", ",", "new_data", "[", "\"tutors\"", "]", ")", "if", "tutor", "in", "tutor_list", "]", "students", ",", "groups", ",", "errored_students", "=", "[", "]", ",", "[", "]", ",", "[", "]", "new_data", "[", "\"students\"", "]", "=", "map", "(", "str", ".", "strip", ",", "new_data", "[", "\"students\"", "]", ")", "# Check the students", "for", "student", "in", "new_data", "[", "\"students\"", "]", ":", "if", "student", "in", "student_list", ":", "students", ".", "append", "(", "student", ")", "else", ":", "if", "student", "in", "other_students", ":", "# Remove user from the other classroom", "self", ".", "database", ".", "classrooms", ".", "find_one_and_update", "(", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"groups.students\"", ":", "student", "}", ",", "{", "\"$pull\"", ":", "{", "\"groups.$.students\"", ":", "student", ",", "\"students\"", ":", "student", "}", "}", ")", "self", ".", "database", ".", "classrooms", ".", "find_one_and_update", "(", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"students\"", ":", "student", "}", ",", "{", "\"$pull\"", ":", "{", "\"students\"", ":", "student", "}", "}", ")", "students", ".", "append", "(", "student", ")", "else", ":", "# Check if user can be registered", "user_info", "=", "self", ".", "user_manager", ".", "get_user_info", "(", "student", ")", "if", "user_info", "is", "None", "or", "student", "in", "tutor_list", ":", "errored_students", ".", "append", "(", "student", ")", "else", ":", "students", ".", "append", "(", "student", ")", "removed_students", "=", "[", "student", "for", "student", "in", "student_list", "if", "student", "not", "in", "new_data", "[", "\"students\"", "]", "]", "self", ".", "database", ".", "classrooms", ".", "find_one_and_update", "(", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"default\"", ":", "True", "}", ",", "{", "\"$push\"", ":", "{", "\"students\"", ":", "{", "\"$each\"", ":", "removed_students", "}", "}", "}", ")", "new_data", "[", "\"students\"", "]", "=", "students", "# Check the groups", "for", "group", "in", "new_data", "[", "\"groups\"", "]", ":", "group", "[", "\"students\"", "]", "=", "[", "student", "for", "student", "in", "map", "(", "str", ".", "strip", ",", "group", "[", "\"students\"", "]", ")", "if", "student", "in", "new_data", "[", "\"students\"", "]", "]", "if", "len", "(", "group", "[", "\"students\"", "]", ")", "<=", "group", "[", "\"size\"", "]", ":", "groups", ".", "append", "(", "group", ")", "new_data", "[", "\"groups\"", "]", "=", "groups", "classroom", "=", "self", ".", "database", ".", "classrooms", ".", "find_one_and_update", "(", "{", "\"_id\"", ":", "ObjectId", "(", "classroomid", ")", "}", ",", "{", "\"$set\"", ":", "{", "\"description\"", ":", "new_data", "[", "\"description\"", "]", ",", "\"students\"", ":", "students", ",", "\"tutors\"", ":", "new_data", "[", "\"tutors\"", "]", ",", "\"groups\"", ":", "groups", "}", "}", ",", "return_document", "=", "ReturnDocument", ".", "AFTER", ")", "return", "classroom", ",", "errored_students" ]
Update classroom and returns a list of errored students
[ "Update", "classroom", "and", "returns", "a", "list", "of", "errored", "students" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/classroom_edit.py#L66-L116
248,871
UCL-INGI/INGInious
inginious/frontend/parsable_text.py
ParsableText.parse
def parse(self, debug=False): """Returns parsed text""" if self._parsed is None: try: if self._mode == "html": self._parsed = self.html(self._content, self._show_everything, self._translation) else: self._parsed = self.rst(self._content, self._show_everything, self._translation, debug=debug) except Exception as e: if debug: raise BaseException("Parsing failed") from e else: self._parsed = self._translation.gettext("<b>Parsing failed</b>: <pre>{}</pre>").format(html.escape(self._content)) return self._parsed
python
def parse(self, debug=False): if self._parsed is None: try: if self._mode == "html": self._parsed = self.html(self._content, self._show_everything, self._translation) else: self._parsed = self.rst(self._content, self._show_everything, self._translation, debug=debug) except Exception as e: if debug: raise BaseException("Parsing failed") from e else: self._parsed = self._translation.gettext("<b>Parsing failed</b>: <pre>{}</pre>").format(html.escape(self._content)) return self._parsed
[ "def", "parse", "(", "self", ",", "debug", "=", "False", ")", ":", "if", "self", ".", "_parsed", "is", "None", ":", "try", ":", "if", "self", ".", "_mode", "==", "\"html\"", ":", "self", ".", "_parsed", "=", "self", ".", "html", "(", "self", ".", "_content", ",", "self", ".", "_show_everything", ",", "self", ".", "_translation", ")", "else", ":", "self", ".", "_parsed", "=", "self", ".", "rst", "(", "self", ".", "_content", ",", "self", ".", "_show_everything", ",", "self", ".", "_translation", ",", "debug", "=", "debug", ")", "except", "Exception", "as", "e", ":", "if", "debug", ":", "raise", "BaseException", "(", "\"Parsing failed\"", ")", "from", "e", "else", ":", "self", ".", "_parsed", "=", "self", ".", "_translation", ".", "gettext", "(", "\"<b>Parsing failed</b>: <pre>{}</pre>\"", ")", ".", "format", "(", "html", ".", "escape", "(", "self", ".", "_content", ")", ")", "return", "self", ".", "_parsed" ]
Returns parsed text
[ "Returns", "parsed", "text" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/parsable_text.py#L144-L157
248,872
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit_file.py
CourseTaskFiles.POST_AUTH
def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ """ Upload or modify a file """ if not id_checker(taskid): raise Exception("Invalid task id") self.get_course_and_check_rights(courseid, allow_all_staff=False) request = web.input(file={}) if request.get("action") == "upload" and request.get('path') is not None and request.get('file') is not None: return self.action_upload(courseid, taskid, request.get('path'), request.get('file')) elif request.get("action") == "edit_save" and request.get('path') is not None and request.get('content') is not None: return self.action_edit_save(courseid, taskid, request.get('path'), request.get('content')) else: return self.show_tab_file(courseid, taskid)
python
def POST_AUTH(self, courseid, taskid): # pylint: disable=arguments-differ if not id_checker(taskid): raise Exception("Invalid task id") self.get_course_and_check_rights(courseid, allow_all_staff=False) request = web.input(file={}) if request.get("action") == "upload" and request.get('path') is not None and request.get('file') is not None: return self.action_upload(courseid, taskid, request.get('path'), request.get('file')) elif request.get("action") == "edit_save" and request.get('path') is not None and request.get('content') is not None: return self.action_edit_save(courseid, taskid, request.get('path'), request.get('content')) else: return self.show_tab_file(courseid, taskid)
[ "def", "POST_AUTH", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "# pylint: disable=arguments-differ", "if", "not", "id_checker", "(", "taskid", ")", ":", "raise", "Exception", "(", "\"Invalid task id\"", ")", "self", ".", "get_course_and_check_rights", "(", "courseid", ",", "allow_all_staff", "=", "False", ")", "request", "=", "web", ".", "input", "(", "file", "=", "{", "}", ")", "if", "request", ".", "get", "(", "\"action\"", ")", "==", "\"upload\"", "and", "request", ".", "get", "(", "'path'", ")", "is", "not", "None", "and", "request", ".", "get", "(", "'file'", ")", "is", "not", "None", ":", "return", "self", ".", "action_upload", "(", "courseid", ",", "taskid", ",", "request", ".", "get", "(", "'path'", ")", ",", "request", ".", "get", "(", "'file'", ")", ")", "elif", "request", ".", "get", "(", "\"action\"", ")", "==", "\"edit_save\"", "and", "request", ".", "get", "(", "'path'", ")", "is", "not", "None", "and", "request", ".", "get", "(", "'content'", ")", "is", "not", "None", ":", "return", "self", ".", "action_edit_save", "(", "courseid", ",", "taskid", ",", "request", ".", "get", "(", "'path'", ")", ",", "request", ".", "get", "(", "'content'", ")", ")", "else", ":", "return", "self", ".", "show_tab_file", "(", "courseid", ",", "taskid", ")" ]
Upload or modify a file
[ "Upload", "or", "modify", "a", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L40-L53
248,873
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit_file.py
CourseTaskFiles.show_tab_file
def show_tab_file(self, courseid, taskid, error=None): """ Return the file tab """ return self.template_helper.get_renderer(False).course_admin.edit_tabs.files( self.course_factory.get_course(courseid), taskid, self.get_task_filelist(self.task_factory, courseid, taskid), error)
python
def show_tab_file(self, courseid, taskid, error=None): return self.template_helper.get_renderer(False).course_admin.edit_tabs.files( self.course_factory.get_course(courseid), taskid, self.get_task_filelist(self.task_factory, courseid, taskid), error)
[ "def", "show_tab_file", "(", "self", ",", "courseid", ",", "taskid", ",", "error", "=", "None", ")", ":", "return", "self", ".", "template_helper", ".", "get_renderer", "(", "False", ")", ".", "course_admin", ".", "edit_tabs", ".", "files", "(", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", ",", "taskid", ",", "self", ".", "get_task_filelist", "(", "self", ".", "task_factory", ",", "courseid", ",", "taskid", ")", ",", "error", ")" ]
Return the file tab
[ "Return", "the", "file", "tab" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L55-L58
248,874
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit_file.py
CourseTaskFiles.action_edit
def action_edit(self, courseid, taskid, path): """ Edit a file """ wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: return "Internal error" try: content = self.task_factory.get_task_fs(courseid, taskid).get(wanted_path).decode("utf-8") return json.dumps({"content": content}) except: return json.dumps({"error": "not-readable"})
python
def action_edit(self, courseid, taskid, path): wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: return "Internal error" try: content = self.task_factory.get_task_fs(courseid, taskid).get(wanted_path).decode("utf-8") return json.dumps({"content": content}) except: return json.dumps({"error": "not-readable"})
[ "def", "action_edit", "(", "self", ",", "courseid", ",", "taskid", ",", "path", ")", ":", "wanted_path", "=", "self", ".", "verify_path", "(", "courseid", ",", "taskid", ",", "path", ")", "if", "wanted_path", "is", "None", ":", "return", "\"Internal error\"", "try", ":", "content", "=", "self", ".", "task_factory", ".", "get_task_fs", "(", "courseid", ",", "taskid", ")", ".", "get", "(", "wanted_path", ")", ".", "decode", "(", "\"utf-8\"", ")", "return", "json", ".", "dumps", "(", "{", "\"content\"", ":", "content", "}", ")", "except", ":", "return", "json", ".", "dumps", "(", "{", "\"error\"", ":", "\"not-readable\"", "}", ")" ]
Edit a file
[ "Edit", "a", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L131-L140
248,875
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit_file.py
CourseTaskFiles.action_edit_save
def action_edit_save(self, courseid, taskid, path, content): """ Save an edited file """ wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: return json.dumps({"error": True}) try: self.task_factory.get_task_fs(courseid, taskid).put(wanted_path, content.encode("utf-8")) return json.dumps({"ok": True}) except: return json.dumps({"error": True})
python
def action_edit_save(self, courseid, taskid, path, content): wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: return json.dumps({"error": True}) try: self.task_factory.get_task_fs(courseid, taskid).put(wanted_path, content.encode("utf-8")) return json.dumps({"ok": True}) except: return json.dumps({"error": True})
[ "def", "action_edit_save", "(", "self", ",", "courseid", ",", "taskid", ",", "path", ",", "content", ")", ":", "wanted_path", "=", "self", ".", "verify_path", "(", "courseid", ",", "taskid", ",", "path", ")", "if", "wanted_path", "is", "None", ":", "return", "json", ".", "dumps", "(", "{", "\"error\"", ":", "True", "}", ")", "try", ":", "self", ".", "task_factory", ".", "get_task_fs", "(", "courseid", ",", "taskid", ")", ".", "put", "(", "wanted_path", ",", "content", ".", "encode", "(", "\"utf-8\"", ")", ")", "return", "json", ".", "dumps", "(", "{", "\"ok\"", ":", "True", "}", ")", "except", ":", "return", "json", ".", "dumps", "(", "{", "\"error\"", ":", "True", "}", ")" ]
Save an edited file
[ "Save", "an", "edited", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L142-L151
248,876
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/task_edit_file.py
CourseTaskFiles.action_download
def action_download(self, courseid, taskid, path): """ Download a file or a directory """ wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: raise web.notfound() task_fs = self.task_factory.get_task_fs(courseid, taskid) (method, mimetype_or_none, file_or_url) = task_fs.distribute(wanted_path) if method == "local": web.header('Content-Type', mimetype_or_none) return file_or_url elif method == "url": raise web.redirect(file_or_url) else: raise web.notfound()
python
def action_download(self, courseid, taskid, path): wanted_path = self.verify_path(courseid, taskid, path) if wanted_path is None: raise web.notfound() task_fs = self.task_factory.get_task_fs(courseid, taskid) (method, mimetype_or_none, file_or_url) = task_fs.distribute(wanted_path) if method == "local": web.header('Content-Type', mimetype_or_none) return file_or_url elif method == "url": raise web.redirect(file_or_url) else: raise web.notfound()
[ "def", "action_download", "(", "self", ",", "courseid", ",", "taskid", ",", "path", ")", ":", "wanted_path", "=", "self", ".", "verify_path", "(", "courseid", ",", "taskid", ",", "path", ")", "if", "wanted_path", "is", "None", ":", "raise", "web", ".", "notfound", "(", ")", "task_fs", "=", "self", ".", "task_factory", ".", "get_task_fs", "(", "courseid", ",", "taskid", ")", "(", "method", ",", "mimetype_or_none", ",", "file_or_url", ")", "=", "task_fs", ".", "distribute", "(", "wanted_path", ")", "if", "method", "==", "\"local\"", ":", "web", ".", "header", "(", "'Content-Type'", ",", "mimetype_or_none", ")", "return", "file_or_url", "elif", "method", "==", "\"url\"", ":", "raise", "web", ".", "redirect", "(", "file_or_url", ")", "else", ":", "raise", "web", ".", "notfound", "(", ")" ]
Download a file or a directory
[ "Download", "a", "file", "or", "a", "directory" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/task_edit_file.py#L235-L251
248,877
UCL-INGI/INGInious
inginious/common/base.py
write_json_or_yaml
def write_json_or_yaml(file_path, content): """ Write JSON or YAML depending on the file extension. """ with codecs.open(file_path, "w", "utf-8") as f: f.write(get_json_or_yaml(file_path, content))
python
def write_json_or_yaml(file_path, content): with codecs.open(file_path, "w", "utf-8") as f: f.write(get_json_or_yaml(file_path, content))
[ "def", "write_json_or_yaml", "(", "file_path", ",", "content", ")", ":", "with", "codecs", ".", "open", "(", "file_path", ",", "\"w\"", ",", "\"utf-8\"", ")", "as", "f", ":", "f", ".", "write", "(", "get_json_or_yaml", "(", "file_path", ",", "content", ")", ")" ]
Write JSON or YAML depending on the file extension.
[ "Write", "JSON", "or", "YAML", "depending", "on", "the", "file", "extension", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/base.py#L43-L46
248,878
UCL-INGI/INGInious
inginious/common/base.py
get_json_or_yaml
def get_json_or_yaml(file_path, content): """ Generate JSON or YAML depending on the file extension. """ if os.path.splitext(file_path)[1] == ".json": return json.dumps(content, sort_keys=False, indent=4, separators=(',', ': ')) else: return inginious.common.custom_yaml.dump(content)
python
def get_json_or_yaml(file_path, content): if os.path.splitext(file_path)[1] == ".json": return json.dumps(content, sort_keys=False, indent=4, separators=(',', ': ')) else: return inginious.common.custom_yaml.dump(content)
[ "def", "get_json_or_yaml", "(", "file_path", ",", "content", ")", ":", "if", "os", ".", "path", ".", "splitext", "(", "file_path", ")", "[", "1", "]", "==", "\".json\"", ":", "return", "json", ".", "dumps", "(", "content", ",", "sort_keys", "=", "False", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")", "else", ":", "return", "inginious", ".", "common", ".", "custom_yaml", ".", "dump", "(", "content", ")" ]
Generate JSON or YAML depending on the file extension.
[ "Generate", "JSON", "or", "YAML", "depending", "on", "the", "file", "extension", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/base.py#L49-L54
248,879
UCL-INGI/INGInious
inginious/frontend/user_manager.py
UserManager._set_session
def _set_session(self, username, realname, email, language): """ Init the session. Preserves potential LTI information. """ self._session.loggedin = True self._session.email = email self._session.username = username self._session.realname = realname self._session.language = language self._session.token = None if "lti" not in self._session: self._session.lti = None
python
def _set_session(self, username, realname, email, language): self._session.loggedin = True self._session.email = email self._session.username = username self._session.realname = realname self._session.language = language self._session.token = None if "lti" not in self._session: self._session.lti = None
[ "def", "_set_session", "(", "self", ",", "username", ",", "realname", ",", "email", ",", "language", ")", ":", "self", ".", "_session", ".", "loggedin", "=", "True", "self", ".", "_session", ".", "email", "=", "email", "self", ".", "_session", ".", "username", "=", "username", "self", ".", "_session", ".", "realname", "=", "realname", "self", ".", "_session", ".", "language", "=", "language", "self", ".", "_session", ".", "token", "=", "None", "if", "\"lti\"", "not", "in", "self", ".", "_session", ":", "self", ".", "_session", ".", "lti", "=", "None" ]
Init the session. Preserves potential LTI information.
[ "Init", "the", "session", ".", "Preserves", "potential", "LTI", "information", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/user_manager.py#L184-L193
248,880
UCL-INGI/INGInious
inginious/frontend/user_manager.py
UserManager._destroy_session
def _destroy_session(self): """ Destroy the session """ self._session.loggedin = False self._session.email = None self._session.username = None self._session.realname = None self._session.token = None self._session.lti = None
python
def _destroy_session(self): self._session.loggedin = False self._session.email = None self._session.username = None self._session.realname = None self._session.token = None self._session.lti = None
[ "def", "_destroy_session", "(", "self", ")", ":", "self", ".", "_session", ".", "loggedin", "=", "False", "self", ".", "_session", ".", "email", "=", "None", "self", ".", "_session", ".", "username", "=", "None", "self", ".", "_session", ".", "realname", "=", "None", "self", ".", "_session", ".", "token", "=", "None", "self", ".", "_session", ".", "lti", "=", "None" ]
Destroy the session
[ "Destroy", "the", "session" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/user_manager.py#L195-L202
248,881
UCL-INGI/INGInious
inginious/frontend/user_manager.py
UserManager.create_lti_session
def create_lti_session(self, user_id, roles, realname, email, course_id, task_id, consumer_key, outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label): """ Creates an LTI cookieless session. Returns the new session id""" self._destroy_session() # don't forget to destroy the current session (cleans the threaded dict from web.py) self._session.load('') # creates a new cookieless session session_id = self._session.session_id self._session.lti = { "email": email, "username": user_id, "realname": realname, "roles": roles, "task": (course_id, task_id), "outcome_service_url": outcome_service_url, "outcome_result_id": outcome_result_id, "consumer_key": consumer_key, "context_title": context_title, "context_label": context_label, "tool_description": tool_desc, "tool_name": tool_name, "tool_url": tool_url } return session_id
python
def create_lti_session(self, user_id, roles, realname, email, course_id, task_id, consumer_key, outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label): self._destroy_session() # don't forget to destroy the current session (cleans the threaded dict from web.py) self._session.load('') # creates a new cookieless session session_id = self._session.session_id self._session.lti = { "email": email, "username": user_id, "realname": realname, "roles": roles, "task": (course_id, task_id), "outcome_service_url": outcome_service_url, "outcome_result_id": outcome_result_id, "consumer_key": consumer_key, "context_title": context_title, "context_label": context_label, "tool_description": tool_desc, "tool_name": tool_name, "tool_url": tool_url } return session_id
[ "def", "create_lti_session", "(", "self", ",", "user_id", ",", "roles", ",", "realname", ",", "email", ",", "course_id", ",", "task_id", ",", "consumer_key", ",", "outcome_service_url", ",", "outcome_result_id", ",", "tool_name", ",", "tool_desc", ",", "tool_url", ",", "context_title", ",", "context_label", ")", ":", "self", ".", "_destroy_session", "(", ")", "# don't forget to destroy the current session (cleans the threaded dict from web.py)", "self", ".", "_session", ".", "load", "(", "''", ")", "# creates a new cookieless session", "session_id", "=", "self", ".", "_session", ".", "session_id", "self", ".", "_session", ".", "lti", "=", "{", "\"email\"", ":", "email", ",", "\"username\"", ":", "user_id", ",", "\"realname\"", ":", "realname", ",", "\"roles\"", ":", "roles", ",", "\"task\"", ":", "(", "course_id", ",", "task_id", ")", ",", "\"outcome_service_url\"", ":", "outcome_service_url", ",", "\"outcome_result_id\"", ":", "outcome_result_id", ",", "\"consumer_key\"", ":", "consumer_key", ",", "\"context_title\"", ":", "context_title", ",", "\"context_label\"", ":", "context_label", ",", "\"tool_description\"", ":", "tool_desc", ",", "\"tool_name\"", ":", "tool_name", ",", "\"tool_url\"", ":", "tool_url", "}", "return", "session_id" ]
Creates an LTI cookieless session. Returns the new session id
[ "Creates", "an", "LTI", "cookieless", "session", ".", "Returns", "the", "new", "session", "id" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/user_manager.py#L204-L228
248,882
UCL-INGI/INGInious
inginious/frontend/user_manager.py
UserManager.user_saw_task
def user_saw_task(self, username, courseid, taskid): """ Set in the database that the user has viewed this task """ self._database.user_tasks.update({"username": username, "courseid": courseid, "taskid": taskid}, {"$setOnInsert": {"username": username, "courseid": courseid, "taskid": taskid, "tried": 0, "succeeded": False, "grade": 0.0, "submissionid": None, "state": ""}}, upsert=True)
python
def user_saw_task(self, username, courseid, taskid): self._database.user_tasks.update({"username": username, "courseid": courseid, "taskid": taskid}, {"$setOnInsert": {"username": username, "courseid": courseid, "taskid": taskid, "tried": 0, "succeeded": False, "grade": 0.0, "submissionid": None, "state": ""}}, upsert=True)
[ "def", "user_saw_task", "(", "self", ",", "username", ",", "courseid", ",", "taskid", ")", ":", "self", ".", "_database", ".", "user_tasks", ".", "update", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "courseid", ",", "\"taskid\"", ":", "taskid", "}", ",", "{", "\"$setOnInsert\"", ":", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "courseid", ",", "\"taskid\"", ":", "taskid", ",", "\"tried\"", ":", "0", ",", "\"succeeded\"", ":", "False", ",", "\"grade\"", ":", "0.0", ",", "\"submissionid\"", ":", "None", ",", "\"state\"", ":", "\"\"", "}", "}", ",", "upsert", "=", "True", ")" ]
Set in the database that the user has viewed this task
[ "Set", "in", "the", "database", "that", "the", "user", "has", "viewed", "this", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/user_manager.py#L518-L523
248,883
UCL-INGI/INGInious
inginious/frontend/user_manager.py
UserManager.update_user_stats
def update_user_stats(self, username, task, submission, result_str, grade, state, newsub): """ Update stats with a new submission """ self.user_saw_task(username, submission["courseid"], submission["taskid"]) if newsub: old_submission = self._database.user_tasks.find_one_and_update( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$inc": {"tried": 1, "tokens.amount": 1}}) # Check if the submission is the default download set_default = task.get_evaluate() == 'last' or \ (task.get_evaluate() == 'student' and old_submission is None) or \ (task.get_evaluate() == 'best' and old_submission.get('grade', 0.0) <= grade) if set_default: self._database.user_tasks.find_one_and_update( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$set": {"succeeded": result_str == "success", "grade": grade, "state": state, "submissionid": submission['_id']}}) else: old_submission = self._database.user_tasks.find_one( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}) if task.get_evaluate() == 'best': # if best, update cache consequently (with best submission) def_sub = list(self._database.submissions.find({ "username": username, "courseid": task.get_course_id(), "taskid": task.get_id(), "status": "done"} ).sort([("grade", pymongo.DESCENDING), ("submitted_on", pymongo.DESCENDING)]).limit(1)) if len(def_sub) > 0: self._database.user_tasks.find_one_and_update( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$set": { "succeeded": def_sub[0]["result"] == "success", "grade": def_sub[0]["grade"], "state": def_sub[0]["state"], "submissionid": def_sub[0]['_id'] }}) elif old_submission["submissionid"] == submission["_id"]: # otherwise, update cache if needed self._database.user_tasks.find_one_and_update( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$set": { "succeeded": submission["result"] == "success", "grade": submission["grade"], "state": submission["state"] }})
python
def update_user_stats(self, username, task, submission, result_str, grade, state, newsub): self.user_saw_task(username, submission["courseid"], submission["taskid"]) if newsub: old_submission = self._database.user_tasks.find_one_and_update( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$inc": {"tried": 1, "tokens.amount": 1}}) # Check if the submission is the default download set_default = task.get_evaluate() == 'last' or \ (task.get_evaluate() == 'student' and old_submission is None) or \ (task.get_evaluate() == 'best' and old_submission.get('grade', 0.0) <= grade) if set_default: self._database.user_tasks.find_one_and_update( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$set": {"succeeded": result_str == "success", "grade": grade, "state": state, "submissionid": submission['_id']}}) else: old_submission = self._database.user_tasks.find_one( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}) if task.get_evaluate() == 'best': # if best, update cache consequently (with best submission) def_sub = list(self._database.submissions.find({ "username": username, "courseid": task.get_course_id(), "taskid": task.get_id(), "status": "done"} ).sort([("grade", pymongo.DESCENDING), ("submitted_on", pymongo.DESCENDING)]).limit(1)) if len(def_sub) > 0: self._database.user_tasks.find_one_and_update( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$set": { "succeeded": def_sub[0]["result"] == "success", "grade": def_sub[0]["grade"], "state": def_sub[0]["state"], "submissionid": def_sub[0]['_id'] }}) elif old_submission["submissionid"] == submission["_id"]: # otherwise, update cache if needed self._database.user_tasks.find_one_and_update( {"username": username, "courseid": submission["courseid"], "taskid": submission["taskid"]}, {"$set": { "succeeded": submission["result"] == "success", "grade": submission["grade"], "state": submission["state"] }})
[ "def", "update_user_stats", "(", "self", ",", "username", ",", "task", ",", "submission", ",", "result_str", ",", "grade", ",", "state", ",", "newsub", ")", ":", "self", ".", "user_saw_task", "(", "username", ",", "submission", "[", "\"courseid\"", "]", ",", "submission", "[", "\"taskid\"", "]", ")", "if", "newsub", ":", "old_submission", "=", "self", ".", "_database", ".", "user_tasks", ".", "find_one_and_update", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "submission", "[", "\"courseid\"", "]", ",", "\"taskid\"", ":", "submission", "[", "\"taskid\"", "]", "}", ",", "{", "\"$inc\"", ":", "{", "\"tried\"", ":", "1", ",", "\"tokens.amount\"", ":", "1", "}", "}", ")", "# Check if the submission is the default download", "set_default", "=", "task", ".", "get_evaluate", "(", ")", "==", "'last'", "or", "(", "task", ".", "get_evaluate", "(", ")", "==", "'student'", "and", "old_submission", "is", "None", ")", "or", "(", "task", ".", "get_evaluate", "(", ")", "==", "'best'", "and", "old_submission", ".", "get", "(", "'grade'", ",", "0.0", ")", "<=", "grade", ")", "if", "set_default", ":", "self", ".", "_database", ".", "user_tasks", ".", "find_one_and_update", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "submission", "[", "\"courseid\"", "]", ",", "\"taskid\"", ":", "submission", "[", "\"taskid\"", "]", "}", ",", "{", "\"$set\"", ":", "{", "\"succeeded\"", ":", "result_str", "==", "\"success\"", ",", "\"grade\"", ":", "grade", ",", "\"state\"", ":", "state", ",", "\"submissionid\"", ":", "submission", "[", "'_id'", "]", "}", "}", ")", "else", ":", "old_submission", "=", "self", ".", "_database", ".", "user_tasks", ".", "find_one", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "submission", "[", "\"courseid\"", "]", ",", "\"taskid\"", ":", "submission", "[", "\"taskid\"", "]", "}", ")", "if", "task", ".", "get_evaluate", "(", ")", "==", "'best'", ":", "# if best, update cache consequently (with best submission)", "def_sub", "=", "list", "(", "self", ".", "_database", ".", "submissions", ".", "find", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "task", ".", "get_course_id", "(", ")", ",", "\"taskid\"", ":", "task", ".", "get_id", "(", ")", ",", "\"status\"", ":", "\"done\"", "}", ")", ".", "sort", "(", "[", "(", "\"grade\"", ",", "pymongo", ".", "DESCENDING", ")", ",", "(", "\"submitted_on\"", ",", "pymongo", ".", "DESCENDING", ")", "]", ")", ".", "limit", "(", "1", ")", ")", "if", "len", "(", "def_sub", ")", ">", "0", ":", "self", ".", "_database", ".", "user_tasks", ".", "find_one_and_update", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "submission", "[", "\"courseid\"", "]", ",", "\"taskid\"", ":", "submission", "[", "\"taskid\"", "]", "}", ",", "{", "\"$set\"", ":", "{", "\"succeeded\"", ":", "def_sub", "[", "0", "]", "[", "\"result\"", "]", "==", "\"success\"", ",", "\"grade\"", ":", "def_sub", "[", "0", "]", "[", "\"grade\"", "]", ",", "\"state\"", ":", "def_sub", "[", "0", "]", "[", "\"state\"", "]", ",", "\"submissionid\"", ":", "def_sub", "[", "0", "]", "[", "'_id'", "]", "}", "}", ")", "elif", "old_submission", "[", "\"submissionid\"", "]", "==", "submission", "[", "\"_id\"", "]", ":", "# otherwise, update cache if needed", "self", ".", "_database", ".", "user_tasks", ".", "find_one_and_update", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "submission", "[", "\"courseid\"", "]", ",", "\"taskid\"", ":", "submission", "[", "\"taskid\"", "]", "}", ",", "{", "\"$set\"", ":", "{", "\"succeeded\"", ":", "submission", "[", "\"result\"", "]", "==", "\"success\"", ",", "\"grade\"", ":", "submission", "[", "\"grade\"", "]", ",", "\"state\"", ":", "submission", "[", "\"state\"", "]", "}", "}", ")" ]
Update stats with a new submission
[ "Update", "stats", "with", "a", "new", "submission" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/user_manager.py#L525-L568
248,884
UCL-INGI/INGInious
inginious/frontend/user_manager.py
UserManager.get_course_aggregations
def get_course_aggregations(self, course): """ Returns a list of the course aggregations""" return natsorted(list(self._database.aggregations.find({"courseid": course.get_id()})), key=lambda x: x["description"])
python
def get_course_aggregations(self, course): return natsorted(list(self._database.aggregations.find({"courseid": course.get_id()})), key=lambda x: x["description"])
[ "def", "get_course_aggregations", "(", "self", ",", "course", ")", ":", "return", "natsorted", "(", "list", "(", "self", ".", "_database", ".", "aggregations", ".", "find", "(", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", "}", ")", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "\"description\"", "]", ")" ]
Returns a list of the course aggregations
[ "Returns", "a", "list", "of", "the", "course", "aggregations" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/user_manager.py#L650-L652
248,885
UCL-INGI/INGInious
inginious/frontend/tasks.py
WebAppTask.get_accessible_time
def get_accessible_time(self, plugin_override=True): """ Get the accessible time of this task """ vals = self._hook_manager.call_hook('task_accessibility', course=self.get_course(), task=self, default=self._accessible) return vals[0] if len(vals) and plugin_override else self._accessible
python
def get_accessible_time(self, plugin_override=True): vals = self._hook_manager.call_hook('task_accessibility', course=self.get_course(), task=self, default=self._accessible) return vals[0] if len(vals) and plugin_override else self._accessible
[ "def", "get_accessible_time", "(", "self", ",", "plugin_override", "=", "True", ")", ":", "vals", "=", "self", ".", "_hook_manager", ".", "call_hook", "(", "'task_accessibility'", ",", "course", "=", "self", ".", "get_course", "(", ")", ",", "task", "=", "self", ",", "default", "=", "self", ".", "_accessible", ")", "return", "vals", "[", "0", "]", "if", "len", "(", "vals", ")", "and", "plugin_override", "else", "self", ".", "_accessible" ]
Get the accessible time of this task
[ "Get", "the", "accessible", "time", "of", "this", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/tasks.py#L68-L71
248,886
UCL-INGI/INGInious
inginious/frontend/tasks.py
WebAppTask.get_deadline
def get_deadline(self): """ Returns a string containing the deadline for this task """ if self.get_accessible_time().is_always_accessible(): return _("No deadline") elif self.get_accessible_time().is_never_accessible(): return _("It's too late") else: # Prefer to show the soft deadline rather than the hard one return self.get_accessible_time().get_soft_end_date().strftime("%d/%m/%Y %H:%M:%S")
python
def get_deadline(self): if self.get_accessible_time().is_always_accessible(): return _("No deadline") elif self.get_accessible_time().is_never_accessible(): return _("It's too late") else: # Prefer to show the soft deadline rather than the hard one return self.get_accessible_time().get_soft_end_date().strftime("%d/%m/%Y %H:%M:%S")
[ "def", "get_deadline", "(", "self", ")", ":", "if", "self", ".", "get_accessible_time", "(", ")", ".", "is_always_accessible", "(", ")", ":", "return", "_", "(", "\"No deadline\"", ")", "elif", "self", ".", "get_accessible_time", "(", ")", ".", "is_never_accessible", "(", ")", ":", "return", "_", "(", "\"It's too late\"", ")", "else", ":", "# Prefer to show the soft deadline rather than the hard one", "return", "self", ".", "get_accessible_time", "(", ")", ".", "get_soft_end_date", "(", ")", ".", "strftime", "(", "\"%d/%m/%Y %H:%M:%S\"", ")" ]
Returns a string containing the deadline for this task
[ "Returns", "a", "string", "containing", "the", "deadline", "for", "this", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/tasks.py#L77-L85
248,887
UCL-INGI/INGInious
inginious/frontend/tasks.py
WebAppTask.get_authors
def get_authors(self, language): """ Return the list of this task's authors """ return self.gettext(language, self._author) if self._author else ""
python
def get_authors(self, language): return self.gettext(language, self._author) if self._author else ""
[ "def", "get_authors", "(", "self", ",", "language", ")", ":", "return", "self", ".", "gettext", "(", "language", ",", "self", ".", "_author", ")", "if", "self", ".", "_author", "else", "\"\"" ]
Return the list of this task's authors
[ "Return", "the", "list", "of", "this", "task", "s", "authors" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/tasks.py#L106-L108
248,888
UCL-INGI/INGInious
inginious/frontend/tasks.py
WebAppTask.adapt_input_for_backend
def adapt_input_for_backend(self, input_data): """ Adapt the input from web.py for the inginious.backend """ for problem in self._problems: input_data = problem.adapt_input_for_backend(input_data) return input_data
python
def adapt_input_for_backend(self, input_data): for problem in self._problems: input_data = problem.adapt_input_for_backend(input_data) return input_data
[ "def", "adapt_input_for_backend", "(", "self", ",", "input_data", ")", ":", "for", "problem", "in", "self", ".", "_problems", ":", "input_data", "=", "problem", ".", "adapt_input_for_backend", "(", "input_data", ")", "return", "input_data" ]
Adapt the input from web.py for the inginious.backend
[ "Adapt", "the", "input", "from", "web", ".", "py", "for", "the", "inginious", ".", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/tasks.py#L110-L114
248,889
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/submissions.py
CourseSubmissionsPage.get_users
def get_users(self, course): """ Returns a sorted list of users """ users = OrderedDict(sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course)).items()), key=lambda k: k[1][0] if k[1] is not None else "")) return users
python
def get_users(self, course): users = OrderedDict(sorted(list(self.user_manager.get_users_info(self.user_manager.get_course_registered_users(course)).items()), key=lambda k: k[1][0] if k[1] is not None else "")) return users
[ "def", "get_users", "(", "self", ",", "course", ")", ":", "users", "=", "OrderedDict", "(", "sorted", "(", "list", "(", "self", ".", "user_manager", ".", "get_users_info", "(", "self", ".", "user_manager", ".", "get_course_registered_users", "(", "course", ")", ")", ".", "items", "(", ")", ")", ",", "key", "=", "lambda", "k", ":", "k", "[", "1", "]", "[", "0", "]", "if", "k", "[", "1", "]", "is", "not", "None", "else", "\"\"", ")", ")", "return", "users" ]
Returns a sorted list of users
[ "Returns", "a", "sorted", "list", "of", "users" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/submissions.py#L107-L111
248,890
UCL-INGI/INGInious
inginious/frontend/pages/course.py
CoursePage.get_course
def get_course(self, courseid): """ Return the course """ try: course = self.course_factory.get_course(courseid) except: raise web.notfound() return course
python
def get_course(self, courseid): try: course = self.course_factory.get_course(courseid) except: raise web.notfound() return course
[ "def", "get_course", "(", "self", ",", "courseid", ")", ":", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", "except", ":", "raise", "web", ".", "notfound", "(", ")", "return", "course" ]
Return the course
[ "Return", "the", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course.py#L15-L22
248,891
UCL-INGI/INGInious
inginious/frontend/pages/course.py
CoursePage.show_page
def show_page(self, course): """ Prepares and shows the course page """ username = self.user_manager.session_username() if not self.user_manager.course_is_open_to_user(course, lti=False): return self.template_helper.get_renderer().course_unavailable() else: tasks = course.get_tasks() last_submissions = self.submission_manager.get_user_last_submissions(5, {"courseid": course.get_id(), "taskid": {"$in": list(tasks.keys())}}) for submission in last_submissions: submission["taskname"] = tasks[submission['taskid']].get_name(self.user_manager.session_language()) tasks_data = {} user_tasks = self.database.user_tasks.find({"username": username, "courseid": course.get_id(), "taskid": {"$in": list(tasks.keys())}}) is_admin = self.user_manager.has_staff_rights_on_course(course, username) tasks_score = [0.0, 0.0] for taskid, task in tasks.items(): tasks_data[taskid] = {"visible": task.get_accessible_time().after_start() or is_admin, "succeeded": False, "grade": 0.0} tasks_score[1] += task.get_grading_weight() if tasks_data[taskid]["visible"] else 0 for user_task in user_tasks: tasks_data[user_task["taskid"]]["succeeded"] = user_task["succeeded"] tasks_data[user_task["taskid"]]["grade"] = user_task["grade"] weighted_score = user_task["grade"]*tasks[user_task["taskid"]].get_grading_weight() tasks_score[0] += weighted_score if tasks_data[user_task["taskid"]]["visible"] else 0 course_grade = round(tasks_score[0]/tasks_score[1]) if tasks_score[1] > 0 else 0 tag_list = course.get_all_tags_names_as_list(is_admin, self.user_manager.session_language()) user_info = self.database.users.find_one({"username": username}) return self.template_helper.get_renderer().course(user_info, course, last_submissions, tasks, tasks_data, course_grade, tag_list)
python
def show_page(self, course): username = self.user_manager.session_username() if not self.user_manager.course_is_open_to_user(course, lti=False): return self.template_helper.get_renderer().course_unavailable() else: tasks = course.get_tasks() last_submissions = self.submission_manager.get_user_last_submissions(5, {"courseid": course.get_id(), "taskid": {"$in": list(tasks.keys())}}) for submission in last_submissions: submission["taskname"] = tasks[submission['taskid']].get_name(self.user_manager.session_language()) tasks_data = {} user_tasks = self.database.user_tasks.find({"username": username, "courseid": course.get_id(), "taskid": {"$in": list(tasks.keys())}}) is_admin = self.user_manager.has_staff_rights_on_course(course, username) tasks_score = [0.0, 0.0] for taskid, task in tasks.items(): tasks_data[taskid] = {"visible": task.get_accessible_time().after_start() or is_admin, "succeeded": False, "grade": 0.0} tasks_score[1] += task.get_grading_weight() if tasks_data[taskid]["visible"] else 0 for user_task in user_tasks: tasks_data[user_task["taskid"]]["succeeded"] = user_task["succeeded"] tasks_data[user_task["taskid"]]["grade"] = user_task["grade"] weighted_score = user_task["grade"]*tasks[user_task["taskid"]].get_grading_weight() tasks_score[0] += weighted_score if tasks_data[user_task["taskid"]]["visible"] else 0 course_grade = round(tasks_score[0]/tasks_score[1]) if tasks_score[1] > 0 else 0 tag_list = course.get_all_tags_names_as_list(is_admin, self.user_manager.session_language()) user_info = self.database.users.find_one({"username": username}) return self.template_helper.get_renderer().course(user_info, course, last_submissions, tasks, tasks_data, course_grade, tag_list)
[ "def", "show_page", "(", "self", ",", "course", ")", ":", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "if", "not", "self", ".", "user_manager", ".", "course_is_open_to_user", "(", "course", ",", "lti", "=", "False", ")", ":", "return", "self", ".", "template_helper", ".", "get_renderer", "(", ")", ".", "course_unavailable", "(", ")", "else", ":", "tasks", "=", "course", ".", "get_tasks", "(", ")", "last_submissions", "=", "self", ".", "submission_manager", ".", "get_user_last_submissions", "(", "5", ",", "{", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"taskid\"", ":", "{", "\"$in\"", ":", "list", "(", "tasks", ".", "keys", "(", ")", ")", "}", "}", ")", "for", "submission", "in", "last_submissions", ":", "submission", "[", "\"taskname\"", "]", "=", "tasks", "[", "submission", "[", "'taskid'", "]", "]", ".", "get_name", "(", "self", ".", "user_manager", ".", "session_language", "(", ")", ")", "tasks_data", "=", "{", "}", "user_tasks", "=", "self", ".", "database", ".", "user_tasks", ".", "find", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "course", ".", "get_id", "(", ")", ",", "\"taskid\"", ":", "{", "\"$in\"", ":", "list", "(", "tasks", ".", "keys", "(", ")", ")", "}", "}", ")", "is_admin", "=", "self", ".", "user_manager", ".", "has_staff_rights_on_course", "(", "course", ",", "username", ")", "tasks_score", "=", "[", "0.0", ",", "0.0", "]", "for", "taskid", ",", "task", "in", "tasks", ".", "items", "(", ")", ":", "tasks_data", "[", "taskid", "]", "=", "{", "\"visible\"", ":", "task", ".", "get_accessible_time", "(", ")", ".", "after_start", "(", ")", "or", "is_admin", ",", "\"succeeded\"", ":", "False", ",", "\"grade\"", ":", "0.0", "}", "tasks_score", "[", "1", "]", "+=", "task", ".", "get_grading_weight", "(", ")", "if", "tasks_data", "[", "taskid", "]", "[", "\"visible\"", "]", "else", "0", "for", "user_task", "in", "user_tasks", ":", "tasks_data", "[", "user_task", "[", "\"taskid\"", "]", "]", "[", "\"succeeded\"", "]", "=", "user_task", "[", "\"succeeded\"", "]", "tasks_data", "[", "user_task", "[", "\"taskid\"", "]", "]", "[", "\"grade\"", "]", "=", "user_task", "[", "\"grade\"", "]", "weighted_score", "=", "user_task", "[", "\"grade\"", "]", "*", "tasks", "[", "user_task", "[", "\"taskid\"", "]", "]", ".", "get_grading_weight", "(", ")", "tasks_score", "[", "0", "]", "+=", "weighted_score", "if", "tasks_data", "[", "user_task", "[", "\"taskid\"", "]", "]", "[", "\"visible\"", "]", "else", "0", "course_grade", "=", "round", "(", "tasks_score", "[", "0", "]", "/", "tasks_score", "[", "1", "]", ")", "if", "tasks_score", "[", "1", "]", ">", "0", "else", "0", "tag_list", "=", "course", ".", "get_all_tags_names_as_list", "(", "is_admin", ",", "self", ".", "user_manager", ".", "session_language", "(", ")", ")", "user_info", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"username\"", ":", "username", "}", ")", "return", "self", ".", "template_helper", ".", "get_renderer", "(", ")", ".", "course", "(", "user_info", ",", "course", ",", "last_submissions", ",", "tasks", ",", "tasks_data", ",", "course_grade", ",", "tag_list", ")" ]
Prepares and shows the course page
[ "Prepares", "and", "shows", "the", "course", "page" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course.py#L40-L74
248,892
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/tools/mavparms.py
mavparms
def mavparms(logfile): '''extract mavlink parameters''' mlog = mavutil.mavlink_connection(filename) while True: try: m = mlog.recv_match(type=['PARAM_VALUE', 'PARM']) if m is None: return except Exception: return if m.get_type() == 'PARAM_VALUE': pname = str(m.param_id).strip() value = m.param_value else: pname = m.Name value = m.Value if len(pname) > 0: if args.changesOnly is True and pname in parms and parms[pname] != value: print("%s %-15s %.6f -> %.6f" % (time.asctime(time.localtime(m._timestamp)), pname, parms[pname], value)) parms[pname] = value
python
def mavparms(logfile): '''extract mavlink parameters''' mlog = mavutil.mavlink_connection(filename) while True: try: m = mlog.recv_match(type=['PARAM_VALUE', 'PARM']) if m is None: return except Exception: return if m.get_type() == 'PARAM_VALUE': pname = str(m.param_id).strip() value = m.param_value else: pname = m.Name value = m.Value if len(pname) > 0: if args.changesOnly is True and pname in parms and parms[pname] != value: print("%s %-15s %.6f -> %.6f" % (time.asctime(time.localtime(m._timestamp)), pname, parms[pname], value)) parms[pname] = value
[ "def", "mavparms", "(", "logfile", ")", ":", "mlog", "=", "mavutil", ".", "mavlink_connection", "(", "filename", ")", "while", "True", ":", "try", ":", "m", "=", "mlog", ".", "recv_match", "(", "type", "=", "[", "'PARAM_VALUE'", ",", "'PARM'", "]", ")", "if", "m", "is", "None", ":", "return", "except", "Exception", ":", "return", "if", "m", ".", "get_type", "(", ")", "==", "'PARAM_VALUE'", ":", "pname", "=", "str", "(", "m", ".", "param_id", ")", ".", "strip", "(", ")", "value", "=", "m", ".", "param_value", "else", ":", "pname", "=", "m", ".", "Name", "value", "=", "m", ".", "Value", "if", "len", "(", "pname", ")", ">", "0", ":", "if", "args", ".", "changesOnly", "is", "True", "and", "pname", "in", "parms", "and", "parms", "[", "pname", "]", "!=", "value", ":", "print", "(", "\"%s %-15s %.6f -> %.6f\"", "%", "(", "time", ".", "asctime", "(", "time", ".", "localtime", "(", "m", ".", "_timestamp", ")", ")", ",", "pname", ",", "parms", "[", "pname", "]", ",", "value", ")", ")", "parms", "[", "pname", "]", "=", "value" ]
extract mavlink parameters
[ "extract", "mavlink", "parameters" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/tools/mavparms.py#L20-L41
248,893
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
MAVLink.send
def send(self, mavmsg, force_mavlink1=False): '''send a MAVLink message''' buf = mavmsg.pack(self, force_mavlink1=force_mavlink1) self.file.write(buf) self.seq = (self.seq + 1) % 256 self.total_packets_sent += 1 self.total_bytes_sent += len(buf) if self.send_callback: self.send_callback(mavmsg, *self.send_callback_args, **self.send_callback_kwargs)
python
def send(self, mavmsg, force_mavlink1=False): '''send a MAVLink message''' buf = mavmsg.pack(self, force_mavlink1=force_mavlink1) self.file.write(buf) self.seq = (self.seq + 1) % 256 self.total_packets_sent += 1 self.total_bytes_sent += len(buf) if self.send_callback: self.send_callback(mavmsg, *self.send_callback_args, **self.send_callback_kwargs)
[ "def", "send", "(", "self", ",", "mavmsg", ",", "force_mavlink1", "=", "False", ")", ":", "buf", "=", "mavmsg", ".", "pack", "(", "self", ",", "force_mavlink1", "=", "force_mavlink1", ")", "self", ".", "file", ".", "write", "(", "buf", ")", "self", ".", "seq", "=", "(", "self", ".", "seq", "+", "1", ")", "%", "256", "self", ".", "total_packets_sent", "+=", "1", "self", ".", "total_bytes_sent", "+=", "len", "(", "buf", ")", "if", "self", ".", "send_callback", ":", "self", ".", "send_callback", "(", "mavmsg", ",", "*", "self", ".", "send_callback_args", ",", "*", "*", "self", ".", "send_callback_kwargs", ")" ]
send a MAVLink message
[ "send", "a", "MAVLink", "message" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7550-L7558
248,894
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
MAVLink.bytes_needed
def bytes_needed(self): '''return number of bytes needed for next parsing stage''' if self.native: ret = self.native.expected_length - self.buf_len() else: ret = self.expected_length - self.buf_len() if ret <= 0: return 1 return ret
python
def bytes_needed(self): '''return number of bytes needed for next parsing stage''' if self.native: ret = self.native.expected_length - self.buf_len() else: ret = self.expected_length - self.buf_len() if ret <= 0: return 1 return ret
[ "def", "bytes_needed", "(", "self", ")", ":", "if", "self", ".", "native", ":", "ret", "=", "self", ".", "native", ".", "expected_length", "-", "self", ".", "buf_len", "(", ")", "else", ":", "ret", "=", "self", ".", "expected_length", "-", "self", ".", "buf_len", "(", ")", "if", "ret", "<=", "0", ":", "return", "1", "return", "ret" ]
return number of bytes needed for next parsing stage
[ "return", "number", "of", "bytes", "needed", "for", "next", "parsing", "stage" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7563-L7572
248,895
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
MAVLink.__callbacks
def __callbacks(self, msg): '''this method exists only to make profiling results easier to read''' if self.callback: self.callback(msg, *self.callback_args, **self.callback_kwargs)
python
def __callbacks(self, msg): '''this method exists only to make profiling results easier to read''' if self.callback: self.callback(msg, *self.callback_args, **self.callback_kwargs)
[ "def", "__callbacks", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "callback", ":", "self", ".", "callback", "(", "msg", ",", "*", "self", ".", "callback_args", ",", "*", "*", "self", ".", "callback_kwargs", ")" ]
this method exists only to make profiling results easier to read
[ "this", "method", "exists", "only", "to", "make", "profiling", "results", "easier", "to", "read" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7579-L7582
248,896
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
MAVLink.parse_char
def parse_char(self, c): '''input some data bytes, possibly returning a new message''' self.buf.extend(c) self.total_bytes_received += len(c) if self.native: if native_testing: self.test_buf.extend(c) m = self.__parse_char_native(self.test_buf) m2 = self.__parse_char_legacy() if m2 != m: print("Native: %s\nLegacy: %s\n" % (m, m2)) raise Exception('Native vs. Legacy mismatch') else: m = self.__parse_char_native(self.buf) else: m = self.__parse_char_legacy() if m != None: self.total_packets_received += 1 self.__callbacks(m) else: # XXX The idea here is if we've read something and there's nothing left in # the buffer, reset it to 0 which frees the memory if self.buf_len() == 0 and self.buf_index != 0: self.buf = bytearray() self.buf_index = 0 return m
python
def parse_char(self, c): '''input some data bytes, possibly returning a new message''' self.buf.extend(c) self.total_bytes_received += len(c) if self.native: if native_testing: self.test_buf.extend(c) m = self.__parse_char_native(self.test_buf) m2 = self.__parse_char_legacy() if m2 != m: print("Native: %s\nLegacy: %s\n" % (m, m2)) raise Exception('Native vs. Legacy mismatch') else: m = self.__parse_char_native(self.buf) else: m = self.__parse_char_legacy() if m != None: self.total_packets_received += 1 self.__callbacks(m) else: # XXX The idea here is if we've read something and there's nothing left in # the buffer, reset it to 0 which frees the memory if self.buf_len() == 0 and self.buf_index != 0: self.buf = bytearray() self.buf_index = 0 return m
[ "def", "parse_char", "(", "self", ",", "c", ")", ":", "self", ".", "buf", ".", "extend", "(", "c", ")", "self", ".", "total_bytes_received", "+=", "len", "(", "c", ")", "if", "self", ".", "native", ":", "if", "native_testing", ":", "self", ".", "test_buf", ".", "extend", "(", "c", ")", "m", "=", "self", ".", "__parse_char_native", "(", "self", ".", "test_buf", ")", "m2", "=", "self", ".", "__parse_char_legacy", "(", ")", "if", "m2", "!=", "m", ":", "print", "(", "\"Native: %s\\nLegacy: %s\\n\"", "%", "(", "m", ",", "m2", ")", ")", "raise", "Exception", "(", "'Native vs. Legacy mismatch'", ")", "else", ":", "m", "=", "self", ".", "__parse_char_native", "(", "self", ".", "buf", ")", "else", ":", "m", "=", "self", ".", "__parse_char_legacy", "(", ")", "if", "m", "!=", "None", ":", "self", ".", "total_packets_received", "+=", "1", "self", ".", "__callbacks", "(", "m", ")", "else", ":", "# XXX The idea here is if we've read something and there's nothing left in", "# the buffer, reset it to 0 which frees the memory", "if", "self", ".", "buf_len", "(", ")", "==", "0", "and", "self", ".", "buf_index", "!=", "0", ":", "self", ".", "buf", "=", "bytearray", "(", ")", "self", ".", "buf_index", "=", "0", "return", "m" ]
input some data bytes, possibly returning a new message
[ "input", "some", "data", "bytes", "possibly", "returning", "a", "new", "message" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7584-L7613
248,897
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
MAVLink.parse_buffer
def parse_buffer(self, s): '''input some data bytes, possibly returning a list of new messages''' m = self.parse_char(s) if m is None: return None ret = [m] while True: m = self.parse_char("") if m is None: return ret ret.append(m) return ret
python
def parse_buffer(self, s): '''input some data bytes, possibly returning a list of new messages''' m = self.parse_char(s) if m is None: return None ret = [m] while True: m = self.parse_char("") if m is None: return ret ret.append(m) return ret
[ "def", "parse_buffer", "(", "self", ",", "s", ")", ":", "m", "=", "self", ".", "parse_char", "(", "s", ")", "if", "m", "is", "None", ":", "return", "None", "ret", "=", "[", "m", "]", "while", "True", ":", "m", "=", "self", ".", "parse_char", "(", "\"\"", ")", "if", "m", "is", "None", ":", "return", "ret", "ret", ".", "append", "(", "m", ")", "return", "ret" ]
input some data bytes, possibly returning a list of new messages
[ "input", "some", "data", "bytes", "possibly", "returning", "a", "list", "of", "new", "messages" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7662-L7673
248,898
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
MAVLink.check_signature
def check_signature(self, msgbuf, srcSystem, srcComponent): '''check signature on incoming message''' if isinstance(msgbuf, array.array): msgbuf = msgbuf.tostring() timestamp_buf = msgbuf[-12:-6] link_id = msgbuf[-13] (tlow, thigh) = struct.unpack('<IH', timestamp_buf) timestamp = tlow + (thigh<<32) # see if the timestamp is acceptable stream_key = (link_id,srcSystem,srcComponent) if stream_key in self.signing.stream_timestamps: if timestamp <= self.signing.stream_timestamps[stream_key]: # reject old timestamp # print('old timestamp') return False else: # a new stream has appeared. Accept the timestamp if it is at most # one minute behind our current timestamp if timestamp + 6000*1000 < self.signing.timestamp: # print('bad new stream ', timestamp/(100.0*1000*60*60*24*365), self.signing.timestamp/(100.0*1000*60*60*24*365)) return False self.signing.stream_timestamps[stream_key] = timestamp # print('new stream') h = hashlib.new('sha256') h.update(self.signing.secret_key) h.update(msgbuf[:-6]) sig1 = str(h.digest())[:6] sig2 = str(msgbuf)[-6:] if sig1 != sig2: # print('sig mismatch') return False # the timestamp we next send with is the max of the received timestamp and # our current timestamp self.signing.timestamp = max(self.signing.timestamp, timestamp) return True
python
def check_signature(self, msgbuf, srcSystem, srcComponent): '''check signature on incoming message''' if isinstance(msgbuf, array.array): msgbuf = msgbuf.tostring() timestamp_buf = msgbuf[-12:-6] link_id = msgbuf[-13] (tlow, thigh) = struct.unpack('<IH', timestamp_buf) timestamp = tlow + (thigh<<32) # see if the timestamp is acceptable stream_key = (link_id,srcSystem,srcComponent) if stream_key in self.signing.stream_timestamps: if timestamp <= self.signing.stream_timestamps[stream_key]: # reject old timestamp # print('old timestamp') return False else: # a new stream has appeared. Accept the timestamp if it is at most # one minute behind our current timestamp if timestamp + 6000*1000 < self.signing.timestamp: # print('bad new stream ', timestamp/(100.0*1000*60*60*24*365), self.signing.timestamp/(100.0*1000*60*60*24*365)) return False self.signing.stream_timestamps[stream_key] = timestamp # print('new stream') h = hashlib.new('sha256') h.update(self.signing.secret_key) h.update(msgbuf[:-6]) sig1 = str(h.digest())[:6] sig2 = str(msgbuf)[-6:] if sig1 != sig2: # print('sig mismatch') return False # the timestamp we next send with is the max of the received timestamp and # our current timestamp self.signing.timestamp = max(self.signing.timestamp, timestamp) return True
[ "def", "check_signature", "(", "self", ",", "msgbuf", ",", "srcSystem", ",", "srcComponent", ")", ":", "if", "isinstance", "(", "msgbuf", ",", "array", ".", "array", ")", ":", "msgbuf", "=", "msgbuf", ".", "tostring", "(", ")", "timestamp_buf", "=", "msgbuf", "[", "-", "12", ":", "-", "6", "]", "link_id", "=", "msgbuf", "[", "-", "13", "]", "(", "tlow", ",", "thigh", ")", "=", "struct", ".", "unpack", "(", "'<IH'", ",", "timestamp_buf", ")", "timestamp", "=", "tlow", "+", "(", "thigh", "<<", "32", ")", "# see if the timestamp is acceptable", "stream_key", "=", "(", "link_id", ",", "srcSystem", ",", "srcComponent", ")", "if", "stream_key", "in", "self", ".", "signing", ".", "stream_timestamps", ":", "if", "timestamp", "<=", "self", ".", "signing", ".", "stream_timestamps", "[", "stream_key", "]", ":", "# reject old timestamp", "# print('old timestamp')", "return", "False", "else", ":", "# a new stream has appeared. Accept the timestamp if it is at most", "# one minute behind our current timestamp", "if", "timestamp", "+", "6000", "*", "1000", "<", "self", ".", "signing", ".", "timestamp", ":", "# print('bad new stream ', timestamp/(100.0*1000*60*60*24*365), self.signing.timestamp/(100.0*1000*60*60*24*365))", "return", "False", "self", ".", "signing", ".", "stream_timestamps", "[", "stream_key", "]", "=", "timestamp", "# print('new stream')", "h", "=", "hashlib", ".", "new", "(", "'sha256'", ")", "h", ".", "update", "(", "self", ".", "signing", ".", "secret_key", ")", "h", ".", "update", "(", "msgbuf", "[", ":", "-", "6", "]", ")", "sig1", "=", "str", "(", "h", ".", "digest", "(", ")", ")", "[", ":", "6", "]", "sig2", "=", "str", "(", "msgbuf", ")", "[", "-", "6", ":", "]", "if", "sig1", "!=", "sig2", ":", "# print('sig mismatch')", "return", "False", "# the timestamp we next send with is the max of the received timestamp and", "# our current timestamp", "self", ".", "signing", ".", "timestamp", "=", "max", "(", "self", ".", "signing", ".", "timestamp", ",", "timestamp", ")", "return", "True" ]
check signature on incoming message
[ "check", "signature", "on", "incoming", "message" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7675-L7712
248,899
JdeRobot/base
src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py
MAVLink.flexifunction_set_send
def flexifunction_set_send(self, target_system, target_component, force_mavlink1=False): ''' Depreciated but used as a compiler flag. Do not remove target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.flexifunction_set_encode(target_system, target_component), force_mavlink1=force_mavlink1)
python
def flexifunction_set_send(self, target_system, target_component, force_mavlink1=False): ''' Depreciated but used as a compiler flag. Do not remove target_system : System ID (uint8_t) target_component : Component ID (uint8_t) ''' return self.send(self.flexifunction_set_encode(target_system, target_component), force_mavlink1=force_mavlink1)
[ "def", "flexifunction_set_send", "(", "self", ",", "target_system", ",", "target_component", ",", "force_mavlink1", "=", "False", ")", ":", "return", "self", ".", "send", "(", "self", ".", "flexifunction_set_encode", "(", "target_system", ",", "target_component", ")", ",", "force_mavlink1", "=", "force_mavlink1", ")" ]
Depreciated but used as a compiler flag. Do not remove target_system : System ID (uint8_t) target_component : Component ID (uint8_t)
[ "Depreciated", "but", "used", "as", "a", "compiler", "flag", ".", "Do", "not", "remove" ]
303b18992785b2fe802212f2d758a60873007f1f
https://github.com/JdeRobot/base/blob/303b18992785b2fe802212f2d758a60873007f1f/src/drivers/MAVLinkServer/MAVProxy/pymavlink/dialects/v10/matrixpilot.py#L7855-L7863