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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
234,900
rigetti/quantumflow
quantumflow/gates.py
join_gates
def join_gates(*gates: Gate) -> Gate: """Direct product of two gates. Qubit count is the sum of each gate's bit count.""" vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
python
def join_gates(*gates: Gate) -> Gate: """Direct product of two gates. Qubit count is the sum of each gate's bit count.""" vectors = [gate.vec for gate in gates] vec = reduce(outer_product, vectors) return Gate(vec.tensor, vec.qubits)
[ "def", "join_gates", "(", "*", "gates", ":", "Gate", ")", "->", "Gate", ":", "vectors", "=", "[", "gate", ".", "vec", "for", "gate", "in", "gates", "]", "vec", "=", "reduce", "(", "outer_product", ",", "vectors", ")", "return", "Gate", "(", "vec", ".", "tensor", ",", "vec", ".", "qubits", ")" ]
Direct product of two gates. Qubit count is the sum of each gate's bit count.
[ "Direct", "product", "of", "two", "gates", ".", "Qubit", "count", "is", "the", "sum", "of", "each", "gate", "s", "bit", "count", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L63-L68
234,901
rigetti/quantumflow
quantumflow/gates.py
control_gate
def control_gate(control: Qubit, gate: Gate) -> Gate: """Return a controlled unitary gate. Given a gate acting on K qubits, return a new gate on K+1 qubits prepended with a control bit. """ if control in gate.qubits: raise ValueError('Gate and control qubits overlap') qubits = [control, *gate.qubits] gate_tensor = join_gates(P0(control), identity_gate(gate.qubits)).tensor \ + join_gates(P1(control), gate).tensor controlled_gate = Gate(qubits=qubits, tensor=gate_tensor) return controlled_gate
python
def control_gate(control: Qubit, gate: Gate) -> Gate: """Return a controlled unitary gate. Given a gate acting on K qubits, return a new gate on K+1 qubits prepended with a control bit. """ if control in gate.qubits: raise ValueError('Gate and control qubits overlap') qubits = [control, *gate.qubits] gate_tensor = join_gates(P0(control), identity_gate(gate.qubits)).tensor \ + join_gates(P1(control), gate).tensor controlled_gate = Gate(qubits=qubits, tensor=gate_tensor) return controlled_gate
[ "def", "control_gate", "(", "control", ":", "Qubit", ",", "gate", ":", "Gate", ")", "->", "Gate", ":", "if", "control", "in", "gate", ".", "qubits", ":", "raise", "ValueError", "(", "'Gate and control qubits overlap'", ")", "qubits", "=", "[", "control", ",", "*", "gate", ".", "qubits", "]", "gate_tensor", "=", "join_gates", "(", "P0", "(", "control", ")", ",", "identity_gate", "(", "gate", ".", "qubits", ")", ")", ".", "tensor", "+", "join_gates", "(", "P1", "(", "control", ")", ",", "gate", ")", ".", "tensor", "controlled_gate", "=", "Gate", "(", "qubits", "=", "qubits", ",", "tensor", "=", "gate_tensor", ")", "return", "controlled_gate" ]
Return a controlled unitary gate. Given a gate acting on K qubits, return a new gate on K+1 qubits prepended with a control bit.
[ "Return", "a", "controlled", "unitary", "gate", ".", "Given", "a", "gate", "acting", "on", "K", "qubits", "return", "a", "new", "gate", "on", "K", "+", "1", "qubits", "prepended", "with", "a", "control", "bit", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L71-L83
234,902
rigetti/quantumflow
quantumflow/gates.py
conditional_gate
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate: """Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1""" assert gate0.qubits == gate1.qubits # FIXME tensor = join_gates(P0(control), gate0).tensor tensor += join_gates(P1(control), gate1).tensor gate = Gate(tensor=tensor, qubits=[control, *gate0.qubits]) return gate
python
def conditional_gate(control: Qubit, gate0: Gate, gate1: Gate) -> Gate: """Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1""" assert gate0.qubits == gate1.qubits # FIXME tensor = join_gates(P0(control), gate0).tensor tensor += join_gates(P1(control), gate1).tensor gate = Gate(tensor=tensor, qubits=[control, *gate0.qubits]) return gate
[ "def", "conditional_gate", "(", "control", ":", "Qubit", ",", "gate0", ":", "Gate", ",", "gate1", ":", "Gate", ")", "->", "Gate", ":", "assert", "gate0", ".", "qubits", "==", "gate1", ".", "qubits", "# FIXME", "tensor", "=", "join_gates", "(", "P0", "(", "control", ")", ",", "gate0", ")", ".", "tensor", "tensor", "+=", "join_gates", "(", "P1", "(", "control", ")", ",", "gate1", ")", ".", "tensor", "gate", "=", "Gate", "(", "tensor", "=", "tensor", ",", "qubits", "=", "[", "control", ",", "*", "gate0", ".", "qubits", "]", ")", "return", "gate" ]
Return a conditional unitary gate. Do gate0 on bit 1 if bit 0 is zero, else do gate1 on 1
[ "Return", "a", "conditional", "unitary", "gate", ".", "Do", "gate0", "on", "bit", "1", "if", "bit", "0", "is", "zero", "else", "do", "gate1", "on", "1" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L86-L94
234,903
rigetti/quantumflow
quantumflow/gates.py
print_gate
def print_gate(gate: Gate, ndigits: int = 2, file: TextIO = None) -> None: """Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout """ N = gate.qubit_nb gate_tensor = gate.vec.asarray() lines = [] for index, amplitude in np.ndenumerate(gate_tensor): ket = "".join([str(n) for n in index[0:N]]) bra = "".join([str(index[n]) for n in range(N, 2*N)]) if round(abs(amplitude)**2, ndigits) > 0.0: lines.append('{} -> {} : {}'.format(bra, ket, amplitude)) lines.sort(key=lambda x: int(x[0:N])) print('\n'.join(lines), file=file)
python
def print_gate(gate: Gate, ndigits: int = 2, file: TextIO = None) -> None: """Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout """ N = gate.qubit_nb gate_tensor = gate.vec.asarray() lines = [] for index, amplitude in np.ndenumerate(gate_tensor): ket = "".join([str(n) for n in index[0:N]]) bra = "".join([str(index[n]) for n in range(N, 2*N)]) if round(abs(amplitude)**2, ndigits) > 0.0: lines.append('{} -> {} : {}'.format(bra, ket, amplitude)) lines.sort(key=lambda x: int(x[0:N])) print('\n'.join(lines), file=file)
[ "def", "print_gate", "(", "gate", ":", "Gate", ",", "ndigits", ":", "int", "=", "2", ",", "file", ":", "TextIO", "=", "None", ")", "->", "None", ":", "N", "=", "gate", ".", "qubit_nb", "gate_tensor", "=", "gate", ".", "vec", ".", "asarray", "(", ")", "lines", "=", "[", "]", "for", "index", ",", "amplitude", "in", "np", ".", "ndenumerate", "(", "gate_tensor", ")", ":", "ket", "=", "\"\"", ".", "join", "(", "[", "str", "(", "n", ")", "for", "n", "in", "index", "[", "0", ":", "N", "]", "]", ")", "bra", "=", "\"\"", ".", "join", "(", "[", "str", "(", "index", "[", "n", "]", ")", "for", "n", "in", "range", "(", "N", ",", "2", "*", "N", ")", "]", ")", "if", "round", "(", "abs", "(", "amplitude", ")", "**", "2", ",", "ndigits", ")", ">", "0.0", ":", "lines", ".", "append", "(", "'{} -> {} : {}'", ".", "format", "(", "bra", ",", "ket", ",", "amplitude", ")", ")", "lines", ".", "sort", "(", "key", "=", "lambda", "x", ":", "int", "(", "x", "[", "0", ":", "N", "]", ")", ")", "print", "(", "'\\n'", ".", "join", "(", "lines", ")", ",", "file", "=", "file", ")" ]
Pretty print a gate tensor Args: gate: ndigits: file: Stream to which to write. Defaults to stdout
[ "Pretty", "print", "a", "gate", "tensor" ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L116-L134
234,904
rigetti/quantumflow
quantumflow/gates.py
random_gate
def random_gate(qubits: Union[int, Qubits]) -> Gate: r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050 """ N, qubits = qubits_count_tuple(qubits) unitary = scipy.stats.unitary_group.rvs(2**N) return Gate(unitary, qubits=qubits, name='RAND{}'.format(N))
python
def random_gate(qubits: Union[int, Qubits]) -> Gate: r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050 """ N, qubits = qubits_count_tuple(qubits) unitary = scipy.stats.unitary_group.rvs(2**N) return Gate(unitary, qubits=qubits, name='RAND{}'.format(N))
[ "def", "random_gate", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Gate", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "unitary", "=", "scipy", ".", "stats", ".", "unitary_group", ".", "rvs", "(", "2", "**", "N", ")", "return", "Gate", "(", "unitary", ",", "qubits", "=", "qubits", ",", "name", "=", "'RAND{}'", ".", "format", "(", "N", ")", ")" ]
r"""Returns a random unitary gate on K qubits. Ref: "How to generate random matrices from the classical compact groups" Francesco Mezzadri, math-ph/0609050
[ "r", "Returns", "a", "random", "unitary", "gate", "on", "K", "qubits", "." ]
13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb
https://github.com/rigetti/quantumflow/blob/13a66cabbe8aabf6e023cc675f4a4ebe6ccda8fb/quantumflow/gates.py#L159-L168
234,905
VirusTotal/yara-python
setup.py
has_function
def has_function(function_name, libraries=None): """Checks if a given functions exists in the current platform.""" compiler = distutils.ccompiler.new_compiler() with muted(sys.stdout, sys.stderr): result = compiler.has_function( function_name, libraries=libraries) if os.path.exists('a.out'): os.remove('a.out') return result
python
def has_function(function_name, libraries=None): """Checks if a given functions exists in the current platform.""" compiler = distutils.ccompiler.new_compiler() with muted(sys.stdout, sys.stderr): result = compiler.has_function( function_name, libraries=libraries) if os.path.exists('a.out'): os.remove('a.out') return result
[ "def", "has_function", "(", "function_name", ",", "libraries", "=", "None", ")", ":", "compiler", "=", "distutils", ".", "ccompiler", ".", "new_compiler", "(", ")", "with", "muted", "(", "sys", ".", "stdout", ",", "sys", ".", "stderr", ")", ":", "result", "=", "compiler", ".", "has_function", "(", "function_name", ",", "libraries", "=", "libraries", ")", "if", "os", ".", "path", ".", "exists", "(", "'a.out'", ")", ":", "os", ".", "remove", "(", "'a.out'", ")", "return", "result" ]
Checks if a given functions exists in the current platform.
[ "Checks", "if", "a", "given", "functions", "exists", "in", "the", "current", "platform", "." ]
c3992bdc3a95d42e9df249ae92e726b74737e859
https://github.com/VirusTotal/yara-python/blob/c3992bdc3a95d42e9df249ae92e726b74737e859/setup.py#L80-L88
234,906
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_message
async def handle_agent_message(self, agent_addr, message): """Dispatch messages received from agents to the right handlers""" message_handlers = { AgentHello: self.handle_agent_hello, AgentJobStarted: self.handle_agent_job_started, AgentJobDone: self.handle_agent_job_done, AgentJobSSHDebug: self.handle_agent_job_ssh_debug, Pong: self._handle_pong } try: func = message_handlers[message.__class__] except: raise TypeError("Unknown message type %s" % message.__class__) self._create_safe_task(func(agent_addr, message))
python
async def handle_agent_message(self, agent_addr, message): """Dispatch messages received from agents to the right handlers""" message_handlers = { AgentHello: self.handle_agent_hello, AgentJobStarted: self.handle_agent_job_started, AgentJobDone: self.handle_agent_job_done, AgentJobSSHDebug: self.handle_agent_job_ssh_debug, Pong: self._handle_pong } try: func = message_handlers[message.__class__] except: raise TypeError("Unknown message type %s" % message.__class__) self._create_safe_task(func(agent_addr, message))
[ "async", "def", "handle_agent_message", "(", "self", ",", "agent_addr", ",", "message", ")", ":", "message_handlers", "=", "{", "AgentHello", ":", "self", ".", "handle_agent_hello", ",", "AgentJobStarted", ":", "self", ".", "handle_agent_job_started", ",", "AgentJobDone", ":", "self", ".", "handle_agent_job_done", ",", "AgentJobSSHDebug", ":", "self", ".", "handle_agent_job_ssh_debug", ",", "Pong", ":", "self", ".", "_handle_pong", "}", "try", ":", "func", "=", "message_handlers", "[", "message", ".", "__class__", "]", "except", ":", "raise", "TypeError", "(", "\"Unknown message type %s\"", "%", "message", ".", "__class__", ")", "self", ".", "_create_safe_task", "(", "func", "(", "agent_addr", ",", "message", ")", ")" ]
Dispatch messages received from agents to the right handlers
[ "Dispatch", "messages", "received", "from", "agents", "to", "the", "right", "handlers" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L59-L72
234,907
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_hello
async def handle_client_hello(self, client_addr, _: ClientHello): """ Handle an ClientHello message. Send available containers to the client """ self._logger.info("New client connected %s", client_addr) self._registered_clients.add(client_addr) await self.send_container_update_to_client([client_addr])
python
async def handle_client_hello(self, client_addr, _: ClientHello): """ Handle an ClientHello message. Send available containers to the client """ self._logger.info("New client connected %s", client_addr) self._registered_clients.add(client_addr) await self.send_container_update_to_client([client_addr])
[ "async", "def", "handle_client_hello", "(", "self", ",", "client_addr", ",", "_", ":", "ClientHello", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"New client connected %s\"", ",", "client_addr", ")", "self", ".", "_registered_clients", ".", "add", "(", "client_addr", ")", "await", "self", ".", "send_container_update_to_client", "(", "[", "client_addr", "]", ")" ]
Handle an ClientHello message. Send available containers to the client
[ "Handle", "an", "ClientHello", "message", ".", "Send", "available", "containers", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L103-L107
234,908
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_ping
async def handle_client_ping(self, client_addr, _: Ping): """ Handle an Ping message. Pong the client """ await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
python
async def handle_client_ping(self, client_addr, _: Ping): """ Handle an Ping message. Pong the client """ await ZMQUtils.send_with_addr(self._client_socket, client_addr, Pong())
[ "async", "def", "handle_client_ping", "(", "self", ",", "client_addr", ",", "_", ":", "Ping", ")", ":", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "client_addr", ",", "Pong", "(", ")", ")" ]
Handle an Ping message. Pong the client
[ "Handle", "an", "Ping", "message", ".", "Pong", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L109-L111
234,909
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_new_job
async def handle_client_new_job(self, client_addr, message: ClientNewJob): """ Handle an ClientNewJob message. Add a job to the queue and triggers an update """ self._logger.info("Adding a new job %s %s to the queue", client_addr, message.job_id) self._waiting_jobs[(client_addr, message.job_id)] = message await self.update_queue()
python
async def handle_client_new_job(self, client_addr, message: ClientNewJob): """ Handle an ClientNewJob message. Add a job to the queue and triggers an update """ self._logger.info("Adding a new job %s %s to the queue", client_addr, message.job_id) self._waiting_jobs[(client_addr, message.job_id)] = message await self.update_queue()
[ "async", "def", "handle_client_new_job", "(", "self", ",", "client_addr", ",", "message", ":", "ClientNewJob", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Adding a new job %s %s to the queue\"", ",", "client_addr", ",", "message", ".", "job_id", ")", "self", ".", "_waiting_jobs", "[", "(", "client_addr", ",", "message", ".", "job_id", ")", "]", "=", "message", "await", "self", ".", "update_queue", "(", ")" ]
Handle an ClientNewJob message. Add a job to the queue and triggers an update
[ "Handle", "an", "ClientNewJob", "message", ".", "Add", "a", "job", "to", "the", "queue", "and", "triggers", "an", "update" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L113-L117
234,910
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_kill_job
async def handle_client_kill_job(self, client_addr, message: ClientKillJob): """ Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. """ # Check if the job is not in the queue if (client_addr, message.job_id) in self._waiting_jobs: del self._waiting_jobs[(client_addr, message.job_id)] # Do not forget to send a JobDone await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendJobDone(message.job_id, ("killed", "You killed the job"), 0.0, {}, {}, {}, "", None, "", "")) # If the job is running, transmit the info to the agent elif (client_addr, message.job_id) in self._job_running: agent_addr = self._job_running[(client_addr, message.job_id)][0] await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendKillJob((client_addr, message.job_id))) else: self._logger.warning("Client %s attempted to kill unknown job %s", str(client_addr), str(message.job_id))
python
async def handle_client_kill_job(self, client_addr, message: ClientKillJob): """ Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent. """ # Check if the job is not in the queue if (client_addr, message.job_id) in self._waiting_jobs: del self._waiting_jobs[(client_addr, message.job_id)] # Do not forget to send a JobDone await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendJobDone(message.job_id, ("killed", "You killed the job"), 0.0, {}, {}, {}, "", None, "", "")) # If the job is running, transmit the info to the agent elif (client_addr, message.job_id) in self._job_running: agent_addr = self._job_running[(client_addr, message.job_id)][0] await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendKillJob((client_addr, message.job_id))) else: self._logger.warning("Client %s attempted to kill unknown job %s", str(client_addr), str(message.job_id))
[ "async", "def", "handle_client_kill_job", "(", "self", ",", "client_addr", ",", "message", ":", "ClientKillJob", ")", ":", "# Check if the job is not in the queue", "if", "(", "client_addr", ",", "message", ".", "job_id", ")", "in", "self", ".", "_waiting_jobs", ":", "del", "self", ".", "_waiting_jobs", "[", "(", "client_addr", ",", "message", ".", "job_id", ")", "]", "# Do not forget to send a JobDone", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "client_addr", ",", "BackendJobDone", "(", "message", ".", "job_id", ",", "(", "\"killed\"", ",", "\"You killed the job\"", ")", ",", "0.0", ",", "{", "}", ",", "{", "}", ",", "{", "}", ",", "\"\"", ",", "None", ",", "\"\"", ",", "\"\"", ")", ")", "# If the job is running, transmit the info to the agent", "elif", "(", "client_addr", ",", "message", ".", "job_id", ")", "in", "self", ".", "_job_running", ":", "agent_addr", "=", "self", ".", "_job_running", "[", "(", "client_addr", ",", "message", ".", "job_id", ")", "]", "[", "0", "]", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_agent_socket", ",", "agent_addr", ",", "BackendKillJob", "(", "(", "client_addr", ",", "message", ".", "job_id", ")", ")", ")", "else", ":", "self", ".", "_logger", ".", "warning", "(", "\"Client %s attempted to kill unknown job %s\"", ",", "str", "(", "client_addr", ")", ",", "str", "(", "message", ".", "job_id", ")", ")" ]
Handle an ClientKillJob message. Remove a job from the waiting list or send the kill message to the right agent.
[ "Handle", "an", "ClientKillJob", "message", ".", "Remove", "a", "job", "from", "the", "waiting", "list", "or", "send", "the", "kill", "message", "to", "the", "right", "agent", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L119-L132
234,911
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_client_get_queue
async def handle_client_get_queue(self, client_addr, _: ClientGetQueue): """ Handles a ClientGetQueue message. Send back info about the job queue""" #jobs_running: a list of tuples in the form #(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end) jobs_running = list() for backend_job_id, content in self._job_running.items(): jobs_running.append((content[1].job_id, backend_job_id[0] == client_addr, self._registered_agents[content[0]], content[1].course_id+"/"+content[1].task_id, content[1].launcher, int(content[2]), int(content[2])+content[1].time_limit)) #jobs_waiting: a list of tuples in the form #(job_id, is_current_client_job, info, launcher, max_time) jobs_waiting = list() for job_client_addr, msg in self._waiting_jobs.items(): if isinstance(msg, ClientNewJob): jobs_waiting.append((msg.job_id, job_client_addr[0] == client_addr, msg.course_id+"/"+msg.task_id, msg.launcher, msg.time_limit)) await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendGetQueue(jobs_running, jobs_waiting))
python
async def handle_client_get_queue(self, client_addr, _: ClientGetQueue): """ Handles a ClientGetQueue message. Send back info about the job queue""" #jobs_running: a list of tuples in the form #(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end) jobs_running = list() for backend_job_id, content in self._job_running.items(): jobs_running.append((content[1].job_id, backend_job_id[0] == client_addr, self._registered_agents[content[0]], content[1].course_id+"/"+content[1].task_id, content[1].launcher, int(content[2]), int(content[2])+content[1].time_limit)) #jobs_waiting: a list of tuples in the form #(job_id, is_current_client_job, info, launcher, max_time) jobs_waiting = list() for job_client_addr, msg in self._waiting_jobs.items(): if isinstance(msg, ClientNewJob): jobs_waiting.append((msg.job_id, job_client_addr[0] == client_addr, msg.course_id+"/"+msg.task_id, msg.launcher, msg.time_limit)) await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendGetQueue(jobs_running, jobs_waiting))
[ "async", "def", "handle_client_get_queue", "(", "self", ",", "client_addr", ",", "_", ":", "ClientGetQueue", ")", ":", "#jobs_running: a list of tuples in the form", "#(job_id, is_current_client_job, agent_name, info, launcher, started_at, max_end)", "jobs_running", "=", "list", "(", ")", "for", "backend_job_id", ",", "content", "in", "self", ".", "_job_running", ".", "items", "(", ")", ":", "jobs_running", ".", "append", "(", "(", "content", "[", "1", "]", ".", "job_id", ",", "backend_job_id", "[", "0", "]", "==", "client_addr", ",", "self", ".", "_registered_agents", "[", "content", "[", "0", "]", "]", ",", "content", "[", "1", "]", ".", "course_id", "+", "\"/\"", "+", "content", "[", "1", "]", ".", "task_id", ",", "content", "[", "1", "]", ".", "launcher", ",", "int", "(", "content", "[", "2", "]", ")", ",", "int", "(", "content", "[", "2", "]", ")", "+", "content", "[", "1", "]", ".", "time_limit", ")", ")", "#jobs_waiting: a list of tuples in the form", "#(job_id, is_current_client_job, info, launcher, max_time)", "jobs_waiting", "=", "list", "(", ")", "for", "job_client_addr", ",", "msg", "in", "self", ".", "_waiting_jobs", ".", "items", "(", ")", ":", "if", "isinstance", "(", "msg", ",", "ClientNewJob", ")", ":", "jobs_waiting", ".", "append", "(", "(", "msg", ".", "job_id", ",", "job_client_addr", "[", "0", "]", "==", "client_addr", ",", "msg", ".", "course_id", "+", "\"/\"", "+", "msg", ".", "task_id", ",", "msg", ".", "launcher", ",", "msg", ".", "time_limit", ")", ")", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "client_addr", ",", "BackendGetQueue", "(", "jobs_running", ",", "jobs_waiting", ")", ")" ]
Handles a ClientGetQueue message. Send back info about the job queue
[ "Handles", "a", "ClientGetQueue", "message", ".", "Send", "back", "info", "about", "the", "job", "queue" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L134-L154
234,912
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.update_queue
async def update_queue(self): """ Send waiting jobs to available agents """ # For now, round-robin not_found_for_agent = [] while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0: agent_addr = self._available_agents.pop(0) # Find first job that can be run on this agent found = False client_addr, job_id, job_msg = None, None, None for (client_addr, job_id), job_msg in self._waiting_jobs.items(): if job_msg.environment in self._containers_on_agent[agent_addr]: found = True break if not found: self._logger.debug("Nothing to do for agent %s", agent_addr) not_found_for_agent.append(agent_addr) continue # Remove the job from the queue del self._waiting_jobs[(client_addr, job_id)] job_id = (client_addr, job_msg.job_id) self._job_running[job_id] = (agent_addr, job_msg, time.time()) self._logger.info("Sending job %s %s to agent %s", client_addr, job_msg.job_id, agent_addr) await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendNewJob(job_id, job_msg.course_id, job_msg.task_id, job_msg.inputdata, job_msg.environment, job_msg.enable_network, job_msg.time_limit, job_msg.hard_time_limit, job_msg.mem_limit, job_msg.debug)) # Do not forget to add again for which we did not find jobs to do self._available_agents += not_found_for_agent
python
async def update_queue(self): """ Send waiting jobs to available agents """ # For now, round-robin not_found_for_agent = [] while len(self._available_agents) > 0 and len(self._waiting_jobs) > 0: agent_addr = self._available_agents.pop(0) # Find first job that can be run on this agent found = False client_addr, job_id, job_msg = None, None, None for (client_addr, job_id), job_msg in self._waiting_jobs.items(): if job_msg.environment in self._containers_on_agent[agent_addr]: found = True break if not found: self._logger.debug("Nothing to do for agent %s", agent_addr) not_found_for_agent.append(agent_addr) continue # Remove the job from the queue del self._waiting_jobs[(client_addr, job_id)] job_id = (client_addr, job_msg.job_id) self._job_running[job_id] = (agent_addr, job_msg, time.time()) self._logger.info("Sending job %s %s to agent %s", client_addr, job_msg.job_id, agent_addr) await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, BackendNewJob(job_id, job_msg.course_id, job_msg.task_id, job_msg.inputdata, job_msg.environment, job_msg.enable_network, job_msg.time_limit, job_msg.hard_time_limit, job_msg.mem_limit, job_msg.debug)) # Do not forget to add again for which we did not find jobs to do self._available_agents += not_found_for_agent
[ "async", "def", "update_queue", "(", "self", ")", ":", "# For now, round-robin", "not_found_for_agent", "=", "[", "]", "while", "len", "(", "self", ".", "_available_agents", ")", ">", "0", "and", "len", "(", "self", ".", "_waiting_jobs", ")", ">", "0", ":", "agent_addr", "=", "self", ".", "_available_agents", ".", "pop", "(", "0", ")", "# Find first job that can be run on this agent", "found", "=", "False", "client_addr", ",", "job_id", ",", "job_msg", "=", "None", ",", "None", ",", "None", "for", "(", "client_addr", ",", "job_id", ")", ",", "job_msg", "in", "self", ".", "_waiting_jobs", ".", "items", "(", ")", ":", "if", "job_msg", ".", "environment", "in", "self", ".", "_containers_on_agent", "[", "agent_addr", "]", ":", "found", "=", "True", "break", "if", "not", "found", ":", "self", ".", "_logger", ".", "debug", "(", "\"Nothing to do for agent %s\"", ",", "agent_addr", ")", "not_found_for_agent", ".", "append", "(", "agent_addr", ")", "continue", "# Remove the job from the queue", "del", "self", ".", "_waiting_jobs", "[", "(", "client_addr", ",", "job_id", ")", "]", "job_id", "=", "(", "client_addr", ",", "job_msg", ".", "job_id", ")", "self", ".", "_job_running", "[", "job_id", "]", "=", "(", "agent_addr", ",", "job_msg", ",", "time", ".", "time", "(", ")", ")", "self", ".", "_logger", ".", "info", "(", "\"Sending job %s %s to agent %s\"", ",", "client_addr", ",", "job_msg", ".", "job_id", ",", "agent_addr", ")", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_agent_socket", ",", "agent_addr", ",", "BackendNewJob", "(", "job_id", ",", "job_msg", ".", "course_id", ",", "job_msg", ".", "task_id", ",", "job_msg", ".", "inputdata", ",", "job_msg", ".", "environment", ",", "job_msg", ".", "enable_network", ",", "job_msg", ".", "time_limit", ",", "job_msg", ".", "hard_time_limit", ",", "job_msg", ".", "mem_limit", ",", "job_msg", ".", "debug", ")", ")", "# Do not forget to add again for which we did not find jobs to do", "self", ".", "_available_agents", "+=", "not_found_for_agent" ]
Send waiting jobs to available agents
[ "Send", "waiting", "jobs", "to", "available", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L156-L193
234,913
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_hello
async def handle_agent_hello(self, agent_addr, message: AgentHello): """ Handle an AgentAvailable message. Add agent_addr to the list of available agents """ self._logger.info("Agent %s (%s) said hello", agent_addr, message.friendly_name) if agent_addr in self._registered_agents: # Delete previous instance of this agent, if any await self._delete_agent(agent_addr) self._registered_agents[agent_addr] = message.friendly_name self._available_agents.extend([agent_addr for _ in range(0, message.available_job_slots)]) self._containers_on_agent[agent_addr] = message.available_containers.keys() self._ping_count[agent_addr] = 0 # update information about available containers for container_name, container_info in message.available_containers.items(): if container_name in self._containers: # check if the id is the same if self._containers[container_name][0] == container_info["id"]: # ok, just add the agent to the list of agents that have the container self._logger.debug("Registering container %s for agent %s", container_name, str(agent_addr)) self._containers[container_name][2].append(agent_addr) elif self._containers[container_name][1] > container_info["created"]: # containers stored have been created after the new one # add the agent, but emit a warning self._logger.warning("Container %s has multiple version: \n" "\t Currently registered agents have version %s (%i)\n" "\t New agent %s has version %s (%i)", container_name, self._containers[container_name][0], self._containers[container_name][1], str(agent_addr), container_info["id"], container_info["created"]) self._containers[container_name][2].append(agent_addr) else: # self._containers[container_name][1] < container_info["created"]: # containers stored have been created before the new one # add the agent, update the infos, and emit a warning self._logger.warning("Container %s has multiple version: \n" "\t Currently registered agents have version %s (%i)\n" "\t New agent %s has version %s (%i)", container_name, self._containers[container_name][0], self._containers[container_name][1], str(agent_addr), container_info["id"], container_info["created"]) self._containers[container_name] = (container_info["id"], container_info["created"], self._containers[container_name][2] + [agent_addr]) else: # just add it self._logger.debug("Registering container %s for agent %s", container_name, str(agent_addr)) self._containers[container_name] = (container_info["id"], container_info["created"], [agent_addr]) # update the queue await self.update_queue() # update clients await self.send_container_update_to_client(self._registered_clients)
python
async def handle_agent_hello(self, agent_addr, message: AgentHello): """ Handle an AgentAvailable message. Add agent_addr to the list of available agents """ self._logger.info("Agent %s (%s) said hello", agent_addr, message.friendly_name) if agent_addr in self._registered_agents: # Delete previous instance of this agent, if any await self._delete_agent(agent_addr) self._registered_agents[agent_addr] = message.friendly_name self._available_agents.extend([agent_addr for _ in range(0, message.available_job_slots)]) self._containers_on_agent[agent_addr] = message.available_containers.keys() self._ping_count[agent_addr] = 0 # update information about available containers for container_name, container_info in message.available_containers.items(): if container_name in self._containers: # check if the id is the same if self._containers[container_name][0] == container_info["id"]: # ok, just add the agent to the list of agents that have the container self._logger.debug("Registering container %s for agent %s", container_name, str(agent_addr)) self._containers[container_name][2].append(agent_addr) elif self._containers[container_name][1] > container_info["created"]: # containers stored have been created after the new one # add the agent, but emit a warning self._logger.warning("Container %s has multiple version: \n" "\t Currently registered agents have version %s (%i)\n" "\t New agent %s has version %s (%i)", container_name, self._containers[container_name][0], self._containers[container_name][1], str(agent_addr), container_info["id"], container_info["created"]) self._containers[container_name][2].append(agent_addr) else: # self._containers[container_name][1] < container_info["created"]: # containers stored have been created before the new one # add the agent, update the infos, and emit a warning self._logger.warning("Container %s has multiple version: \n" "\t Currently registered agents have version %s (%i)\n" "\t New agent %s has version %s (%i)", container_name, self._containers[container_name][0], self._containers[container_name][1], str(agent_addr), container_info["id"], container_info["created"]) self._containers[container_name] = (container_info["id"], container_info["created"], self._containers[container_name][2] + [agent_addr]) else: # just add it self._logger.debug("Registering container %s for agent %s", container_name, str(agent_addr)) self._containers[container_name] = (container_info["id"], container_info["created"], [agent_addr]) # update the queue await self.update_queue() # update clients await self.send_container_update_to_client(self._registered_clients)
[ "async", "def", "handle_agent_hello", "(", "self", ",", "agent_addr", ",", "message", ":", "AgentHello", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Agent %s (%s) said hello\"", ",", "agent_addr", ",", "message", ".", "friendly_name", ")", "if", "agent_addr", "in", "self", ".", "_registered_agents", ":", "# Delete previous instance of this agent, if any", "await", "self", ".", "_delete_agent", "(", "agent_addr", ")", "self", ".", "_registered_agents", "[", "agent_addr", "]", "=", "message", ".", "friendly_name", "self", ".", "_available_agents", ".", "extend", "(", "[", "agent_addr", "for", "_", "in", "range", "(", "0", ",", "message", ".", "available_job_slots", ")", "]", ")", "self", ".", "_containers_on_agent", "[", "agent_addr", "]", "=", "message", ".", "available_containers", ".", "keys", "(", ")", "self", ".", "_ping_count", "[", "agent_addr", "]", "=", "0", "# update information about available containers", "for", "container_name", ",", "container_info", "in", "message", ".", "available_containers", ".", "items", "(", ")", ":", "if", "container_name", "in", "self", ".", "_containers", ":", "# check if the id is the same", "if", "self", ".", "_containers", "[", "container_name", "]", "[", "0", "]", "==", "container_info", "[", "\"id\"", "]", ":", "# ok, just add the agent to the list of agents that have the container", "self", ".", "_logger", ".", "debug", "(", "\"Registering container %s for agent %s\"", ",", "container_name", ",", "str", "(", "agent_addr", ")", ")", "self", ".", "_containers", "[", "container_name", "]", "[", "2", "]", ".", "append", "(", "agent_addr", ")", "elif", "self", ".", "_containers", "[", "container_name", "]", "[", "1", "]", ">", "container_info", "[", "\"created\"", "]", ":", "# containers stored have been created after the new one", "# add the agent, but emit a warning", "self", ".", "_logger", ".", "warning", "(", "\"Container %s has multiple version: \\n\"", "\"\\t Currently registered agents have version %s (%i)\\n\"", "\"\\t New agent %s has version %s (%i)\"", ",", "container_name", ",", "self", ".", "_containers", "[", "container_name", "]", "[", "0", "]", ",", "self", ".", "_containers", "[", "container_name", "]", "[", "1", "]", ",", "str", "(", "agent_addr", ")", ",", "container_info", "[", "\"id\"", "]", ",", "container_info", "[", "\"created\"", "]", ")", "self", ".", "_containers", "[", "container_name", "]", "[", "2", "]", ".", "append", "(", "agent_addr", ")", "else", ":", "# self._containers[container_name][1] < container_info[\"created\"]:", "# containers stored have been created before the new one", "# add the agent, update the infos, and emit a warning", "self", ".", "_logger", ".", "warning", "(", "\"Container %s has multiple version: \\n\"", "\"\\t Currently registered agents have version %s (%i)\\n\"", "\"\\t New agent %s has version %s (%i)\"", ",", "container_name", ",", "self", ".", "_containers", "[", "container_name", "]", "[", "0", "]", ",", "self", ".", "_containers", "[", "container_name", "]", "[", "1", "]", ",", "str", "(", "agent_addr", ")", ",", "container_info", "[", "\"id\"", "]", ",", "container_info", "[", "\"created\"", "]", ")", "self", ".", "_containers", "[", "container_name", "]", "=", "(", "container_info", "[", "\"id\"", "]", ",", "container_info", "[", "\"created\"", "]", ",", "self", ".", "_containers", "[", "container_name", "]", "[", "2", "]", "+", "[", "agent_addr", "]", ")", "else", ":", "# just add it", "self", ".", "_logger", ".", "debug", "(", "\"Registering container %s for agent %s\"", ",", "container_name", ",", "str", "(", "agent_addr", ")", ")", "self", ".", "_containers", "[", "container_name", "]", "=", "(", "container_info", "[", "\"id\"", "]", ",", "container_info", "[", "\"created\"", "]", ",", "[", "agent_addr", "]", ")", "# update the queue", "await", "self", ".", "update_queue", "(", ")", "# update clients", "await", "self", ".", "send_container_update_to_client", "(", "self", ".", "_registered_clients", ")" ]
Handle an AgentAvailable message. Add agent_addr to the list of available agents
[ "Handle", "an", "AgentAvailable", "message", ".", "Add", "agent_addr", "to", "the", "list", "of", "available", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L195-L248
234,914
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_started
async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted): """Handle an AgentJobStarted message. Send the data back to the client""" self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr) await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobStarted(message.job_id[1]))
python
async def handle_agent_job_started(self, agent_addr, message: AgentJobStarted): """Handle an AgentJobStarted message. Send the data back to the client""" self._logger.debug("Job %s %s started on agent %s", message.job_id[0], message.job_id[1], agent_addr) await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobStarted(message.job_id[1]))
[ "async", "def", "handle_agent_job_started", "(", "self", ",", "agent_addr", ",", "message", ":", "AgentJobStarted", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Job %s %s started on agent %s\"", ",", "message", ".", "job_id", "[", "0", "]", ",", "message", ".", "job_id", "[", "1", "]", ",", "agent_addr", ")", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "message", ".", "job_id", "[", "0", "]", ",", "BackendJobStarted", "(", "message", ".", "job_id", "[", "1", "]", ")", ")" ]
Handle an AgentJobStarted message. Send the data back to the client
[ "Handle", "an", "AgentJobStarted", "message", ".", "Send", "the", "data", "back", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L250-L253
234,915
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_done
async def handle_agent_job_done(self, agent_addr, message: AgentJobDone): """Handle an AgentJobDone message. Send the data back to the client, and start new job if needed""" if agent_addr in self._registered_agents: self._logger.info("Job %s %s finished on agent %s", message.job_id[0], message.job_id[1], agent_addr) # Remove the job from the list of running jobs del self._job_running[message.job_id] # Sent the data back to the client await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobDone(message.job_id[1], message.result, message.grade, message.problems, message.tests, message.custom, message.state, message.archive, message.stdout, message.stderr)) # The agent is available now self._available_agents.append(agent_addr) else: self._logger.warning("Job result %s %s from non-registered agent %s", message.job_id[0], message.job_id[1], agent_addr) # update the queue await self.update_queue()
python
async def handle_agent_job_done(self, agent_addr, message: AgentJobDone): """Handle an AgentJobDone message. Send the data back to the client, and start new job if needed""" if agent_addr in self._registered_agents: self._logger.info("Job %s %s finished on agent %s", message.job_id[0], message.job_id[1], agent_addr) # Remove the job from the list of running jobs del self._job_running[message.job_id] # Sent the data back to the client await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobDone(message.job_id[1], message.result, message.grade, message.problems, message.tests, message.custom, message.state, message.archive, message.stdout, message.stderr)) # The agent is available now self._available_agents.append(agent_addr) else: self._logger.warning("Job result %s %s from non-registered agent %s", message.job_id[0], message.job_id[1], agent_addr) # update the queue await self.update_queue()
[ "async", "def", "handle_agent_job_done", "(", "self", ",", "agent_addr", ",", "message", ":", "AgentJobDone", ")", ":", "if", "agent_addr", "in", "self", ".", "_registered_agents", ":", "self", ".", "_logger", ".", "info", "(", "\"Job %s %s finished on agent %s\"", ",", "message", ".", "job_id", "[", "0", "]", ",", "message", ".", "job_id", "[", "1", "]", ",", "agent_addr", ")", "# Remove the job from the list of running jobs", "del", "self", ".", "_job_running", "[", "message", ".", "job_id", "]", "# Sent the data back to the client", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "message", ".", "job_id", "[", "0", "]", ",", "BackendJobDone", "(", "message", ".", "job_id", "[", "1", "]", ",", "message", ".", "result", ",", "message", ".", "grade", ",", "message", ".", "problems", ",", "message", ".", "tests", ",", "message", ".", "custom", ",", "message", ".", "state", ",", "message", ".", "archive", ",", "message", ".", "stdout", ",", "message", ".", "stderr", ")", ")", "# The agent is available now", "self", ".", "_available_agents", ".", "append", "(", "agent_addr", ")", "else", ":", "self", ".", "_logger", ".", "warning", "(", "\"Job result %s %s from non-registered agent %s\"", ",", "message", ".", "job_id", "[", "0", "]", ",", "message", ".", "job_id", "[", "1", "]", ",", "agent_addr", ")", "# update the queue", "await", "self", ".", "update_queue", "(", ")" ]
Handle an AgentJobDone message. Send the data back to the client, and start new job if needed
[ "Handle", "an", "AgentJobDone", "message", ".", "Send", "the", "data", "back", "to", "the", "client", "and", "start", "new", "job", "if", "needed" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L255-L277
234,916
UCL-INGI/INGInious
inginious/backend/backend.py
Backend.handle_agent_job_ssh_debug
async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug): """Handle an AgentJobSSHDebug message. Send the data back to the client""" await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port, message.password))
python
async def handle_agent_job_ssh_debug(self, _, message: AgentJobSSHDebug): """Handle an AgentJobSSHDebug message. Send the data back to the client""" await ZMQUtils.send_with_addr(self._client_socket, message.job_id[0], BackendJobSSHDebug(message.job_id[1], message.host, message.port, message.password))
[ "async", "def", "handle_agent_job_ssh_debug", "(", "self", ",", "_", ",", "message", ":", "AgentJobSSHDebug", ")", ":", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "message", ".", "job_id", "[", "0", "]", ",", "BackendJobSSHDebug", "(", "message", ".", "job_id", "[", "1", "]", ",", "message", ".", "host", ",", "message", ".", "port", ",", "message", ".", "password", ")", ")" ]
Handle an AgentJobSSHDebug message. Send the data back to the client
[ "Handle", "an", "AgentJobSSHDebug", "message", ".", "Send", "the", "data", "back", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L279-L282
234,917
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._do_ping
async def _do_ping(self): """ Ping the agents """ # the list() call here is needed, as we remove entries from _registered_agents! for agent_addr, friendly_name in list(self._registered_agents.items()): try: ping_count = self._ping_count.get(agent_addr, 0) if ping_count > 5: self._logger.warning("Agent %s (%s) does not respond: removing from list.", agent_addr, friendly_name) delete_agent = True else: self._ping_count[agent_addr] = ping_count + 1 await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, Ping()) delete_agent = False except: # This should not happen, but it's better to check anyway. self._logger.exception("Failed to send ping to agent %s (%s). Removing it from list.", agent_addr, friendly_name) delete_agent = True if delete_agent: try: await self._delete_agent(agent_addr) except: self._logger.exception("Failed to delete agent %s (%s)!", agent_addr, friendly_name) self._loop.call_later(1, self._create_safe_task, self._do_ping())
python
async def _do_ping(self): """ Ping the agents """ # the list() call here is needed, as we remove entries from _registered_agents! for agent_addr, friendly_name in list(self._registered_agents.items()): try: ping_count = self._ping_count.get(agent_addr, 0) if ping_count > 5: self._logger.warning("Agent %s (%s) does not respond: removing from list.", agent_addr, friendly_name) delete_agent = True else: self._ping_count[agent_addr] = ping_count + 1 await ZMQUtils.send_with_addr(self._agent_socket, agent_addr, Ping()) delete_agent = False except: # This should not happen, but it's better to check anyway. self._logger.exception("Failed to send ping to agent %s (%s). Removing it from list.", agent_addr, friendly_name) delete_agent = True if delete_agent: try: await self._delete_agent(agent_addr) except: self._logger.exception("Failed to delete agent %s (%s)!", agent_addr, friendly_name) self._loop.call_later(1, self._create_safe_task, self._do_ping())
[ "async", "def", "_do_ping", "(", "self", ")", ":", "# the list() call here is needed, as we remove entries from _registered_agents!", "for", "agent_addr", ",", "friendly_name", "in", "list", "(", "self", ".", "_registered_agents", ".", "items", "(", ")", ")", ":", "try", ":", "ping_count", "=", "self", ".", "_ping_count", ".", "get", "(", "agent_addr", ",", "0", ")", "if", "ping_count", ">", "5", ":", "self", ".", "_logger", ".", "warning", "(", "\"Agent %s (%s) does not respond: removing from list.\"", ",", "agent_addr", ",", "friendly_name", ")", "delete_agent", "=", "True", "else", ":", "self", ".", "_ping_count", "[", "agent_addr", "]", "=", "ping_count", "+", "1", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_agent_socket", ",", "agent_addr", ",", "Ping", "(", ")", ")", "delete_agent", "=", "False", "except", ":", "# This should not happen, but it's better to check anyway.", "self", ".", "_logger", ".", "exception", "(", "\"Failed to send ping to agent %s (%s). Removing it from list.\"", ",", "agent_addr", ",", "friendly_name", ")", "delete_agent", "=", "True", "if", "delete_agent", ":", "try", ":", "await", "self", ".", "_delete_agent", "(", "agent_addr", ")", "except", ":", "self", ".", "_logger", ".", "exception", "(", "\"Failed to delete agent %s (%s)!\"", ",", "agent_addr", ",", "friendly_name", ")", "self", ".", "_loop", ".", "call_later", "(", "1", ",", "self", ".", "_create_safe_task", ",", "self", ".", "_do_ping", "(", ")", ")" ]
Ping the agents
[ "Ping", "the", "agents" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L314-L339
234,918
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._delete_agent
async def _delete_agent(self, agent_addr): """ Deletes an agent """ self._available_agents = [agent for agent in self._available_agents if agent != agent_addr] del self._registered_agents[agent_addr] await self._recover_jobs(agent_addr)
python
async def _delete_agent(self, agent_addr): """ Deletes an agent """ self._available_agents = [agent for agent in self._available_agents if agent != agent_addr] del self._registered_agents[agent_addr] await self._recover_jobs(agent_addr)
[ "async", "def", "_delete_agent", "(", "self", ",", "agent_addr", ")", ":", "self", ".", "_available_agents", "=", "[", "agent", "for", "agent", "in", "self", ".", "_available_agents", "if", "agent", "!=", "agent_addr", "]", "del", "self", ".", "_registered_agents", "[", "agent_addr", "]", "await", "self", ".", "_recover_jobs", "(", "agent_addr", ")" ]
Deletes an agent
[ "Deletes", "an", "agent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L341-L345
234,919
UCL-INGI/INGInious
inginious/backend/backend.py
Backend._recover_jobs
async def _recover_jobs(self, agent_addr): """ Recover the jobs sent to a crashed agent """ for (client_addr, job_id), (agent, job_msg, _) in reversed(list(self._job_running.items())): if agent == agent_addr: await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendJobDone(job_id, ("crash", "Agent restarted"), 0.0, {}, {}, {}, "", None, None, None)) del self._job_running[(client_addr, job_id)] await self.update_queue()
python
async def _recover_jobs(self, agent_addr): """ Recover the jobs sent to a crashed agent """ for (client_addr, job_id), (agent, job_msg, _) in reversed(list(self._job_running.items())): if agent == agent_addr: await ZMQUtils.send_with_addr(self._client_socket, client_addr, BackendJobDone(job_id, ("crash", "Agent restarted"), 0.0, {}, {}, {}, "", None, None, None)) del self._job_running[(client_addr, job_id)] await self.update_queue()
[ "async", "def", "_recover_jobs", "(", "self", ",", "agent_addr", ")", ":", "for", "(", "client_addr", ",", "job_id", ")", ",", "(", "agent", ",", "job_msg", ",", "_", ")", "in", "reversed", "(", "list", "(", "self", ".", "_job_running", ".", "items", "(", ")", ")", ")", ":", "if", "agent", "==", "agent_addr", ":", "await", "ZMQUtils", ".", "send_with_addr", "(", "self", ".", "_client_socket", ",", "client_addr", ",", "BackendJobDone", "(", "job_id", ",", "(", "\"crash\"", ",", "\"Agent restarted\"", ")", ",", "0.0", ",", "{", "}", ",", "{", "}", ",", "{", "}", ",", "\"\"", ",", "None", ",", "None", ",", "None", ")", ")", "del", "self", ".", "_job_running", "[", "(", "client_addr", ",", "job_id", ")", "]", "await", "self", ".", "update_queue", "(", ")" ]
Recover the jobs sent to a crashed agent
[ "Recover", "the", "jobs", "sent", "to", "a", "crashed", "agent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/backend/backend.py#L347-L356
234,920
UCL-INGI/INGInious
inginious/frontend/accessible_time.py
parse_date
def parse_date(date, default=None): """ Parse a valid date """ if date == "": if default is not None: return default else: raise Exception("Unknown format for " + date) for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%d/%m/%Y %H", "%d/%m/%Y"]: try: return datetime.strptime(date, format_type) except ValueError: pass raise Exception("Unknown format for " + date)
python
def parse_date(date, default=None): """ Parse a valid date """ if date == "": if default is not None: return default else: raise Exception("Unknown format for " + date) for format_type in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d %H", "%Y-%m-%d", "%d/%m/%Y %H:%M:%S", "%d/%m/%Y %H:%M", "%d/%m/%Y %H", "%d/%m/%Y"]: try: return datetime.strptime(date, format_type) except ValueError: pass raise Exception("Unknown format for " + date)
[ "def", "parse_date", "(", "date", ",", "default", "=", "None", ")", ":", "if", "date", "==", "\"\"", ":", "if", "default", "is", "not", "None", ":", "return", "default", "else", ":", "raise", "Exception", "(", "\"Unknown format for \"", "+", "date", ")", "for", "format_type", "in", "[", "\"%Y-%m-%d %H:%M:%S\"", ",", "\"%Y-%m-%d %H:%M\"", ",", "\"%Y-%m-%d %H\"", ",", "\"%Y-%m-%d\"", ",", "\"%d/%m/%Y %H:%M:%S\"", ",", "\"%d/%m/%Y %H:%M\"", ",", "\"%d/%m/%Y %H\"", ",", "\"%d/%m/%Y\"", "]", ":", "try", ":", "return", "datetime", ".", "strptime", "(", "date", ",", "format_type", ")", "except", "ValueError", ":", "pass", "raise", "Exception", "(", "\"Unknown format for \"", "+", "date", ")" ]
Parse a valid date
[ "Parse", "a", "valid", "date" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/accessible_time.py#L11-L25
234,921
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.GET
def GET(self): """ Handles GET request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() error = False reset = None msg = "" data = web.input() if "activate" in data: msg, error = self.activate_user(data) elif "reset" in data: msg, error, reset = self.get_reset_data(data) return self.template_helper.get_renderer().register(reset, msg, error)
python
def GET(self): """ Handles GET request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() error = False reset = None msg = "" data = web.input() if "activate" in data: msg, error = self.activate_user(data) elif "reset" in data: msg, error, reset = self.get_reset_data(data) return self.template_helper.get_renderer().register(reset, msg, error)
[ "def", "GET", "(", "self", ")", ":", "if", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", "or", "not", "self", ".", "app", ".", "allow_registration", ":", "raise", "web", ".", "notfound", "(", ")", "error", "=", "False", "reset", "=", "None", "msg", "=", "\"\"", "data", "=", "web", ".", "input", "(", ")", "if", "\"activate\"", "in", "data", ":", "msg", ",", "error", "=", "self", ".", "activate_user", "(", "data", ")", "elif", "\"reset\"", "in", "data", ":", "msg", ",", "error", ",", "reset", "=", "self", ".", "get_reset_data", "(", "data", ")", "return", "self", ".", "template_helper", ".", "get_renderer", "(", ")", ".", "register", "(", "reset", ",", "msg", ",", "error", ")" ]
Handles GET request
[ "Handles", "GET", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L20-L35
234,922
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.get_reset_data
def get_reset_data(self, data): """ Returns the user info to reset """ error = False reset = None msg = "" user = self.database.users.find_one({"reset": data["reset"]}) if user is None: error = True msg = "Invalid reset hash." else: reset = {"hash": data["reset"], "username": user["username"], "realname": user["realname"]} return msg, error, reset
python
def get_reset_data(self, data): """ Returns the user info to reset """ error = False reset = None msg = "" user = self.database.users.find_one({"reset": data["reset"]}) if user is None: error = True msg = "Invalid reset hash." else: reset = {"hash": data["reset"], "username": user["username"], "realname": user["realname"]} return msg, error, reset
[ "def", "get_reset_data", "(", "self", ",", "data", ")", ":", "error", "=", "False", "reset", "=", "None", "msg", "=", "\"\"", "user", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"reset\"", ":", "data", "[", "\"reset\"", "]", "}", ")", "if", "user", "is", "None", ":", "error", "=", "True", "msg", "=", "\"Invalid reset hash.\"", "else", ":", "reset", "=", "{", "\"hash\"", ":", "data", "[", "\"reset\"", "]", ",", "\"username\"", ":", "user", "[", "\"username\"", "]", ",", "\"realname\"", ":", "user", "[", "\"realname\"", "]", "}", "return", "msg", ",", "error", ",", "reset" ]
Returns the user info to reset
[ "Returns", "the", "user", "info", "to", "reset" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L37-L49
234,923
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.register_user
def register_user(self, data): """ Parses input and register user """ error = False msg = "" email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain # Check input format if re.match(r"^[-_|~0-9A-Z]{4,}$", data["username"], re.IGNORECASE) is None: error = True msg = _("Invalid username format.") elif email_re.match(data["email"]) is None: error = True msg = _("Invalid email format.") elif len(data["passwd"]) < 6: error = True msg = _("Password too short.") elif data["passwd"] != data["passwd2"]: error = True msg = _("Passwords don't match !") if not error: existing_user = self.database.users.find_one({"$or": [{"username": data["username"]}, {"email": data["email"]}]}) if existing_user is not None: error = True if existing_user["username"] == data["username"]: msg = _("This username is already taken !") else: msg = _("This email address is already in use !") else: passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest() activate_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest() self.database.users.insert({"username": data["username"], "realname": data["realname"], "email": data["email"], "password": passwd_hash, "activate": activate_hash, "bindings": {}, "language": self.user_manager._session.get("language", "en")}) try: web.sendmail(web.config.smtp_sendername, data["email"], _("Welcome on INGInious"), _("""Welcome on INGInious ! To activate your account, please click on the following link : """) + web.ctx.home + "/register?activate=" + activate_hash) msg = _("You are succesfully registered. An email has been sent to you for activation.") except: error = True msg = _("Something went wrong while sending you activation email. Please contact the administrator.") return msg, error
python
def register_user(self, data): """ Parses input and register user """ error = False msg = "" email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain # Check input format if re.match(r"^[-_|~0-9A-Z]{4,}$", data["username"], re.IGNORECASE) is None: error = True msg = _("Invalid username format.") elif email_re.match(data["email"]) is None: error = True msg = _("Invalid email format.") elif len(data["passwd"]) < 6: error = True msg = _("Password too short.") elif data["passwd"] != data["passwd2"]: error = True msg = _("Passwords don't match !") if not error: existing_user = self.database.users.find_one({"$or": [{"username": data["username"]}, {"email": data["email"]}]}) if existing_user is not None: error = True if existing_user["username"] == data["username"]: msg = _("This username is already taken !") else: msg = _("This email address is already in use !") else: passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest() activate_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest() self.database.users.insert({"username": data["username"], "realname": data["realname"], "email": data["email"], "password": passwd_hash, "activate": activate_hash, "bindings": {}, "language": self.user_manager._session.get("language", "en")}) try: web.sendmail(web.config.smtp_sendername, data["email"], _("Welcome on INGInious"), _("""Welcome on INGInious ! To activate your account, please click on the following link : """) + web.ctx.home + "/register?activate=" + activate_hash) msg = _("You are succesfully registered. An email has been sent to you for activation.") except: error = True msg = _("Something went wrong while sending you activation email. Please contact the administrator.") return msg, error
[ "def", "register_user", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "email_re", "=", "re", ".", "compile", "(", "r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"", "# dot-atom", "r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-011\\013\\014\\016-\\177])*\"'", "# quoted-string", "r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+[A-Z]{2,6}\\.?$'", ",", "re", ".", "IGNORECASE", ")", "# domain", "# Check input format", "if", "re", ".", "match", "(", "r\"^[-_|~0-9A-Z]{4,}$\"", ",", "data", "[", "\"username\"", "]", ",", "re", ".", "IGNORECASE", ")", "is", "None", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Invalid username format.\"", ")", "elif", "email_re", ".", "match", "(", "data", "[", "\"email\"", "]", ")", "is", "None", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Invalid email format.\"", ")", "elif", "len", "(", "data", "[", "\"passwd\"", "]", ")", "<", "6", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Password too short.\"", ")", "elif", "data", "[", "\"passwd\"", "]", "!=", "data", "[", "\"passwd2\"", "]", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Passwords don't match !\"", ")", "if", "not", "error", ":", "existing_user", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"$or\"", ":", "[", "{", "\"username\"", ":", "data", "[", "\"username\"", "]", "}", ",", "{", "\"email\"", ":", "data", "[", "\"email\"", "]", "}", "]", "}", ")", "if", "existing_user", "is", "not", "None", ":", "error", "=", "True", "if", "existing_user", "[", "\"username\"", "]", "==", "data", "[", "\"username\"", "]", ":", "msg", "=", "_", "(", "\"This username is already taken !\"", ")", "else", ":", "msg", "=", "_", "(", "\"This email address is already in use !\"", ")", "else", ":", "passwd_hash", "=", "hashlib", ".", "sha512", "(", "data", "[", "\"passwd\"", "]", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ")", "activate_hash", "=", "hashlib", ".", "sha512", "(", "str", "(", "random", ".", "getrandbits", "(", "256", ")", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ")", "self", ".", "database", ".", "users", ".", "insert", "(", "{", "\"username\"", ":", "data", "[", "\"username\"", "]", ",", "\"realname\"", ":", "data", "[", "\"realname\"", "]", ",", "\"email\"", ":", "data", "[", "\"email\"", "]", ",", "\"password\"", ":", "passwd_hash", ",", "\"activate\"", ":", "activate_hash", ",", "\"bindings\"", ":", "{", "}", ",", "\"language\"", ":", "self", ".", "user_manager", ".", "_session", ".", "get", "(", "\"language\"", ",", "\"en\"", ")", "}", ")", "try", ":", "web", ".", "sendmail", "(", "web", ".", "config", ".", "smtp_sendername", ",", "data", "[", "\"email\"", "]", ",", "_", "(", "\"Welcome on INGInious\"", ")", ",", "_", "(", "\"\"\"Welcome on INGInious !\n\nTo activate your account, please click on the following link :\n\"\"\"", ")", "+", "web", ".", "ctx", ".", "home", "+", "\"/register?activate=\"", "+", "activate_hash", ")", "msg", "=", "_", "(", "\"You are succesfully registered. An email has been sent to you for activation.\"", ")", "except", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Something went wrong while sending you activation email. Please contact the administrator.\"", ")", "return", "msg", ",", "error" ]
Parses input and register user
[ "Parses", "input", "and", "register", "user" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L63-L117
234,924
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.lost_passwd
def lost_passwd(self, data): """ Send a reset link to user to recover its password """ error = False msg = "" # Check input format email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain if email_re.match(data["recovery_email"]) is None: error = True msg = _("Invalid email format.") if not error: reset_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest() user = self.database.users.find_one_and_update({"email": data["recovery_email"]}, {"$set": {"reset": reset_hash}}) if user is None: error = True msg = _("This email address was not found in database.") else: try: web.sendmail(web.config.smtp_sendername, data["recovery_email"], _("INGInious password recovery"), _("""Dear {realname}, Someone (probably you) asked to reset your INGInious password. If this was you, please click on the following link : """).format(realname=user["realname"]) + web.ctx.home + "/register?reset=" + reset_hash) msg = _("An email has been sent to you to reset your password.") except: error = True msg = _("Something went wrong while sending you reset email. Please contact the administrator.") return msg, error
python
def lost_passwd(self, data): """ Send a reset link to user to recover its password """ error = False msg = "" # Check input format email_re = re.compile( r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*" # dot-atom r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?$', re.IGNORECASE) # domain if email_re.match(data["recovery_email"]) is None: error = True msg = _("Invalid email format.") if not error: reset_hash = hashlib.sha512(str(random.getrandbits(256)).encode("utf-8")).hexdigest() user = self.database.users.find_one_and_update({"email": data["recovery_email"]}, {"$set": {"reset": reset_hash}}) if user is None: error = True msg = _("This email address was not found in database.") else: try: web.sendmail(web.config.smtp_sendername, data["recovery_email"], _("INGInious password recovery"), _("""Dear {realname}, Someone (probably you) asked to reset your INGInious password. If this was you, please click on the following link : """).format(realname=user["realname"]) + web.ctx.home + "/register?reset=" + reset_hash) msg = _("An email has been sent to you to reset your password.") except: error = True msg = _("Something went wrong while sending you reset email. Please contact the administrator.") return msg, error
[ "def", "lost_passwd", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "# Check input format", "email_re", "=", "re", ".", "compile", "(", "r\"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\"", "# dot-atom", "r'|^\"([\\001-\\010\\013\\014\\016-\\037!#-\\[\\]-\\177]|\\\\[\\001-011\\013\\014\\016-\\177])*\"'", "# quoted-string", "r')@(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+[A-Z]{2,6}\\.?$'", ",", "re", ".", "IGNORECASE", ")", "# domain", "if", "email_re", ".", "match", "(", "data", "[", "\"recovery_email\"", "]", ")", "is", "None", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Invalid email format.\"", ")", "if", "not", "error", ":", "reset_hash", "=", "hashlib", ".", "sha512", "(", "str", "(", "random", ".", "getrandbits", "(", "256", ")", ")", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ")", "user", "=", "self", ".", "database", ".", "users", ".", "find_one_and_update", "(", "{", "\"email\"", ":", "data", "[", "\"recovery_email\"", "]", "}", ",", "{", "\"$set\"", ":", "{", "\"reset\"", ":", "reset_hash", "}", "}", ")", "if", "user", "is", "None", ":", "error", "=", "True", "msg", "=", "_", "(", "\"This email address was not found in database.\"", ")", "else", ":", "try", ":", "web", ".", "sendmail", "(", "web", ".", "config", ".", "smtp_sendername", ",", "data", "[", "\"recovery_email\"", "]", ",", "_", "(", "\"INGInious password recovery\"", ")", ",", "_", "(", "\"\"\"Dear {realname},\n\nSomeone (probably you) asked to reset your INGInious password. If this was you, please click on the following link :\n\"\"\"", ")", ".", "format", "(", "realname", "=", "user", "[", "\"realname\"", "]", ")", "+", "web", ".", "ctx", ".", "home", "+", "\"/register?reset=\"", "+", "reset_hash", ")", "msg", "=", "_", "(", "\"An email has been sent to you to reset your password.\"", ")", "except", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Something went wrong while sending you reset email. Please contact the administrator.\"", ")", "return", "msg", ",", "error" ]
Send a reset link to user to recover its password
[ "Send", "a", "reset", "link", "to", "user", "to", "recover", "its", "password" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L119-L151
234,925
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.reset_passwd
def reset_passwd(self, data): """ Reset the user password """ error = False msg = "" # Check input format if len(data["passwd"]) < 6: error = True msg = _("Password too short.") elif data["passwd"] != data["passwd2"]: error = True msg = _("Passwords don't match !") if not error: passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest() user = self.database.users.find_one_and_update({"reset": data["reset_hash"]}, {"$set": {"password": passwd_hash}, "$unset": {"reset": True, "activate": True}}) if user is None: error = True msg = _("Invalid reset hash.") else: msg = _("Your password has been successfully changed.") return msg, error
python
def reset_passwd(self, data): """ Reset the user password """ error = False msg = "" # Check input format if len(data["passwd"]) < 6: error = True msg = _("Password too short.") elif data["passwd"] != data["passwd2"]: error = True msg = _("Passwords don't match !") if not error: passwd_hash = hashlib.sha512(data["passwd"].encode("utf-8")).hexdigest() user = self.database.users.find_one_and_update({"reset": data["reset_hash"]}, {"$set": {"password": passwd_hash}, "$unset": {"reset": True, "activate": True}}) if user is None: error = True msg = _("Invalid reset hash.") else: msg = _("Your password has been successfully changed.") return msg, error
[ "def", "reset_passwd", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "# Check input format", "if", "len", "(", "data", "[", "\"passwd\"", "]", ")", "<", "6", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Password too short.\"", ")", "elif", "data", "[", "\"passwd\"", "]", "!=", "data", "[", "\"passwd2\"", "]", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Passwords don't match !\"", ")", "if", "not", "error", ":", "passwd_hash", "=", "hashlib", ".", "sha512", "(", "data", "[", "\"passwd\"", "]", ".", "encode", "(", "\"utf-8\"", ")", ")", ".", "hexdigest", "(", ")", "user", "=", "self", ".", "database", ".", "users", ".", "find_one_and_update", "(", "{", "\"reset\"", ":", "data", "[", "\"reset_hash\"", "]", "}", ",", "{", "\"$set\"", ":", "{", "\"password\"", ":", "passwd_hash", "}", ",", "\"$unset\"", ":", "{", "\"reset\"", ":", "True", ",", "\"activate\"", ":", "True", "}", "}", ")", "if", "user", "is", "None", ":", "error", "=", "True", "msg", "=", "_", "(", "\"Invalid reset hash.\"", ")", "else", ":", "msg", "=", "_", "(", "\"Your password has been successfully changed.\"", ")", "return", "msg", ",", "error" ]
Reset the user password
[ "Reset", "the", "user", "password" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L153-L177
234,926
UCL-INGI/INGInious
inginious/frontend/pages/register.py
RegistrationPage.POST
def POST(self): """ Handles POST request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() reset = None msg = "" error = False data = web.input() if "register" in data: msg, error = self.register_user(data) elif "lostpasswd" in data: msg, error = self.lost_passwd(data) elif "resetpasswd" in data: msg, error, reset = self.get_reset_data(data) if reset: msg, error = self.reset_passwd(data) if not error: reset = None return self.template_helper.get_renderer().register(reset, msg, error)
python
def POST(self): """ Handles POST request """ if self.user_manager.session_logged_in() or not self.app.allow_registration: raise web.notfound() reset = None msg = "" error = False data = web.input() if "register" in data: msg, error = self.register_user(data) elif "lostpasswd" in data: msg, error = self.lost_passwd(data) elif "resetpasswd" in data: msg, error, reset = self.get_reset_data(data) if reset: msg, error = self.reset_passwd(data) if not error: reset = None return self.template_helper.get_renderer().register(reset, msg, error)
[ "def", "POST", "(", "self", ")", ":", "if", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", "or", "not", "self", ".", "app", ".", "allow_registration", ":", "raise", "web", ".", "notfound", "(", ")", "reset", "=", "None", "msg", "=", "\"\"", "error", "=", "False", "data", "=", "web", ".", "input", "(", ")", "if", "\"register\"", "in", "data", ":", "msg", ",", "error", "=", "self", ".", "register_user", "(", "data", ")", "elif", "\"lostpasswd\"", "in", "data", ":", "msg", ",", "error", "=", "self", ".", "lost_passwd", "(", "data", ")", "elif", "\"resetpasswd\"", "in", "data", ":", "msg", ",", "error", ",", "reset", "=", "self", ".", "get_reset_data", "(", "data", ")", "if", "reset", ":", "msg", ",", "error", "=", "self", ".", "reset_passwd", "(", "data", ")", "if", "not", "error", ":", "reset", "=", "None", "return", "self", ".", "template_helper", ".", "get_renderer", "(", ")", ".", "register", "(", "reset", ",", "msg", ",", "error", ")" ]
Handles POST request
[ "Handles", "POST", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/register.py#L179-L199
234,927
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory.get_readable_tasks
def get_readable_tasks(self, course): """ Returns the list of all available tasks in a course """ course_fs = self._filesystem.from_subfolder(course.get_id()) tasks = [ task[0:len(task)-1] # remove trailing / for task in course_fs.list(folders=True, files=False, recursive=False) if self._task_file_exists(course_fs.from_subfolder(task))] return tasks
python
def get_readable_tasks(self, course): """ Returns the list of all available tasks in a course """ course_fs = self._filesystem.from_subfolder(course.get_id()) tasks = [ task[0:len(task)-1] # remove trailing / for task in course_fs.list(folders=True, files=False, recursive=False) if self._task_file_exists(course_fs.from_subfolder(task))] return tasks
[ "def", "get_readable_tasks", "(", "self", ",", "course", ")", ":", "course_fs", "=", "self", ".", "_filesystem", ".", "from_subfolder", "(", "course", ".", "get_id", "(", ")", ")", "tasks", "=", "[", "task", "[", "0", ":", "len", "(", "task", ")", "-", "1", "]", "# remove trailing /", "for", "task", "in", "course_fs", ".", "list", "(", "folders", "=", "True", ",", "files", "=", "False", ",", "recursive", "=", "False", ")", "if", "self", ".", "_task_file_exists", "(", "course_fs", ".", "from_subfolder", "(", "task", ")", ")", "]", "return", "tasks" ]
Returns the list of all available tasks in a course
[ "Returns", "the", "list", "of", "all", "available", "tasks", "in", "a", "course" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L122-L129
234,928
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory._task_file_exists
def _task_file_exists(self, task_fs): """ Returns true if a task file exists in this directory """ for filename in ["task.{}".format(ext) for ext in self.get_available_task_file_extensions()]: if task_fs.exists(filename): return True return False
python
def _task_file_exists(self, task_fs): """ Returns true if a task file exists in this directory """ for filename in ["task.{}".format(ext) for ext in self.get_available_task_file_extensions()]: if task_fs.exists(filename): return True return False
[ "def", "_task_file_exists", "(", "self", ",", "task_fs", ")", ":", "for", "filename", "in", "[", "\"task.{}\"", ".", "format", "(", "ext", ")", "for", "ext", "in", "self", ".", "get_available_task_file_extensions", "(", ")", "]", ":", "if", "task_fs", ".", "exists", "(", "filename", ")", ":", "return", "True", "return", "False" ]
Returns true if a task file exists in this directory
[ "Returns", "true", "if", "a", "task", "file", "exists", "in", "this", "directory" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L131-L136
234,929
UCL-INGI/INGInious
inginious/common/task_factory.py
TaskFactory.delete_all_possible_task_files
def delete_all_possible_task_files(self, courseid, taskid): """ Deletes all possibles task files in directory, to allow to change the format """ if not id_checker(courseid): raise InvalidNameException("Course with invalid name: " + courseid) if not id_checker(taskid): raise InvalidNameException("Task with invalid name: " + taskid) task_fs = self.get_task_fs(courseid, taskid) for ext in self.get_available_task_file_extensions(): try: task_fs.delete("task."+ext) except: pass
python
def delete_all_possible_task_files(self, courseid, taskid): """ Deletes all possibles task files in directory, to allow to change the format """ if not id_checker(courseid): raise InvalidNameException("Course with invalid name: " + courseid) if not id_checker(taskid): raise InvalidNameException("Task with invalid name: " + taskid) task_fs = self.get_task_fs(courseid, taskid) for ext in self.get_available_task_file_extensions(): try: task_fs.delete("task."+ext) except: pass
[ "def", "delete_all_possible_task_files", "(", "self", ",", "courseid", ",", "taskid", ")", ":", "if", "not", "id_checker", "(", "courseid", ")", ":", "raise", "InvalidNameException", "(", "\"Course with invalid name: \"", "+", "courseid", ")", "if", "not", "id_checker", "(", "taskid", ")", ":", "raise", "InvalidNameException", "(", "\"Task with invalid name: \"", "+", "taskid", ")", "task_fs", "=", "self", ".", "get_task_fs", "(", "courseid", ",", "taskid", ")", "for", "ext", "in", "self", ".", "get_available_task_file_extensions", "(", ")", ":", "try", ":", "task_fs", ".", "delete", "(", "\"task.\"", "+", "ext", ")", "except", ":", "pass" ]
Deletes all possibles task files in directory, to allow to change the format
[ "Deletes", "all", "possibles", "task", "files", "in", "directory", "to", "allow", "to", "change", "the", "format" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/task_factory.py#L138-L149
234,930
UCL-INGI/INGInious
inginious/frontend/plugins/auth/saml2_auth.py
prepare_request
def prepare_request(settings): """ Prepare SAML request """ # Set the ACS url and binding method settings["sp"]["assertionConsumerService"] = { "url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"], "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" } # If server is behind proxys or balancers use the HTTP_X_FORWARDED fields data = web.input() return { 'https': 'on' if web.ctx.protocol == 'https' else 'off', 'http_host': web.ctx.environ["SERVER_NAME"], 'server_port': web.ctx.environ["SERVER_PORT"], 'script_name': web.ctx.homepath, 'get_data': data.copy(), 'post_data': data.copy(), # Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144 # 'lowercase_urlencoding': True, 'query_string': web.ctx.query }
python
def prepare_request(settings): """ Prepare SAML request """ # Set the ACS url and binding method settings["sp"]["assertionConsumerService"] = { "url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"], "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" } # If server is behind proxys or balancers use the HTTP_X_FORWARDED fields data = web.input() return { 'https': 'on' if web.ctx.protocol == 'https' else 'off', 'http_host': web.ctx.environ["SERVER_NAME"], 'server_port': web.ctx.environ["SERVER_PORT"], 'script_name': web.ctx.homepath, 'get_data': data.copy(), 'post_data': data.copy(), # Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144 # 'lowercase_urlencoding': True, 'query_string': web.ctx.query }
[ "def", "prepare_request", "(", "settings", ")", ":", "# Set the ACS url and binding method", "settings", "[", "\"sp\"", "]", "[", "\"assertionConsumerService\"", "]", "=", "{", "\"url\"", ":", "web", ".", "ctx", ".", "homedomain", "+", "web", ".", "ctx", ".", "homepath", "+", "\"/auth/callback/\"", "+", "settings", "[", "\"id\"", "]", ",", "\"binding\"", ":", "\"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\"", "}", "# If server is behind proxys or balancers use the HTTP_X_FORWARDED fields", "data", "=", "web", ".", "input", "(", ")", "return", "{", "'https'", ":", "'on'", "if", "web", ".", "ctx", ".", "protocol", "==", "'https'", "else", "'off'", ",", "'http_host'", ":", "web", ".", "ctx", ".", "environ", "[", "\"SERVER_NAME\"", "]", ",", "'server_port'", ":", "web", ".", "ctx", ".", "environ", "[", "\"SERVER_PORT\"", "]", ",", "'script_name'", ":", "web", ".", "ctx", ".", "homepath", ",", "'get_data'", ":", "data", ".", "copy", "(", ")", ",", "'post_data'", ":", "data", ".", "copy", "(", ")", ",", "# Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144", "# 'lowercase_urlencoding': True,", "'query_string'", ":", "web", ".", "ctx", ".", "query", "}" ]
Prepare SAML request
[ "Prepare", "SAML", "request" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/auth/saml2_auth.py#L98-L119
234,931
UCL-INGI/INGInious
inginious/common/filesystems/provider.py
FileSystemProvider._checkpath
def _checkpath(self, path): """ Checks that a given path is valid. If it's not, raises NotFoundException """ if path.startswith("/") or ".." in path or path.strip() != path: raise NotFoundException()
python
def _checkpath(self, path): """ Checks that a given path is valid. If it's not, raises NotFoundException """ if path.startswith("/") or ".." in path or path.strip() != path: raise NotFoundException()
[ "def", "_checkpath", "(", "self", ",", "path", ")", ":", "if", "path", ".", "startswith", "(", "\"/\"", ")", "or", "\"..\"", "in", "path", "or", "path", ".", "strip", "(", ")", "!=", "path", ":", "raise", "NotFoundException", "(", ")" ]
Checks that a given path is valid. If it's not, raises NotFoundException
[ "Checks", "that", "a", "given", "path", "is", "valid", ".", "If", "it", "s", "not", "raises", "NotFoundException" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/filesystems/provider.py#L41-L44
234,932
UCL-INGI/INGInious
inginious/frontend/pages/api/courses.py
APICourses.API_GET
def API_GET(self, courseid=None): # pylint: disable=arguments-differ """ List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #the name of the course "require_password": False, #indicates if this course requires a password or not "is_registered": False, #indicates if the user is registered to this course or not "tasks": #only appears if is_registered is True { "taskid1": "name of task1", "taskid2": "name of task2" #... }, "grade": 0.0 #the current grade in the course. Only appears if is_registered is True } #... } If you use the endpoint /api/v0/courses/the_course_id, this dict will contain one entry or the page will return 404 Not Found. """ output = [] if courseid is None: courses = self.course_factory.get_all_courses() else: try: courses = {courseid: self.course_factory.get_course(courseid)} except: raise APINotFound("Course not found") username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) for courseid, course in courses.items(): if self.user_manager.course_is_open_to_user(course, username, False) or course.is_registration_possible(user_info): data = { "id": courseid, "name": course.get_name(self.user_manager.session_language()), "require_password": course.is_password_needed_for_registration(), "is_registered": self.user_manager.course_is_open_to_user(course, username, False) } if self.user_manager.course_is_open_to_user(course, username, False): data["tasks"] = {taskid: task.get_name(self.user_manager.session_language()) for taskid, task in course.get_tasks().items()} data["grade"] = self.user_manager.get_course_cache(username, course)["grade"] output.append(data) return 200, output
python
def API_GET(self, courseid=None): # pylint: disable=arguments-differ """ List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #the name of the course "require_password": False, #indicates if this course requires a password or not "is_registered": False, #indicates if the user is registered to this course or not "tasks": #only appears if is_registered is True { "taskid1": "name of task1", "taskid2": "name of task2" #... }, "grade": 0.0 #the current grade in the course. Only appears if is_registered is True } #... } If you use the endpoint /api/v0/courses/the_course_id, this dict will contain one entry or the page will return 404 Not Found. """ output = [] if courseid is None: courses = self.course_factory.get_all_courses() else: try: courses = {courseid: self.course_factory.get_course(courseid)} except: raise APINotFound("Course not found") username = self.user_manager.session_username() user_info = self.database.users.find_one({"username": username}) for courseid, course in courses.items(): if self.user_manager.course_is_open_to_user(course, username, False) or course.is_registration_possible(user_info): data = { "id": courseid, "name": course.get_name(self.user_manager.session_language()), "require_password": course.is_password_needed_for_registration(), "is_registered": self.user_manager.course_is_open_to_user(course, username, False) } if self.user_manager.course_is_open_to_user(course, username, False): data["tasks"] = {taskid: task.get_name(self.user_manager.session_language()) for taskid, task in course.get_tasks().items()} data["grade"] = self.user_manager.get_course_cache(username, course)["grade"] output.append(data) return 200, output
[ "def", "API_GET", "(", "self", ",", "courseid", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "output", "=", "[", "]", "if", "courseid", "is", "None", ":", "courses", "=", "self", ".", "course_factory", ".", "get_all_courses", "(", ")", "else", ":", "try", ":", "courses", "=", "{", "courseid", ":", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", "}", "except", ":", "raise", "APINotFound", "(", "\"Course not found\"", ")", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "user_info", "=", "self", ".", "database", ".", "users", ".", "find_one", "(", "{", "\"username\"", ":", "username", "}", ")", "for", "courseid", ",", "course", "in", "courses", ".", "items", "(", ")", ":", "if", "self", ".", "user_manager", ".", "course_is_open_to_user", "(", "course", ",", "username", ",", "False", ")", "or", "course", ".", "is_registration_possible", "(", "user_info", ")", ":", "data", "=", "{", "\"id\"", ":", "courseid", ",", "\"name\"", ":", "course", ".", "get_name", "(", "self", ".", "user_manager", ".", "session_language", "(", ")", ")", ",", "\"require_password\"", ":", "course", ".", "is_password_needed_for_registration", "(", ")", ",", "\"is_registered\"", ":", "self", ".", "user_manager", ".", "course_is_open_to_user", "(", "course", ",", "username", ",", "False", ")", "}", "if", "self", ".", "user_manager", ".", "course_is_open_to_user", "(", "course", ",", "username", ",", "False", ")", ":", "data", "[", "\"tasks\"", "]", "=", "{", "taskid", ":", "task", ".", "get_name", "(", "self", ".", "user_manager", ".", "session_language", "(", ")", ")", "for", "taskid", ",", "task", "in", "course", ".", "get_tasks", "(", ")", ".", "items", "(", ")", "}", "data", "[", "\"grade\"", "]", "=", "self", ".", "user_manager", ".", "get_course_cache", "(", "username", ",", "course", ")", "[", "\"grade\"", "]", "output", ".", "append", "(", "data", ")", "return", "200", ",", "output" ]
List courses available to the connected client. Returns a dict in the form :: { "courseid1": { "name": "Name of the course", #the name of the course "require_password": False, #indicates if this course requires a password or not "is_registered": False, #indicates if the user is registered to this course or not "tasks": #only appears if is_registered is True { "taskid1": "name of task1", "taskid2": "name of task2" #... }, "grade": 0.0 #the current grade in the course. Only appears if is_registered is True } #... } If you use the endpoint /api/v0/courses/the_course_id, this dict will contain one entry or the page will return 404 Not Found.
[ "List", "courses", "available", "to", "the", "connected", "client", ".", "Returns", "a", "dict", "in", "the", "form" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/courses.py#L16-L67
234,933
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
_api_convert_output
def _api_convert_output(return_value): """ Convert the output to what the client asks """ content_type = web.ctx.environ.get('CONTENT_TYPE', 'text/json') if "text/json" in content_type: web.header('Content-Type', 'text/json; charset=utf-8') return json.dumps(return_value) if "text/html" in content_type: web.header('Content-Type', 'text/html; charset=utf-8') dump = yaml.dump(return_value) return "<pre>" + web.websafe(dump) + "</pre>" if "text/yaml" in content_type or \ "text/x-yaml" in content_type or \ "application/yaml" in content_type or \ "application/x-yaml" in content_type: web.header('Content-Type', 'text/yaml; charset=utf-8') dump = yaml.dump(return_value) return dump web.header('Content-Type', 'text/json; charset=utf-8') return json.dumps(return_value)
python
def _api_convert_output(return_value): """ Convert the output to what the client asks """ content_type = web.ctx.environ.get('CONTENT_TYPE', 'text/json') if "text/json" in content_type: web.header('Content-Type', 'text/json; charset=utf-8') return json.dumps(return_value) if "text/html" in content_type: web.header('Content-Type', 'text/html; charset=utf-8') dump = yaml.dump(return_value) return "<pre>" + web.websafe(dump) + "</pre>" if "text/yaml" in content_type or \ "text/x-yaml" in content_type or \ "application/yaml" in content_type or \ "application/x-yaml" in content_type: web.header('Content-Type', 'text/yaml; charset=utf-8') dump = yaml.dump(return_value) return dump web.header('Content-Type', 'text/json; charset=utf-8') return json.dumps(return_value)
[ "def", "_api_convert_output", "(", "return_value", ")", ":", "content_type", "=", "web", ".", "ctx", ".", "environ", ".", "get", "(", "'CONTENT_TYPE'", ",", "'text/json'", ")", "if", "\"text/json\"", "in", "content_type", ":", "web", ".", "header", "(", "'Content-Type'", ",", "'text/json; charset=utf-8'", ")", "return", "json", ".", "dumps", "(", "return_value", ")", "if", "\"text/html\"", "in", "content_type", ":", "web", ".", "header", "(", "'Content-Type'", ",", "'text/html; charset=utf-8'", ")", "dump", "=", "yaml", ".", "dump", "(", "return_value", ")", "return", "\"<pre>\"", "+", "web", ".", "websafe", "(", "dump", ")", "+", "\"</pre>\"", "if", "\"text/yaml\"", "in", "content_type", "or", "\"text/x-yaml\"", "in", "content_type", "or", "\"application/yaml\"", "in", "content_type", "or", "\"application/x-yaml\"", "in", "content_type", ":", "web", ".", "header", "(", "'Content-Type'", ",", "'text/yaml; charset=utf-8'", ")", "dump", "=", "yaml", ".", "dump", "(", "return_value", ")", "return", "dump", "web", ".", "header", "(", "'Content-Type'", ",", "'text/json; charset=utf-8'", ")", "return", "json", ".", "dumps", "(", "return_value", ")" ]
Convert the output to what the client asks
[ "Convert", "the", "output", "to", "what", "the", "client", "asks" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L163-L182
234,934
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIPage._handle_api
def _handle_api(self, handler, handler_args, handler_kwargs): """ Handle call to subclasses and convert the output to an appropriate value """ try: status_code, return_value = handler(*handler_args, **handler_kwargs) except APIError as error: return error.send() web.ctx.status = _convert_http_status(status_code) return _api_convert_output(return_value)
python
def _handle_api(self, handler, handler_args, handler_kwargs): """ Handle call to subclasses and convert the output to an appropriate value """ try: status_code, return_value = handler(*handler_args, **handler_kwargs) except APIError as error: return error.send() web.ctx.status = _convert_http_status(status_code) return _api_convert_output(return_value)
[ "def", "_handle_api", "(", "self", ",", "handler", ",", "handler_args", ",", "handler_kwargs", ")", ":", "try", ":", "status_code", ",", "return_value", "=", "handler", "(", "*", "handler_args", ",", "*", "*", "handler_kwargs", ")", "except", "APIError", "as", "error", ":", "return", "error", ".", "send", "(", ")", "web", ".", "ctx", ".", "status", "=", "_convert_http_status", "(", "status_code", ")", "return", "_api_convert_output", "(", "return_value", ")" ]
Handle call to subclasses and convert the output to an appropriate value
[ "Handle", "call", "to", "subclasses", "and", "convert", "the", "output", "to", "an", "appropriate", "value" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L47-L55
234,935
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIPage._guess_available_methods
def _guess_available_methods(self): """ Guess the method implemented by the subclass""" available_methods = [] for m in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]: self_method = getattr(type(self), "API_{}".format(m)) super_method = getattr(APIPage, "API_{}".format(m)) if self_method != super_method: available_methods.append(m) return available_methods
python
def _guess_available_methods(self): """ Guess the method implemented by the subclass""" available_methods = [] for m in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]: self_method = getattr(type(self), "API_{}".format(m)) super_method = getattr(APIPage, "API_{}".format(m)) if self_method != super_method: available_methods.append(m) return available_methods
[ "def", "_guess_available_methods", "(", "self", ")", ":", "available_methods", "=", "[", "]", "for", "m", "in", "[", "\"GET\"", ",", "\"POST\"", ",", "\"PUT\"", ",", "\"DELETE\"", ",", "\"PATCH\"", ",", "\"HEAD\"", ",", "\"OPTIONS\"", "]", ":", "self_method", "=", "getattr", "(", "type", "(", "self", ")", ",", "\"API_{}\"", ".", "format", "(", "m", ")", ")", "super_method", "=", "getattr", "(", "APIPage", ",", "\"API_{}\"", ".", "format", "(", "m", ")", ")", "if", "self_method", "!=", "super_method", ":", "available_methods", ".", "append", "(", "m", ")", "return", "available_methods" ]
Guess the method implemented by the subclass
[ "Guess", "the", "method", "implemented", "by", "the", "subclass" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L57-L65
234,936
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIAuthenticatedPage._verify_authentication
def _verify_authentication(self, handler, args, kwargs): """ Verify that the user is authenticated """ if not self.user_manager.session_logged_in(): raise APIForbidden() return handler(*args, **kwargs)
python
def _verify_authentication(self, handler, args, kwargs): """ Verify that the user is authenticated """ if not self.user_manager.session_logged_in(): raise APIForbidden() return handler(*args, **kwargs)
[ "def", "_verify_authentication", "(", "self", ",", "handler", ",", "args", ",", "kwargs", ")", ":", "if", "not", "self", ".", "user_manager", ".", "session_logged_in", "(", ")", ":", "raise", "APIForbidden", "(", ")", "return", "handler", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Verify that the user is authenticated
[ "Verify", "that", "the", "user", "is", "authenticated" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L109-L113
234,937
UCL-INGI/INGInious
inginious/frontend/pages/api/_api_page.py
APIError.send
def send(self): """ Send the API Exception to the client """ web.ctx.status = _convert_http_status(self.status_code) return _api_convert_output(self.return_value)
python
def send(self): """ Send the API Exception to the client """ web.ctx.status = _convert_http_status(self.status_code) return _api_convert_output(self.return_value)
[ "def", "send", "(", "self", ")", ":", "web", ".", "ctx", ".", "status", "=", "_convert_http_status", "(", "self", ".", "status_code", ")", "return", "_api_convert_output", "(", "self", ".", "return_value", ")" ]
Send the API Exception to the client
[ "Send", "the", "API", "Exception", "to", "the", "client" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/_api_page.py#L124-L127
234,938
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._job_done_callback
def _job_done_callback(self, submissionid, task, result, grade, problems, tests, custom, state, archive, stdout, stderr, newsub=True): """ Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the job """ submission = self.get_submission(submissionid, False) submission = self.get_input_from_submission(submission) data = { "status": ("done" if result[0] == "success" or result[0] == "failed" else "error"), # error only if error was made by INGInious "result": result[0], "grade": grade, "text": result[1], "tests": tests, "problems": problems, "archive": (self._gridfs.put(archive) if archive is not None else None), "custom": custom, "state": state, "stdout": stdout, "stderr": stderr } unset_obj = { "jobid": "", "ssh_host": "", "ssh_port": "", "ssh_password": "" } # Save submission to database submission = self._database.submissions.find_one_and_update( {"_id": submission["_id"]}, {"$set": data, "$unset": unset_obj}, return_document=ReturnDocument.AFTER ) self._hook_manager.call_hook("submission_done", submission=submission, archive=archive, newsub=newsub) for username in submission["username"]: self._user_manager.update_user_stats(username, task, submission, result[0], grade, state, newsub) if "outcome_service_url" in submission and "outcome_result_id" in submission and "outcome_consumer_key" in submission: for username in submission["username"]: self._lti_outcome_manager.add(username, submission["courseid"], submission["taskid"], submission["outcome_consumer_key"], submission["outcome_service_url"], submission["outcome_result_id"])
python
def _job_done_callback(self, submissionid, task, result, grade, problems, tests, custom, state, archive, stdout, stderr, newsub=True): """ Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the job """ submission = self.get_submission(submissionid, False) submission = self.get_input_from_submission(submission) data = { "status": ("done" if result[0] == "success" or result[0] == "failed" else "error"), # error only if error was made by INGInious "result": result[0], "grade": grade, "text": result[1], "tests": tests, "problems": problems, "archive": (self._gridfs.put(archive) if archive is not None else None), "custom": custom, "state": state, "stdout": stdout, "stderr": stderr } unset_obj = { "jobid": "", "ssh_host": "", "ssh_port": "", "ssh_password": "" } # Save submission to database submission = self._database.submissions.find_one_and_update( {"_id": submission["_id"]}, {"$set": data, "$unset": unset_obj}, return_document=ReturnDocument.AFTER ) self._hook_manager.call_hook("submission_done", submission=submission, archive=archive, newsub=newsub) for username in submission["username"]: self._user_manager.update_user_stats(username, task, submission, result[0], grade, state, newsub) if "outcome_service_url" in submission and "outcome_result_id" in submission and "outcome_consumer_key" in submission: for username in submission["username"]: self._lti_outcome_manager.add(username, submission["courseid"], submission["taskid"], submission["outcome_consumer_key"], submission["outcome_service_url"], submission["outcome_result_id"])
[ "def", "_job_done_callback", "(", "self", ",", "submissionid", ",", "task", ",", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "state", ",", "archive", ",", "stdout", ",", "stderr", ",", "newsub", "=", "True", ")", ":", "submission", "=", "self", ".", "get_submission", "(", "submissionid", ",", "False", ")", "submission", "=", "self", ".", "get_input_from_submission", "(", "submission", ")", "data", "=", "{", "\"status\"", ":", "(", "\"done\"", "if", "result", "[", "0", "]", "==", "\"success\"", "or", "result", "[", "0", "]", "==", "\"failed\"", "else", "\"error\"", ")", ",", "# error only if error was made by INGInious", "\"result\"", ":", "result", "[", "0", "]", ",", "\"grade\"", ":", "grade", ",", "\"text\"", ":", "result", "[", "1", "]", ",", "\"tests\"", ":", "tests", ",", "\"problems\"", ":", "problems", ",", "\"archive\"", ":", "(", "self", ".", "_gridfs", ".", "put", "(", "archive", ")", "if", "archive", "is", "not", "None", "else", "None", ")", ",", "\"custom\"", ":", "custom", ",", "\"state\"", ":", "state", ",", "\"stdout\"", ":", "stdout", ",", "\"stderr\"", ":", "stderr", "}", "unset_obj", "=", "{", "\"jobid\"", ":", "\"\"", ",", "\"ssh_host\"", ":", "\"\"", ",", "\"ssh_port\"", ":", "\"\"", ",", "\"ssh_password\"", ":", "\"\"", "}", "# Save submission to database", "submission", "=", "self", ".", "_database", ".", "submissions", ".", "find_one_and_update", "(", "{", "\"_id\"", ":", "submission", "[", "\"_id\"", "]", "}", ",", "{", "\"$set\"", ":", "data", ",", "\"$unset\"", ":", "unset_obj", "}", ",", "return_document", "=", "ReturnDocument", ".", "AFTER", ")", "self", ".", "_hook_manager", ".", "call_hook", "(", "\"submission_done\"", ",", "submission", "=", "submission", ",", "archive", "=", "archive", ",", "newsub", "=", "newsub", ")", "for", "username", "in", "submission", "[", "\"username\"", "]", ":", "self", ".", "_user_manager", ".", "update_user_stats", "(", "username", ",", "task", ",", "submission", ",", "result", "[", "0", "]", ",", "grade", ",", "state", ",", "newsub", ")", "if", "\"outcome_service_url\"", "in", "submission", "and", "\"outcome_result_id\"", "in", "submission", "and", "\"outcome_consumer_key\"", "in", "submission", ":", "for", "username", "in", "submission", "[", "\"username\"", "]", ":", "self", ".", "_lti_outcome_manager", ".", "add", "(", "username", ",", "submission", "[", "\"courseid\"", "]", ",", "submission", "[", "\"taskid\"", "]", ",", "submission", "[", "\"outcome_consumer_key\"", "]", ",", "submission", "[", "\"outcome_service_url\"", "]", ",", "submission", "[", "\"outcome_result_id\"", "]", ")" ]
Callback called by Client when a job is done. Updates the submission in the database with the data returned after the completion of the job
[ "Callback", "called", "by", "Client", "when", "a", "job", "is", "done", ".", "Updates", "the", "submission", "in", "the", "database", "with", "the", "data", "returned", "after", "the", "completion", "of", "the", "job" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L46-L93
234,939
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._before_submission_insertion
def _before_submission_insertion(self, task, inputdata, debug, obj): """ Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the database. Should be overridden in subclasses. :param task: Task related to the submission :param inputdata: input of the student :param debug: True, False or "ssh". See add_job. :param obj: the new document that will be inserted """ username = self._user_manager.session_username() if task.is_group_task() and not self._user_manager.has_staff_rights_on_course(task.get_course(), username): group = self._database.aggregations.find_one( {"courseid": task.get_course_id(), "groups.students": username}, {"groups": {"$elemMatch": {"students": username}}}) obj.update({"username": group["groups"][0]["students"]}) else: obj.update({"username": [username]}) lti_info = self._user_manager.session_lti_info() if lti_info is not None and task.get_course().lti_send_back_grade(): outcome_service_url = lti_info["outcome_service_url"] outcome_result_id = lti_info["outcome_result_id"] outcome_consumer_key = lti_info["consumer_key"] # safety check if outcome_result_id is None or outcome_service_url is None: self._logger.error("outcome_result_id or outcome_service_url is None, but grade needs to be sent back to TC! Ignoring.") return obj.update({"outcome_service_url": outcome_service_url, "outcome_result_id": outcome_result_id, "outcome_consumer_key": outcome_consumer_key})
python
def _before_submission_insertion(self, task, inputdata, debug, obj): """ Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the database. Should be overridden in subclasses. :param task: Task related to the submission :param inputdata: input of the student :param debug: True, False or "ssh". See add_job. :param obj: the new document that will be inserted """ username = self._user_manager.session_username() if task.is_group_task() and not self._user_manager.has_staff_rights_on_course(task.get_course(), username): group = self._database.aggregations.find_one( {"courseid": task.get_course_id(), "groups.students": username}, {"groups": {"$elemMatch": {"students": username}}}) obj.update({"username": group["groups"][0]["students"]}) else: obj.update({"username": [username]}) lti_info = self._user_manager.session_lti_info() if lti_info is not None and task.get_course().lti_send_back_grade(): outcome_service_url = lti_info["outcome_service_url"] outcome_result_id = lti_info["outcome_result_id"] outcome_consumer_key = lti_info["consumer_key"] # safety check if outcome_result_id is None or outcome_service_url is None: self._logger.error("outcome_result_id or outcome_service_url is None, but grade needs to be sent back to TC! Ignoring.") return obj.update({"outcome_service_url": outcome_service_url, "outcome_result_id": outcome_result_id, "outcome_consumer_key": outcome_consumer_key})
[ "def", "_before_submission_insertion", "(", "self", ",", "task", ",", "inputdata", ",", "debug", ",", "obj", ")", ":", "username", "=", "self", ".", "_user_manager", ".", "session_username", "(", ")", "if", "task", ".", "is_group_task", "(", ")", "and", "not", "self", ".", "_user_manager", ".", "has_staff_rights_on_course", "(", "task", ".", "get_course", "(", ")", ",", "username", ")", ":", "group", "=", "self", ".", "_database", ".", "aggregations", ".", "find_one", "(", "{", "\"courseid\"", ":", "task", ".", "get_course_id", "(", ")", ",", "\"groups.students\"", ":", "username", "}", ",", "{", "\"groups\"", ":", "{", "\"$elemMatch\"", ":", "{", "\"students\"", ":", "username", "}", "}", "}", ")", "obj", ".", "update", "(", "{", "\"username\"", ":", "group", "[", "\"groups\"", "]", "[", "0", "]", "[", "\"students\"", "]", "}", ")", "else", ":", "obj", ".", "update", "(", "{", "\"username\"", ":", "[", "username", "]", "}", ")", "lti_info", "=", "self", ".", "_user_manager", ".", "session_lti_info", "(", ")", "if", "lti_info", "is", "not", "None", "and", "task", ".", "get_course", "(", ")", ".", "lti_send_back_grade", "(", ")", ":", "outcome_service_url", "=", "lti_info", "[", "\"outcome_service_url\"", "]", "outcome_result_id", "=", "lti_info", "[", "\"outcome_result_id\"", "]", "outcome_consumer_key", "=", "lti_info", "[", "\"consumer_key\"", "]", "# safety check", "if", "outcome_result_id", "is", "None", "or", "outcome_service_url", "is", "None", ":", "self", ".", "_logger", ".", "error", "(", "\"outcome_result_id or outcome_service_url is None, but grade needs to be sent back to TC! Ignoring.\"", ")", "return", "obj", ".", "update", "(", "{", "\"outcome_service_url\"", ":", "outcome_service_url", ",", "\"outcome_result_id\"", ":", "outcome_result_id", ",", "\"outcome_consumer_key\"", ":", "outcome_consumer_key", "}", ")" ]
Called before any new submission is inserted into the database. Allows you to modify obj, the new document that will be inserted into the database. Should be overridden in subclasses. :param task: Task related to the submission :param inputdata: input of the student :param debug: True, False or "ssh". See add_job. :param obj: the new document that will be inserted
[ "Called", "before", "any", "new", "submission", "is", "inserted", "into", "the", "database", ".", "Allows", "you", "to", "modify", "obj", "the", "new", "document", "that", "will", "be", "inserted", "into", "the", "database", ".", "Should", "be", "overridden", "in", "subclasses", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L95-L129
234,940
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_submission
def get_submission(self, submissionid, user_check=True): """ Get a submission from the database """ sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)}) if user_check and not self.user_is_submission_owner(sub): return None return sub
python
def get_submission(self, submissionid, user_check=True): """ Get a submission from the database """ sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)}) if user_check and not self.user_is_submission_owner(sub): return None return sub
[ "def", "get_submission", "(", "self", ",", "submissionid", ",", "user_check", "=", "True", ")", ":", "sub", "=", "self", ".", "_database", ".", "submissions", ".", "find_one", "(", "{", "'_id'", ":", "ObjectId", "(", "submissionid", ")", "}", ")", "if", "user_check", "and", "not", "self", ".", "user_is_submission_owner", "(", "sub", ")", ":", "return", "None", "return", "sub" ]
Get a submission from the database
[ "Get", "a", "submission", "from", "the", "database" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L208-L213
234,941
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._delete_exceeding_submissions
def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1): """ Deletes exceeding submissions from the database, to keep the database relatively small """ if max_submissions_bound <= 0: max_submissions = task.get_stored_submissions() elif task.get_stored_submissions() <= 0: max_submissions = max_submissions_bound else: max_submissions = min(max_submissions_bound, task.get_stored_submissions()) if max_submissions <= 0: return [] tasks = list(self._database.submissions.find( {"username": username, "courseid": task.get_course_id(), "taskid": task.get_id()}, projection=["_id", "status", "result", "grade", "submitted_on"], sort=[('submitted_on', pymongo.ASCENDING)])) # List the entries to keep to_keep = set([]) if task.get_evaluate() == 'best': # Find the best "status"="done" and "result"="success" idx_best = -1 for idx, val in enumerate(tasks): if val["status"] == "done": if idx_best == -1 or tasks[idx_best]["grade"] < val["grade"]: idx_best = idx # Always keep the best submission if idx_best != -1: to_keep.add(tasks[idx_best]["_id"]) elif task.get_evaluate() == 'student': user_task = self._database.user_tasks.find_one({ "courseid": task.get_course_id(), "taskid": task.get_id(), "username": username }) submissionid = user_task.get('submissionid', None) if submissionid: to_keep.add(submissionid) # Always keep running submissions for val in tasks: if val["status"] == "waiting": to_keep.add(val["_id"]) while len(to_keep) < max_submissions and len(tasks) > 0: to_keep.add(tasks.pop()["_id"]) to_delete = {val["_id"] for val in tasks}.difference(to_keep) self._database.submissions.delete_many({"_id": {"$in": list(to_delete)}}) return list(map(str, to_delete))
python
def _delete_exceeding_submissions(self, username, task, max_submissions_bound=-1): """ Deletes exceeding submissions from the database, to keep the database relatively small """ if max_submissions_bound <= 0: max_submissions = task.get_stored_submissions() elif task.get_stored_submissions() <= 0: max_submissions = max_submissions_bound else: max_submissions = min(max_submissions_bound, task.get_stored_submissions()) if max_submissions <= 0: return [] tasks = list(self._database.submissions.find( {"username": username, "courseid": task.get_course_id(), "taskid": task.get_id()}, projection=["_id", "status", "result", "grade", "submitted_on"], sort=[('submitted_on', pymongo.ASCENDING)])) # List the entries to keep to_keep = set([]) if task.get_evaluate() == 'best': # Find the best "status"="done" and "result"="success" idx_best = -1 for idx, val in enumerate(tasks): if val["status"] == "done": if idx_best == -1 or tasks[idx_best]["grade"] < val["grade"]: idx_best = idx # Always keep the best submission if idx_best != -1: to_keep.add(tasks[idx_best]["_id"]) elif task.get_evaluate() == 'student': user_task = self._database.user_tasks.find_one({ "courseid": task.get_course_id(), "taskid": task.get_id(), "username": username }) submissionid = user_task.get('submissionid', None) if submissionid: to_keep.add(submissionid) # Always keep running submissions for val in tasks: if val["status"] == "waiting": to_keep.add(val["_id"]) while len(to_keep) < max_submissions and len(tasks) > 0: to_keep.add(tasks.pop()["_id"]) to_delete = {val["_id"] for val in tasks}.difference(to_keep) self._database.submissions.delete_many({"_id": {"$in": list(to_delete)}}) return list(map(str, to_delete))
[ "def", "_delete_exceeding_submissions", "(", "self", ",", "username", ",", "task", ",", "max_submissions_bound", "=", "-", "1", ")", ":", "if", "max_submissions_bound", "<=", "0", ":", "max_submissions", "=", "task", ".", "get_stored_submissions", "(", ")", "elif", "task", ".", "get_stored_submissions", "(", ")", "<=", "0", ":", "max_submissions", "=", "max_submissions_bound", "else", ":", "max_submissions", "=", "min", "(", "max_submissions_bound", ",", "task", ".", "get_stored_submissions", "(", ")", ")", "if", "max_submissions", "<=", "0", ":", "return", "[", "]", "tasks", "=", "list", "(", "self", ".", "_database", ".", "submissions", ".", "find", "(", "{", "\"username\"", ":", "username", ",", "\"courseid\"", ":", "task", ".", "get_course_id", "(", ")", ",", "\"taskid\"", ":", "task", ".", "get_id", "(", ")", "}", ",", "projection", "=", "[", "\"_id\"", ",", "\"status\"", ",", "\"result\"", ",", "\"grade\"", ",", "\"submitted_on\"", "]", ",", "sort", "=", "[", "(", "'submitted_on'", ",", "pymongo", ".", "ASCENDING", ")", "]", ")", ")", "# List the entries to keep", "to_keep", "=", "set", "(", "[", "]", ")", "if", "task", ".", "get_evaluate", "(", ")", "==", "'best'", ":", "# Find the best \"status\"=\"done\" and \"result\"=\"success\"", "idx_best", "=", "-", "1", "for", "idx", ",", "val", "in", "enumerate", "(", "tasks", ")", ":", "if", "val", "[", "\"status\"", "]", "==", "\"done\"", ":", "if", "idx_best", "==", "-", "1", "or", "tasks", "[", "idx_best", "]", "[", "\"grade\"", "]", "<", "val", "[", "\"grade\"", "]", ":", "idx_best", "=", "idx", "# Always keep the best submission", "if", "idx_best", "!=", "-", "1", ":", "to_keep", ".", "add", "(", "tasks", "[", "idx_best", "]", "[", "\"_id\"", "]", ")", "elif", "task", ".", "get_evaluate", "(", ")", "==", "'student'", ":", "user_task", "=", "self", ".", "_database", ".", "user_tasks", ".", "find_one", "(", "{", "\"courseid\"", ":", "task", ".", "get_course_id", "(", ")", ",", "\"taskid\"", ":", "task", ".", "get_id", "(", ")", ",", "\"username\"", ":", "username", "}", ")", "submissionid", "=", "user_task", ".", "get", "(", "'submissionid'", ",", "None", ")", "if", "submissionid", ":", "to_keep", ".", "add", "(", "submissionid", ")", "# Always keep running submissions", "for", "val", "in", "tasks", ":", "if", "val", "[", "\"status\"", "]", "==", "\"waiting\"", ":", "to_keep", ".", "add", "(", "val", "[", "\"_id\"", "]", ")", "while", "len", "(", "to_keep", ")", "<", "max_submissions", "and", "len", "(", "tasks", ")", ">", "0", ":", "to_keep", ".", "add", "(", "tasks", ".", "pop", "(", ")", "[", "\"_id\"", "]", ")", "to_delete", "=", "{", "val", "[", "\"_id\"", "]", "for", "val", "in", "tasks", "}", ".", "difference", "(", "to_keep", ")", "self", ".", "_database", ".", "submissions", ".", "delete_many", "(", "{", "\"_id\"", ":", "{", "\"$in\"", ":", "list", "(", "to_delete", ")", "}", "}", ")", "return", "list", "(", "map", "(", "str", ",", "to_delete", ")", ")" ]
Deletes exceeding submissions from the database, to keep the database relatively small
[ "Deletes", "exceeding", "submissions", "from", "the", "database", "to", "keep", "the", "database", "relatively", "small" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L284-L337
234,942
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.is_done
def is_done(self, submissionid_or_submission, user_check=True): """ Tells if a submission is done and its result is available """ # TODO: not a very nice way to avoid too many database call. Should be refactored. if isinstance(submissionid_or_submission, dict): submission = submissionid_or_submission else: submission = self.get_submission(submissionid_or_submission, False) if user_check and not self.user_is_submission_owner(submission): return None return submission["status"] == "done" or submission["status"] == "error"
python
def is_done(self, submissionid_or_submission, user_check=True): """ Tells if a submission is done and its result is available """ # TODO: not a very nice way to avoid too many database call. Should be refactored. if isinstance(submissionid_or_submission, dict): submission = submissionid_or_submission else: submission = self.get_submission(submissionid_or_submission, False) if user_check and not self.user_is_submission_owner(submission): return None return submission["status"] == "done" or submission["status"] == "error"
[ "def", "is_done", "(", "self", ",", "submissionid_or_submission", ",", "user_check", "=", "True", ")", ":", "# TODO: not a very nice way to avoid too many database call. Should be refactored.", "if", "isinstance", "(", "submissionid_or_submission", ",", "dict", ")", ":", "submission", "=", "submissionid_or_submission", "else", ":", "submission", "=", "self", ".", "get_submission", "(", "submissionid_or_submission", ",", "False", ")", "if", "user_check", "and", "not", "self", ".", "user_is_submission_owner", "(", "submission", ")", ":", "return", "None", "return", "submission", "[", "\"status\"", "]", "==", "\"done\"", "or", "submission", "[", "\"status\"", "]", "==", "\"error\"" ]
Tells if a submission is done and its result is available
[ "Tells", "if", "a", "submission", "is", "done", "and", "its", "result", "is", "available" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L379-L388
234,943
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.user_is_submission_owner
def user_is_submission_owner(self, submission): """ Returns true if the current user is the owner of this jobid, false else """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to verify if he owns a jobid") return self._user_manager.session_username() in submission["username"]
python
def user_is_submission_owner(self, submission): """ Returns true if the current user is the owner of this jobid, false else """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to verify if he owns a jobid") return self._user_manager.session_username() in submission["username"]
[ "def", "user_is_submission_owner", "(", "self", ",", "submission", ")", ":", "if", "not", "self", ".", "_user_manager", ".", "session_logged_in", "(", ")", ":", "raise", "Exception", "(", "\"A user must be logged in to verify if he owns a jobid\"", ")", "return", "self", ".", "_user_manager", ".", "session_username", "(", ")", "in", "submission", "[", "\"username\"", "]" ]
Returns true if the current user is the owner of this jobid, false else
[ "Returns", "true", "if", "the", "current", "user", "is", "the", "owner", "of", "this", "jobid", "false", "else" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L404-L409
234,944
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_user_submissions
def get_user_submissions(self, task): """ Get all the user's submissions for a given task """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to get his submissions") cursor = self._database.submissions.find({"username": self._user_manager.session_username(), "taskid": task.get_id(), "courseid": task.get_course_id()}) cursor.sort([("submitted_on", -1)]) return list(cursor)
python
def get_user_submissions(self, task): """ Get all the user's submissions for a given task """ if not self._user_manager.session_logged_in(): raise Exception("A user must be logged in to get his submissions") cursor = self._database.submissions.find({"username": self._user_manager.session_username(), "taskid": task.get_id(), "courseid": task.get_course_id()}) cursor.sort([("submitted_on", -1)]) return list(cursor)
[ "def", "get_user_submissions", "(", "self", ",", "task", ")", ":", "if", "not", "self", ".", "_user_manager", ".", "session_logged_in", "(", ")", ":", "raise", "Exception", "(", "\"A user must be logged in to get his submissions\"", ")", "cursor", "=", "self", ".", "_database", ".", "submissions", ".", "find", "(", "{", "\"username\"", ":", "self", ".", "_user_manager", ".", "session_username", "(", ")", ",", "\"taskid\"", ":", "task", ".", "get_id", "(", ")", ",", "\"courseid\"", ":", "task", ".", "get_course_id", "(", ")", "}", ")", "cursor", ".", "sort", "(", "[", "(", "\"submitted_on\"", ",", "-", "1", ")", "]", ")", "return", "list", "(", "cursor", ")" ]
Get all the user's submissions for a given task
[ "Get", "all", "the", "user", "s", "submissions", "for", "a", "given", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L411-L419
234,945
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager.get_user_last_submissions
def get_user_last_submissions(self, limit=5, request=None): """ Get last submissions of a user """ if request is None: request = {} request.update({"username": self._user_manager.session_username()}) # Before, submissions were first sorted by submission date, then grouped # and then resorted by submission date before limiting. Actually, grouping # and pushing, keeping the max date, followed by result filtering is much more # efficient data = self._database.submissions.aggregate([ {"$match": request}, {"$group": {"_id": {"courseid": "$courseid", "taskid": "$taskid"}, "submitted_on": {"$max": "$submitted_on"}, "submissions": {"$push": { "_id": "$_id", "result": "$result", "status" : "$status", "courseid": "$courseid", "taskid": "$taskid", "submitted_on": "$submitted_on" }}, }}, {"$project": { "submitted_on": 1, "submissions": { # This could be replaced by $filter if mongo v3.2 is set as dependency "$setDifference": [ {"$map": { "input": "$submissions", "as": "submission", "in": { "$cond": [{"$eq": ["$submitted_on", "$$submission.submitted_on"]}, "$$submission", False] } }}, [False] ] } }}, {"$sort": {"submitted_on": pymongo.DESCENDING}}, {"$limit": limit} ]) return [item["submissions"][0] for item in data]
python
def get_user_last_submissions(self, limit=5, request=None): """ Get last submissions of a user """ if request is None: request = {} request.update({"username": self._user_manager.session_username()}) # Before, submissions were first sorted by submission date, then grouped # and then resorted by submission date before limiting. Actually, grouping # and pushing, keeping the max date, followed by result filtering is much more # efficient data = self._database.submissions.aggregate([ {"$match": request}, {"$group": {"_id": {"courseid": "$courseid", "taskid": "$taskid"}, "submitted_on": {"$max": "$submitted_on"}, "submissions": {"$push": { "_id": "$_id", "result": "$result", "status" : "$status", "courseid": "$courseid", "taskid": "$taskid", "submitted_on": "$submitted_on" }}, }}, {"$project": { "submitted_on": 1, "submissions": { # This could be replaced by $filter if mongo v3.2 is set as dependency "$setDifference": [ {"$map": { "input": "$submissions", "as": "submission", "in": { "$cond": [{"$eq": ["$submitted_on", "$$submission.submitted_on"]}, "$$submission", False] } }}, [False] ] } }}, {"$sort": {"submitted_on": pymongo.DESCENDING}}, {"$limit": limit} ]) return [item["submissions"][0] for item in data]
[ "def", "get_user_last_submissions", "(", "self", ",", "limit", "=", "5", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "{", "}", "request", ".", "update", "(", "{", "\"username\"", ":", "self", ".", "_user_manager", ".", "session_username", "(", ")", "}", ")", "# Before, submissions were first sorted by submission date, then grouped", "# and then resorted by submission date before limiting. Actually, grouping", "# and pushing, keeping the max date, followed by result filtering is much more", "# efficient", "data", "=", "self", ".", "_database", ".", "submissions", ".", "aggregate", "(", "[", "{", "\"$match\"", ":", "request", "}", ",", "{", "\"$group\"", ":", "{", "\"_id\"", ":", "{", "\"courseid\"", ":", "\"$courseid\"", ",", "\"taskid\"", ":", "\"$taskid\"", "}", ",", "\"submitted_on\"", ":", "{", "\"$max\"", ":", "\"$submitted_on\"", "}", ",", "\"submissions\"", ":", "{", "\"$push\"", ":", "{", "\"_id\"", ":", "\"$_id\"", ",", "\"result\"", ":", "\"$result\"", ",", "\"status\"", ":", "\"$status\"", ",", "\"courseid\"", ":", "\"$courseid\"", ",", "\"taskid\"", ":", "\"$taskid\"", ",", "\"submitted_on\"", ":", "\"$submitted_on\"", "}", "}", ",", "}", "}", ",", "{", "\"$project\"", ":", "{", "\"submitted_on\"", ":", "1", ",", "\"submissions\"", ":", "{", "# This could be replaced by $filter if mongo v3.2 is set as dependency", "\"$setDifference\"", ":", "[", "{", "\"$map\"", ":", "{", "\"input\"", ":", "\"$submissions\"", ",", "\"as\"", ":", "\"submission\"", ",", "\"in\"", ":", "{", "\"$cond\"", ":", "[", "{", "\"$eq\"", ":", "[", "\"$submitted_on\"", ",", "\"$$submission.submitted_on\"", "]", "}", ",", "\"$$submission\"", ",", "False", "]", "}", "}", "}", ",", "[", "False", "]", "]", "}", "}", "}", ",", "{", "\"$sort\"", ":", "{", "\"submitted_on\"", ":", "pymongo", ".", "DESCENDING", "}", "}", ",", "{", "\"$limit\"", ":", "limit", "}", "]", ")", "return", "[", "item", "[", "\"submissions\"", "]", "[", "0", "]", "for", "item", "in", "data", "]" ]
Get last submissions of a user
[ "Get", "last", "submissions", "of", "a", "user" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L421-L465
234,946
UCL-INGI/INGInious
inginious/frontend/submission_manager.py
WebAppSubmissionManager._handle_ssh_callback
def _handle_ssh_callback(self, submission_id, host, port, password): """ Handles the creation of a remote ssh server """ if host is not None: # ignore late calls (a bit hacky, but...) obj = { "ssh_host": host, "ssh_port": port, "ssh_password": password } self._database.submissions.update_one({"_id": submission_id}, {"$set": obj})
python
def _handle_ssh_callback(self, submission_id, host, port, password): """ Handles the creation of a remote ssh server """ if host is not None: # ignore late calls (a bit hacky, but...) obj = { "ssh_host": host, "ssh_port": port, "ssh_password": password } self._database.submissions.update_one({"_id": submission_id}, {"$set": obj})
[ "def", "_handle_ssh_callback", "(", "self", ",", "submission_id", ",", "host", ",", "port", ",", "password", ")", ":", "if", "host", "is", "not", "None", ":", "# ignore late calls (a bit hacky, but...)", "obj", "=", "{", "\"ssh_host\"", ":", "host", ",", "\"ssh_port\"", ":", "port", ",", "\"ssh_password\"", ":", "password", "}", "self", ".", "_database", ".", "submissions", ".", "update_one", "(", "{", "\"_id\"", ":", "submission_id", "}", ",", "{", "\"$set\"", ":", "obj", "}", ")" ]
Handles the creation of a remote ssh server
[ "Handles", "the", "creation", "of", "a", "remote", "ssh", "server" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/submission_manager.py#L569-L577
234,947
UCL-INGI/INGInious
inginious/common/entrypoints.py
filesystem_from_config_dict
def filesystem_from_config_dict(config_fs): """ Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider. Exits if there is an error. """ if "module" not in config_fs: print("Key 'module' should be defined for the filesystem provider ('fs' configuration option)", file=sys.stderr) exit(1) filesystem_providers = get_filesystems_providers() if config_fs["module"] not in filesystem_providers: print("Unknown filesystem provider "+config_fs["module"], file=sys.stderr) exit(1) fs_class = filesystem_providers[config_fs["module"]] fs_args_needed = fs_class.get_needed_args() fs_args = {} for arg_name, (arg_type, arg_required, _) in fs_args_needed.items(): if arg_name in config_fs: fs_args[arg_name] = arg_type(config_fs[arg_name]) elif arg_required: print("fs option {} is required".format(arg_name), file=sys.stderr) exit(1) try: return fs_class.init_from_args(**fs_args) except: print("Unable to load class " + config_fs["module"], file=sys.stderr) raise
python
def filesystem_from_config_dict(config_fs): """ Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider. Exits if there is an error. """ if "module" not in config_fs: print("Key 'module' should be defined for the filesystem provider ('fs' configuration option)", file=sys.stderr) exit(1) filesystem_providers = get_filesystems_providers() if config_fs["module"] not in filesystem_providers: print("Unknown filesystem provider "+config_fs["module"], file=sys.stderr) exit(1) fs_class = filesystem_providers[config_fs["module"]] fs_args_needed = fs_class.get_needed_args() fs_args = {} for arg_name, (arg_type, arg_required, _) in fs_args_needed.items(): if arg_name in config_fs: fs_args[arg_name] = arg_type(config_fs[arg_name]) elif arg_required: print("fs option {} is required".format(arg_name), file=sys.stderr) exit(1) try: return fs_class.init_from_args(**fs_args) except: print("Unable to load class " + config_fs["module"], file=sys.stderr) raise
[ "def", "filesystem_from_config_dict", "(", "config_fs", ")", ":", "if", "\"module\"", "not", "in", "config_fs", ":", "print", "(", "\"Key 'module' should be defined for the filesystem provider ('fs' configuration option)\"", ",", "file", "=", "sys", ".", "stderr", ")", "exit", "(", "1", ")", "filesystem_providers", "=", "get_filesystems_providers", "(", ")", "if", "config_fs", "[", "\"module\"", "]", "not", "in", "filesystem_providers", ":", "print", "(", "\"Unknown filesystem provider \"", "+", "config_fs", "[", "\"module\"", "]", ",", "file", "=", "sys", ".", "stderr", ")", "exit", "(", "1", ")", "fs_class", "=", "filesystem_providers", "[", "config_fs", "[", "\"module\"", "]", "]", "fs_args_needed", "=", "fs_class", ".", "get_needed_args", "(", ")", "fs_args", "=", "{", "}", "for", "arg_name", ",", "(", "arg_type", ",", "arg_required", ",", "_", ")", "in", "fs_args_needed", ".", "items", "(", ")", ":", "if", "arg_name", "in", "config_fs", ":", "fs_args", "[", "arg_name", "]", "=", "arg_type", "(", "config_fs", "[", "arg_name", "]", ")", "elif", "arg_required", ":", "print", "(", "\"fs option {} is required\"", ".", "format", "(", "arg_name", ")", ",", "file", "=", "sys", ".", "stderr", ")", "exit", "(", "1", ")", "try", ":", "return", "fs_class", ".", "init_from_args", "(", "*", "*", "fs_args", ")", "except", ":", "print", "(", "\"Unable to load class \"", "+", "config_fs", "[", "\"module\"", "]", ",", "file", "=", "sys", ".", "stderr", ")", "raise" ]
Given a dict containing an entry "module" which contains a FSProvider identifier, parse the configuration and returns a fs_provider. Exits if there is an error.
[ "Given", "a", "dict", "containing", "an", "entry", "module", "which", "contains", "a", "FSProvider", "identifier", "parse", "the", "configuration", "and", "returns", "a", "fs_provider", ".", "Exits", "if", "there", "is", "an", "error", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/entrypoints.py#L20-L48
234,948
UCL-INGI/INGInious
inginious/agent/docker_agent/_timeout_watcher.py
TimeoutWatcher._kill_it_with_fire
async def _kill_it_with_fire(self, container_id): """ Kill a container, with fire. """ if container_id in self._watching: self._watching.remove(container_id) self._container_had_error.add(container_id) try: await self._docker_interface.kill_container(container_id) except: pass
python
async def _kill_it_with_fire(self, container_id): """ Kill a container, with fire. """ if container_id in self._watching: self._watching.remove(container_id) self._container_had_error.add(container_id) try: await self._docker_interface.kill_container(container_id) except: pass
[ "async", "def", "_kill_it_with_fire", "(", "self", ",", "container_id", ")", ":", "if", "container_id", "in", "self", ".", "_watching", ":", "self", ".", "_watching", ".", "remove", "(", "container_id", ")", "self", ".", "_container_had_error", ".", "add", "(", "container_id", ")", "try", ":", "await", "self", ".", "_docker_interface", ".", "kill_container", "(", "container_id", ")", "except", ":", "pass" ]
Kill a container, with fire.
[ "Kill", "a", "container", "with", "fire", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/docker_agent/_timeout_watcher.py#L95-L105
234,949
UCL-INGI/INGInious
inginious/frontend/cookieless_app.py
CookieLessCompatibleSession._cleanup
def _cleanup(self): """Cleanup the stored sessions""" current_time = time.time() timeout = self._config.timeout if current_time - self._last_cleanup_time > timeout: self.store.cleanup(timeout) self._last_cleanup_time = current_time
python
def _cleanup(self): """Cleanup the stored sessions""" current_time = time.time() timeout = self._config.timeout if current_time - self._last_cleanup_time > timeout: self.store.cleanup(timeout) self._last_cleanup_time = current_time
[ "def", "_cleanup", "(", "self", ")", ":", "current_time", "=", "time", ".", "time", "(", ")", "timeout", "=", "self", ".", "_config", ".", "timeout", "if", "current_time", "-", "self", ".", "_last_cleanup_time", ">", "timeout", ":", "self", ".", "store", ".", "cleanup", "(", "timeout", ")", "self", ".", "_last_cleanup_time", "=", "current_time" ]
Cleanup the stored sessions
[ "Cleanup", "the", "stored", "sessions" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/cookieless_app.py#L255-L261
234,950
UCL-INGI/INGInious
inginious/frontend/cookieless_app.py
CookieLessCompatibleSession.expired
def expired(self): """Called when an expired session is atime""" self._data["_killed"] = True self.save() raise SessionExpired(self._config.expired_message)
python
def expired(self): """Called when an expired session is atime""" self._data["_killed"] = True self.save() raise SessionExpired(self._config.expired_message)
[ "def", "expired", "(", "self", ")", ":", "self", ".", "_data", "[", "\"_killed\"", "]", "=", "True", "self", ".", "save", "(", ")", "raise", "SessionExpired", "(", "self", ".", "_config", ".", "expired_message", ")" ]
Called when an expired session is atime
[ "Called", "when", "an", "expired", "session", "is", "atime" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/cookieless_app.py#L263-L267
234,951
UCL-INGI/INGInious
inginious/frontend/pages/preferences/delete.py
DeletePage.delete_account
def delete_account(self, data): """ Delete account from DB """ error = False msg = "" username = self.user_manager.session_username() # Check input format result = self.database.users.find_one_and_delete({"username": username, "email": data.get("delete_email", "")}) if not result: error = True msg = _("The specified email is incorrect.") else: self.database.submissions.remove({"username": username}) self.database.user_tasks.remove({"username": username}) all_courses = self.course_factory.get_all_courses() for courseid, course in all_courses.items(): if self.user_manager.course_is_open_to_user(course, username): self.user_manager.course_unregister_user(course, username) self.user_manager.disconnect_user() raise web.seeother("/index") return msg, error
python
def delete_account(self, data): """ Delete account from DB """ error = False msg = "" username = self.user_manager.session_username() # Check input format result = self.database.users.find_one_and_delete({"username": username, "email": data.get("delete_email", "")}) if not result: error = True msg = _("The specified email is incorrect.") else: self.database.submissions.remove({"username": username}) self.database.user_tasks.remove({"username": username}) all_courses = self.course_factory.get_all_courses() for courseid, course in all_courses.items(): if self.user_manager.course_is_open_to_user(course, username): self.user_manager.course_unregister_user(course, username) self.user_manager.disconnect_user() raise web.seeother("/index") return msg, error
[ "def", "delete_account", "(", "self", ",", "data", ")", ":", "error", "=", "False", "msg", "=", "\"\"", "username", "=", "self", ".", "user_manager", ".", "session_username", "(", ")", "# Check input format", "result", "=", "self", ".", "database", ".", "users", ".", "find_one_and_delete", "(", "{", "\"username\"", ":", "username", ",", "\"email\"", ":", "data", ".", "get", "(", "\"delete_email\"", ",", "\"\"", ")", "}", ")", "if", "not", "result", ":", "error", "=", "True", "msg", "=", "_", "(", "\"The specified email is incorrect.\"", ")", "else", ":", "self", ".", "database", ".", "submissions", ".", "remove", "(", "{", "\"username\"", ":", "username", "}", ")", "self", ".", "database", ".", "user_tasks", ".", "remove", "(", "{", "\"username\"", ":", "username", "}", ")", "all_courses", "=", "self", ".", "course_factory", ".", "get_all_courses", "(", ")", "for", "courseid", ",", "course", "in", "all_courses", ".", "items", "(", ")", ":", "if", "self", ".", "user_manager", ".", "course_is_open_to_user", "(", "course", ",", "username", ")", ":", "self", ".", "user_manager", ".", "course_unregister_user", "(", "course", ",", "username", ")", "self", ".", "user_manager", ".", "disconnect_user", "(", ")", "raise", "web", ".", "seeother", "(", "\"/index\"", ")", "return", "msg", ",", "error" ]
Delete account from DB
[ "Delete", "account", "from", "DB" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/preferences/delete.py#L15-L41
234,952
UCL-INGI/INGInious
inginious/common/custom_yaml.py
dump
def dump(data, stream=None, **kwds): """ Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. Dict keys are produced in the order in which they appear in OrderedDicts. Safe version. If objects are not "conventional" objects, they will be dumped converted to string with the str() function. They will then not be recovered when loading with the load() function. """ # Display OrderedDicts correctly class OrderedDumper(SafeDumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( original_yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, list(data.items())) # Display long strings correctly def _long_str_representer(dumper, data): if data.find("\n") != -1: # Drop some uneeded data # \t are forbidden in YAML data = data.replace("\t", " ") # empty spaces at end of line are always useless in INGInious, and forbidden in YAML data = "\n".join([p.rstrip() for p in data.split("\n")]) return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') else: return dumper.represent_scalar('tag:yaml.org,2002:str', data) # Default representation for some odd objects def _default_representer(dumper, data): return _long_str_representer(dumper, str(data)) OrderedDumper.add_representer(str, _long_str_representer) OrderedDumper.add_representer(str, _long_str_representer) OrderedDumper.add_representer(OrderedDict, _dict_representer) OrderedDumper.add_representer(None, _default_representer) s = original_yaml.dump(data, stream, OrderedDumper, encoding='utf-8', allow_unicode=True, default_flow_style=False, indent=4, **kwds) if s is not None: return s.decode('utf-8') else: return
python
def dump(data, stream=None, **kwds): """ Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. Dict keys are produced in the order in which they appear in OrderedDicts. Safe version. If objects are not "conventional" objects, they will be dumped converted to string with the str() function. They will then not be recovered when loading with the load() function. """ # Display OrderedDicts correctly class OrderedDumper(SafeDumper): pass def _dict_representer(dumper, data): return dumper.represent_mapping( original_yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, list(data.items())) # Display long strings correctly def _long_str_representer(dumper, data): if data.find("\n") != -1: # Drop some uneeded data # \t are forbidden in YAML data = data.replace("\t", " ") # empty spaces at end of line are always useless in INGInious, and forbidden in YAML data = "\n".join([p.rstrip() for p in data.split("\n")]) return dumper.represent_scalar('tag:yaml.org,2002:str', data, style='|') else: return dumper.represent_scalar('tag:yaml.org,2002:str', data) # Default representation for some odd objects def _default_representer(dumper, data): return _long_str_representer(dumper, str(data)) OrderedDumper.add_representer(str, _long_str_representer) OrderedDumper.add_representer(str, _long_str_representer) OrderedDumper.add_representer(OrderedDict, _dict_representer) OrderedDumper.add_representer(None, _default_representer) s = original_yaml.dump(data, stream, OrderedDumper, encoding='utf-8', allow_unicode=True, default_flow_style=False, indent=4, **kwds) if s is not None: return s.decode('utf-8') else: return
[ "def", "dump", "(", "data", ",", "stream", "=", "None", ",", "*", "*", "kwds", ")", ":", "# Display OrderedDicts correctly", "class", "OrderedDumper", "(", "SafeDumper", ")", ":", "pass", "def", "_dict_representer", "(", "dumper", ",", "data", ")", ":", "return", "dumper", ".", "represent_mapping", "(", "original_yaml", ".", "resolver", ".", "BaseResolver", ".", "DEFAULT_MAPPING_TAG", ",", "list", "(", "data", ".", "items", "(", ")", ")", ")", "# Display long strings correctly", "def", "_long_str_representer", "(", "dumper", ",", "data", ")", ":", "if", "data", ".", "find", "(", "\"\\n\"", ")", "!=", "-", "1", ":", "# Drop some uneeded data", "# \\t are forbidden in YAML", "data", "=", "data", ".", "replace", "(", "\"\\t\"", ",", "\" \"", ")", "# empty spaces at end of line are always useless in INGInious, and forbidden in YAML", "data", "=", "\"\\n\"", ".", "join", "(", "[", "p", ".", "rstrip", "(", ")", "for", "p", "in", "data", ".", "split", "(", "\"\\n\"", ")", "]", ")", "return", "dumper", ".", "represent_scalar", "(", "'tag:yaml.org,2002:str'", ",", "data", ",", "style", "=", "'|'", ")", "else", ":", "return", "dumper", ".", "represent_scalar", "(", "'tag:yaml.org,2002:str'", ",", "data", ")", "# Default representation for some odd objects", "def", "_default_representer", "(", "dumper", ",", "data", ")", ":", "return", "_long_str_representer", "(", "dumper", ",", "str", "(", "data", ")", ")", "OrderedDumper", ".", "add_representer", "(", "str", ",", "_long_str_representer", ")", "OrderedDumper", ".", "add_representer", "(", "str", ",", "_long_str_representer", ")", "OrderedDumper", ".", "add_representer", "(", "OrderedDict", ",", "_dict_representer", ")", "OrderedDumper", ".", "add_representer", "(", "None", ",", "_default_representer", ")", "s", "=", "original_yaml", ".", "dump", "(", "data", ",", "stream", ",", "OrderedDumper", ",", "encoding", "=", "'utf-8'", ",", "allow_unicode", "=", "True", ",", "default_flow_style", "=", "False", ",", "indent", "=", "4", ",", "*", "*", "kwds", ")", "if", "s", "is", "not", "None", ":", "return", "s", ".", "decode", "(", "'utf-8'", ")", "else", ":", "return" ]
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. Dict keys are produced in the order in which they appear in OrderedDicts. Safe version. If objects are not "conventional" objects, they will be dumped converted to string with the str() function. They will then not be recovered when loading with the load() function.
[ "Serialize", "a", "Python", "object", "into", "a", "YAML", "stream", ".", "If", "stream", "is", "None", "return", "the", "produced", "string", "instead", ".", "Dict", "keys", "are", "produced", "in", "the", "order", "in", "which", "they", "appear", "in", "OrderedDicts", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/custom_yaml.py#L40-L87
234,953
UCL-INGI/INGInious
inginious/frontend/pages/api/tasks.py
APITasks._check_for_parsable_text
def _check_for_parsable_text(self, val): """ Util to remove parsable text from a dict, recursively """ if isinstance(val, ParsableText): return val.original_content() if isinstance(val, list): for key, val2 in enumerate(val): val[key] = self._check_for_parsable_text(val2) return val if isinstance(val, dict): for key, val2 in val.items(): val[key] = self._check_for_parsable_text(val2) return val
python
def _check_for_parsable_text(self, val): """ Util to remove parsable text from a dict, recursively """ if isinstance(val, ParsableText): return val.original_content() if isinstance(val, list): for key, val2 in enumerate(val): val[key] = self._check_for_parsable_text(val2) return val if isinstance(val, dict): for key, val2 in val.items(): val[key] = self._check_for_parsable_text(val2) return val
[ "def", "_check_for_parsable_text", "(", "self", ",", "val", ")", ":", "if", "isinstance", "(", "val", ",", "ParsableText", ")", ":", "return", "val", ".", "original_content", "(", ")", "if", "isinstance", "(", "val", ",", "list", ")", ":", "for", "key", ",", "val2", "in", "enumerate", "(", "val", ")", ":", "val", "[", "key", "]", "=", "self", ".", "_check_for_parsable_text", "(", "val2", ")", "return", "val", "if", "isinstance", "(", "val", ",", "dict", ")", ":", "for", "key", ",", "val2", "in", "val", ".", "items", "(", ")", ":", "val", "[", "key", "]", "=", "self", ".", "_check_for_parsable_text", "(", "val2", ")", "return", "val" ]
Util to remove parsable text from a dict, recursively
[ "Util", "to", "remove", "parsable", "text", "from", "a", "dict", "recursively" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/tasks.py#L17-L28
234,954
UCL-INGI/INGInious
inginious/frontend/pages/api/tasks.py
APITasks.API_GET
def API_GET(self, courseid, taskid=None): # pylint: disable=arguments-differ """ List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", #the name of the course "authors": [], "deadline": "", "status": "success" # can be "succeeded", "failed" or "notattempted" "grade": 0.0, "grade_weight": 0.0, "context": "" # context of the task, in RST "problems": # dict of the subproblems { # see the format of task.yaml for the content of the dict. Contains everything but # responses of multiple-choice and match problems. } } #... } If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id, this dict will contain one entry or the page will return 404 Not Found. """ try: course = self.course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not self.user_manager.course_is_open_to_user(course, lti=False): raise APIForbidden("You are not registered to this course") if taskid is None: tasks = course.get_tasks() else: try: tasks = {taskid: course.get_task(taskid)} except: raise APINotFound("Task not found") output = [] for taskid, task in tasks.items(): task_cache = self.user_manager.get_task_cache(self.user_manager.session_username(), task.get_course_id(), task.get_id()) data = { "id": taskid, "name": task.get_name(self.user_manager.session_language()), "authors": task.get_authors(self.user_manager.session_language()), "deadline": task.get_deadline(), "status": "notviewed" if task_cache is None else "notattempted" if task_cache["tried"] == 0 else "succeeded" if task_cache["succeeded"] else "failed", "grade": task_cache.get("grade", 0.0) if task_cache is not None else 0.0, "grade_weight": task.get_grading_weight(), "context": task.get_context(self.user_manager.session_language()).original_content(), "problems": [] } for problem in task.get_problems(): pcontent = problem.get_original_content() pcontent["id"] = problem.get_id() if pcontent["type"] == "match": del pcontent["answer"] if pcontent["type"] == "multiple_choice": pcontent["choices"] = {key: val["text"] for key, val in enumerate(pcontent["choices"])} pcontent = self._check_for_parsable_text(pcontent) data["problems"].append(pcontent) output.append(data) return 200, output
python
def API_GET(self, courseid, taskid=None): # pylint: disable=arguments-differ """ List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", #the name of the course "authors": [], "deadline": "", "status": "success" # can be "succeeded", "failed" or "notattempted" "grade": 0.0, "grade_weight": 0.0, "context": "" # context of the task, in RST "problems": # dict of the subproblems { # see the format of task.yaml for the content of the dict. Contains everything but # responses of multiple-choice and match problems. } } #... } If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id, this dict will contain one entry or the page will return 404 Not Found. """ try: course = self.course_factory.get_course(courseid) except: raise APINotFound("Course not found") if not self.user_manager.course_is_open_to_user(course, lti=False): raise APIForbidden("You are not registered to this course") if taskid is None: tasks = course.get_tasks() else: try: tasks = {taskid: course.get_task(taskid)} except: raise APINotFound("Task not found") output = [] for taskid, task in tasks.items(): task_cache = self.user_manager.get_task_cache(self.user_manager.session_username(), task.get_course_id(), task.get_id()) data = { "id": taskid, "name": task.get_name(self.user_manager.session_language()), "authors": task.get_authors(self.user_manager.session_language()), "deadline": task.get_deadline(), "status": "notviewed" if task_cache is None else "notattempted" if task_cache["tried"] == 0 else "succeeded" if task_cache["succeeded"] else "failed", "grade": task_cache.get("grade", 0.0) if task_cache is not None else 0.0, "grade_weight": task.get_grading_weight(), "context": task.get_context(self.user_manager.session_language()).original_content(), "problems": [] } for problem in task.get_problems(): pcontent = problem.get_original_content() pcontent["id"] = problem.get_id() if pcontent["type"] == "match": del pcontent["answer"] if pcontent["type"] == "multiple_choice": pcontent["choices"] = {key: val["text"] for key, val in enumerate(pcontent["choices"])} pcontent = self._check_for_parsable_text(pcontent) data["problems"].append(pcontent) output.append(data) return 200, output
[ "def", "API_GET", "(", "self", ",", "courseid", ",", "taskid", "=", "None", ")", ":", "# pylint: disable=arguments-differ", "try", ":", "course", "=", "self", ".", "course_factory", ".", "get_course", "(", "courseid", ")", "except", ":", "raise", "APINotFound", "(", "\"Course not found\"", ")", "if", "not", "self", ".", "user_manager", ".", "course_is_open_to_user", "(", "course", ",", "lti", "=", "False", ")", ":", "raise", "APIForbidden", "(", "\"You are not registered to this course\"", ")", "if", "taskid", "is", "None", ":", "tasks", "=", "course", ".", "get_tasks", "(", ")", "else", ":", "try", ":", "tasks", "=", "{", "taskid", ":", "course", ".", "get_task", "(", "taskid", ")", "}", "except", ":", "raise", "APINotFound", "(", "\"Task not found\"", ")", "output", "=", "[", "]", "for", "taskid", ",", "task", "in", "tasks", ".", "items", "(", ")", ":", "task_cache", "=", "self", ".", "user_manager", ".", "get_task_cache", "(", "self", ".", "user_manager", ".", "session_username", "(", ")", ",", "task", ".", "get_course_id", "(", ")", ",", "task", ".", "get_id", "(", ")", ")", "data", "=", "{", "\"id\"", ":", "taskid", ",", "\"name\"", ":", "task", ".", "get_name", "(", "self", ".", "user_manager", ".", "session_language", "(", ")", ")", ",", "\"authors\"", ":", "task", ".", "get_authors", "(", "self", ".", "user_manager", ".", "session_language", "(", ")", ")", ",", "\"deadline\"", ":", "task", ".", "get_deadline", "(", ")", ",", "\"status\"", ":", "\"notviewed\"", "if", "task_cache", "is", "None", "else", "\"notattempted\"", "if", "task_cache", "[", "\"tried\"", "]", "==", "0", "else", "\"succeeded\"", "if", "task_cache", "[", "\"succeeded\"", "]", "else", "\"failed\"", ",", "\"grade\"", ":", "task_cache", ".", "get", "(", "\"grade\"", ",", "0.0", ")", "if", "task_cache", "is", "not", "None", "else", "0.0", ",", "\"grade_weight\"", ":", "task", ".", "get_grading_weight", "(", ")", ",", "\"context\"", ":", "task", ".", "get_context", "(", "self", ".", "user_manager", ".", "session_language", "(", ")", ")", ".", "original_content", "(", ")", ",", "\"problems\"", ":", "[", "]", "}", "for", "problem", "in", "task", ".", "get_problems", "(", ")", ":", "pcontent", "=", "problem", ".", "get_original_content", "(", ")", "pcontent", "[", "\"id\"", "]", "=", "problem", ".", "get_id", "(", ")", "if", "pcontent", "[", "\"type\"", "]", "==", "\"match\"", ":", "del", "pcontent", "[", "\"answer\"", "]", "if", "pcontent", "[", "\"type\"", "]", "==", "\"multiple_choice\"", ":", "pcontent", "[", "\"choices\"", "]", "=", "{", "key", ":", "val", "[", "\"text\"", "]", "for", "key", ",", "val", "in", "enumerate", "(", "pcontent", "[", "\"choices\"", "]", ")", "}", "pcontent", "=", "self", ".", "_check_for_parsable_text", "(", "pcontent", ")", "data", "[", "\"problems\"", "]", ".", "append", "(", "pcontent", ")", "output", ".", "append", "(", "data", ")", "return", "200", ",", "output" ]
List tasks available to the connected client. Returns a dict in the form :: { "taskid1": { "name": "Name of the course", #the name of the course "authors": [], "deadline": "", "status": "success" # can be "succeeded", "failed" or "notattempted" "grade": 0.0, "grade_weight": 0.0, "context": "" # context of the task, in RST "problems": # dict of the subproblems { # see the format of task.yaml for the content of the dict. Contains everything but # responses of multiple-choice and match problems. } } #... } If you use the endpoint /api/v0/courses/the_course_id/tasks/the_task_id, this dict will contain one entry or the page will return 404 Not Found.
[ "List", "tasks", "available", "to", "the", "connected", "client", ".", "Returns", "a", "dict", "in", "the", "form" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/api/tasks.py#L30-L103
234,955
UCL-INGI/INGInious
base-containers/base/inginious/input.py
load_input
def load_input(): """ Open existing input file """ file = open(_input_file, 'r') result = json.loads(file.read().strip('\0').strip()) file.close() return result
python
def load_input(): """ Open existing input file """ file = open(_input_file, 'r') result = json.loads(file.read().strip('\0').strip()) file.close() return result
[ "def", "load_input", "(", ")", ":", "file", "=", "open", "(", "_input_file", ",", "'r'", ")", "result", "=", "json", ".", "loads", "(", "file", ".", "read", "(", ")", ".", "strip", "(", "'\\0'", ")", ".", "strip", "(", ")", ")", "file", ".", "close", "(", ")", "return", "result" ]
Open existing input file
[ "Open", "existing", "input", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/input.py#L14-L19
234,956
UCL-INGI/INGInious
base-containers/base/inginious/input.py
parse_template
def parse_template(input_filename, output_filename=''): """ Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file """ data = load_input() with open(input_filename, 'rb') as file: template = file.read().decode("utf-8") # Check if 'input' in data if not 'input' in data: raise ValueError("Could not find 'input' in data") # Parse template for field in data['input']: subs = ["filename", "value"] if isinstance(data['input'][field], dict) and "filename" in data['input'][field] and "value" in data['input'][field] else [""] for sub in subs: displayed_field = field + (":" if sub else "") + sub regex = re.compile("@([^@]*)@" + displayed_field + '@([^@]*)@') for prefix, postfix in set(regex.findall(template)): if sub == "value": text = open(data['input'][field][sub], 'rb').read().decode('utf-8') elif sub: text = data['input'][field][sub] else: text = data['input'][field] rep = "\n".join([prefix + v + postfix for v in text.splitlines()]) template = template.replace("@{0}@{1}@{2}@".format(prefix, displayed_field, postfix), rep) if output_filename == '': output_filename=input_filename # Ensure directory of resulting file exists try: os.makedirs(os.path.dirname(output_filename)) except OSError as e: pass # Write file with open(output_filename, 'wb') as file: file.write(template.encode("utf-8"))
python
def parse_template(input_filename, output_filename=''): """ Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file """ data = load_input() with open(input_filename, 'rb') as file: template = file.read().decode("utf-8") # Check if 'input' in data if not 'input' in data: raise ValueError("Could not find 'input' in data") # Parse template for field in data['input']: subs = ["filename", "value"] if isinstance(data['input'][field], dict) and "filename" in data['input'][field] and "value" in data['input'][field] else [""] for sub in subs: displayed_field = field + (":" if sub else "") + sub regex = re.compile("@([^@]*)@" + displayed_field + '@([^@]*)@') for prefix, postfix in set(regex.findall(template)): if sub == "value": text = open(data['input'][field][sub], 'rb').read().decode('utf-8') elif sub: text = data['input'][field][sub] else: text = data['input'][field] rep = "\n".join([prefix + v + postfix for v in text.splitlines()]) template = template.replace("@{0}@{1}@{2}@".format(prefix, displayed_field, postfix), rep) if output_filename == '': output_filename=input_filename # Ensure directory of resulting file exists try: os.makedirs(os.path.dirname(output_filename)) except OSError as e: pass # Write file with open(output_filename, 'wb') as file: file.write(template.encode("utf-8"))
[ "def", "parse_template", "(", "input_filename", ",", "output_filename", "=", "''", ")", ":", "data", "=", "load_input", "(", ")", "with", "open", "(", "input_filename", ",", "'rb'", ")", "as", "file", ":", "template", "=", "file", ".", "read", "(", ")", ".", "decode", "(", "\"utf-8\"", ")", "# Check if 'input' in data", "if", "not", "'input'", "in", "data", ":", "raise", "ValueError", "(", "\"Could not find 'input' in data\"", ")", "# Parse template", "for", "field", "in", "data", "[", "'input'", "]", ":", "subs", "=", "[", "\"filename\"", ",", "\"value\"", "]", "if", "isinstance", "(", "data", "[", "'input'", "]", "[", "field", "]", ",", "dict", ")", "and", "\"filename\"", "in", "data", "[", "'input'", "]", "[", "field", "]", "and", "\"value\"", "in", "data", "[", "'input'", "]", "[", "field", "]", "else", "[", "\"\"", "]", "for", "sub", "in", "subs", ":", "displayed_field", "=", "field", "+", "(", "\":\"", "if", "sub", "else", "\"\"", ")", "+", "sub", "regex", "=", "re", ".", "compile", "(", "\"@([^@]*)@\"", "+", "displayed_field", "+", "'@([^@]*)@'", ")", "for", "prefix", ",", "postfix", "in", "set", "(", "regex", ".", "findall", "(", "template", ")", ")", ":", "if", "sub", "==", "\"value\"", ":", "text", "=", "open", "(", "data", "[", "'input'", "]", "[", "field", "]", "[", "sub", "]", ",", "'rb'", ")", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "elif", "sub", ":", "text", "=", "data", "[", "'input'", "]", "[", "field", "]", "[", "sub", "]", "else", ":", "text", "=", "data", "[", "'input'", "]", "[", "field", "]", "rep", "=", "\"\\n\"", ".", "join", "(", "[", "prefix", "+", "v", "+", "postfix", "for", "v", "in", "text", ".", "splitlines", "(", ")", "]", ")", "template", "=", "template", ".", "replace", "(", "\"@{0}@{1}@{2}@\"", ".", "format", "(", "prefix", ",", "displayed_field", ",", "postfix", ")", ",", "rep", ")", "if", "output_filename", "==", "''", ":", "output_filename", "=", "input_filename", "# Ensure directory of resulting file exists", "try", ":", "os", ".", "makedirs", "(", "os", ".", "path", ".", "dirname", "(", "output_filename", ")", ")", "except", "OSError", "as", "e", ":", "pass", "# Write file", "with", "open", "(", "output_filename", ",", "'wb'", ")", "as", "file", ":", "file", ".", "write", "(", "template", ".", "encode", "(", "\"utf-8\"", ")", ")" ]
Parses a template file Replaces all occurences of @@problem_id@@ by the value of the 'problem_id' key in data dictionary input_filename: file to parse output_filename: if not specified, overwrite input file
[ "Parses", "a", "template", "file", "Replaces", "all", "occurences", "of" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/input.py#L49-L92
234,957
UCL-INGI/INGInious
inginious/client/client.py
_callable_once
def _callable_once(func): """ Returns a function that is only callable once; any other call will do nothing """ def once(*args, **kwargs): if not once.called: once.called = True return func(*args, **kwargs) once.called = False return once
python
def _callable_once(func): """ Returns a function that is only callable once; any other call will do nothing """ def once(*args, **kwargs): if not once.called: once.called = True return func(*args, **kwargs) once.called = False return once
[ "def", "_callable_once", "(", "func", ")", ":", "def", "once", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "once", ".", "called", ":", "once", ".", "called", "=", "True", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "once", ".", "called", "=", "False", "return", "once" ]
Returns a function that is only callable once; any other call will do nothing
[ "Returns", "a", "function", "that", "is", "only", "callable", "once", ";", "any", "other", "call", "will", "do", "nothing" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L17-L26
234,958
UCL-INGI/INGInious
inginious/client/client.py
Client._ask_queue_update
async def _ask_queue_update(self): """ Send a ClientGetQueue message to the backend, if one is not already sent """ try: while True: await asyncio.sleep(self._queue_update_timer) if self._queue_update_last_attempt == 0 or self._queue_update_last_attempt > self._queue_update_last_attempt_max: if self._queue_update_last_attempt: self._logger.error("Asking for a job queue update despite previous update not yet received") else: self._logger.debug("Asking for a job queue update") self._queue_update_last_attempt = 1 await self._simple_send(ClientGetQueue()) else: self._logger.error("Not asking for a job queue update as previous update not yet received") except asyncio.CancelledError: return except KeyboardInterrupt: return
python
async def _ask_queue_update(self): """ Send a ClientGetQueue message to the backend, if one is not already sent """ try: while True: await asyncio.sleep(self._queue_update_timer) if self._queue_update_last_attempt == 0 or self._queue_update_last_attempt > self._queue_update_last_attempt_max: if self._queue_update_last_attempt: self._logger.error("Asking for a job queue update despite previous update not yet received") else: self._logger.debug("Asking for a job queue update") self._queue_update_last_attempt = 1 await self._simple_send(ClientGetQueue()) else: self._logger.error("Not asking for a job queue update as previous update not yet received") except asyncio.CancelledError: return except KeyboardInterrupt: return
[ "async", "def", "_ask_queue_update", "(", "self", ")", ":", "try", ":", "while", "True", ":", "await", "asyncio", ".", "sleep", "(", "self", ".", "_queue_update_timer", ")", "if", "self", ".", "_queue_update_last_attempt", "==", "0", "or", "self", ".", "_queue_update_last_attempt", ">", "self", ".", "_queue_update_last_attempt_max", ":", "if", "self", ".", "_queue_update_last_attempt", ":", "self", ".", "_logger", ".", "error", "(", "\"Asking for a job queue update despite previous update not yet received\"", ")", "else", ":", "self", ".", "_logger", ".", "debug", "(", "\"Asking for a job queue update\"", ")", "self", ".", "_queue_update_last_attempt", "=", "1", "await", "self", ".", "_simple_send", "(", "ClientGetQueue", "(", ")", ")", "else", ":", "self", ".", "_logger", ".", "error", "(", "\"Not asking for a job queue update as previous update not yet received\"", ")", "except", "asyncio", ".", "CancelledError", ":", "return", "except", "KeyboardInterrupt", ":", "return" ]
Send a ClientGetQueue message to the backend, if one is not already sent
[ "Send", "a", "ClientGetQueue", "message", "to", "the", "backend", "if", "one", "is", "not", "already", "sent" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L144-L162
234,959
UCL-INGI/INGInious
inginious/client/client.py
Client._handle_job_queue_update
async def _handle_job_queue_update(self, message: BackendGetQueue): """ Handles a BackendGetQueue containing a snapshot of the job queue """ self._logger.debug("Received job queue update") self._queue_update_last_attempt = 0 self._queue_cache = message # Do some precomputation new_job_queue_cache = {} # format is job_id: (nb_jobs_before, max_remaining_time) for (job_id, is_local, _, _2, _3, _4, max_end) in message.jobs_running: if is_local: new_job_queue_cache[job_id] = (-1, max_end - time.time()) wait_time = 0 nb_tasks = 0 for (job_id, is_local, _, _2, timeout) in message.jobs_waiting: if timeout > 0: wait_time += timeout if is_local: new_job_queue_cache[job_id] = (nb_tasks, wait_time) nb_tasks += 1 self._queue_job_cache = new_job_queue_cache
python
async def _handle_job_queue_update(self, message: BackendGetQueue): """ Handles a BackendGetQueue containing a snapshot of the job queue """ self._logger.debug("Received job queue update") self._queue_update_last_attempt = 0 self._queue_cache = message # Do some precomputation new_job_queue_cache = {} # format is job_id: (nb_jobs_before, max_remaining_time) for (job_id, is_local, _, _2, _3, _4, max_end) in message.jobs_running: if is_local: new_job_queue_cache[job_id] = (-1, max_end - time.time()) wait_time = 0 nb_tasks = 0 for (job_id, is_local, _, _2, timeout) in message.jobs_waiting: if timeout > 0: wait_time += timeout if is_local: new_job_queue_cache[job_id] = (nb_tasks, wait_time) nb_tasks += 1 self._queue_job_cache = new_job_queue_cache
[ "async", "def", "_handle_job_queue_update", "(", "self", ",", "message", ":", "BackendGetQueue", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"Received job queue update\"", ")", "self", ".", "_queue_update_last_attempt", "=", "0", "self", ".", "_queue_cache", "=", "message", "# Do some precomputation", "new_job_queue_cache", "=", "{", "}", "# format is job_id: (nb_jobs_before, max_remaining_time)", "for", "(", "job_id", ",", "is_local", ",", "_", ",", "_2", ",", "_3", ",", "_4", ",", "max_end", ")", "in", "message", ".", "jobs_running", ":", "if", "is_local", ":", "new_job_queue_cache", "[", "job_id", "]", "=", "(", "-", "1", ",", "max_end", "-", "time", ".", "time", "(", ")", ")", "wait_time", "=", "0", "nb_tasks", "=", "0", "for", "(", "job_id", ",", "is_local", ",", "_", ",", "_2", ",", "timeout", ")", "in", "message", ".", "jobs_waiting", ":", "if", "timeout", ">", "0", ":", "wait_time", "+=", "timeout", "if", "is_local", ":", "new_job_queue_cache", "[", "job_id", "]", "=", "(", "nb_tasks", ",", "wait_time", ")", "nb_tasks", "+=", "1", "self", ".", "_queue_job_cache", "=", "new_job_queue_cache" ]
Handles a BackendGetQueue containing a snapshot of the job queue
[ "Handles", "a", "BackendGetQueue", "containing", "a", "snapshot", "of", "the", "job", "queue" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L164-L185
234,960
UCL-INGI/INGInious
inginious/client/client.py
Client.new_job
def new_job(self, task, inputdata, callback, launcher_name="Unknown", debug=False, ssh_callback=None): """ Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback: a function that will be called asynchronously in the client's process, with the results. it's signature must be (result, grade, problems, tests, custom, archive), where: result is itself a tuple containing the result string and the main feedback (i.e. ('success', 'You succeeded'); grade is a number between 0 and 100 indicating the grade of the users; problems is a dict of tuple, in the form {'problemid': result}; test is a dict of tests made in the container custom is a dict containing random things set in the container archive is either None or a bytes containing a tgz archive of files from the job :type callback: __builtin__.function or __builtin__.instancemethod :param launcher_name: for informational use :type launcher_name: str :param debug: Either True(outputs more info), False(default), or "ssh" (starts a remote ssh server. ssh_callback needs to be defined) :type debug: bool or string :param ssh_callback: a callback function that will be called with (host, port, password), the needed credentials to connect to the remote ssh server. May be called with host, port, password being None, meaning no session was open. :type ssh_callback: __builtin__.function or __builtin__.instancemethod or None :return: the new job id """ job_id = str(uuid.uuid4()) if debug == "ssh" and ssh_callback is None: self._logger.error("SSH callback not set in %s/%s", task.get_course_id(), task.get_id()) callback(("crash", "SSH callback not set."), 0.0, {}, {}, {}, None, "", "") return # wrap ssh_callback to ensure it is called at most once, and that it can always be called to simplify code ssh_callback = _callable_once(ssh_callback if ssh_callback is not None else lambda _1, _2, _3: None) environment = task.get_environment() if environment not in self._available_containers: self._logger.warning("Env %s not available for task %s/%s", environment, task.get_course_id(), task.get_id()) ssh_callback(None, None, None) # ssh_callback must be called once callback(("crash", "Environment not available."), 0.0, {}, {}, "", {}, None, "", "") return enable_network = task.allow_network_access_grading() try: limits = task.get_limits() time_limit = int(limits.get('time', 20)) hard_time_limit = int(limits.get('hard_time', 3 * time_limit)) mem_limit = int(limits.get('memory', 200)) except: self._logger.exception("Cannot retrieve limits for task %s/%s", task.get_course_id(), task.get_id()) ssh_callback(None, None, None) # ssh_callback must be called once callback(("crash", "Error while reading task limits"), 0.0, {}, {}, "", {}, None, "", "") return msg = ClientNewJob(job_id, task.get_course_id(), task.get_id(), inputdata, environment, enable_network, time_limit, hard_time_limit, mem_limit, debug, launcher_name) self._loop.call_soon_threadsafe(asyncio.ensure_future, self._create_transaction(msg, task=task, callback=callback, ssh_callback=ssh_callback)) return job_id
python
def new_job(self, task, inputdata, callback, launcher_name="Unknown", debug=False, ssh_callback=None): """ Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback: a function that will be called asynchronously in the client's process, with the results. it's signature must be (result, grade, problems, tests, custom, archive), where: result is itself a tuple containing the result string and the main feedback (i.e. ('success', 'You succeeded'); grade is a number between 0 and 100 indicating the grade of the users; problems is a dict of tuple, in the form {'problemid': result}; test is a dict of tests made in the container custom is a dict containing random things set in the container archive is either None or a bytes containing a tgz archive of files from the job :type callback: __builtin__.function or __builtin__.instancemethod :param launcher_name: for informational use :type launcher_name: str :param debug: Either True(outputs more info), False(default), or "ssh" (starts a remote ssh server. ssh_callback needs to be defined) :type debug: bool or string :param ssh_callback: a callback function that will be called with (host, port, password), the needed credentials to connect to the remote ssh server. May be called with host, port, password being None, meaning no session was open. :type ssh_callback: __builtin__.function or __builtin__.instancemethod or None :return: the new job id """ job_id = str(uuid.uuid4()) if debug == "ssh" and ssh_callback is None: self._logger.error("SSH callback not set in %s/%s", task.get_course_id(), task.get_id()) callback(("crash", "SSH callback not set."), 0.0, {}, {}, {}, None, "", "") return # wrap ssh_callback to ensure it is called at most once, and that it can always be called to simplify code ssh_callback = _callable_once(ssh_callback if ssh_callback is not None else lambda _1, _2, _3: None) environment = task.get_environment() if environment not in self._available_containers: self._logger.warning("Env %s not available for task %s/%s", environment, task.get_course_id(), task.get_id()) ssh_callback(None, None, None) # ssh_callback must be called once callback(("crash", "Environment not available."), 0.0, {}, {}, "", {}, None, "", "") return enable_network = task.allow_network_access_grading() try: limits = task.get_limits() time_limit = int(limits.get('time', 20)) hard_time_limit = int(limits.get('hard_time', 3 * time_limit)) mem_limit = int(limits.get('memory', 200)) except: self._logger.exception("Cannot retrieve limits for task %s/%s", task.get_course_id(), task.get_id()) ssh_callback(None, None, None) # ssh_callback must be called once callback(("crash", "Error while reading task limits"), 0.0, {}, {}, "", {}, None, "", "") return msg = ClientNewJob(job_id, task.get_course_id(), task.get_id(), inputdata, environment, enable_network, time_limit, hard_time_limit, mem_limit, debug, launcher_name) self._loop.call_soon_threadsafe(asyncio.ensure_future, self._create_transaction(msg, task=task, callback=callback, ssh_callback=ssh_callback)) return job_id
[ "def", "new_job", "(", "self", ",", "task", ",", "inputdata", ",", "callback", ",", "launcher_name", "=", "\"Unknown\"", ",", "debug", "=", "False", ",", "ssh_callback", "=", "None", ")", ":", "job_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", "if", "debug", "==", "\"ssh\"", "and", "ssh_callback", "is", "None", ":", "self", ".", "_logger", ".", "error", "(", "\"SSH callback not set in %s/%s\"", ",", "task", ".", "get_course_id", "(", ")", ",", "task", ".", "get_id", "(", ")", ")", "callback", "(", "(", "\"crash\"", ",", "\"SSH callback not set.\"", ")", ",", "0.0", ",", "{", "}", ",", "{", "}", ",", "{", "}", ",", "None", ",", "\"\"", ",", "\"\"", ")", "return", "# wrap ssh_callback to ensure it is called at most once, and that it can always be called to simplify code", "ssh_callback", "=", "_callable_once", "(", "ssh_callback", "if", "ssh_callback", "is", "not", "None", "else", "lambda", "_1", ",", "_2", ",", "_3", ":", "None", ")", "environment", "=", "task", ".", "get_environment", "(", ")", "if", "environment", "not", "in", "self", ".", "_available_containers", ":", "self", ".", "_logger", ".", "warning", "(", "\"Env %s not available for task %s/%s\"", ",", "environment", ",", "task", ".", "get_course_id", "(", ")", ",", "task", ".", "get_id", "(", ")", ")", "ssh_callback", "(", "None", ",", "None", ",", "None", ")", "# ssh_callback must be called once", "callback", "(", "(", "\"crash\"", ",", "\"Environment not available.\"", ")", ",", "0.0", ",", "{", "}", ",", "{", "}", ",", "\"\"", ",", "{", "}", ",", "None", ",", "\"\"", ",", "\"\"", ")", "return", "enable_network", "=", "task", ".", "allow_network_access_grading", "(", ")", "try", ":", "limits", "=", "task", ".", "get_limits", "(", ")", "time_limit", "=", "int", "(", "limits", ".", "get", "(", "'time'", ",", "20", ")", ")", "hard_time_limit", "=", "int", "(", "limits", ".", "get", "(", "'hard_time'", ",", "3", "*", "time_limit", ")", ")", "mem_limit", "=", "int", "(", "limits", ".", "get", "(", "'memory'", ",", "200", ")", ")", "except", ":", "self", ".", "_logger", ".", "exception", "(", "\"Cannot retrieve limits for task %s/%s\"", ",", "task", ".", "get_course_id", "(", ")", ",", "task", ".", "get_id", "(", ")", ")", "ssh_callback", "(", "None", ",", "None", ",", "None", ")", "# ssh_callback must be called once", "callback", "(", "(", "\"crash\"", ",", "\"Error while reading task limits\"", ")", ",", "0.0", ",", "{", "}", ",", "{", "}", ",", "\"\"", ",", "{", "}", ",", "None", ",", "\"\"", ",", "\"\"", ")", "return", "msg", "=", "ClientNewJob", "(", "job_id", ",", "task", ".", "get_course_id", "(", ")", ",", "task", ".", "get_id", "(", ")", ",", "inputdata", ",", "environment", ",", "enable_network", ",", "time_limit", ",", "hard_time_limit", ",", "mem_limit", ",", "debug", ",", "launcher_name", ")", "self", ".", "_loop", ".", "call_soon_threadsafe", "(", "asyncio", ".", "ensure_future", ",", "self", ".", "_create_transaction", "(", "msg", ",", "task", "=", "task", ",", "callback", "=", "callback", ",", "ssh_callback", "=", "ssh_callback", ")", ")", "return", "job_id" ]
Add a new job. Every callback will be called once and only once. :type task: Task :param inputdata: input from the student :type inputdata: Storage or dict :param callback: a function that will be called asynchronously in the client's process, with the results. it's signature must be (result, grade, problems, tests, custom, archive), where: result is itself a tuple containing the result string and the main feedback (i.e. ('success', 'You succeeded'); grade is a number between 0 and 100 indicating the grade of the users; problems is a dict of tuple, in the form {'problemid': result}; test is a dict of tests made in the container custom is a dict containing random things set in the container archive is either None or a bytes containing a tgz archive of files from the job :type callback: __builtin__.function or __builtin__.instancemethod :param launcher_name: for informational use :type launcher_name: str :param debug: Either True(outputs more info), False(default), or "ssh" (starts a remote ssh server. ssh_callback needs to be defined) :type debug: bool or string :param ssh_callback: a callback function that will be called with (host, port, password), the needed credentials to connect to the remote ssh server. May be called with host, port, password being None, meaning no session was open. :type ssh_callback: __builtin__.function or __builtin__.instancemethod or None :return: the new job id
[ "Add", "a", "new", "job", ".", "Every", "callback", "will", "be", "called", "once", "and", "only", "once", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L253-L311
234,961
UCL-INGI/INGInious
inginious/client/client.py
Client.kill_job
def kill_job(self, job_id): """ Kills a running job """ self._loop.call_soon_threadsafe(asyncio.ensure_future, self._simple_send(ClientKillJob(job_id)))
python
def kill_job(self, job_id): """ Kills a running job """ self._loop.call_soon_threadsafe(asyncio.ensure_future, self._simple_send(ClientKillJob(job_id)))
[ "def", "kill_job", "(", "self", ",", "job_id", ")", ":", "self", ".", "_loop", ".", "call_soon_threadsafe", "(", "asyncio", ".", "ensure_future", ",", "self", ".", "_simple_send", "(", "ClientKillJob", "(", "job_id", ")", ")", ")" ]
Kills a running job
[ "Kills", "a", "running", "job" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client.py#L313-L317
234,962
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_codeblock
def get_codeblock(language, text): """ Generates rst codeblock for given text and language """ rst = "\n\n.. code-block:: " + language + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
python
def get_codeblock(language, text): """ Generates rst codeblock for given text and language """ rst = "\n\n.. code-block:: " + language + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
[ "def", "get_codeblock", "(", "language", ",", "text", ")", ":", "rst", "=", "\"\\n\\n.. code-block:: \"", "+", "language", "+", "\"\\n\\n\"", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "rst", "+=", "\"\\t\"", "+", "line", "+", "\"\\n\"", "rst", "+=", "\"\\n\"", "return", "rst" ]
Generates rst codeblock for given text and language
[ "Generates", "rst", "codeblock", "for", "given", "text", "and", "language" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L9-L16
234,963
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_imageblock
def get_imageblock(filename, format=''): """ Generates rst raw block for given image filename and format""" _, extension = os.path.splitext(filename) with open(filename, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode('utf-8') return '\n\n.. raw:: html\n\n\t<img src="data:image/' + (format if format else extension[1:]) + ';base64,' + encoded_string +'">\n'
python
def get_imageblock(filename, format=''): """ Generates rst raw block for given image filename and format""" _, extension = os.path.splitext(filename) with open(filename, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()).decode('utf-8') return '\n\n.. raw:: html\n\n\t<img src="data:image/' + (format if format else extension[1:]) + ';base64,' + encoded_string +'">\n'
[ "def", "get_imageblock", "(", "filename", ",", "format", "=", "''", ")", ":", "_", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "image_file", ":", "encoded_string", "=", "base64", ".", "b64encode", "(", "image_file", ".", "read", "(", ")", ")", ".", "decode", "(", "'utf-8'", ")", "return", "'\\n\\n.. raw:: html\\n\\n\\t<img src=\"data:image/'", "+", "(", "format", "if", "format", "else", "extension", "[", "1", ":", "]", ")", "+", "';base64,'", "+", "encoded_string", "+", "'\">\\n'" ]
Generates rst raw block for given image filename and format
[ "Generates", "rst", "raw", "block", "for", "given", "image", "filename", "and", "format" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L18-L25
234,964
UCL-INGI/INGInious
base-containers/base/inginious/rst.py
get_admonition
def get_admonition(cssclass, title, text): """ Generates rst admonition block given a bootstrap alert css class, title, and text""" rst = ("\n\n.. admonition:: " + title + "\n") if title else "\n\n.. note:: \n" rst += "\t:class: alert alert-" + cssclass + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
python
def get_admonition(cssclass, title, text): """ Generates rst admonition block given a bootstrap alert css class, title, and text""" rst = ("\n\n.. admonition:: " + title + "\n") if title else "\n\n.. note:: \n" rst += "\t:class: alert alert-" + cssclass + "\n\n" for line in text.splitlines(): rst += "\t" + line + "\n" rst += "\n" return rst
[ "def", "get_admonition", "(", "cssclass", ",", "title", ",", "text", ")", ":", "rst", "=", "(", "\"\\n\\n.. admonition:: \"", "+", "title", "+", "\"\\n\"", ")", "if", "title", "else", "\"\\n\\n.. note:: \\n\"", "rst", "+=", "\"\\t:class: alert alert-\"", "+", "cssclass", "+", "\"\\n\\n\"", "for", "line", "in", "text", ".", "splitlines", "(", ")", ":", "rst", "+=", "\"\\t\"", "+", "line", "+", "\"\\n\"", "rst", "+=", "\"\\n\"", "return", "rst" ]
Generates rst admonition block given a bootstrap alert css class, title, and text
[ "Generates", "rst", "admonition", "block", "given", "a", "bootstrap", "alert", "css", "class", "title", "and", "text" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/rst.py#L27-L35
234,965
UCL-INGI/INGInious
base-containers/base/inginious/lang.py
init
def init(): """ Install gettext with the default parameters """ if "_" not in builtins.__dict__: # avoid installing lang two times os.environ["LANGUAGE"] = inginious.input.get_lang() if inginious.DEBUG: gettext.install("messages", get_lang_dir_path()) else: gettext.install("messages", get_lang_dir_path())
python
def init(): """ Install gettext with the default parameters """ if "_" not in builtins.__dict__: # avoid installing lang two times os.environ["LANGUAGE"] = inginious.input.get_lang() if inginious.DEBUG: gettext.install("messages", get_lang_dir_path()) else: gettext.install("messages", get_lang_dir_path())
[ "def", "init", "(", ")", ":", "if", "\"_\"", "not", "in", "builtins", ".", "__dict__", ":", "# avoid installing lang two times", "os", ".", "environ", "[", "\"LANGUAGE\"", "]", "=", "inginious", ".", "input", ".", "get_lang", "(", ")", "if", "inginious", ".", "DEBUG", ":", "gettext", ".", "install", "(", "\"messages\"", ",", "get_lang_dir_path", "(", ")", ")", "else", ":", "gettext", ".", "install", "(", "\"messages\"", ",", "get_lang_dir_path", "(", ")", ")" ]
Install gettext with the default parameters
[ "Install", "gettext", "with", "the", "default", "parameters" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/base-containers/base/inginious/lang.py#L22-L29
234,966
UCL-INGI/INGInious
inginious/common/filesystems/local.py
LocalFSProvider._recursive_overwrite
def _recursive_overwrite(self, src, dest): """ Copy src to dest, recursively and with file overwrite. """ if os.path.isdir(src): if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(src) for f in files: self._recursive_overwrite(os.path.join(src, f), os.path.join(dest, f)) else: shutil.copyfile(src, dest, follow_symlinks=False)
python
def _recursive_overwrite(self, src, dest): """ Copy src to dest, recursively and with file overwrite. """ if os.path.isdir(src): if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(src) for f in files: self._recursive_overwrite(os.path.join(src, f), os.path.join(dest, f)) else: shutil.copyfile(src, dest, follow_symlinks=False)
[ "def", "_recursive_overwrite", "(", "self", ",", "src", ",", "dest", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "dest", ")", ":", "os", ".", "makedirs", "(", "dest", ")", "files", "=", "os", ".", "listdir", "(", "src", ")", "for", "f", "in", "files", ":", "self", ".", "_recursive_overwrite", "(", "os", ".", "path", ".", "join", "(", "src", ",", "f", ")", ",", "os", ".", "path", ".", "join", "(", "dest", ",", "f", ")", ")", "else", ":", "shutil", ".", "copyfile", "(", "src", ",", "dest", ",", "follow_symlinks", "=", "False", ")" ]
Copy src to dest, recursively and with file overwrite.
[ "Copy", "src", "to", "dest", "recursively", "and", "with", "file", "overwrite", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/filesystems/local.py#L134-L146
234,967
UCL-INGI/INGInious
inginious/frontend/plugins/git_repo/__init__.py
init
def init(plugin_manager, _, _2, config): """ Init the plugin Available configuration: :: plugins: - plugin_module: inginious.frontend.plugins.git_repo repo_directory: "./repo_submissions" """ submission_git_saver = SubmissionGitSaver(plugin_manager, config) submission_git_saver.daemon = True submission_git_saver.start()
python
def init(plugin_manager, _, _2, config): """ Init the plugin Available configuration: :: plugins: - plugin_module: inginious.frontend.plugins.git_repo repo_directory: "./repo_submissions" """ submission_git_saver = SubmissionGitSaver(plugin_manager, config) submission_git_saver.daemon = True submission_git_saver.start()
[ "def", "init", "(", "plugin_manager", ",", "_", ",", "_2", ",", "config", ")", ":", "submission_git_saver", "=", "SubmissionGitSaver", "(", "plugin_manager", ",", "config", ")", "submission_git_saver", ".", "daemon", "=", "True", "submission_git_saver", ".", "start", "(", ")" ]
Init the plugin Available configuration: :: plugins: - plugin_module: inginious.frontend.plugins.git_repo repo_directory: "./repo_submissions"
[ "Init", "the", "plugin" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/git_repo/__init__.py#L97-L111
234,968
UCL-INGI/INGInious
inginious/common/tags.py
Tag.get_type_as_str
def get_type_as_str(self): """ Return a textual description of the type """ if self.get_type() == 0: return _("Skill") elif self.get_type() == 1: return _("Misconception") elif self.get_type() == 2: return _("Category") else: return _("Unknown type")
python
def get_type_as_str(self): """ Return a textual description of the type """ if self.get_type() == 0: return _("Skill") elif self.get_type() == 1: return _("Misconception") elif self.get_type() == 2: return _("Category") else: return _("Unknown type")
[ "def", "get_type_as_str", "(", "self", ")", ":", "if", "self", ".", "get_type", "(", ")", "==", "0", ":", "return", "_", "(", "\"Skill\"", ")", "elif", "self", ".", "get_type", "(", ")", "==", "1", ":", "return", "_", "(", "\"Misconception\"", ")", "elif", "self", ".", "get_type", "(", ")", "==", "2", ":", "return", "_", "(", "\"Category\"", ")", "else", ":", "return", "_", "(", "\"Unknown type\"", ")" ]
Return a textual description of the type
[ "Return", "a", "textual", "description", "of", "the", "type" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tags.py#L58-L67
234,969
UCL-INGI/INGInious
inginious/common/tags.py
Tag.create_tags_from_dict
def create_tags_from_dict(cls, tag_dict): """ Build a tuple of list of Tag objects based on the tag_dict. The tuple contains 3 lists. - The first list contains skill tags - The second list contains misconception tags - The third list contains category tags """ tag_list_common = [] tag_list_misconception = [] tag_list_organisational = [] for tag in tag_dict: try: id = tag_dict[tag]["id"] name = tag_dict[tag]["name"] visible = tag_dict[tag]["visible"] description = tag_dict[tag]["description"] type = tag_dict[tag]["type"] if type == 2: tag_list_organisational.insert(int(tag), Tag(id, name, description, visible, type)) elif type == 1: tag_list_misconception.insert(int(tag), Tag(id, name, description, visible, type)) else: tag_list_common.insert(int(tag), Tag(id, name, description, visible, type)) except KeyError: pass return tag_list_common, tag_list_misconception, tag_list_organisational
python
def create_tags_from_dict(cls, tag_dict): """ Build a tuple of list of Tag objects based on the tag_dict. The tuple contains 3 lists. - The first list contains skill tags - The second list contains misconception tags - The third list contains category tags """ tag_list_common = [] tag_list_misconception = [] tag_list_organisational = [] for tag in tag_dict: try: id = tag_dict[tag]["id"] name = tag_dict[tag]["name"] visible = tag_dict[tag]["visible"] description = tag_dict[tag]["description"] type = tag_dict[tag]["type"] if type == 2: tag_list_organisational.insert(int(tag), Tag(id, name, description, visible, type)) elif type == 1: tag_list_misconception.insert(int(tag), Tag(id, name, description, visible, type)) else: tag_list_common.insert(int(tag), Tag(id, name, description, visible, type)) except KeyError: pass return tag_list_common, tag_list_misconception, tag_list_organisational
[ "def", "create_tags_from_dict", "(", "cls", ",", "tag_dict", ")", ":", "tag_list_common", "=", "[", "]", "tag_list_misconception", "=", "[", "]", "tag_list_organisational", "=", "[", "]", "for", "tag", "in", "tag_dict", ":", "try", ":", "id", "=", "tag_dict", "[", "tag", "]", "[", "\"id\"", "]", "name", "=", "tag_dict", "[", "tag", "]", "[", "\"name\"", "]", "visible", "=", "tag_dict", "[", "tag", "]", "[", "\"visible\"", "]", "description", "=", "tag_dict", "[", "tag", "]", "[", "\"description\"", "]", "type", "=", "tag_dict", "[", "tag", "]", "[", "\"type\"", "]", "if", "type", "==", "2", ":", "tag_list_organisational", ".", "insert", "(", "int", "(", "tag", ")", ",", "Tag", "(", "id", ",", "name", ",", "description", ",", "visible", ",", "type", ")", ")", "elif", "type", "==", "1", ":", "tag_list_misconception", ".", "insert", "(", "int", "(", "tag", ")", ",", "Tag", "(", "id", ",", "name", ",", "description", ",", "visible", ",", "type", ")", ")", "else", ":", "tag_list_common", ".", "insert", "(", "int", "(", "tag", ")", ",", "Tag", "(", "id", ",", "name", ",", "description", ",", "visible", ",", "type", ")", ")", "except", "KeyError", ":", "pass", "return", "tag_list_common", ",", "tag_list_misconception", ",", "tag_list_organisational" ]
Build a tuple of list of Tag objects based on the tag_dict. The tuple contains 3 lists. - The first list contains skill tags - The second list contains misconception tags - The third list contains category tags
[ "Build", "a", "tuple", "of", "list", "of", "Tag", "objects", "based", "on", "the", "tag_dict", ".", "The", "tuple", "contains", "3", "lists", ".", "-", "The", "first", "list", "contains", "skill", "tags", "-", "The", "second", "list", "contains", "misconception", "tags", "-", "The", "third", "list", "contains", "category", "tags" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/common/tags.py#L73-L100
234,970
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.run
async def run(self): """ Runs the agent. Answer to the requests made by the Backend. May raise an asyncio.CancelledError, in which case the agent should clean itself and restart completely. """ self._logger.info("Agent started") self.__backend_socket.connect(self.__backend_addr) # Tell the backend we are up and have `concurrency` threads available self._logger.info("Saying hello to the backend") await ZMQUtils.send(self.__backend_socket, AgentHello(self.__friendly_name, self.__concurrency, self.environments)) self.__last_ping = time.time() run_listen = self._loop.create_task(self.__run_listen()) self._loop.call_later(1, self._create_safe_task, self.__check_last_ping(run_listen)) await run_listen
python
async def run(self): """ Runs the agent. Answer to the requests made by the Backend. May raise an asyncio.CancelledError, in which case the agent should clean itself and restart completely. """ self._logger.info("Agent started") self.__backend_socket.connect(self.__backend_addr) # Tell the backend we are up and have `concurrency` threads available self._logger.info("Saying hello to the backend") await ZMQUtils.send(self.__backend_socket, AgentHello(self.__friendly_name, self.__concurrency, self.environments)) self.__last_ping = time.time() run_listen = self._loop.create_task(self.__run_listen()) self._loop.call_later(1, self._create_safe_task, self.__check_last_ping(run_listen)) await run_listen
[ "async", "def", "run", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"Agent started\"", ")", "self", ".", "__backend_socket", ".", "connect", "(", "self", ".", "__backend_addr", ")", "# Tell the backend we are up and have `concurrency` threads available", "self", ".", "_logger", ".", "info", "(", "\"Saying hello to the backend\"", ")", "await", "ZMQUtils", ".", "send", "(", "self", ".", "__backend_socket", ",", "AgentHello", "(", "self", ".", "__friendly_name", ",", "self", ".", "__concurrency", ",", "self", ".", "environments", ")", ")", "self", ".", "__last_ping", "=", "time", ".", "time", "(", ")", "run_listen", "=", "self", ".", "_loop", ".", "create_task", "(", "self", ".", "__run_listen", "(", ")", ")", "self", ".", "_loop", ".", "call_later", "(", "1", ",", "self", ".", "_create_safe_task", ",", "self", ".", "__check_last_ping", "(", "run_listen", ")", ")", "await", "run_listen" ]
Runs the agent. Answer to the requests made by the Backend. May raise an asyncio.CancelledError, in which case the agent should clean itself and restart completely.
[ "Runs", "the", "agent", ".", "Answer", "to", "the", "requests", "made", "by", "the", "Backend", ".", "May", "raise", "an", "asyncio", ".", "CancelledError", "in", "which", "case", "the", "agent", "should", "clean", "itself", "and", "restart", "completely", "." ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L100-L117
234,971
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__check_last_ping
async def __check_last_ping(self, run_listen): """ Check if the last timeout is too old. If it is, kills the run_listen task """ if self.__last_ping < time.time()-10: self._logger.warning("Last ping too old. Restarting the agent.") run_listen.cancel() self.__cancel_remaining_safe_tasks() else: self._loop.call_later(1, self._create_safe_task, self.__check_last_ping(run_listen))
python
async def __check_last_ping(self, run_listen): """ Check if the last timeout is too old. If it is, kills the run_listen task """ if self.__last_ping < time.time()-10: self._logger.warning("Last ping too old. Restarting the agent.") run_listen.cancel() self.__cancel_remaining_safe_tasks() else: self._loop.call_later(1, self._create_safe_task, self.__check_last_ping(run_listen))
[ "async", "def", "__check_last_ping", "(", "self", ",", "run_listen", ")", ":", "if", "self", ".", "__last_ping", "<", "time", ".", "time", "(", ")", "-", "10", ":", "self", ".", "_logger", ".", "warning", "(", "\"Last ping too old. Restarting the agent.\"", ")", "run_listen", ".", "cancel", "(", ")", "self", ".", "__cancel_remaining_safe_tasks", "(", ")", "else", ":", "self", ".", "_loop", ".", "call_later", "(", "1", ",", "self", ".", "_create_safe_task", ",", "self", ".", "__check_last_ping", "(", "run_listen", ")", ")" ]
Check if the last timeout is too old. If it is, kills the run_listen task
[ "Check", "if", "the", "last", "timeout", "is", "too", "old", ".", "If", "it", "is", "kills", "the", "run_listen", "task" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L119-L126
234,972
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__run_listen
async def __run_listen(self): """ Listen to the backend """ while True: message = await ZMQUtils.recv(self.__backend_socket) await self.__handle_backend_message(message)
python
async def __run_listen(self): """ Listen to the backend """ while True: message = await ZMQUtils.recv(self.__backend_socket) await self.__handle_backend_message(message)
[ "async", "def", "__run_listen", "(", "self", ")", ":", "while", "True", ":", "message", "=", "await", "ZMQUtils", ".", "recv", "(", "self", ".", "__backend_socket", ")", "await", "self", ".", "__handle_backend_message", "(", "message", ")" ]
Listen to the backend
[ "Listen", "to", "the", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L128-L132
234,973
UCL-INGI/INGInious
inginious/agent/__init__.py
Agent.__handle_ping
async def __handle_ping(self, _ : Ping): """ Handle a Ping message. Pong the backend """ self.__last_ping = time.time() await ZMQUtils.send(self.__backend_socket, Pong())
python
async def __handle_ping(self, _ : Ping): """ Handle a Ping message. Pong the backend """ self.__last_ping = time.time() await ZMQUtils.send(self.__backend_socket, Pong())
[ "async", "def", "__handle_ping", "(", "self", ",", "_", ":", "Ping", ")", ":", "self", ".", "__last_ping", "=", "time", ".", "time", "(", ")", "await", "ZMQUtils", ".", "send", "(", "self", ".", "__backend_socket", ",", "Pong", "(", ")", ")" ]
Handle a Ping message. Pong the backend
[ "Handle", "a", "Ping", "message", ".", "Pong", "the", "backend" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/agent/__init__.py#L147-L150
234,974
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/utils.py
get_menu
def get_menu(course, current, renderer, plugin_manager, user_manager): """ Returns the HTML of the menu used in the administration. ```current``` is the current page of section """ default_entries = [] if user_manager.has_admin_rights_on_course(course): default_entries += [("settings", "<i class='fa fa-cog fa-fw'></i>&nbsp; " + _("Course settings"))] default_entries += [("stats", "<i class='fa fa-area-chart fa-fw'></i>&nbsp; " + _("Stats")), ("students", "<i class='fa fa-user fa-fw'></i>&nbsp; " + _("Students"))] if not course.is_lti(): default_entries += [("aggregations", "<i class='fa fa-group fa-fw'></i>&nbsp; " + (_("Classrooms") if course.use_classrooms() else _("Teams")))] default_entries += [("tasks", "<i class='fa fa-tasks fa-fw'></i>&nbsp; " + _("Tasks")), ("submissions", "<i class='fa fa-search fa-fw'></i>&nbsp; " + _("View submissions")), ("download", "<i class='fa fa-download fa-fw'></i>&nbsp; " + _("Download submissions"))] if user_manager.has_admin_rights_on_course(course): if web.ctx.app_stack[0].webdav_host: default_entries += [("webdav", "<i class='fa fa-folder-open fa-fw'></i>&nbsp; " + _("WebDAV access"))] default_entries += [("replay", "<i class='fa fa-refresh fa-fw'></i>&nbsp; " + _("Replay submissions")), ("danger", "<i class='fa fa-bomb fa-fw'></i>&nbsp; " + _("Danger zone"))] # Hook should return a tuple (link,name) where link is the relative link from the index of the course administration. additional_entries = [entry for entry in plugin_manager.call_hook('course_admin_menu', course=course) if entry is not None] return renderer.course_admin.menu(course, default_entries + additional_entries, current)
python
def get_menu(course, current, renderer, plugin_manager, user_manager): """ Returns the HTML of the menu used in the administration. ```current``` is the current page of section """ default_entries = [] if user_manager.has_admin_rights_on_course(course): default_entries += [("settings", "<i class='fa fa-cog fa-fw'></i>&nbsp; " + _("Course settings"))] default_entries += [("stats", "<i class='fa fa-area-chart fa-fw'></i>&nbsp; " + _("Stats")), ("students", "<i class='fa fa-user fa-fw'></i>&nbsp; " + _("Students"))] if not course.is_lti(): default_entries += [("aggregations", "<i class='fa fa-group fa-fw'></i>&nbsp; " + (_("Classrooms") if course.use_classrooms() else _("Teams")))] default_entries += [("tasks", "<i class='fa fa-tasks fa-fw'></i>&nbsp; " + _("Tasks")), ("submissions", "<i class='fa fa-search fa-fw'></i>&nbsp; " + _("View submissions")), ("download", "<i class='fa fa-download fa-fw'></i>&nbsp; " + _("Download submissions"))] if user_manager.has_admin_rights_on_course(course): if web.ctx.app_stack[0].webdav_host: default_entries += [("webdav", "<i class='fa fa-folder-open fa-fw'></i>&nbsp; " + _("WebDAV access"))] default_entries += [("replay", "<i class='fa fa-refresh fa-fw'></i>&nbsp; " + _("Replay submissions")), ("danger", "<i class='fa fa-bomb fa-fw'></i>&nbsp; " + _("Danger zone"))] # Hook should return a tuple (link,name) where link is the relative link from the index of the course administration. additional_entries = [entry for entry in plugin_manager.call_hook('course_admin_menu', course=course) if entry is not None] return renderer.course_admin.menu(course, default_entries + additional_entries, current)
[ "def", "get_menu", "(", "course", ",", "current", ",", "renderer", ",", "plugin_manager", ",", "user_manager", ")", ":", "default_entries", "=", "[", "]", "if", "user_manager", ".", "has_admin_rights_on_course", "(", "course", ")", ":", "default_entries", "+=", "[", "(", "\"settings\"", ",", "\"<i class='fa fa-cog fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"Course settings\"", ")", ")", "]", "default_entries", "+=", "[", "(", "\"stats\"", ",", "\"<i class='fa fa-area-chart fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"Stats\"", ")", ")", ",", "(", "\"students\"", ",", "\"<i class='fa fa-user fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"Students\"", ")", ")", "]", "if", "not", "course", ".", "is_lti", "(", ")", ":", "default_entries", "+=", "[", "(", "\"aggregations\"", ",", "\"<i class='fa fa-group fa-fw'></i>&nbsp; \"", "+", "(", "_", "(", "\"Classrooms\"", ")", "if", "course", ".", "use_classrooms", "(", ")", "else", "_", "(", "\"Teams\"", ")", ")", ")", "]", "default_entries", "+=", "[", "(", "\"tasks\"", ",", "\"<i class='fa fa-tasks fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"Tasks\"", ")", ")", ",", "(", "\"submissions\"", ",", "\"<i class='fa fa-search fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"View submissions\"", ")", ")", ",", "(", "\"download\"", ",", "\"<i class='fa fa-download fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"Download submissions\"", ")", ")", "]", "if", "user_manager", ".", "has_admin_rights_on_course", "(", "course", ")", ":", "if", "web", ".", "ctx", ".", "app_stack", "[", "0", "]", ".", "webdav_host", ":", "default_entries", "+=", "[", "(", "\"webdav\"", ",", "\"<i class='fa fa-folder-open fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"WebDAV access\"", ")", ")", "]", "default_entries", "+=", "[", "(", "\"replay\"", ",", "\"<i class='fa fa-refresh fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"Replay submissions\"", ")", ")", ",", "(", "\"danger\"", ",", "\"<i class='fa fa-bomb fa-fw'></i>&nbsp; \"", "+", "_", "(", "\"Danger zone\"", ")", ")", "]", "# Hook should return a tuple (link,name) where link is the relative link from the index of the course administration.", "additional_entries", "=", "[", "entry", "for", "entry", "in", "plugin_manager", ".", "call_hook", "(", "'course_admin_menu'", ",", "course", "=", "course", ")", "if", "entry", "is", "not", "None", "]", "return", "renderer", ".", "course_admin", ".", "menu", "(", "course", ",", "default_entries", "+", "additional_entries", ",", "current", ")" ]
Returns the HTML of the menu used in the administration. ```current``` is the current page of section
[ "Returns", "the", "HTML", "of", "the", "menu", "used", "in", "the", "administration", ".", "current", "is", "the", "current", "page", "of", "section" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/utils.py#L252-L278
234,975
UCL-INGI/INGInious
inginious/frontend/pages/course_admin/utils.py
UnicodeWriter.writerow
def writerow(self, row): """ Writes a row to the CSV file """ self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) self.queue.seek(0)
python
def writerow(self, row): """ Writes a row to the CSV file """ self.writer.writerow(row) # Fetch UTF-8 output from the queue ... data = self.queue.getvalue() # write to the target stream self.stream.write(data) # empty queue self.queue.truncate(0) self.queue.seek(0)
[ "def", "writerow", "(", "self", ",", "row", ")", ":", "self", ".", "writer", ".", "writerow", "(", "row", ")", "# Fetch UTF-8 output from the queue ...", "data", "=", "self", ".", "queue", ".", "getvalue", "(", ")", "# write to the target stream", "self", ".", "stream", ".", "write", "(", "data", ")", "# empty queue", "self", ".", "queue", ".", "truncate", "(", "0", ")", "self", ".", "queue", ".", "seek", "(", "0", ")" ]
Writes a row to the CSV file
[ "Writes", "a", "row", "to", "the", "CSV", "file" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/pages/course_admin/utils.py#L175-L184
234,976
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper.get_renderer
def get_renderer(self, with_layout=True): """ Get the default renderer """ if with_layout and self.is_lti(): return self._default_renderer_lti elif with_layout: return self._default_renderer else: return self._default_renderer_nolayout
python
def get_renderer(self, with_layout=True): """ Get the default renderer """ if with_layout and self.is_lti(): return self._default_renderer_lti elif with_layout: return self._default_renderer else: return self._default_renderer_nolayout
[ "def", "get_renderer", "(", "self", ",", "with_layout", "=", "True", ")", ":", "if", "with_layout", "and", "self", ".", "is_lti", "(", ")", ":", "return", "self", ".", "_default_renderer_lti", "elif", "with_layout", ":", "return", "self", ".", "_default_renderer", "else", ":", "return", "self", ".", "_default_renderer_nolayout" ]
Get the default renderer
[ "Get", "the", "default", "renderer" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L63-L70
234,977
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._javascript_helper
def _javascript_helper(self, position): """ Add javascript links for the current page and for the plugins """ if position not in ["header", "footer"]: position = "footer" # Load javascript files from plugins if position == "header": entries = [entry for entry in self._plugin_manager.call_hook("javascript_header") if entry is not None] else: entries = [entry for entry in self._plugin_manager.call_hook("javascript_footer") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["javascript"][position] entries = ["<script src='" + entry + "' type='text/javascript' charset='utf-8'></script>" for entry in entries] return "\n".join(entries)
python
def _javascript_helper(self, position): """ Add javascript links for the current page and for the plugins """ if position not in ["header", "footer"]: position = "footer" # Load javascript files from plugins if position == "header": entries = [entry for entry in self._plugin_manager.call_hook("javascript_header") if entry is not None] else: entries = [entry for entry in self._plugin_manager.call_hook("javascript_footer") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["javascript"][position] entries = ["<script src='" + entry + "' type='text/javascript' charset='utf-8'></script>" for entry in entries] return "\n".join(entries)
[ "def", "_javascript_helper", "(", "self", ",", "position", ")", ":", "if", "position", "not", "in", "[", "\"header\"", ",", "\"footer\"", "]", ":", "position", "=", "\"footer\"", "# Load javascript files from plugins", "if", "position", "==", "\"header\"", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "\"javascript_header\"", ")", "if", "entry", "is", "not", "None", "]", "else", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "\"javascript_footer\"", ")", "if", "entry", "is", "not", "None", "]", "# Load javascript for the current page", "entries", "+=", "self", ".", "_get_ctx", "(", ")", "[", "\"javascript\"", "]", "[", "position", "]", "entries", "=", "[", "\"<script src='\"", "+", "entry", "+", "\"' type='text/javascript' charset='utf-8'></script>\"", "for", "entry", "in", "entries", "]", "return", "\"\\n\"", ".", "join", "(", "entries", ")" ]
Add javascript links for the current page and for the plugins
[ "Add", "javascript", "links", "for", "the", "current", "page", "and", "for", "the", "plugins" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L117-L130
234,978
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._css_helper
def _css_helper(self): """ Add CSS links for the current page and for the plugins """ entries = [entry for entry in self._plugin_manager.call_hook("css") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["css"] entries = ["<link href='" + entry + "' rel='stylesheet'>" for entry in entries] return "\n".join(entries)
python
def _css_helper(self): """ Add CSS links for the current page and for the plugins """ entries = [entry for entry in self._plugin_manager.call_hook("css") if entry is not None] # Load javascript for the current page entries += self._get_ctx()["css"] entries = ["<link href='" + entry + "' rel='stylesheet'>" for entry in entries] return "\n".join(entries)
[ "def", "_css_helper", "(", "self", ")", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "\"css\"", ")", "if", "entry", "is", "not", "None", "]", "# Load javascript for the current page", "entries", "+=", "self", ".", "_get_ctx", "(", ")", "[", "\"css\"", "]", "entries", "=", "[", "\"<link href='\"", "+", "entry", "+", "\"' rel='stylesheet'>\"", "for", "entry", "in", "entries", "]", "return", "\"\\n\"", ".", "join", "(", "entries", ")" ]
Add CSS links for the current page and for the plugins
[ "Add", "CSS", "links", "for", "the", "current", "page", "and", "for", "the", "plugins" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L132-L138
234,979
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._get_ctx
def _get_ctx(self): """ Get web.ctx object for the Template helper """ if self._WEB_CTX_KEY not in web.ctx: web.ctx[self._WEB_CTX_KEY] = { "javascript": {"footer": [], "header": []}, "css": []} return web.ctx.get(self._WEB_CTX_KEY)
python
def _get_ctx(self): """ Get web.ctx object for the Template helper """ if self._WEB_CTX_KEY not in web.ctx: web.ctx[self._WEB_CTX_KEY] = { "javascript": {"footer": [], "header": []}, "css": []} return web.ctx.get(self._WEB_CTX_KEY)
[ "def", "_get_ctx", "(", "self", ")", ":", "if", "self", ".", "_WEB_CTX_KEY", "not", "in", "web", ".", "ctx", ":", "web", ".", "ctx", "[", "self", ".", "_WEB_CTX_KEY", "]", "=", "{", "\"javascript\"", ":", "{", "\"footer\"", ":", "[", "]", ",", "\"header\"", ":", "[", "]", "}", ",", "\"css\"", ":", "[", "]", "}", "return", "web", ".", "ctx", ".", "get", "(", "self", ".", "_WEB_CTX_KEY", ")" ]
Get web.ctx object for the Template helper
[ "Get", "web", ".", "ctx", "object", "for", "the", "Template", "helper" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L140-L146
234,980
UCL-INGI/INGInious
inginious/frontend/template_helper.py
TemplateHelper._generic_hook
def _generic_hook(self, name, **kwargs): """ A generic hook that links the TemplateHelper with PluginManager """ entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None] return "\n".join(entries)
python
def _generic_hook(self, name, **kwargs): """ A generic hook that links the TemplateHelper with PluginManager """ entries = [entry for entry in self._plugin_manager.call_hook(name, **kwargs) if entry is not None] return "\n".join(entries)
[ "def", "_generic_hook", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "entries", "=", "[", "entry", "for", "entry", "in", "self", ".", "_plugin_manager", ".", "call_hook", "(", "name", ",", "*", "*", "kwargs", ")", "if", "entry", "is", "not", "None", "]", "return", "\"\\n\"", ".", "join", "(", "entries", ")" ]
A generic hook that links the TemplateHelper with PluginManager
[ "A", "generic", "hook", "that", "links", "the", "TemplateHelper", "with", "PluginManager" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/template_helper.py#L148-L151
234,981
UCL-INGI/INGInious
inginious/client/client_buffer.py
ClientBuffer.new_job
def new_job(self, task, inputdata, launcher_name="Unknown", debug=False): """ Runs a new job. It works exactly like the Client class, instead that there is no callback """ bjobid = uuid.uuid4() self._waiting_jobs.append(str(bjobid)) self._client.new_job(task, inputdata, (lambda result, grade, problems, tests, custom, archive, stdout, stderr: self._callback(bjobid, result, grade, problems, tests, custom, archive, stdout, stderr)), launcher_name, debug) return bjobid
python
def new_job(self, task, inputdata, launcher_name="Unknown", debug=False): """ Runs a new job. It works exactly like the Client class, instead that there is no callback """ bjobid = uuid.uuid4() self._waiting_jobs.append(str(bjobid)) self._client.new_job(task, inputdata, (lambda result, grade, problems, tests, custom, archive, stdout, stderr: self._callback(bjobid, result, grade, problems, tests, custom, archive, stdout, stderr)), launcher_name, debug) return bjobid
[ "def", "new_job", "(", "self", ",", "task", ",", "inputdata", ",", "launcher_name", "=", "\"Unknown\"", ",", "debug", "=", "False", ")", ":", "bjobid", "=", "uuid", ".", "uuid4", "(", ")", "self", ".", "_waiting_jobs", ".", "append", "(", "str", "(", "bjobid", ")", ")", "self", ".", "_client", ".", "new_job", "(", "task", ",", "inputdata", ",", "(", "lambda", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "archive", ",", "stdout", ",", "stderr", ":", "self", ".", "_callback", "(", "bjobid", ",", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "archive", ",", "stdout", ",", "stderr", ")", ")", ",", "launcher_name", ",", "debug", ")", "return", "bjobid" ]
Runs a new job. It works exactly like the Client class, instead that there is no callback
[ "Runs", "a", "new", "job", ".", "It", "works", "exactly", "like", "the", "Client", "class", "instead", "that", "there", "is", "no", "callback" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client_buffer.py#L19-L27
234,982
UCL-INGI/INGInious
inginious/client/client_buffer.py
ClientBuffer._callback
def _callback(self, bjobid, result, grade, problems, tests, custom, archive, stdout, stderr): """ Callback for self._client.new_job """ self._jobs_done[str(bjobid)] = (result, grade, problems, tests, custom, archive, stdout, stderr) self._waiting_jobs.remove(str(bjobid))
python
def _callback(self, bjobid, result, grade, problems, tests, custom, archive, stdout, stderr): """ Callback for self._client.new_job """ self._jobs_done[str(bjobid)] = (result, grade, problems, tests, custom, archive, stdout, stderr) self._waiting_jobs.remove(str(bjobid))
[ "def", "_callback", "(", "self", ",", "bjobid", ",", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "archive", ",", "stdout", ",", "stderr", ")", ":", "self", ".", "_jobs_done", "[", "str", "(", "bjobid", ")", "]", "=", "(", "result", ",", "grade", ",", "problems", ",", "tests", ",", "custom", ",", "archive", ",", "stdout", ",", "stderr", ")", "self", ".", "_waiting_jobs", ".", "remove", "(", "str", "(", "bjobid", ")", ")" ]
Callback for self._client.new_job
[ "Callback", "for", "self", ".", "_client", ".", "new_job" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/client/client_buffer.py#L29-L32
234,983
UCL-INGI/INGInious
inginious/frontend/plugins/auth/ldap_auth.py
init
def init(plugin_manager, _, _2, conf): """ Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, encryption: "ssl", base_dn: "o=test,c=be", request: "(uid={})", name: "LDAP Login" *host* The host of the ldap server *encryption* Encryption method used to connect to the LDAP server Can be either "none", "ssl" or "tls" *request* Request made to the server in order to find the dn of the user. The characters "{}" will be replaced by the login name. """ encryption = conf.get("encryption", "none") if encryption not in ["none", "ssl", "tls"]: raise Exception("Unknown encryption method {}".format(encryption)) if encryption == "none": conf["encryption"] = None if conf.get("port", 0) == 0: conf["port"] = None the_method = LdapAuthMethod(conf.get("id"), conf.get('name', 'LDAP'), conf.get("imlink", ""), conf) plugin_manager.add_page(r'/auth/page/([^/]+)', LDAPAuthenticationPage) plugin_manager.register_auth_method(the_method)
python
def init(plugin_manager, _, _2, conf): """ Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, encryption: "ssl", base_dn: "o=test,c=be", request: "(uid={})", name: "LDAP Login" *host* The host of the ldap server *encryption* Encryption method used to connect to the LDAP server Can be either "none", "ssl" or "tls" *request* Request made to the server in order to find the dn of the user. The characters "{}" will be replaced by the login name. """ encryption = conf.get("encryption", "none") if encryption not in ["none", "ssl", "tls"]: raise Exception("Unknown encryption method {}".format(encryption)) if encryption == "none": conf["encryption"] = None if conf.get("port", 0) == 0: conf["port"] = None the_method = LdapAuthMethod(conf.get("id"), conf.get('name', 'LDAP'), conf.get("imlink", ""), conf) plugin_manager.add_page(r'/auth/page/([^/]+)', LDAPAuthenticationPage) plugin_manager.register_auth_method(the_method)
[ "def", "init", "(", "plugin_manager", ",", "_", ",", "_2", ",", "conf", ")", ":", "encryption", "=", "conf", ".", "get", "(", "\"encryption\"", ",", "\"none\"", ")", "if", "encryption", "not", "in", "[", "\"none\"", ",", "\"ssl\"", ",", "\"tls\"", "]", ":", "raise", "Exception", "(", "\"Unknown encryption method {}\"", ".", "format", "(", "encryption", ")", ")", "if", "encryption", "==", "\"none\"", ":", "conf", "[", "\"encryption\"", "]", "=", "None", "if", "conf", ".", "get", "(", "\"port\"", ",", "0", ")", "==", "0", ":", "conf", "[", "\"port\"", "]", "=", "None", "the_method", "=", "LdapAuthMethod", "(", "conf", ".", "get", "(", "\"id\"", ")", ",", "conf", ".", "get", "(", "'name'", ",", "'LDAP'", ")", ",", "conf", ".", "get", "(", "\"imlink\"", ",", "\"\"", ")", ",", "conf", ")", "plugin_manager", ".", "add_page", "(", "r'/auth/page/([^/]+)'", ",", "LDAPAuthenticationPage", ")", "plugin_manager", ".", "register_auth_method", "(", "the_method", ")" ]
Allow to connect through a LDAP service Available configuration: :: plugins: - plugin_module": "inginious.frontend.plugins.auth.ldap_auth", host: "ldap.test.be", port: 0, encryption: "ssl", base_dn: "o=test,c=be", request: "(uid={})", name: "LDAP Login" *host* The host of the ldap server *encryption* Encryption method used to connect to the LDAP server Can be either "none", "ssl" or "tls" *request* Request made to the server in order to find the dn of the user. The characters "{}" will be replaced by the login name.
[ "Allow", "to", "connect", "through", "a", "LDAP", "service" ]
cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c
https://github.com/UCL-INGI/INGInious/blob/cbda9a9c7f2b8e8eb1e6d7d51f0d18092086300c/inginious/frontend/plugins/auth/ldap_auth.py#L127-L165
234,984
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
234,985
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): """ 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)
[ "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
234,986
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): """ 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)
[ "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
234,987
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): """ 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)
[ "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
234,988
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): """ 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)
[ "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
234,989
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): """ 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)
[ "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
234,990
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): """ 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)
[ "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
234,991
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): """ 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))
[ "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
234,992
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): """ 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()))))
[ "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
234,993
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): """ 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"))
[ "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
234,994
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): """ 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"]
[ "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
234,995
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): """ 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
[ "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
234,996
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): """ 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__] = {}
[ "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
234,997
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): """ 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()
[ "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
234,998
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): """ 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)
[ "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
234,999
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): """ 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
[ "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