Exemplo n.º 1
0
import os, commands
from file import File
from path import Path
from convert import makeFileStreamable
from settings import MOVIE_PATH_ID
from utils import stripUnicode

from log import LogFile
log = LogFile().getLogger()

FIND_FAIL_STRING = 'No such file or directory'


class TvRunner(object):
    def __init__(self):
        self.paths = dict()

    def loadPaths(self):
        self.paths = Path.getAllPaths()

    @staticmethod
    def getOrCreateRemotePath(localPath):
        log.debug('Get or create path for %s' % localPath)
        newPath = Path(localPath, localPath)
        newPath.post()
        data = Path.getPathByLocalPathAndRemotePath(localPath, localPath)
        pathid = data['results'][0]['pk']
        log.debug('Got path')

        return pathid
Exemplo n.º 2
0
computeParticipation = 'y' == getUserInput('\nCompute participation using chat files? y/n ', False, 'n')

outputName = getUserInput('\nEnter output filename: ', False, 'output_file.xlsx')

if '.xlsx' not in outputName:
    outputName = outputName + '.xlsx'


###########################################################################
########################################## Grade calculations start here ##

# Create a log object for the roster. 
# File must contain 'First Name' and 'Last Name' columns. (Blackboard
# grade center file works for this.
roster = LogFile(logPath + rosterName)

# Get all names
firstNames = roster.raw_data['First Name'].array
lastNames = roster.raw_data['Last Name'].array

# Make a student object for every name. Store students
# in studentList
studentList = []

# For every row in roster, create a student with the first and last 
# name of that row. 
for first, last in zip(firstNames, lastNames):

    studentList.append( Student( first, last ) )
Exemplo n.º 3
0
 def __init__(self,
              profile,
              intent="r",
              direction="f",
              order="n",
              pcs=None,
              scale=1,
              cwd=None,
              startupinfo=None,
              use_icclu=False,
              use_cam_clipping=False,
              logfile=None,
              worker=None,
              show_actual_if_clipped=False,
              input_encoding=None,
              output_encoding=None,
              convert_video_rgb_to_clut65=False,
              verbose=1):
     if not profile:
         raise Error("Xicclu: Profile is %r" % profile)
     WorkerBase.__init__(self)
     self.scale = scale
     self.convert_video_rgb_to_clut65 = convert_video_rgb_to_clut65
     self.logfile = logfile
     self.worker = worker
     self.temp = False
     utilname = "icclu" if use_icclu else "xicclu"
     xicclu = get_argyll_util(utilname)
     if not xicclu:
         raise Error(lang.getstr("argyll.util.not_found", utilname))
     if not isinstance(profile, (CGATS.CGATS, ICCP.ICCProfile)):
         if profile.lower().endswith(".cal"):
             profile = CGATS.CGATS(profile)
         else:
             profile = ICCP.ICCProfile(profile)
     is_profile = isinstance(profile, ICCP.ICCProfile)
     if (is_profile and profile.version >= 4
             and not profile.convert_iccv4_tags_to_iccv2()):
         raise Error("\n".join([
             lang.getstr("profile.iccv4.unsupported"),
             profile.getDescription()
         ]))
     if not profile.fileName or not os.path.isfile(profile.fileName):
         if profile.fileName:
             prefix = os.path.basename(profile.fileName)
         elif is_profile:
             prefix = make_filename_safe(profile.getDescription(),
                                         concat=False) + profile_ext
         else:
             # CGATS (.cal)
             prefix = "cal"
         prefix += "-"
         if not cwd:
             cwd = self.create_tempdir()
             if isinstance(cwd, Exception):
                 raise cwd
         fd, profile.fileName = tempfile.mkstemp("", prefix, dir=cwd)
         stream = os.fdopen(fd, "wb")
         profile.write(stream)
         stream.close()
         self.temp = True
     elif not cwd:
         cwd = os.path.dirname(profile.fileName)
     profile_basename = safe_unicode(os.path.basename(profile.fileName))
     profile_path = profile.fileName
     if sys.platform == "win32":
         profile_path = win32api.GetShortPathName(profile_path)
     self.profile_path = safe_str(profile_path)
     if sys.platform == "win32" and not startupinfo:
         startupinfo = sp.STARTUPINFO()
         startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
         startupinfo.wShowWindow = sp.SW_HIDE
     xicclu = safe_str(xicclu)
     cwd = safe_str(cwd)
     self.verbose = verbose
     args = [xicclu, "-v%i" % verbose, "-s%s" % scale]
     self.show_actual_if_clipped = False
     if utilname == "xicclu":
         if (is_profile and show_actual_if_clipped
                 and "A2B0" in profile.tags
                 and ("B2A0" in profile.tags or direction == "if")):
             args.append("-a")
             self.show_actual_if_clipped = True
         if use_cam_clipping:
             args.append("-b")
         if get_argyll_version("xicclu") >= [1, 6]:
             # Add encoding parameters
             # Note: Not adding -e -E can cause problems due to unitialized
             # in_tvenc and out_tvenc variables in xicclu.c for Argyll 1.6.x
             if not input_encoding:
                 input_encoding = "n"
             if not output_encoding:
                 output_encoding = "n"
             args += [
                 "-e" + safe_str(input_encoding),
                 "-E" + safe_str(output_encoding)
             ]
     args.append("-f" + direction)
     self.output_scale = 1.0
     if is_profile:
         if profile.profileClass not in ("abst", "link"):
             args.append("-i" + intent)
             if order != "n":
                 args.append("-o" + order)
         if profile.profileClass != "link":
             if (direction in ("f", "ib") and
                 (pcs == "x" or
                  (profile.connectionColorSpace == "XYZ" and not pcs))):
                 # In case of forward lookup with XYZ PCS, use 0..100 scaling
                 # internally so we get extra precision from xicclu for the
                 # decimal part. Scale back to 0..1 later.
                 pcs = "X"
                 self.output_scale = 100.0
             if pcs:
                 args.append("-p" + pcs)
     args.append(self.profile_path)
     if debug or verbose > 1:
         self.sessionlogfile = LogFile(profile_basename + ".xicclu",
                                       os.path.dirname(profile.fileName))
         if is_profile:
             profile_act = ICCP.ICCProfile(profile.fileName)
             self.sessionlogfile.write(
                 "Profile ID %s (actual %s)" % (hexlify(
                     profile.ID), hexlify(profile_act.calculateID(False))))
         if cwd:
             self.log(lang.getstr("working_dir"))
             indent = "  "
             for name in cwd.split(os.path.sep):
                 self.log(
                     textwrap.fill(name + os.path.sep,
                                   80,
                                   expand_tabs=False,
                                   replace_whitespace=False,
                                   initial_indent=indent,
                                   subsequent_indent=indent))
                 indent += " "
             self.log("")
         self.log(lang.getstr("commandline"))
         printcmdline(xicclu, args[1:], fn=self.log, cwd=cwd)
         self.log("")
     self.startupinfo = startupinfo
     self.args = args
     self.cwd = cwd
     self.spawn()
Exemplo n.º 4
0
def main():
    # Variables globales
    global monitor_processes_thread, monitor_time_thread, monitor_usb_thread, window
    global START_TIME, END_TIME
    global banned_processes_founded
    global btn_start_test, btn_upload_test, btn_finish_test
    global full_name_entry
    global log_file
    global ss

    # Crea directorios del programa / si es que no existen
    create_directory()

    # Inicializa variables para almacenar hilos
    monitor_processes_thread = threading.Thread(target=monitor_processes)
    monitor_time_thread = threading.Thread(target=monitor_time)
    monitor_usb_thread = threading.Thread(target=monitor_usb)

    # Inicializa archivo de log
    log_file = LogFile()

    # Realiza escaneo de procesos y USB por primera vez
    monitor_processes(first_scan=True)
    monitor_usb(first_scan=True)

    # Si se encontraron procesos prohibidos se muestra mensaje con cada uno de ellos y finaliza ejecución
    if len(banned_processes_founded) > 0:
        banned_process = [
            banned_processes_founded[process]['alias']
            for process in banned_processes_founded
        ]
        messagebox.showerror(
            title="No se puede iniciar la prueba",
            message="Cerrar los siguientes programas: {}".format(
                ", ".join(banned_process)))
        #window.destroy()

    # Si se encontro un dispositivo USB conectado muestra mensaje de alerta y finaliza ejecución
    elif usb_plugged:
        messagebox.showerror(
            title="No se puede iniciar la prueba",
            message=
            "Favor de desconectar cualquier medio de almacenamiento USB/SD")

    elif hasattr(sys, 'real_prefix'):
        messagebox.showerror(
            title="No se puede iniciar la prueba",
            message="El programa se esta ejecutando en una maquina virutal")
    # Si no se encontro nada sospechoso se procede con la ejecución normal del programa
    else:
        # Inicializa variables de tiempo
        end_time_hour = int(END_TIME.split(":")[0])
        end_time_minute = int(END_TIME.split(":")[1])

        start_time_hour = int(START_TIME.split(":")[0])
        start_time_minute = int(START_TIME.split(":")[1])
        now = datetime.now()

        actual_hour = now.hour
        actual_minute = now.minute

        print(f"\nStart time: {start_time_hour}:{start_time_minute}")
        print(f"End time: {end_time_hour}:{end_time_minute}")
        print(f"Actual time: {actual_hour}:{actual_minute}")
        """
        if (start_time_hour == actual_hour and start_time_minute <= actual_minute and start_time_hour != end_time_hour)\
            or\
            (end_time_hour == actual_hour and end_time_minute >= actual_minute and start_time_hour != end_time_hour)\
            or\
            (start_time_hour == end_time_hour and start_time_minute <= actual_minute < end_time_minute)\
            or\
            (start_time_hour < actual_hour < end_time_hour):

        """

        # Crea pantalla de inicio
        ss = StartScreen(get_student_data, set_start_time)
        ss.focus_force()
        ss.mainloop()

        # Configura ventana principal del programa
        window = tkinter.Tk()
        window.title("Secure Exam")
        window.geometry("720x400")
        window.resizable(False, False)

        # log_file.add_start_time(datetime.now().isoformat())

        # Establece dimensiones de botones
        btn_width = 200
        btn_height = 60

        # Crea botones principales inicio de prueba en linea, entregar archivo adjunto y finalizar
        # prueba respectivamente

        btn_start_test = tkinter.Button(window,
                                        text="Iniciar prueba en linea",
                                        font=("Open Sans", 10),
                                        command=lambda: os.startfile("sb.url"))

        btn_start_test.place(x=20, y=150, width=btn_width, height=btn_height)

        btn_upload_test = tkinter.Button(
            window,
            text="Entregar archivo adjunto",
            font=("Open Sans", 10),
            command=upload_test,
            # state="disabled"
        )

        btn_upload_test.place(x=250, y=150, width=btn_width, height=btn_height)

        btn_finish_test = tkinter.Button(
            window,
            text="Finalizar Prueba",
            font=("Open Sans", 10),
            command=finish_test,
        )

        btn_finish_test.place(x=500, y=150, width=btn_width, height=btn_height)

        # Forza foco en ventana actual
        window.focus_force()

        # Si se presiona el botón de cerrar ventana no realiza nada
        window.protocol("WM_DELETE_WINDOW", lambda: None)

        # Inicia ventana principal
        window.mainloop()
    """
Exemplo n.º 5
0
class Xicclu(WorkerBase):
    def __init__(self,
                 profile,
                 intent="r",
                 direction="f",
                 order="n",
                 pcs=None,
                 scale=1,
                 cwd=None,
                 startupinfo=None,
                 use_icclu=False,
                 use_cam_clipping=False,
                 logfile=None,
                 worker=None,
                 show_actual_if_clipped=False,
                 input_encoding=None,
                 output_encoding=None,
                 convert_video_rgb_to_clut65=False,
                 verbose=1):
        if not profile:
            raise Error("Xicclu: Profile is %r" % profile)
        WorkerBase.__init__(self)
        self.scale = scale
        self.convert_video_rgb_to_clut65 = convert_video_rgb_to_clut65
        self.logfile = logfile
        self.worker = worker
        self.temp = False
        utilname = "icclu" if use_icclu else "xicclu"
        xicclu = get_argyll_util(utilname)
        if not xicclu:
            raise Error(lang.getstr("argyll.util.not_found", utilname))
        if not isinstance(profile, (CGATS.CGATS, ICCP.ICCProfile)):
            if profile.lower().endswith(".cal"):
                profile = CGATS.CGATS(profile)
            else:
                profile = ICCP.ICCProfile(profile)
        is_profile = isinstance(profile, ICCP.ICCProfile)
        if (is_profile and profile.version >= 4
                and not profile.convert_iccv4_tags_to_iccv2()):
            raise Error("\n".join([
                lang.getstr("profile.iccv4.unsupported"),
                profile.getDescription()
            ]))
        if not profile.fileName or not os.path.isfile(profile.fileName):
            if profile.fileName:
                prefix = os.path.basename(profile.fileName)
            elif is_profile:
                prefix = make_filename_safe(profile.getDescription(),
                                            concat=False) + profile_ext
            else:
                # CGATS (.cal)
                prefix = "cal"
            prefix += "-"
            if not cwd:
                cwd = self.create_tempdir()
                if isinstance(cwd, Exception):
                    raise cwd
            fd, profile.fileName = tempfile.mkstemp("", prefix, dir=cwd)
            stream = os.fdopen(fd, "wb")
            profile.write(stream)
            stream.close()
            self.temp = True
        elif not cwd:
            cwd = os.path.dirname(profile.fileName)
        profile_basename = safe_unicode(os.path.basename(profile.fileName))
        profile_path = profile.fileName
        if sys.platform == "win32":
            profile_path = win32api.GetShortPathName(profile_path)
        self.profile_path = safe_str(profile_path)
        if sys.platform == "win32" and not startupinfo:
            startupinfo = sp.STARTUPINFO()
            startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = sp.SW_HIDE
        xicclu = safe_str(xicclu)
        cwd = safe_str(cwd)
        self.verbose = verbose
        args = [xicclu, "-v%i" % verbose, "-s%s" % scale]
        self.show_actual_if_clipped = False
        if utilname == "xicclu":
            if (is_profile and show_actual_if_clipped
                    and "A2B0" in profile.tags
                    and ("B2A0" in profile.tags or direction == "if")):
                args.append("-a")
                self.show_actual_if_clipped = True
            if use_cam_clipping:
                args.append("-b")
            if get_argyll_version("xicclu") >= [1, 6]:
                # Add encoding parameters
                # Note: Not adding -e -E can cause problems due to unitialized
                # in_tvenc and out_tvenc variables in xicclu.c for Argyll 1.6.x
                if not input_encoding:
                    input_encoding = "n"
                if not output_encoding:
                    output_encoding = "n"
                args += [
                    "-e" + safe_str(input_encoding),
                    "-E" + safe_str(output_encoding)
                ]
        args.append("-f" + direction)
        self.output_scale = 1.0
        if is_profile:
            if profile.profileClass not in ("abst", "link"):
                args.append("-i" + intent)
                if order != "n":
                    args.append("-o" + order)
            if profile.profileClass != "link":
                if (direction in ("f", "ib") and
                    (pcs == "x" or
                     (profile.connectionColorSpace == "XYZ" and not pcs))):
                    # In case of forward lookup with XYZ PCS, use 0..100 scaling
                    # internally so we get extra precision from xicclu for the
                    # decimal part. Scale back to 0..1 later.
                    pcs = "X"
                    self.output_scale = 100.0
                if pcs:
                    args.append("-p" + pcs)
        args.append(self.profile_path)
        if debug or verbose > 1:
            self.sessionlogfile = LogFile(profile_basename + ".xicclu",
                                          os.path.dirname(profile.fileName))
            if is_profile:
                profile_act = ICCP.ICCProfile(profile.fileName)
                self.sessionlogfile.write(
                    "Profile ID %s (actual %s)" % (hexlify(
                        profile.ID), hexlify(profile_act.calculateID(False))))
            if cwd:
                self.log(lang.getstr("working_dir"))
                indent = "  "
                for name in cwd.split(os.path.sep):
                    self.log(
                        textwrap.fill(name + os.path.sep,
                                      80,
                                      expand_tabs=False,
                                      replace_whitespace=False,
                                      initial_indent=indent,
                                      subsequent_indent=indent))
                    indent += " "
                self.log("")
            self.log(lang.getstr("commandline"))
            printcmdline(xicclu, args[1:], fn=self.log, cwd=cwd)
            self.log("")
        self.startupinfo = startupinfo
        self.args = args
        self.cwd = cwd
        self.spawn()

    def spawn(self):
        self.closed = False
        self.output = []
        self.errors = []
        self.stdout = tempfile.SpooledTemporaryFile()
        self.stderr = tempfile.SpooledTemporaryFile()
        self.subprocess = sp.Popen(self.args,
                                   stdin=sp.PIPE,
                                   stdout=self.stdout,
                                   stderr=self.stderr,
                                   cwd=self.cwd,
                                   startupinfo=self.startupinfo)

    def devi_devip(self, n):
        if n > 236 / 256.0:
            n = colormath.convert_range(n, 236 / 256.0, 1, 236 / 256.0,
                                        255 / 256.0)
        return VidRGB_to_cLUT65(eeColor_to_VidRGB(n))

    def __call__(self, idata):
        if not isinstance(idata, str):
            verbose = self.verbose
            if self.convert_video_rgb_to_clut65:
                devi_devip = self.devi_devip
            else:
                devi_devip = lambda v: v
            scale = float(self.scale)
            idata = list(idata)  # Make a copy
            for i, v in enumerate(idata):
                if isinstance(v, (float, int)):
                    self([idata])
                    return
                if not isinstance(v, str):
                    if verbose:
                        for n in v:
                            if not isinstance(n, (float, int)):
                                raise TypeError("xicclu: Expecting list of "
                                                "strings or n-tuples with "
                                                "floats")
                    idata[i] = " ".join(
                        str(devi_devip(n / scale) * scale) for n in v)
        else:
            idata = idata.splitlines()
        numrows = len(idata)
        chunklen = 1000
        i = 0
        p = self.subprocess
        prevperc = -1
        while True:
            # Process in chunks to prevent broken pipe if input data is too
            # large
            if getattr(sys, "_sigbreak", False) and not self.subprocess_abort:
                self.subprocess_abort = True
                safe_print("Got SIGBREAK, aborting subprocess...")
            if self.subprocess_abort or self.thread_abort:
                if p.poll() is None:
                    p.stdin.write("\n")
                    p.stdin.close()
                    p.wait()
                raise Info(lang.getstr("aborted"))
            if p.poll() is None:
                # We don't use communicate() because it will end the
                # process
                p.stdin.write("\n".join(idata[chunklen * i:chunklen *
                                              (i + 1)]) + "\n")
                p.stdin.flush()
            else:
                # Error
                break
            perc = round(chunklen * (i + 1) / float(numrows) * 100)
            if perc > prevperc and self.logfile:
                self.logfile.write("\r%i%%" % min(perc, 100))
                prevperc = perc
            if chunklen * (i + 1) > numrows - 1:
                break
            i += 1

    def __enter__(self):
        return self

    def __exit__(self, etype=None, value=None, tb=None):
        self.exit()
        if tb:
            return False

    def close(self, raise_exception=True):
        if self.closed:
            return
        p = self.subprocess
        if p.poll() is None:
            try:
                p.stdin.write("\n")
            except IOError:
                pass
            p.stdin.close()
        p.wait()
        self.stdout.seek(0)
        self.output = self.stdout.readlines()
        self.stdout.close()
        self.stderr.seek(0)
        self.errors = self.stderr.readlines()
        self.stderr.close()
        if self.sessionlogfile and self.errors:
            self.sessionlogfile.write("\n".join(self.errors))
        if self.logfile:
            self.logfile.write("\n")
        self.closed = True
        if p.returncode and raise_exception:
            # Error
            raise IOError("\n".join(self.errors))

    def exit(self, raise_exception=True):
        self.close(raise_exception)
        if self.temp and os.path.isfile(self.profile_path):
            os.remove(self.profile_path)
            if self.tempdir and not os.listdir(self.tempdir):
                try:
                    shutil.rmtree(self.tempdir, True)
                except Exception as exception:
                    safe_print("Warning - temporary directory '%s' could "
                               "not be removed: %s" % tuple(
                                   safe_unicode(s)
                                   for s in (self.tempdir, exception)))

    def get(self,
            raw=False,
            get_clip=False,
            output_format=None,
            reverse=False):
        if raw:
            if self.sessionlogfile:
                self.sessionlogfile.write("\n".join(self.output))
                self.sessionlogfile.close()
            return self.output
        parsed = []
        j = 0
        verbose = self.verbose
        scale = float(self.scale)
        output_scale = float(self.output_scale)
        if self.convert_video_rgb_to_clut65:
            devop_devo = VidRGB_to_eeColor
        else:
            devop_devo = lambda v: v
        if output_format:
            fmt = output_format[0]
            maxv = output_format[1]
        # Interesting: In CPython, testing for 'if not x' is slightly quicker
        # than testing for 'if x'. Also, struct.pack is faster if the second
        # argument is passed as an integer.
        for i, line in enumerate(self.output):
            if verbose:
                line = line.strip()
                if line.startswith("["):
                    if parsed and get_clip and self.show_actual_if_clipped:
                        parts = line.strip("[]").split(",")
                        actual = [float(v)
                                  for v in parts[0].split()[1:4]]  # Actual CIE
                        actual.append(float(parts[1].split()[-1]))  # deltaE
                        parsed[-1].append(actual)
                    elif self.sessionlogfile:
                        self.sessionlogfile.write(line)
                    continue
                elif not "->" in line:
                    if self.sessionlogfile and line:
                        self.sessionlogfile.write(line)
                    continue
                elif self.sessionlogfile:
                    self.sessionlogfile.write("#%i %s" % (j, line))
                parts = line.split("->")[-1].strip().split()
                clip = parts.pop() == "(clip)"
                if clip:
                    parts.pop()
                j += 1
            else:
                parts = line.split()
            if reverse:
                parts = reversed(parts)
            if not output_format:
                out = [devop_devo(float(v) / output_scale) for v in parts]
                if get_clip and not self.show_actual_if_clipped:
                    out.append(clip)
            else:
                out = "".join(
                    struct.pack(
                        fmt, int(round(devop_devo(float(v) / scale) * maxv)))
                    for v in parts)
            parsed.append(out)
        if self.sessionlogfile:
            self.sessionlogfile.close()
        return parsed

    @Property
    def subprocess_abort():
        def fget(self):
            if self.worker:
                return self.worker.subprocess_abort
            return False

        def fset(self, v):
            pass

        return locals()

    @Property
    def thread_abort():
        def fget(self):
            if self.worker:
                return self.worker.thread_abort
            return None

        def fset(self, v):
            pass

        return locals()