Esempio n. 1
0
    def change(self, **kwargs):
        args = list()
        data = list()
        for key, value in kwargs.iteritems():
            if isinstance(value, int):
                data.append("{}={}".format(key, value))
            elif isinstance(value, str):
                data.append("{}='{}'".format(key, value))

        for key, value in self.__mappings__.iteritems():
            column_name = value.name
            column_value = getattr(self, key)
            if column_value is not None:
                if isinstance(value, StringField):
                    column_value = "'{}'".format(column_value)
                elif isinstance(value, IntegerField):
                    column_value = column_value
                args.append("{}={}".format(column_name, column_value))
        if len(args) > 0 and len(data) > 0:
            sql = "UPDATE {} SET {} WHERE {}".format(self.__table__,
                                                     ",".join(data),
                                                     " AND ".join(args))
            if self.__show_sql__:
                print sql
            config.execute(sql)
Esempio n. 2
0
 def clear(self):
     if self.session.get(Config.CART_SESSION_ID):
         del self.session[Config.CART_SESSION_ID]
     username = self.session.get('user_id')
     if username:
         sql = text('delete from cart where username = :username')
         execute(sql, {'username': username})
     self.save()
Esempio n. 3
0
 def remove(self, product):
     product_id = str(product['id'])
     if product_id in self.cart:
         del self.cart[product_id]
         username = self.session.get('user_id')
         if username:
             sql = text('delete from cart where username = :username and product = :product')
             execute(sql, {'username': username, 'product': int(product['id'])})
         self.save()
Esempio n. 4
0
 def add(self, product, num=1, update_num=False):
     product['id'] = str(product['id'])
     if product['id'] not in self.cart:
         self.cart[product['id']] = {'num': 0, 'price': str(product['price'])}
     if update_num:
         self.cart[product['id']]['num'] = num
     else:
         self.cart[product['id']]['num'] += num
     username = self.session.get('user_id')
     if username:
         sql = text(
             'insert into cart (username, product, num) values (:username, :product, :num) on duplicate key update num = :num')
         execute(sql, {'username': username, 'product': int(product['id']), 'num': self.cart[product['id']]['num']})
     self.save()
Esempio n. 5
0
 def create(self, cart: Cart):
     sql = text("insert into order_ (price, name,"
                "phone, address) values (:price,:name,:phone,:address)")
     result = execute(sql, {'price': cart.get_total_price, 'name': self.name, 'phone': self.phone,
                            'address': self.address})
     sql = text(
         f"insert into order_items (id, product, price, num) VALUES ({result.lastrowid}, :product, :price, :num)")
     for item in cart:
         product = item['product']
         execute(sql, {'product': product['id'], 'price': product['price'], 'num': item['num']})
     username = session.get('user_id')
     if username:
         sql = text("insert into orders (username, order_id) VALUES (:name,:id)")
         execute(sql, {'name': username, 'id': result.lastrowid})
     self.id = result.lastrowid
Esempio n. 6
0
 def remove(self):
     args = list()
     for key, value in self.__mappings__.iteritems():
         column_name = value.name
         column_value = getattr(self, key)
         if column_value is not None:
             if isinstance(value, StringField):
                 column_value = "'{}'".format(column_value)
             elif isinstance(value, IntegerField):
                 column_value = column_value
             args.append("{}={}".format(column_name, column_value))
     if len(args) > 0:
         sql = "DELETE FROM {} WHERE {}".format(self.__table__,
                                                " AND ".join(args))
         if self.__show_sql__:
             print sql
         config.execute(sql)
Esempio n. 7
0
 def find_all(self):
     result = None
     sql = "SELECT * FROM {}".format(self.__table__)
     if self.__show_sql__:
         print sql
     try:
         result = config.execute(sql)
     except XssforkTaskError as e:
         raise XssforkTaskFindError(e)
     return result
Esempio n. 8
0
 def find_lastest_id(self):
     result = None
     sql = "SELECT last_insert_rowid() FROM {}".format(self.__table__)
     if self.__show_sql__:
         print sql
     try:
         result = config.execute(sql)[0][0]
     except XssforkTaskError as e:
         raise XssforkTaskFindError(e)
     return str(result)
Esempio n. 9
0
 def save(self):
     fields = list()
     args = list()
     for key, value in self.__mappings__.iteritems():
         column_name = value.name
         column_value = getattr(self, key)
         if column_value is not None:
             fields.append(column_name)
             if isinstance(value, StringField):
                 args.append("'%s'" % column_value)
             elif isinstance(value, IntegerField):
                 args.append(column_value)
     sql = 'INSERT INTO {} ({}) VALUES ({})'.format(self.__table__,
                                                    ', '.join(fields),
                                                    ', '.join(args))
     if self.__show_sql__:
         print sql
     try:
         config.execute(sql)
     except XssforkTaskError as e:
         raise XssforkTaskSaveError(e)
Esempio n. 10
0
def run(slug, tag="reference|student", stdin="" ):
    
    cmd = [cfg["safeexec-executable-abspath"]]
    #~ cmd += ["--chroot_dir", cfg["java_jail-abspath"]]
    #~ cmd += ["--exec_dir", "/" + refdir]
    cmd += ["--fsize", "5"]
    cmd += ["--nproc", "1"]
    cmd += ["--clock", "1"]
    cmd += ["--mem", "600000"]   # TODO: move to config?
    cmd += ["--exec", slug+'.exe']
    #~ cmd += args
    
    running = execute(cmd, stdin, flag_badchars = True)

    def check_run_error():

        if running.returncode != 0 or not running.stderr.startswith("OK"):

            if 'student' in tag.lower():   #  for students -- humanreadable info 
                errmsg = running.stderr
                if "elapsed time:" in errmsg:
                  errmsg = errmsg[:errmsg.index("elapsed time:")]
                errmsg = errmsg.replace("Command terminated by signal (8: SIGFPE)",
                                        "Floating point exception")
                errmsg = errmsg.replace("Command terminated by signal (11: SIGSEGV)",
                                        "Segmentation fault (core dumped)")
                result = "<div>Crashed! "
                if errmsg != "":
                  result += "Error messages:" + pre(errmsg)
                if running.stdout != "":
                  result += "Produced this output:"+pre(running.stdout)
        #        result += "Return code:"+pre(str(running.returncode))
                result += "</div>"
                
                return ("Sandbox Limit", result)

                
            else:   # for reference -- more detailed
              return ("Internal Error", 
                      "<div>Reference solution crashed!"+
                      "<br>stdout:"+pre(running.stdout)  +
                      "stderr:"+pre(running.stderr)      +
                      "val:"+pre(str(running.returncode))+
                      "</div>" 
                      )
        
    running.error = check_run_error()
    
    return running
Esempio n. 11
0
def run(slug, tag="reference|student", stdin=""):

    cmd = [cfg["safeexec-executable-abspath"]]
    #~ cmd += ["--chroot_dir", cfg["java_jail-abspath"]]
    #~ cmd += ["--exec_dir", "/" + refdir]
    cmd += ["--fsize", "5"]
    cmd += ["--nproc", "1"]
    cmd += ["--clock", "1"]
    cmd += ["--mem", "600000"]  # TODO: move to config?
    cmd += ["--exec", slug + '.exe']
    #~ cmd += args

    running = execute(cmd, stdin, flag_badchars=True)

    def check_run_error():

        if running.returncode != 0 or not running.stderr.startswith("OK"):

            if 'student' in tag.lower():  #  for students -- humanreadable info
                errmsg = running.stderr
                if "elapsed time:" in errmsg:
                    errmsg = errmsg[:errmsg.index("elapsed time:")]
                errmsg = errmsg.replace(
                    "Command terminated by signal (8: SIGFPE)",
                    "Floating point exception")
                errmsg = errmsg.replace(
                    "Command terminated by signal (11: SIGSEGV)",
                    "Segmentation fault (core dumped)")
                result = "<div>Crashed! "
                if errmsg != "":
                    result += "Error messages:" + pre(errmsg)
                if running.stdout != "":
                    result += "Produced this output:" + pre(running.stdout)
        #        result += "Return code:"+pre(str(running.returncode))
                result += "</div>"

                return ("Sandbox Limit", result)

            else:  # for reference -- more detailed
                return ("Internal Error",
                        "<div>Reference solution crashed!" + "<br>stdout:" +
                        pre(running.stdout) + "stderr:" + pre(running.stderr) +
                        "val:" + pre(str(running.returncode)) + "</div>")

    running.error = check_run_error()

    return running
Esempio n. 12
0
def compile(jail,
            dir,
            slug,
            code,
            tag="reference|student",
            translate_line=None):

    os.makedirs(jail + dir, 0o755, exist_ok=True)
    os.chdir(jail + dir)

    # SAVE to FILE
    with open(slug + ".cs", "w", encoding="utf-8") as f:
        f.write(code)

    # remove previous compilation result (if such exists)
    if os.path.isfile(slug + '.exe'):
        os.remove(slug + '.exe')

    # COMPILE
    compiler_cmd = [cfg["cs_compiler"], slug + ".cs"]
    compiling = execute(compiler_cmd, "")

    def check_compile_err():

        if (compiling.stderr != "" or compiling.returncode != 0
                or not os.path.isfile(jail + dir + slug + suffix)):

            if 'student' in tag.lower():  #  humanreadable info for students
                errmsg = re.sub(
                    '(\.cs:)(\d+)(?!\d)',  # should  be adapted for C#
                    lambda m: m.group(1) + translate_line(m.group(2)),
                    compiling.stderr)
                return ("Syntax Error", errmsg)

            else:  # for reference compilation - more detailed dump
                return (
                    "Internal Error (Compiling %s)" % tag,
                    "cmd:" +
                    pre(" ".join(compiler_cmd)) +  # websheet.slug + suffix
                    "<br>stdout:" + pre(compiling.stdout) + "<br>stderr:" +
                    pre(compiling.stderr) + "<br>retval:" +
                    pre(str(compiling.returncode)))

    compiling.error = check_compile_err()
    return compiling
Esempio n. 13
0
 def find(self):
     results = None
     args = list()
     for key, value in self.__mappings__.iteritems():
         column_name = value.name
         column_value = getattr(self, key)
         if column_value is not None:
             if isinstance(value, StringField):
                 column_value = "'{}'".format(column_value)
             elif isinstance(value, IntegerField):
                 column_value = column_value
             args.append("{}={}".format(column_name, column_value))
     sql = "SELECT * FROM {}".format(self.__table__,) if len(args) == 0 else \
         "SELECT * FROM {} WHERE {}".format(self.__table__, " AND ".join(args))
     if self.__show_sql__:
         print sql
     try:
         results = config.execute(sql)
     except XssforkTaskError as e:
         raise XssforkTaskFindError(e)
     return results
Esempio n. 14
0
def compile( jail, dir, slug, code, tag="reference|student", translate_line=None ):
   
    os.makedirs( jail + dir, 0o755, exist_ok=True);
    os.chdir(jail + dir)
    
    # SAVE to FILE
    with open(slug + ".cs", "w", encoding="utf-8") as f:
      f.write(code)
      
    # remove previous compilation result (if such exists)
    if os.path.isfile( slug + '.exe' ):
        os.remove( slug + '.exe' )
    
    
    # COMPILE
    compiler_cmd = [cfg["cs_compiler"],   slug+".cs"]
    compiling = execute(compiler_cmd, "")
    
    def check_compile_err():
        
        if (compiling.stderr != "" or compiling.returncode != 0
        or not os.path.isfile(jail + dir + slug + suffix)):

            if 'student' in tag.lower():   #  humanreadable info for students
                errmsg = re.sub('(\.cs:)(\d+)(?!\d)',   # should  be adapted for C#
                       lambda m : m.group(1)+translate_line(m.group(2)),  
                       compiling.stderr)
                return ("Syntax Error", errmsg)
                
            else:     # for reference compilation - more detailed dump
                return  (
                    "Internal Error (Compiling %s)"%tag ,
                    "cmd:"+pre(" ".join(compiler_cmd))+ # websheet.slug + suffix
                    "<br>stdout:"+pre(compiling.stdout)+
                    "<br>stderr:"+pre(compiling.stderr)+
                    "<br>retval:"+pre(str(compiling.returncode))
                    )                    
                    
    compiling.error  =  check_compile_err()
    return compiling
Esempio n. 15
0
def pay_it_for_order(order_id):
    sql = text("update order_ set state = 'd' where id = :id")
    execute(sql, {'id': order_id})
Esempio n. 16
0
def set_order_trans(order_id, trans_id):
    sql = text('update order_ set trans_id = :trans where id = :order_id')
    execute(sql, {'trans': trans_id, 'order_id': order_id})
Esempio n. 17
0
def update_user(name, sex, phone):
    username = session.get('user_id')
    if not username:
        return None
    sql = text('update user set name = :name,sex= :sex, phone= :phone where username = :username')
    execute(sql, {'username': username, 'name': name, 'sex': sex, 'phone': phone})
Esempio n. 18
0
def register_user(user: User):
    sql = text("INSERT INTO user (username, password) VALUES (:name , :password)")
    return execute(sql, {"name": user.username, 'password': user.password})
Esempio n. 19
0
parser.add_option("--skip", dest="skip")
parser.add_option("--limit", dest="limit")

(options, args) = parser.parse_args()

if len(args) != 1:
    parser.print_help()
    exit(1)

#CCS.aliases = {'focal-plane': 'focal-plane-sim', 'bot-bench': 'bot-bench-sim'}
#CCS.aliases = {'focal-plane': 'ts8-fp', 'bot-bench': 'bot-bench' }

# Assume if run is set we are running under eTraveler
if options.run:
    fp = CCS.attachProxy('focal-plane')
    time.sleep(10.0)
    versions.write_versions(fp)
    configs.write_config(fp, ['Sequencer', 'Rafts'])

import config

cfg = config.parseConfig(args[0])
config.execute(
    cfg, {
        "dry_run": options.dry_run,
        "run": options.run,
        "symlink": options.symlink,
        "skip": options.skip,
        "limit": options.limit
    })
Esempio n. 20
0
 def listar_productos(self):
     prod = config.select(producto)
     result = config.execute(prod)
Esempio n. 21
0
def grade(reference_solution, student_solution, translate_line, websheet):
    cpp_compiler = config.config_jo["cpp_compiler"]

    unusable_cppflags = []

    # following http://bits.usc.edu/cs103/compile/
    default_cppflags = ["-g",
                        "-Wall", "-Wshadow", "-Wunreachable-code",
                        "-Wconversion",
                        "-Wno-sign-compare", "-Wno-write-strings"]
    if "clang" in cpp_compiler: # good options, but not in g++
        default_cppflags += ["-Wvla", "-Wno-shorten-64-to-32", "-Wno-sign-conversion", "-fsanitize=undefined"]
    else:
      unusable_cppflags = ["-Wno-array-bounds","-Wno-return-stack-address","-Wunreachable-code"]

    websheet.unusable_cppflags = unusable_cppflags

    # create a temp directory
    refdir = config.create_tempdir()
    studir = config.create_tempdir()

    # put slug.cpp
    jail = config.config_jo["java_jail-abspath"]
    refcpp = open(jail + refdir + websheet.slug + ".cpp", "w", encoding="utf-8")
    refcpp.write(reference_solution)
    refcpp.close()
    
    stucpp = open(jail + studir + websheet.slug + ".cpp", "w", encoding="utf-8")
    stucpp.write(student_solution)
    stucpp.close()
    
    suffix = ""
    if websheet.lang == "C++func": suffix = ".o"

    compile_list = [cpp_compiler] + websheet.cppflags(default_cppflags)
    
    compile_args = []
    if websheet.lang == "C++func":
      compile_args += ["-c"]      
    compile_args += [websheet.slug + ".cpp", "-o", websheet.slug + suffix]

    # build reference
    if not websheet.example:
      os.chdir(jail + refdir)
      refcompile = execute(compile_list + compile_args, "")
      if (refcompile.stderr != "" or refcompile.returncode != 0
          or not os.path.isfile(jail + refdir + websheet.slug + suffix)):
        return ("Internal Error (Compiling Reference)",
                "cmd:"+pre(" ".join(compile_list))+
                "<br>stdout:"+pre(refcompile.stdout)+
                "<br>stderr:"+pre(refcompile.stderr)+
                "<br>retval:"+pre(str(refcompile.returncode)))

    # build student
    os.chdir(jail + studir)
    stucompile = execute(compile_list + compile_args, "")
      
    result = "<div>Compiling: saving your code as "+tt(websheet.slug+".cpp")
    result += " and calling "+tt(" ".join(["compile"] + compile_args))
    if stucompile.stdout!="":
      result += pre(stucompile.stdout)
    result += "</div>"
    if (stucompile.stderr != "" or stucompile.returncode != 0
        or not os.path.isfile(jail + studir + websheet.slug + suffix)):
      msg = re.sub('(\.cpp:)(\d+)(?!\d)', 
                   lambda m : m.group(1)+translate_line(m.group(2)),
                   stucompile.stderr)
      result += "<div>Did not compile. Error message:"+pre(msg)+"</div>"
      return ("Syntax Error", result)

    if len(websheet.tests)==0:
      return ("Internal Error", "No tests defined!")

    def example_literal(cpptype):
      known = {"int":"0", "double":"0.0", "bool":"false", "char":"'x'", "string":'""', "char*": '(char*)NULL', "char[]": '""'}
      if cpptype in known: return known[cpptype]
      return None

    for test in websheet.tests:
      if websheet.lang =='C++func' and test[0]=="check-function":
        funcname = test[1]
        returntype = test[2]
        if (returntype == "void"):
          global void_functions
          void_functions += [funcname]
        argtypes = test[3]
        literals = [None] * len(argtypes)
        for i in range(len(literals)):
          literals[i] = example_literal(argtypes[i])
          if literals[i] == None:
            return ("Internal Error", tt("need example_literal for " + argtypes[i]))
        tester = student_solution 
        tester += "\n#include <iostream>\n" + returntype + "(*some_unique_identifier)(" + ', '.join(argtypes) + ") = &" + funcname + ";"
        tester += "\n" + " void even_uniquer() { " + funcname + "(" + ', '.join(literals) + ");}"
        tester += "\n" + "int main() {}\n"

        newslug = websheet.slug + "test"
        cpp = open(jail + refdir + newslug + ".cpp", "w")
        cpp.write(tester)
        cpp.close()

        compile_list = [cpp_compiler] + websheet.cppflags(default_cppflags)

        compile_list += [newslug + ".cpp", "-o", newslug + suffix]

        os.chdir(jail + refdir)
        refcompile = execute(compile_list, "")

        if (refcompile.stderr != "" or refcompile.returncode != 0
            or not os.path.isfile(jail + refdir + websheet.slug + suffix)):
          text = ("<div><!--"+refcompile.stderr+"-->"+
                  "You must define a function " 
                  + tt(funcname) + 
                  ( " taking no arguments" if len(argtypes)==0 else 
                    (" taking arguments of types " + tt(", ".join(argtypes))))
                  + " and with return type " + tt(returntype) + "</div>")

          return ("Failed Tests",
                  text + "<!--" +
                  "stdout:"+pre(refcompile.stdout)+
                  "<br>stderr:"+pre(refcompile.stderr)+
                  "<br>retval:"+pre(str(refcompile.returncode))
          +"-->"   )
              
        continue # check-function
      
      if websheet.lang=='C++func' and test[0]=="call-function":
        funcname = test[1]
        args = test[2]        
        testline = funcname + "(" + ', '.join(args) + ")"
        testmain = "\n#include <iostream>\nint main(){std::cout << std::showpoint << std::boolalpha;"
        if funcname not in void_functions: testmain += "std::cout << "
        testmain += testline + ";}\n"
        stutester = student_solution + testmain
        reftester = reference_solution + testmain
        newslug = websheet.slug + "test"

        compile_list = [cpp_compiler] + websheet.cppflags(default_cppflags)

        compile_list += [newslug + ".cpp", "-o", newslug]

        if not websheet.example:

          cpp = open(jail + refdir + newslug + ".cpp", "w")
#        print(reftester)
          cpp.write(reftester)
          cpp.close()
          os.chdir(jail + refdir)
          refcompile = execute(compile_list, "")

          if (refcompile.stderr != "" or refcompile.returncode != 0
              or not os.path.isfile(jail + refdir + newslug)):
            return ("Internal Error: Reference Type Check Failed",
                    "<!--" +
                    "stdout:"+pre(refcompile.stdout)+
                    "<br>stderr:"+pre(refcompile.stderr)+
                    "<br>retval:"+pre(str(refcompile.returncode))
                    +"-->"   )

        cpp = open(jail + studir + newslug + ".cpp", "w")
        cpp.write(stutester)
        cpp.close()
        os.chdir(jail + studir)
        stucompile = execute(compile_list, "")

        if (stucompile.stderr != "" or stucompile.returncode != 0
            or not os.path.isfile(jail + refdir + newslug)):
          return ("Internal Error: Type Check Failed",
                  "<!--" +
                  "stdout:"+pre(stucompile.stdout)+
                  "<br>stderr:"+pre(stucompile.stderr)+
                  "<br>retval:"+pre(str(stucompile.returncode))
          +"-->"   )
         # call-function
        if funcname in void_functions:
          result += "<div>Calling " + tt(testline) + "&hellip;</div>"
        else:
          result += "<div>Printing the result of calling " + tt(testline) + "&hellip;</div>"

        exename = newslug
        stdin = ""
        args = []

      if websheet.lang=='C++': # normal test, calling main
        stdin = ""
        args = []
        if 'stdin' in test:
          stdin = test['stdin']
        if 'args' in test:
          args = test['args']

        cmd = websheet.slug
        if len(args) > 0: cmd += " " + " ".join(args)
        result += "<div>Running " + tt("./" + cmd)

        if len(stdin) > 0: 
          result += " on input " + pre(stdin)
        else:
          result += "&hellip;"
        result += "</div>"

        exename = websheet.slug
      
      cfg = config.config_jo

      cmd = [cfg["safeexec-executable-abspath"]]
      cmd += ["--chroot_dir", cfg["java_jail-abspath"]]
      cmd += ["--exec_dir", "/" + refdir]
      cmd += ["--clock", "1"]
      cmd += ["--mem", "40000"]
      cmd += ["--exec", exename]
      cmd += args

      if not websheet.example:
        runref = execute(cmd, stdin)

        if runref.returncode != 0 or not runref.stderr.startswith("OK"):
          result += "<div>Reference solution crashed!"
          result += "<br>stdout:"+pre(runref.stdout)
          result += "stderr:"+pre(runref.stderr)
          result += "val:"+pre(str(runref.returncode))
          result += "</div>"
          return ("Internal Error", result)

      cmd = [cfg["safeexec-executable-abspath"]]
      cmd += ["--chroot_dir", cfg["java_jail-abspath"]]
      cmd += ["--exec_dir", "/" + studir]
      cmd += ["--clock", "1"]
      cmd += ["--mem", "40000"]
      cmd += ["--exec", exename]
      cmd += args

      runstu = execute(cmd, stdin, flag_badchars = True)
      if websheet.slug == "ascii_table":
          # this is the unique exercise where a corrcet solution uses a badchar
          runstu.stdout = runstu.stdout.replace("\\u007f", chr(127))
      if runstu.returncode != 0 or not runstu.stderr.startswith("OK"):
        result += "<div>Crashed! "
        errmsg = runstu.stderr
        if "elapsed time:" in errmsg:
          errmsg = errmsg[:errmsg.index("elapsed time:")]
        errmsg = errmsg.replace("Command terminated by signal (8: SIGFPE)",
                                "Floating point exception")
        errmsg = errmsg.replace("Command terminated by signal (11: SIGSEGV)",
                                "Segmentation fault (core dumped)")
        if errmsg != "":
          result += "Error messages:" + pre(errmsg)
        if runstu.stdout != "":
          result += "Produced this output:"+pre(runstu.stdout)
#        result += "Return code:"+pre(str(runstu.returncode))
        result += "</div>"
        return ("Sandbox Limit", result)
      
      if websheet.example:
        result += "<div>Printed this output:"
        result += pre(runstu.stdout) + "</div>"
        continue

      stucanon = re.sub(' +$', '', runstu.stdout, flags=re.MULTILINE)
      refcanon = re.sub(' +$', '', runref.stdout, flags=re.MULTILINE)

      if (stucanon == refcanon 
          or stucanon == refcanon + "\n" and not refcanon.endswith("\n")):
        result += "<div>Passed! Printed this correct output:"
        result += pre(runstu.stdout, True) + "</div>"
      elif stucanon == refcanon + "\n":
        result += "<div>Failed! Printed this output:"
        result += pre(runstu.stdout, True)
        result += "which is almost correct but <i>you printed an extra newline at the end</i>.</div>"
        return ("Failed Tests", result)
      elif refcanon == stucanon + "\n":
        result += "<div>Failed! Printed this output:"
        result += pre(runstu.stdout, True)
        result += "which is almost correct but <i>you are missing a newline at the end</i>.</div>"
        return ("Failed Tests", result)
      else:
        result += "<div>Failed! Printed this incorrect output:"
        result += pre(runstu.stdout, True)
        result += "Expected this correct output instead:"
        result += pre(runref.stdout, True) + "</div>"
        return ("Failed Tests", result)

    if websheet.example:
      return ("Example", result)
    else:
      result += "<div>Passed all tests!</div>"
      return ("Passed", result)
Esempio n. 22
0
def grade(reference_solution, student_solution, translate_line, websheet):
    cpp_compiler = config.config_jo["cpp_compiler"]

    unusable_cppflags = []

    # following http://bits.usc.edu/cs103/compile/
    default_cppflags = [
        "-g", "-Wall", "-Wshadow", "-Wunreachable-code", "-Wconversion",
        "-Wno-sign-compare", "-Wno-write-strings"
    ]
    if "clang" in cpp_compiler:  # good options, but not in g++
        default_cppflags += [
            "-Wvla", "-Wno-shorten-64-to-32", "-Wno-sign-conversion",
            "-fsanitize=undefined"
        ]
    else:
        unusable_cppflags = [
            "-Wno-array-bounds", "-Wno-return-stack-address",
            "-Wunreachable-code"
        ]

    websheet.unusable_cppflags = unusable_cppflags

    # create a temp directory
    refdir = config.create_tempdir()
    studir = config.create_tempdir()

    # put slug.cpp
    jail = config.config_jo["java_jail-abspath"]
    refcpp = open(jail + refdir + websheet.slug + ".cpp",
                  "w",
                  encoding="utf-8")
    refcpp.write(reference_solution)
    refcpp.close()

    stucpp = open(jail + studir + websheet.slug + ".cpp",
                  "w",
                  encoding="utf-8")
    stucpp.write(student_solution)
    stucpp.close()

    suffix = ""
    if websheet.lang == "C++func": suffix = ".o"

    compile_list = [cpp_compiler] + websheet.cppflags(default_cppflags)

    compile_args = []
    if websheet.lang == "C++func":
        compile_args += ["-c"]
    compile_args += [websheet.slug + ".cpp", "-o", websheet.slug + suffix]

    # build reference
    if not websheet.example:
        os.chdir(jail + refdir)
        refcompile = execute(compile_list + compile_args, "")
        if (refcompile.stderr != "" or refcompile.returncode != 0
                or not os.path.isfile(jail + refdir + websheet.slug + suffix)):
            return ("Internal Error (Compiling Reference)",
                    "cmd:" + pre(" ".join(compile_list)) + "<br>stdout:" +
                    pre(refcompile.stdout) + "<br>stderr:" +
                    pre(refcompile.stderr) + "<br>retval:" +
                    pre(str(refcompile.returncode)))

    # build student
    os.chdir(jail + studir)
    stucompile = execute(compile_list + compile_args, "")

    result = "<div>Compiling: saving your code as " + tt(websheet.slug +
                                                         ".cpp")
    result += " and calling " + tt(" ".join(["compile"] + compile_args))
    if stucompile.stdout != "":
        result += pre(stucompile.stdout)
    result += "</div>"
    if (stucompile.stderr != "" or stucompile.returncode != 0
            or not os.path.isfile(jail + studir + websheet.slug + suffix)):
        msg = re.sub('(\.cpp:)(\d+)(?!\d)',
                     lambda m: m.group(1) + translate_line(m.group(2)),
                     stucompile.stderr)
        result += "<div>Did not compile. Error message:" + pre(msg) + "</div>"
        return ("Syntax Error", result)

    if len(websheet.tests) == 0:
        return ("Internal Error", "No tests defined!")

    def example_literal(cpptype):
        known = {
            "int": "0",
            "double": "0.0",
            "bool": "false",
            "char": "'x'",
            "string": '""',
            "char*": '(char*)NULL',
            "char[]": '""'
        }
        if cpptype in known: return known[cpptype]
        return None

    for test in websheet.tests:
        if websheet.lang == 'C++func' and test[0] == "check-function":
            funcname = test[1]
            returntype = test[2]
            if (returntype == "void"):
                global void_functions
                void_functions += [funcname]
            argtypes = test[3]
            literals = [None] * len(argtypes)
            for i in range(len(literals)):
                literals[i] = example_literal(argtypes[i])
                if literals[i] == None:
                    return ("Internal Error",
                            tt("need example_literal for " + argtypes[i]))
            tester = student_solution
            tester += "\n#include <iostream>\n" + returntype + "(*some_unique_identifier)(" + ', '.join(
                argtypes) + ") = &" + funcname + ";"
            tester += "\n" + " void even_uniquer() { " + funcname + "(" + ', '.join(
                literals) + ");}"
            tester += "\n" + "int main() {}\n"

            newslug = websheet.slug + "test"
            cpp = open(jail + refdir + newslug + ".cpp", "w")
            cpp.write(tester)
            cpp.close()

            compile_list = [cpp_compiler] + websheet.cppflags(default_cppflags)

            compile_list += [newslug + ".cpp", "-o", newslug + suffix]

            os.chdir(jail + refdir)
            refcompile = execute(compile_list, "")

            if (refcompile.stderr != "" or refcompile.returncode != 0
                    or not os.path.isfile(jail + refdir + websheet.slug +
                                          suffix)):
                text = ("<div><!--" + refcompile.stderr + "-->" +
                        "You must define a function " + tt(funcname) +
                        (" taking no arguments" if len(argtypes) == 0 else
                         (" taking arguments of types " +
                          tt(", ".join(argtypes)))) +
                        " and with return type " + tt(returntype) + "</div>")

                return ("Failed Tests", text + "<!--" + "stdout:" +
                        pre(refcompile.stdout) + "<br>stderr:" +
                        pre(refcompile.stderr) + "<br>retval:" +
                        pre(str(refcompile.returncode)) + "-->")

            continue  # check-function

        if websheet.lang == 'C++func' and test[0] == "call-function":
            funcname = test[1]
            args = test[2]
            testline = funcname + "(" + ', '.join(args) + ")"
            testmain = "\n#include <iostream>\nint main(){std::cout << std::showpoint << std::boolalpha;"
            if funcname not in void_functions: testmain += "std::cout << "
            testmain += testline + ";}\n"
            stutester = student_solution + testmain
            reftester = reference_solution + testmain
            newslug = websheet.slug + "test"

            compile_list = [cpp_compiler] + websheet.cppflags(default_cppflags)

            compile_list += [newslug + ".cpp", "-o", newslug]

            if not websheet.example:

                cpp = open(jail + refdir + newslug + ".cpp", "w")
                #        print(reftester)
                cpp.write(reftester)
                cpp.close()
                os.chdir(jail + refdir)
                refcompile = execute(compile_list, "")

                if (refcompile.stderr != "" or refcompile.returncode != 0
                        or not os.path.isfile(jail + refdir + newslug)):
                    return ("Internal Error: Reference Type Check Failed",
                            "<!--" + "stdout:" + pre(refcompile.stdout) +
                            "<br>stderr:" + pre(refcompile.stderr) +
                            "<br>retval:" + pre(str(refcompile.returncode)) +
                            "-->")

            cpp = open(jail + studir + newslug + ".cpp", "w")
            cpp.write(stutester)
            cpp.close()
            os.chdir(jail + studir)
            stucompile = execute(compile_list, "")

            if (stucompile.stderr != "" or stucompile.returncode != 0
                    or not os.path.isfile(jail + refdir + newslug)):
                return ("Internal Error: Type Check Failed", "<!--" +
                        "stdout:" + pre(stucompile.stdout) + "<br>stderr:" +
                        pre(stucompile.stderr) + "<br>retval:" +
                        pre(str(stucompile.returncode)) + "-->")
            # call-function
            if funcname in void_functions:
                result += "<div>Calling " + tt(testline) + "&hellip;</div>"
            else:
                result += "<div>Printing the result of calling " + tt(
                    testline) + "&hellip;</div>"

            exename = newslug
            stdin = ""
            args = []

        if websheet.lang == 'C++':  # normal test, calling main
            stdin = ""
            args = []
            if 'stdin' in test:
                stdin = test['stdin']
            if 'args' in test:
                args = test['args']

            cmd = websheet.slug
            if len(args) > 0: cmd += " " + " ".join(args)
            result += "<div>Running " + tt("./" + cmd)

            if len(stdin) > 0:
                result += " on input " + pre(stdin)
            else:
                result += "&hellip;"
            result += "</div>"

            exename = websheet.slug

        cfg = config.config_jo

        cmd = [cfg["safeexec-executable-abspath"]]
        cmd += ["--chroot_dir", cfg["java_jail-abspath"]]
        cmd += ["--exec_dir", "/" + refdir]
        cmd += ["--clock", "1"]
        cmd += ["--mem", "40000"]
        cmd += ["--exec", exename]
        cmd += args

        if not websheet.example:
            runref = execute(cmd, stdin)

            if runref.returncode != 0 or not runref.stderr.startswith("OK"):
                result += "<div>Reference solution crashed!"
                result += "<br>stdout:" + pre(runref.stdout)
                result += "stderr:" + pre(runref.stderr)
                result += "val:" + pre(str(runref.returncode))
                result += "</div>"
                return ("Internal Error", result)

        cmd = [cfg["safeexec-executable-abspath"]]
        cmd += ["--chroot_dir", cfg["java_jail-abspath"]]
        cmd += ["--exec_dir", "/" + studir]
        cmd += ["--clock", "1"]
        cmd += ["--mem", "40000"]
        cmd += ["--exec", exename]
        cmd += args

        runstu = execute(cmd, stdin, flag_badchars=True)
        if websheet.slug == "ascii_table":
            # this is the unique exercise where a corrcet solution uses a badchar
            runstu.stdout = runstu.stdout.replace("\\u007f", chr(127))
        if runstu.returncode != 0 or not runstu.stderr.startswith("OK"):
            result += "<div>Crashed! "
            errmsg = runstu.stderr
            if "elapsed time:" in errmsg:
                errmsg = errmsg[:errmsg.index("elapsed time:")]
            errmsg = errmsg.replace("Command terminated by signal (8: SIGFPE)",
                                    "Floating point exception")
            errmsg = errmsg.replace(
                "Command terminated by signal (11: SIGSEGV)",
                "Segmentation fault (core dumped)")
            if errmsg != "":
                result += "Error messages:" + pre(errmsg)
            if runstu.stdout != "":
                result += "Produced this output:" + pre(runstu.stdout)
#        result += "Return code:"+pre(str(runstu.returncode))
            result += "</div>"
            return ("Sandbox Limit", result)

        if websheet.example:
            result += "<div>Printed this output:"
            result += pre(runstu.stdout) + "</div>"
            continue

        stucanon = re.sub(' +$', '', runstu.stdout, flags=re.MULTILINE)
        refcanon = re.sub(' +$', '', runref.stdout, flags=re.MULTILINE)

        if (stucanon == refcanon or stucanon == refcanon + "\n"
                and not refcanon.endswith("\n")):
            result += "<div>Passed! Printed this correct output:"
            result += pre(runstu.stdout, True) + "</div>"
        elif stucanon == refcanon + "\n":
            result += "<div>Failed! Printed this output:"
            result += pre(runstu.stdout, True)
            result += "which is almost correct but <i>you printed an extra newline at the end</i>.</div>"
            return ("Failed Tests", result)
        elif refcanon == stucanon + "\n":
            result += "<div>Failed! Printed this output:"
            result += pre(runstu.stdout, True)
            result += "which is almost correct but <i>you are missing a newline at the end</i>.</div>"
            return ("Failed Tests", result)
        else:
            result += "<div>Failed! Printed this incorrect output:"
            result += pre(runstu.stdout, True)
            result += "Expected this correct output instead:"
            result += pre(runref.stdout, True) + "</div>"
            return ("Failed Tests", result)

    if websheet.example:
        return ("Example", result)
    else:
        result += "<div>Passed all tests!</div>"
        return ("Passed", result)
Esempio n. 23
0
def compile(jail,
            dir,
            slug,
            code,
            tag="reference|student",
            translate_line=None):

    os.makedirs(jail + dir, 0o755, exist_ok=True)
    os.chdir(jail + dir)

    # SAVE to FILE
    with open(slug + ".cpp", "w", encoding="utf-8") as f:
        f.write(code)

    # remove previous compilation result (if such exists)
    if os.path.isfile(slug):
        os.remove(slug)

    # COMPILE
    default_cppflags = [
        "-g", "-Wall", "-Wshadow", "-Wunreachable-code", "-Wconversion",
        "-Wno-sign-compare", "-Wno-write-strings"
    ]
    if "clang" in cfg["cpp_compiler"]:  # good options, but not in g++
        default_cppflags += [
            "-Wvla", "-Wno-shorten-64-to-32", "-Wno-sign-conversion",
            "-fsanitize=undefined"
        ]
    else:
        unusable_cppflags = [
            "-Wno-array-bounds", "-Wno-return-stack-address",
            "-Wunreachable-code"
        ]

    compile_args = [slug + ".cpp", "-o", slug]

    #~ def cppflags( defaultflags):
    #~ flags = [i for i in defaultflags if i not in self.cppflags_remove]
    #~ flags += self.cppflags_add
    #~ return [i for i in flags if i not in self.unusable_cppflags]
    #~
    #~ compile_list = [cpp_compiler] + cppflags(default_cppflags)

    compiler_cmd = [cfg["cpp_compiler"]] + default_cppflags + compile_args

    compiling = execute(compiler_cmd, "")

    def check_compile_err():

        if (compiling.stderr != "" or compiling.returncode != 0
                or not os.path.isfile(jail + dir + slug + suffix)):

            if 'student' in tag.lower():  #  humanreadable info for students
                errmsg = re.sub(
                    '(\.cpp:)(\d+)(?!\d)',  # should  be adapted for C#
                    lambda m: m.group(1) + translate_line(m.group(2)),
                    compiling.stderr)
                return ("Syntax Error", errmsg)

            else:  # for reference compilation - more detailed dump
                return (
                    "Internal Error (Compiling %s)" % tag,
                    "cmd:" +
                    pre(" ".join(compiler_cmd)) +  # websheet.slug + suffix
                    "<br>stdout:" + pre(compiling.stdout) + "<br>stderr:" +
                    pre(compiling.stderr) + "<br>retval:" +
                    pre(str(compiling.returncode)))

    compiling.error = check_compile_err()
    return compiling
Esempio n. 24
0
CCS.setDefaultTimeout(Duration.ofSeconds(30))

# Parse command line options

parser = OptionParser()
parser.add_option("--dry-run",
                  action="store_true",
                  dest="dry_run",
                  default=False)
parser.add_option("-9", "--ds9", action="store_true", dest="ds9")
parser.add_option("--run", dest="run")
parser.add_option("--symlink", dest="symlink")
(options, args) = parser.parse_args()

if len(args) != 1:
    parser.print_help()
    exit(1)

#CCS.aliases = {'focal-plane': 'focal-plane-sim', 'bot-bench': 'bot-bench-sim'}
#CCS.aliases = {'focal-plane': 'focal-plane-sim'}
#ccs_sub.write_versions()

import config

cfg = config.parseConfig(args[0])
config.execute(cfg, {
    "dry_run": options.dry_run,
    "run": options.run,
    "symlink": options.symlink
})
Esempio n. 25
0
def compile( jail, dir, slug, code, tag="reference|student", translate_line=None ):
   
    os.makedirs( jail + dir, 0o755, exist_ok=True);
    os.chdir(jail + dir)
    
    # SAVE to FILE
    with open(slug + ".cpp", "w", encoding="utf-8") as f:
      f.write(code)
      
    # remove previous compilation result (if such exists)
    if os.path.isfile( slug ):
        os.remove( slug )
    
    
    # COMPILE
    default_cppflags = ["-g",
                        "-Wall", "-Wshadow", "-Wunreachable-code",
                        "-Wconversion",
                        "-Wno-sign-compare", "-Wno-write-strings"]
    if "clang" in cfg["cpp_compiler"]: # good options, but not in g++
        default_cppflags += ["-Wvla", "-Wno-shorten-64-to-32", "-Wno-sign-conversion", "-fsanitize=undefined"]
    else:
      unusable_cppflags = ["-Wno-array-bounds","-Wno-return-stack-address","-Wunreachable-code"]

    
    compile_args = [slug + ".cpp", "-o", slug]

    #~ def cppflags( defaultflags):
        #~ flags = [i for i in defaultflags if i not in self.cppflags_remove]
        #~ flags += self.cppflags_add
        #~ return [i for i in flags if i not in self.unusable_cppflags]
#~ 
    #~ compile_list = [cpp_compiler] + cppflags(default_cppflags)
    
    compiler_cmd = [cfg["cpp_compiler"]] + default_cppflags + compile_args

    compiling = execute(compiler_cmd, "")

    
    def check_compile_err():
        
        if (compiling.stderr != "" or compiling.returncode != 0
        or not os.path.isfile(jail + dir + slug + suffix)):

            if 'student' in tag.lower():   #  humanreadable info for students
                errmsg = re.sub('(\.cpp:)(\d+)(?!\d)',   # should  be adapted for C#
                       lambda m : m.group(1)+translate_line(m.group(2)),  
                       compiling.stderr)
                return ("Syntax Error", errmsg)
                
            else:     # for reference compilation - more detailed dump
                return  (
                    "Internal Error (Compiling %s)"%tag ,
                    "cmd:"+pre(" ".join(compiler_cmd))+ # websheet.slug + suffix
                    "<br>stdout:"+pre(compiling.stdout)+
                    "<br>stderr:"+pre(compiling.stderr)+
                    "<br>retval:"+pre(str(compiling.returncode))
                    )                    
                    
    compiling.error  =  check_compile_err()
    return compiling