/// <summary>
        /// Constructor.
        /// </summary>
        public ViewFeedbackResult(
            Section section,
            Submission submission,
            IList<Checkpoint> checkpoints)
        {
            LastName = submission.Commit.User.LastName;
            FirstName = submission.Commit.User.FirstName;
            UserId = submission.Commit.User.Id;
            RepoName = submission.Commit.GetRepoName();
            SubmissionId = submission.Id;
            PullRequestNumber = submission.PullRequestNumber;
            PushDate = submission.Commit.PushDate;
            Feedback = submission.Feedback;
            Unread = submission.DateFeedbackRead == null;

            var dueDate = submission.Checkpoint
                .SectionDates
                ?.FirstOrDefault(sd => sd.Section == section)
                ?.DueDate;

            FutureCheckpoints = dueDate != null
                && submission.Checkpoint
                    .Project
                    .Checkpoints
                    .Any
                    (
                        c => c.SectionDates?.Any
                        (
                            sd => sd.SectionId == section.Id && sd.DueDate > dueDate.Value
                        ) ?? false
                    );
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 public PastSubmissionResult(Submission submission, Section section)
 {
     CheckpointDisplayName = submission.Checkpoint.DisplayName;
     CommitDate = submission.Commit.PushDate;
     DaysLate = submission.GetDaysLate(section);
     PullRequestNumber = submission.PullRequestNumber;
     Feedback = submission.Feedback;
     Build = submission.Commit.Build;
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 public UserSubmissionResult(
     Section section,
     Checkpoint checkpoint,
     Submission submission)
 {
     CheckpointName = checkpoint.Name;
     CheckpointDisplayName = checkpoint.DisplayName;
     CheckpointDueDate = checkpoint.SectionDates
         .Single(sd => sd.Section == section)
         .DueDate;
     Submission = submission;
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 public SectionSubmissionResult(
     User user,
     Submission submission)
 {
     LastName = user.LastName;
     FirstName = user.FirstName;
     UserId = user.Id;
     CommitDate = submission?.Commit?.PushDate;
     PullRequestNumber = submission?.PullRequestNumber;
     BuildId = submission?.Commit?.Build?.Id;
     Commit = submission?.Commit;
 }
        /// <summary>
        /// Constructor.
        /// </summary>
        public GradeSubmissionResult(
            User user,
            Section section,
            Submission currentSubmission,
            IList<Submission> pastSubmissions)
        {
            LastName = user.LastName;
            FirstName = user.FirstName;
            SubmissionId = currentSubmission.Id;
            CommitDate = currentSubmission.Commit.PushDate;
            DaysLate = currentSubmission.GetDaysLate(section);
            PullRequestNumber = currentSubmission.PullRequestNumber;
            Feedback = currentSubmission.Feedback;
            FeedbackSent = currentSubmission.FeedbackSent;
            Build = currentSubmission.Commit.Build;
            PastSubmissions = pastSubmissions
                .Select(ps => new PastSubmissionResult(ps, section))
                .ToList();

            RequiredTestsPassed =
                currentSubmission.Commit.Build.Status == BuildStatus.Completed &&
                currentSubmission.Commit.Build.TestResults
                    .Select
                    (
                        tr => new
                        {
                            Required = currentSubmission.Checkpoint
                                .TestClasses
                                .FirstOrDefault
                                (
                                    tc => tc.TestClass.ClassName == tr.ClassName
                                )?.Required ?? false,
                            Passed = tr.Succeeded
                        }
                    )
                    .All
                    (
                        tr => !tr.Required || tr.Passed
                    );
        }
        public ReplResult Execute(string inp)
        {
            new PermissionSet(PermissionState.Unrestricted).Assert();

            result = new ReplResult();
            lock (lockObject)
            {
                try
                {
                    submission = Session.CompileSubmission<object>(inp);

                    var thread = new Thread(new ParameterizedThreadStart(ExecuteSubmission), 1024 * 1024);
                    thread.Start(submission);
                    if (!thread.Join(4000))
                    {
                        thread.Abort();
                    }
                    if (!thread.Join(500))
                    {
                        // Some kind of submission that can't be aborted, process needs to die
                        result.ExecutionStillOngoing = true;
                    }
                }
                catch (CompilationErrorException ex)
                {
                    result.CompilationErrors = ex.Diagnostics.Select(x => x.Info.ToString()).ToArray();
                }
                catch (Exception ex)
                {
                    result.ExecutionResult = ex.ToString();
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                }
            }

            return result;
        }
        private void SubmissionPage_Loaded(object sender, RoutedEventArgs e)
        {
           
            if (NavigationContext.QueryString.Contains(new KeyValuePair<string,string>("type","tobesubmit")))
            {
                App.currentSubmissionIndex = Convert.ToInt32(NavigationContext.QueryString["selectedItem"]);
                //if (App.currentSubmissionIndex >= App.toBeSubmit.Count()); TODO problem
                Submission currentSub = App.toBeSubmit[App.currentSubmissionIndex];
                LoadSavedImage(currentSub);
                LoadContent(currentSub);
                LoadButtons();

            }
            else if (NavigationContext.QueryString.Contains(new KeyValuePair<string, string>("type", "submission")))
            {
                if (NetworkInterface.GetIsNetworkAvailable())
                {
                    SubmissionProgressBar.IsIndeterminate = true;
                }
                String lowResImageName = NavigationContext.QueryString["selectedItem"];
                Submission currentSub = new Submission();
                for (int i = 0; i < App.sentSubmissions.Count; i++)
                {
                    if (App.sentSubmissions[i].LowResImageName == lowResImageName)
                    {
                        LoadSubmittedImage(App.sentSubmissions[i]);
                       LoadContent(App.sentSubmissions[i]);
                      
                        return;
                    }
                }
               
            }


        }
Example #8
0
        public async Task <ActionResult <string> > Create(Submission submission)
        {
            var referenceNumber = await commandBus.Invoke <string>(new PersistSupplierSubmissionCommand(submission));

            return(new JsonResult(new { submissionId = referenceNumber, referenceNumber }));
        }
Example #9
0
        // TODO: Extract common logic between SubmitBinaryFile and Submit methods
        public ActionResult SubmitBinaryFile(BinarySubmissionModel participantSubmission, bool official, int?returnProblem)
        {
            if (participantSubmission?.File == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, Resource.ContestsGeneral.Upload_file);
            }

            var problem = this.Data.Problems.All().FirstOrDefault(x => x.Id == participantSubmission.ProblemId);

            if (problem == null)
            {
                throw new HttpException((int)HttpStatusCode.Unauthorized, Resource.ContestsGeneral.Problem_not_found);
            }

            if (official && !this.ValidateContestIp(this.Request.UserHostAddress, problem.ContestId))
            {
                return(this.RedirectToAction("NewContestIp", new { id = problem.ContestId }));
            }

            var participant = this.Data.Participants.GetWithContest(problem.ContestId, this.UserProfile.Id, official);

            if (participant == null)
            {
                throw new HttpException((int)HttpStatusCode.Unauthorized, Resource.ContestsGeneral.User_is_not_registered_for_exam);
            }

            this.ValidateContest(participant.Contest, official);
            ValidateSubmissionType(participantSubmission.SubmissionTypeId, participant.Contest);

            if (this.Data.Submissions.HasSubmissionTimeLimitPassedForParticipant(participant.Id, participant.Contest.LimitBetweenSubmissions))
            {
                throw new HttpException((int)HttpStatusCode.ServiceUnavailable, Resource.ContestsGeneral.Submission_was_sent_too_soon);
            }

            if (problem.SourceCodeSizeLimit < participantSubmission.File.ContentLength)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, Resource.ContestsGeneral.Submission_too_long);
            }

            // Validate submission type existence
            var submissionType = this.Data.SubmissionTypes.GetById(participantSubmission.SubmissionTypeId);

            if (submissionType == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, Resource.ContestsGeneral.Invalid_request);
            }

            // Validate if binary files are allowed
            if (!submissionType.AllowBinaryFilesUpload)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, Resource.ContestsGeneral.Binary_files_not_allowed);
            }

            // Validate file extension
            if (!submissionType.AllowedFileExtensionsList.Contains(
                    participantSubmission.File.FileName.GetFileExtension()))
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, Resource.ContestsGeneral.Invalid_extention);
            }

            if (!this.ModelState.IsValid)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, Resource.ContestsGeneral.Invalid_request);
            }

            var newSubmission = new Submission
            {
                Content          = participantSubmission.File.InputStream.ToByteArray(),
                FileExtension    = participantSubmission.File.FileName.GetFileExtension(),
                ProblemId        = participantSubmission.ProblemId,
                SubmissionTypeId = participantSubmission.SubmissionTypeId,
                ParticipantId    = participant.Id
            };

            this.Data.Submissions.Add(newSubmission);

            this.Data.SaveChanges();

            this.TempData.Add(GlobalConstants.InfoMessage, Resource.ContestsGeneral.Solution_uploaded);
            return(this.Redirect(string.Format("/Contests/{2}/Index/{0}#{1}", problem.ContestId, returnProblem ?? 0, official ? CompeteActionName : PracticeActionName)));
        }
Example #10
0
 public ErrorCode SetAggregationStrategyInterval(Submission method, uint intervalMsOrCount)
 {
     return((ErrorCode)TuningFork_setAggregationStrategyInterval(method, intervalMsOrCount));
 }
Example #11
0
 public IActionResult Update([FromBody] Submission submission)
 {
     return(Ok());
 }
        private void SeedCategoryContestProblem(IOjsDbContext context)
        {
            foreach (var categoryToBeDeleted in context.ContestCategories)
            {
                context.ContestCategories.Remove(categoryToBeDeleted);
            }

            foreach (var contestToBeDeleted in context.Contests)
            {
                context.Contests.Remove(contestToBeDeleted);
            }

            foreach (var problemToBeDeleted in context.Problems)
            {
                context.Problems.Remove(problemToBeDeleted);
            }

            var category = new ContestCategory
            {
                Name      = "Category",
                OrderBy   = 1,
                IsVisible = true,
                IsDeleted = false,
            };

            var otherCategory = new ContestCategory
            {
                Name      = "Other Category",
                OrderBy   = 1,
                IsVisible = true,
                IsDeleted = false,
            };

            var contest = new Contest
            {
                Name              = "Contest",
                OrderBy           = 1,
                PracticeStartTime = DateTime.Now.AddDays(-2),
                StartTime         = DateTime.Now.AddDays(-2),
                IsVisible         = true,
                IsDeleted         = false,
                Category          = category
            };

            var otherContest = new Contest
            {
                Name              = "Other Contest",
                OrderBy           = 2,
                PracticeStartTime = DateTime.Now.AddDays(-2),
                StartTime         = DateTime.Now.AddDays(-2),
                IsVisible         = true,
                IsDeleted         = false,
                Category          = category
            };

            var problemGroup1 = new ProblemGroup
            {
                OrderBy = 0,
                Contest = contest
            };

            var problemGroup2 = new ProblemGroup
            {
                OrderBy = 1,
                Contest = contest
            };

            var problem = new Problem
            {
                Name          = "Problem",
                MaximumPoints = 100,
                TimeLimit     = 10,
                MemoryLimit   = 10,
                OrderBy       = 1,
                ShowResults   = true,
                IsDeleted     = false,
                ProblemGroup  = problemGroup1
            };

            var otherProblem = new Problem
            {
                Name          = "Other Problem",
                MaximumPoints = 100,
                TimeLimit     = 10,
                MemoryLimit   = 10,
                OrderBy       = 1,
                ShowResults   = true,
                IsDeleted     = false,
                ProblemGroup  = problemGroup2
            };

            var test = new Test
            {
                InputDataAsString  = "Input",
                OutputDataAsString = "Output",
                OrderBy            = 0,
                IsTrialTest        = false,
                Problem            = problem,
            };

            var user = new UserProfile
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            var participant = new Participant
            {
                Contest    = contest,
                IsOfficial = false,
                User       = user
            };

            var submission = new Submission
            {
                Problem     = problem,
                Participant = participant,
                CreatedOn   = DateTime.Now
            };

            for (int i = 0; i < 10; i++)
            {
                test.TestRuns.Add(new TestRun
                {
                    MemoryUsed       = 100,
                    TimeUsed         = 100,
                    CheckerComment   = "Checked!",
                    ExecutionComment = "Executed!",
                    ResultType       = TestRunResultType.CorrectAnswer,
                    Submission       = submission
                });
            }

            context.Problems.Add(problem);
            context.Problems.Add(otherProblem);
            context.Contests.Add(otherContest);
            context.ContestCategories.Add(otherCategory);
            context.Tests.Add(test);
        }
 public static SubmissionModel BuildFromSubmission(Submission submission)
 {
     return(new SubmissionModel(submission.Id, submission.Filename, submission.DateSubmitted, submission.Entries.Select(x => SubmissionEntryModel.BuildFromSubmissionEntry(x))));
 }
Example #14
0
 public override string ToString()
 {
     return($"Id: {Id}, Title: {Title}, Description is: {Description} and submission date is: {Submission.ToShortDateString()}");
 }
Example #15
0
 internal List <Conference> LoadConferences(Submission submissionProxy)
 {
     throw new NotImplementedException();
 }
Example #16
0
        public async Task <IActionResult> Upload(List <IFormFile> component_zipfile, string component_title, string component_description)
        {
            var submission = new Submission()
            {
                FolderGuid  = Guid.NewGuid(),
                Timestamp   = DateTime.Now,
                Description = component_description,
                Title       = component_title,
                CreatorId   = 1
            };

            _context.Submissions.Add(submission);
            _context.SaveChanges();



            if (component_zipfile.Count == 0)
            {
                return(new StatusCodeResult(400));
            }

            IFormFile file = component_zipfile[0];

            long size = file.Length;

            var filePath = Path.GetTempFileName();

            //ZipFile.Extract

            string directory       = $"submissions/{submission.FolderGuid}/";
            string compressedPath  = $"{directory}/compressed.zip";
            string destinationPath = $"{directory}/src/";

            if (size > 0)
            {
                if (!Directory.Exists(directory))
                {
                    System.IO.Directory.CreateDirectory(destinationPath);
                }


                using (var stream = System.IO.File.Create(compressedPath))
                {
                    await file.CopyToAsync(stream);
                }



                ZipFile.ExtractToDirectory(compressedPath, destinationPath);
            }

            /*
             * After unpack, screenshot this site
             */

            Capture capture = new Capture($"https://localhost:44306/submissions/{submission.FolderGuid}/src/index.html", $"{directory}/thumbnail.png");



            //return Ok(new { file.FileName, size, submission.FolderGuid });
            return(Redirect("http://localhost:4200/upload"));
        }
Example #17
0
        public async Task <bool> RemoveAsync(string smeu, ulong author)
        {
            using (SmeuContext database = smeuBaseFactory.GetSmeuBase())
            {
                // first check if this combination is a duplicate
                Duplicate duplicate = (from d in database.Duplicates
                                       where d.Author == author && d.Original.Smeu == smeu
                                       orderby d.Date descending
                                       select d).FirstOrDefault();

                if (duplicate != null)
                {
                    // remove the duplicate
                    IMessage msg = await(client.GetChannel(settings.SmeuChannelId) as IMessageChannel).GetMessageAsync(duplicate.MessageId);
                    await msg.DeleteAsync();

                    database.Duplicates.Remove(duplicate);
                    await database.SaveChangesAsync();

                    return(true);
                }

                // check if there is an original
                Submission submission = await(from s in database.Submissions
                                              where s.Author == author && s.Smeu == smeu
                                              select s).Include(x => x.Duplicates).FirstOrDefaultAsync();

                if (submission != null)
                {
                    // remove the original message
                    IMessage msg = await(client.GetChannel(settings.SmeuChannelId) as IMessageChannel).GetMessageAsync(submission.MessageId);
                    await msg.DeleteAsync();

                    // check if a duplicate must take this submission's place
                    if (submission.Duplicates.Count > 0)
                    {
                        duplicate = (from d in submission.Duplicates
                                     orderby d.Date ascending
                                     select d).First();

                        // change details of this submission to the first duplicate
                        submission.Author    = duplicate.Author;
                        submission.Date      = duplicate.Date;
                        submission.MessageId = duplicate.MessageId;

                        database.Submissions.Update(submission);
                        database.Duplicates.Remove(duplicate);
                    }
                    else
                    {
                        database.Submissions.Remove(submission);
                    }

                    await database.SaveChangesAsync();

                    return(true);
                }

                return(false);
            }
        }
Example #18
0
        public IActionResult Edit(int id, [Bind("SubmissionId,SubmissionName,SubmissionServiceId, SubmissionStatusId,SubmissionPlacementStartDate,SubmissionReferralId, SubmissionArchiveReasonId")] Submission submission)
        {
            if (id != submission.SubmissionId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                _context.Update(submission);
                // get referral
                var referral = _context.Referral
                               .Where(r => r.ReferralId == submission.SubmissionReferralId).FirstOrDefault();

                submission.SubmissionReferral = referral;

                var service = _context.Service
                              .Where(r => r.ServiceId == submission.SubmissionServiceId).FirstOrDefault();

                submission.SubmissionService = service;

                var subrefid = submission.SubmissionReferralId;

                // Submission model = await _context.Submission.FindAsync(id);

                if (submission.SubmissionStatusId == 1)
                {
                    Placement model = new Placement();
                    model.PlacementRefId            = referral.ReferralName;
                    model.PlacementServiceId        = submission.SubmissionServiceId;
                    model.PlacementType             = referral.ReferralType;
                    model.PlacementGenderId         = referral.ReferralGenderId;
                    model.PlacementLocalAuthorityId = referral.ReferralLocalAuthorityId;

                    try
                    {
                        _context.Update(model);
                    }
                    catch (Exception)
                    {
                        throw;
                    }

                    //If a submission has been set to 'Placed', update the referral to placed.

                    try
                    {
                        referral.ReferralStatusId = 1;
                        _context.SaveChanges();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }



                // Update the referral with the highest status (actually the lowest)
                var allsubmissions = _context.Submission.Where(s => s.SubmissionReferralId == referral.ReferralId);

                int?highest = 8;
                //int subid = 6;

                foreach (Submission s in allsubmissions)
                {
                    //var substat = _context.Status.Where(r => r.StatusId == s.SubmissionStatusId);

                    if (s.SubmissionStatusId < highest && s.SubmissionStatusId > 2)
                    {
                        highest = s.SubmissionStatusId;
                        //subid = s.SubmissionStatus.StatusId;
                    }
                }

                /* only  update referral if status is not Archived  or Placed (the Archive  decison made at head office and is made directly on the referral record
                 * because if all submissions are rejected by the services, head-office may submit to other services. Does this need to be confirmed with Kerry?*/



                if (highest > 2 & referral.ReferralStatusId > 2)
                {
                    referral.ReferralStatusId = (int)highest;
                    try
                    {
                        _context.Update(referral);
                        _context.SaveChanges();
                    }
                    catch (Exception)
                    { throw; }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(submission));
        }
        private static string[] doSend()
        {
            System.Console.WriteLine("Starting send");
            GLExchange pdClient = new GLExchange(getPDConfig());

            string sourceLanguage = ConfigurationManager.AppSettings[CONFIG_SOURCE_LANGUAGE];

            if (string.IsNullOrEmpty(sourceLanguage))
            {
                throw new Exception("Configuration option '" + CONFIG_SOURCE_LANGUAGE + "' is not set");
            }
            string targetLanguagesStr = ConfigurationManager.AppSettings[CONFIG_TARGET_LANGUAGES];

            if (string.IsNullOrEmpty(targetLanguagesStr))
            {
                throw new Exception("Configuration option '" + CONFIG_TARGET_LANGUAGES + "' is not set");
            }
            string fileFormat = ConfigurationManager.AppSettings[CONFIG_FILE_FORMAT];

            if (string.IsNullOrEmpty(fileFormat))
            {
                throw new Exception("Configuration option '" + CONFIG_FILE_FORMAT + "' is not set");
            }
            HashSet <String> targetLanguages = new HashSet <string>();

            if (targetLanguagesStr.IndexOf(CONFIG_SEPARATOR) > 0)
            {
                string[] langsArray = targetLanguagesStr.Split(new char[] { CONFIG_SEPARATOR }, StringSplitOptions.RemoveEmptyEntries);
                if (langsArray.Length > 0)
                {
                    foreach (string lang in langsArray)
                    {
                        if (lang.Trim().Length > 1)
                        {
                            targetLanguages.Add(lang.Trim());
                        }
                    }
                }
            }
            else
            {
                if (targetLanguagesStr.Trim().Length > 1)
                {
                    targetLanguages.Add(targetLanguagesStr.Trim());
                }
            }
            if (targetLanguages.Count <= 0)
            {
                throw new Exception("Not able to find target languages");
            }

            string shortcode = ConfigurationManager.AppSettings[CONFIG_PROJECT];

            if (string.IsNullOrEmpty(shortcode))
            {
                throw new Exception("Configuration option '" + CONFIG_PROJECT + "' is not set");
            }
            Project project = pdClient.getProject(shortcode);

            DateTime   dt         = DateTime.Now;
            DateTime   dueDate    = dt.AddDays(5); // get this from the UI, i am hard coding to 5 days from now
            Submission submission = new Submission();

            submission.name    = "GLC_Sample_Code_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm");
            submission.project = project;
            submission.dueDate = dueDate;

            pdClient.initSubmission(submission);

            string folder = SOURCE_ROOT_FOLDER + sourceLanguage;

            string[] filePaths;
            try
            {
                filePaths = Directory.GetFiles(folder);
            }
            catch (Exception ex)
            {
                throw new Exception("Directory '" + folder + "' not found." + ex.Message);
            }

            string report = "";

            foreach (string filePath in filePaths)
            {
                // read file into memory stream
                MemoryStream m          = new MemoryStream();
                FileStream   fileStream = File.OpenRead(filePath);
                m.SetLength(fileStream.Length);
                fileStream.Read(m.GetBuffer(), 0, (int)fileStream.Length);
                string filename = filePath.Substring(filePath.LastIndexOf("\\") + 1);

                Document document = new Document();
                document.fileformat      = fileFormat;
                document.name            = filename;
                document.sourceLanguage  = sourceLanguage;
                document.targetLanguages = targetLanguages.ToArray <String>();
                document.setDataFromMemoryStream(m);

                string ticket = null;
                try
                {
                    ticket = pdClient.uploadTranslatable(document);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    m.Flush();
                    m.Close();
                    fileStream.Close();
                }
                if (ticket != null)
                {
                    report += filePath + " -> " + ticket + "\n";
                }
            }

            System.Console.WriteLine(report);

            string[] submissionTickets = pdClient.startSubmission();
            System.Console.WriteLine("Started Sub : " + submission.name + " [" + submissionTickets[0] + "]");

            return(submissionTickets);
        }
Example #20
0
    protected void SubmissionButton_Click(object sender, EventArgs e)
    {
        if (SubmissionUpload.HasFile)
        {
            try
            {
                ApplicationDbContext dbContext = new ApplicationDbContext();

                string fileName = Path.GetFileName(SubmissionUpload.FileName);
                string fileType = Path.GetExtension(fileName).Replace(".", "");

                Assignment CurrentAssignment = (Assignment)Session["CurrentAssignment"];

                Assignment assignment = dbContext.Assignments.Where(a => a.Id == CurrentAssignment.Id).FirstOrDefault();

                var sub = dbContext.Submissions.Where(s => s.Member.Id == member.Id && s.Assignment.Id == assignment.Id && s.Course.Id == course.Id).FirstOrDefault();

                Submission submission;

                if (sub != null)
                {
                    submission = dbContext.Submissions.Find(sub.Id);
                }
                else
                {
                    submission = new Submission();
                }

                submission.Title    = SubmissionUpload.FileName;
                submission.FileType = fileType;
                submission.Data     = SubmissionUpload.FileBytes;

                submission.Assignment = dbContext.Assignments.Where(a => a.Id == CurrentAssignment.Id).FirstOrDefault();
                submission.Member     = dbContext.Members.Where(m => m.Id == member.Id).FirstOrDefault();
                submission.Course     = dbContext.Courses.Where(c => c.Id == course.Id).FirstOrDefault();

                if (sub == null)
                {
                    dbContext.Submissions.Add(submission);
                }

                dbContext.SaveChanges();

                SubmissionRepeater.DataBind();

                HomePanel.Visible       = false;
                AssignmentPanel.Visible = true;

                ActivePanelLabel.Text = "Assignments";
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Response.Write(string.Format("Property: {0} Error: {1}",
                                                     validationError.PropertyName,
                                                     validationError.ErrorMessage));
                    }
                }
            }
        }
    }
Example #21
0
        public ActionResult SaveUploadedFile(int Id)
        {
            var isSavedSuccessfully = true;
            var fName = "";

            try
            {
                var task = projectTasksRepository.GetProjectTaskById(Id);
                // Checking if all files are required
                foreach (string fileName in Request.Files)
                {
                    var file = Request.Files[fileName];
                    //Save file content goes here
                    fName = file.FileName;

                    if (!task.FilesRequired.Any(i => i.Name == fName))
                    {
                        Response.ClearHeaders();
                        Response.ClearContent();
                        Response.StatusCode        = 400;
                        Response.StatusDescription = "File not allowed";
                        Response.ContentType       = "application/json";
                        return(Json(new { Message = "File is not in this Task. See required files above." }));
                    }
                }

                if (Request.Files.Count == task.FilesRequired.Count)
                {
                    var newSubmission = new Submission {
                        ProjectTaskId = task.Id, Created = DateTime.Now, ApplicationUsers = new List <ApplicationUser>()
                    };

                    // Add group members to submission
                    var members = 0;
                    foreach (var k in Request.Form.Keys)
                    {
                        var key    = k.ToString();
                        var userId = Request.Form[key];
                        if (key.StartsWith("user") && !string.IsNullOrEmpty(userId) && members <= task.MaxGroupSize)
                        {
                            members++;
                            newSubmission.ApplicationUsers.Add(db.Users.FirstOrDefault(i => i.Id == userId));
                            db.Submissions.Add(newSubmission);
                        }
                    }
                    // Add current user to submission
                    var currentUserId = User.Identity.GetUserId();
                    var currentUser   = db.Users.FirstOrDefault(i => i.Id == currentUserId);
                    newSubmission.ApplicationUsers.Add(currentUser);
                    db.Submissions.Add(newSubmission);
                    db.SaveChanges();

                    // All files are valid and all files are there, so we save them
                    foreach (string fileName in Request.Files)
                    {
                        var file = Request.Files[fileName];

                        if (file != null && file.ContentLength > 0)
                        {
                            var originalDirectory = new DirectoryInfo(string.Format("{0}Uploads\\Submissions", Server.MapPath(@"\")));

                            var pathString = Path.Combine(originalDirectory.ToString(), newSubmission.Id.ToString());

                            var fileName1 = Path.GetFileName(file.FileName);

                            var isExists = Directory.Exists(pathString);

                            if (!isExists)
                            {
                                Directory.CreateDirectory(pathString);
                            }

                            var path = string.Format("{0}\\{1}", pathString, file.FileName);
                            file.SaveAs(path);
                        }
                    }
                    var subHelper = new SubmissionsHelper(db);
                    subHelper.CreateCppSubmission(task, newSubmission);
                }
                else
                {
                    Response.ClearHeaders();
                    Response.ClearContent();
                    Response.StatusCode        = 400;
                    Response.StatusDescription = "Test requires " + task.FilesRequired.Count + " but the submission only had " + Request.Files.Count;
                    Response.ContentType       = "application/json";
                    return(Json(new { Message = "Test requires " + task.FilesRequired.Count + " files, but the submission only had " + Request.Files.Count + ".", JsonRequestBehavior.AllowGet }));
                }
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
                isSavedSuccessfully = false;
            }

            if (isSavedSuccessfully)
            {
                return(Json(new { Message = fName }));
            }
            return(Json(new { Message = "Error in saving file" }));
        }
 public void CreateSubmussion(Submission submission)
 {
     _context.Submissions.Add(submission);
 }
Example #23
0
 public SubmissionRequest(string level, Score score)
 {
     type       = "submission";
     submission = new Submission(level, score);
 }
        private void ProcessSubmission(Submission submission)
        {
            // TODO: Check for N+1 queries problem
            this.logger.InfoFormat("Work on submission №{0} started.", submission.Id);

            var executionStrategy = this.CreateExecutionStrategy(submission.SubmissionType.ExecutionStrategyType);
            var context           = new ExecutionContext
            {
                SubmissionId = submission.Id,
                AdditionalCompilerArguments = submission.SubmissionType.AdditionalCompilerArguments,
                CheckerAssemblyName         = submission.Problem.Checker.DllFile,
                CheckerParameter            = submission.Problem.Checker.Parameter,
                CheckerTypeName             = submission.Problem.Checker.ClassName,
                FileContent           = submission.Content,
                AllowedFileExtensions = submission.SubmissionType.AllowedFileExtensions,
                CompilerType          = submission.SubmissionType.CompilerType,
                MemoryLimit           = submission.Problem.MemoryLimit,
                TimeLimit             = submission.Problem.TimeLimit,
                TaskSkeleton          = submission.Problem.SolutionSkeleton,
                Tests = submission.Problem.Tests.AsQueryable().Select(x =>
                                                                      new TestContext
                {
                    Id          = x.Id,
                    Input       = x.InputDataAsString,
                    Output      = x.OutputDataAsString,
                    IsTrialTest = x.IsTrialTest
                }).ToList(),
            };

            ExecutionResult executionResult;

            try
            {
                executionResult = executionStrategy.Execute(context);
            }
            catch (Exception exception)
            {
                this.logger.ErrorFormat("executionStrategy.Execute on submission №{0} has thrown an exception: {1}", submission.Id, exception);
                submission.ProcessingComment = $"Exception in executionStrategy.Execute: {exception.Message}";
                return;
            }

            submission.IsCompiledSuccessfully = executionResult.IsCompiledSuccessfully;
            submission.CompilerComment        = executionResult.CompilerComment;

            if (!executionResult.IsCompiledSuccessfully)
            {
                return;
            }

            foreach (var testResult in executionResult.TestResults)
            {
                var testRun = new TestRun
                {
                    CheckerComment         = testResult.CheckerDetails.Comment,
                    ExpectedOutputFragment = testResult.CheckerDetails.ExpectedOutputFragment,
                    UserOutputFragment     = testResult.CheckerDetails.UserOutputFragment,
                    ExecutionComment       = testResult.ExecutionComment,
                    MemoryUsed             = testResult.MemoryUsed,
                    ResultType             = testResult.ResultType,
                    TestId   = testResult.Id,
                    TimeUsed = testResult.TimeUsed,
                };
                submission.TestRuns.Add(testRun);
            }

            this.logger.InfoFormat("Work on submission №{0} ended.", submission.Id);
        }
Example #25
0
        public static void Run(int labNumber)
        {
            rng = new Random(labNumber);
            char version = versions[new Random().Next(versions.Length)];

            string fName = Utility.BuildFileName(labNumber, version);

            string[]     inputLines = null;
            StreamReader fReader    = null;
            bool         fileFound  = false;

            while (!fileFound)
            {
                try
                {
                    fReader    = Utility.OpenFile(@fName);
                    fileFound  = true;
                    lines      = Int32.Parse(fReader.ReadLine());
                    inputLines = new string[lines];
                    for (int ndx = 0; ndx < inputLines.Length; ndx++)
                    {
                        inputLines[ndx] = fReader.ReadLine();
                    }
                }
                catch (FileNotFoundException fnfe)
                {
                    Console.WriteLine("Test source file not found, aborting...");
                    throw fnfe;
                }
                finally
                {
                    fReader.Close();
                }
            }
            //for (int cntr = 0; cntr < inputLines.Length; ++cntr)
            //{
            //    Console.WriteLine(inputLines[cntr]);
            //}
            //Console.WriteLine("inputLines.Length = " + inputLines.Length);
            //Console.ReadKey();

            string[] inputs  = new string[inputLines.Length];
            string[] inputs0 = inputLines[0].Split(':');
            string[] word1s  = inputs0;

            string[]   inputs1 = inputLines[1].Split(':');
            string[]   inputs2 = inputLines[2].Split(':');
            string[]   inputs3 = inputLines[3].Split(':');
            string[]   inputs4 = inputLines[4].Split(':');
            string[]   inputs5 = inputLines[5].Split(':');
            double[][] stats   = new double[inputs1.Length][];
            stats[0] = new double[5];
            for (int cols = 0; cols < inputs1.Length; cols++)
            {
                stats[0][cols] = Double.Parse(inputs1[cols]);
            }
            stats[1] = new double[5];
            for (int cols = 0; cols < inputs2.Length; cols++)
            {
                stats[1][cols] = Double.Parse(inputs2[cols]);
            }
            stats[2] = new double[5];
            for (int cols = 0; cols < inputs3.Length; cols++)
            {
                stats[2][cols] = Double.Parse(inputs3[cols]);
            }
            stats[3] = new double[5];
            for (int cols = 0; cols < inputs4.Length; cols++)
            {
                stats[3][cols] = Double.Parse(inputs4[cols]);
            }
            stats[4] = new double[5];
            for (int cols = 0; cols < inputs5.Length; cols++)
            {
                stats[4][cols] = Double.Parse(inputs5[cols]);
            }

            string[]   inputs6  = inputLines[6].Split(':');
            string[]   inputs7  = inputLines[7].Split(':');
            string[]   inputs8  = inputLines[8].Split(':');
            string[]   inputs9  = inputLines[9].Split(':');
            string[]   inputs10 = inputLines[10].Split(':');
            double[][] normals  = new double[inputs6.Length][];
            normals[0] = new double[5];
            for (int cols = 0; cols < inputs6.Length; cols++)
            {
                normals[0][cols] = Double.Parse(inputs6[cols]);
            }
            normals[1] = new double[5];
            for (int cols = 0; cols < inputs7.Length; cols++)
            {
                normals[1][cols] = Double.Parse(inputs7[cols]);
            }
            normals[2] = new double[5];
            for (int cols = 0; cols < inputs8.Length; cols++)
            {
                normals[2][cols] = Double.Parse(inputs8[cols]);
            }
            normals[3] = new double[5];
            for (int cols = 0; cols < inputs9.Length; cols++)
            {
                normals[3][cols] = Double.Parse(inputs9[cols]);
            }
            normals[4] = new double[5];
            for (int cols = 0; cols < inputs10.Length; cols++)
            {
                normals[4][cols] = Double.Parse(inputs10[cols]);
            }

            string[]   inputs11 = inputLines[11].Split(':');
            string[]   inputs12 = inputLines[12].Split(':');
            string[]   inputs13 = inputLines[13].Split(':');
            string[]   inputs14 = inputLines[14].Split(':');
            string[]   inputs15 = inputLines[15].Split(':');
            string[][] uniques  = new string[inputs11.Length][];
            uniques[0] = inputs11;
            uniques[1] = inputs12;
            uniques[2] = inputs13;
            uniques[3] = inputs14;
            uniques[4] = inputs15;

            string[]   inputs16 = inputLines[16].Split(':');
            string[]   inputs17 = inputLines[17].Split(':');
            string[]   inputs18 = inputLines[18].Split(':');
            string[]   inputs19 = inputLines[19].Split(':');
            string[]   inputs20 = inputLines[20].Split(':');
            string[][] acros    = new string[inputs16.Length][];
            acros[0] = inputs16;
            acros[1] = inputs17;
            acros[2] = inputs18;
            acros[3] = inputs19;
            acros[4] = inputs20;

            string[] inputs21 = inputLines[21].Split(':');
            string[] word2s   = inputs21;

            string[] inputs22 = inputLines[22].Split(':');
            int[]    seeds    = new int[inputs22.Length];
            for (int ndx = 0; ndx < inputs22.Length; ndx++)
            {
                seeds[ndx] = Int32.Parse(inputs22[ndx]);
            }

            string[] inputs23 = inputLines[23].Split(':');

            int[] seed2s = new int[inputs23.Length];
            for (int ndx = 0; ndx < inputs23.Length; ndx++)
            {
                seed2s[ndx] = Int32.Parse(inputs23[ndx]);
            }

            string[] inputs24 = inputLines[24].Split(':');
            string[] inputs25 = inputLines[25].Split(':');
            string[] inputs26 = inputLines[26].Split(':');
            string[] inputs27 = inputLines[27].Split(':');
            string[] inputs28 = inputLines[28].Split(':');
            int[][]  asciis   = new int[inputs24.Length][];
            asciis[0] = new int[5];
            for (int ndx = 0; ndx < inputs24.Length; ndx++)
            {
                asciis[0][ndx] = Int32.Parse(inputs24[ndx]);
            }
            asciis[1] = new int[5];
            for (int ndx = 0; ndx < inputs25.Length; ndx++)
            {
                asciis[1][ndx] = Int32.Parse(inputs25[ndx]);
            }
            asciis[2] = new int[5];
            for (int ndx = 0; ndx < inputs26.Length; ndx++)
            {
                asciis[2][ndx] = Int32.Parse(inputs26[ndx]);
            }
            asciis[3] = new int[5];
            for (int ndx = 0; ndx < inputs27.Length; ndx++)
            {
                asciis[3][ndx] = Int32.Parse(inputs27[ndx]);
            }
            asciis[4] = new int[5];
            for (int ndx = 0; ndx < inputs28.Length; ndx++)
            {
                asciis[4][ndx] = Int32.Parse(inputs28[ndx]);
            }

            string[] inputs29 = inputLines[29].Split(':');
            string[] word3s   = inputs29;

            double labScore  = 0;
            double testScore = 0;

            Console.WriteLine("\n\tTest1 Processing");
            // Test1
            for (int ndx = 0; ndx < word1s.Length; ndx++)
            {
                string s = word1s[ndx];
                testScore = 0;
                int[] expected = new int[s.Length];
                for (int cntr = 0; cntr < s.Length; cntr++)
                {
                    expected[cntr] = (int)s[cntr];
                }
                int[] submitted = Submission.Test1(s.ToCharArray());
                bool  success   = CompareArrays(expected, submitted);
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore +
                              " [ " + s + " " + "]\tExpected: ");
                PrintArray(expected);
                Console.Write("\tSubmitted: ");
                PrintArray(submitted);
                Console.WriteLine();
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest2 Processing");
            // Test2
            for (int ndx = 0; ndx < stats.Length; ndx++)
            {
                testScore = 0;
                double[] expected  = GetStats(stats[ndx]);
                double[] submitted = Submission.Test2(stats[ndx]);
                bool     success   = CompareArrays(expected, submitted);
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore + " [ ");
                PrintArray(stats[ndx]);
                Console.Write("]\tExpected: ");
                PrintArray(expected);
                Console.Write("\tSubmitted: ");
                PrintArray(submitted);
                Console.WriteLine();
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest3 Processing");
            // Test3
            for (int ndx = 0; ndx < normals.Length; ndx++)
            {
                testScore = 0;
                double[] keepIt = DuplicateArray(normals[ndx]);
                Normalize(keepIt);
                double[] expected = keepIt;
                double[] passItOn = DuplicateArray(normals[ndx]);
                Submission.Test3(passItOn);
                double[] submitted = passItOn;
                bool     success   = CompareArrays(expected, submitted);
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore + " [ ");
                PrintArray(normals[ndx]);
                Console.Write("]\tExpected: ");
                PrintArray(expected);
                Console.Write("\tSubmitted: ");
                PrintArray(submitted);
                Console.WriteLine();
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest4 Processing");
            // Test4
            for (int ndx = 0; ndx < uniques.Length; ndx++)
            {
                testScore = 0;
                bool expected  = IsUnique(uniques[ndx]);
                bool submitted = Submission.Test4(uniques[ndx]);
                bool success   = expected == submitted;
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore + " [ ");
                PrintArray(uniques[ndx]);
                Console.WriteLine("]\tExpected: " + expected + "\tSubmitted: " + submitted);
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest5 Processing");
            // Test5
            for (int ndx = 0; ndx < acros.Length; ndx++)
            {
                testScore = 0;
                string expected  = Acronym(acros[ndx]);
                string submitted = Submission.Test5(acros[ndx]);
                bool   success   = expected == submitted;
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore + " [ ");
                PrintArray(acros[ndx]);
                Console.WriteLine("]\tExpected: " + expected + "\tSubmitted: " + submitted);
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest6 Processing");
            // Test6
            for (int ndx = 0; ndx < word2s.Length; ndx++)
            {
                testScore = 0;
                string expected  = new string(ReverseMe(word2s[ndx].ToCharArray()));
                string submitted = new string(Submission.Test6(word2s[ndx].ToCharArray()));
                bool   success   = expected == submitted; //  CompareArrays(expected,submitted);
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore + " [ ");
                Console.Write(word2s[ndx]);
                Console.Write(" ]\tExpected: ");
                Console.Write(expected);
                Console.Write("\tSubmitted: ");
                Console.Write(submitted);
                Console.WriteLine();
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest7 Processing");
            // Test7
            for (int ndx = 0; ndx < seeds.Length; ndx++)
            {
                Random rng = new Random(seeds[ndx]);
                int    r   = rng.Next(2, 4);
                int    c   = rng.Next(3, 5);
                int[,] source = new int[r, c];
                for (int row = 0; row < source.GetLength(0); row++)
                {
                    for (int col = 0; col < source.GetLength(1); col++)
                    {
                        source[row, col] = rng.Next(1, 10);
                    }
                }
                testScore        = 0;
                int[,] expected  = Transpose(source);
                int[,] submitted = Submission.Test7(source);
                bool success = Compare2DArrays(expected, submitted);
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore + " [ ");
                Print2DArray(source);
                Console.Write(" ]\tExpected: ");
                Print2DArray(expected);
                Console.Write("\tSubmitted: ");
                Print2DArray(submitted);
                Console.WriteLine();
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest8 Processing");
            // Test8
            for (int ndx = 0; ndx < seed2s.Length; ndx++)
            {
                testScore = 0;
                Random rng  = new Random(seed2s[ndx]);
                int    size = rng.Next(2, 5);
                int[]  ar1  = new int[size];
                int[]  ar2  = new int[size];
                int[]  ar3  = new int[size];

                for (int cntr = 0; cntr < ar1.Length; cntr++)
                {
                    ar1[cntr] = rng.Next(1, 10);
                    ar2[cntr] = rng.Next(1, 6);
                    ar3[cntr] = rng.Next(6, 10);
                }
                int[,] expected   = Build2DArray(ar1, ar2, ar3);
                int [,] submitted = Submission.Test8(ar1, ar2, ar3);
                bool success = Compare2DArrays(expected, submitted);
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore + " [ ");
                PrintArray(ar1);
                Console.Write("/ ");
                PrintArray(ar2);
                Console.Write("/ ");
                PrintArray(ar3);
                Console.Write("]\tExpected: ");
                Print2DArray(expected);
                Console.Write("\tSubmitted: ");
                Print2DArray(submitted);
                Console.WriteLine();
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest9 Processing");
            // Test9
            for (int ndx = 0; ndx < asciis.Length; ndx++)
            {
                testScore = 0;
                string expected  = new string(GetWords(asciis[ndx]));
                string submitted = new string(Submission.Test9(asciis[ndx]));
                bool   success   = expected == submitted;
                if (success)
                {
                    testScore = 2;
                }
                Console.Write("Pass[" + (ndx + 1) + "]: score = " + testScore + " [ ");
                PrintArray(asciis[ndx]);
                Console.WriteLine("]\tExpected: " + expected + "\tSubmitted: " + submitted);
                labScore += testScore;
            }

            Console.WriteLine("\n\tTest10 Processing");
            // Test10
            for (int ndx = 0; ndx < word3s.Length; ndx++)
            {
                testScore = 0;
                char[] exp      = Choppy(DuplicateArray(word3s[ndx].ToCharArray()));
                string expected = new string(exp);
                char[] sub      = DuplicateArray(word3s[ndx].ToCharArray());
                Submission.Test10(sub);
                string submitted = new string(sub);
                bool   success   = expected == submitted;
                if (success)
                {
                    testScore = 2;
                }
                Console.WriteLine("Pass[" + (ndx + 1) + "]: score = " + testScore +
                                  " [ " + word3s[ndx] + " ]\tExpected: " + expected +
                                  "\tSubmitted: " + submitted);
                labScore += testScore;
            }

            Console.WriteLine("\n\tLab score: " + labScore + "\t" + fName);
        }
Example #26
0
        public async Task <List <Plagiarism> > GetPlagiarismsAsync(Submission submission, SuspicionLevels suspicionLevels)
        {
            /* Dictionaries by submission id and snippet type */
            var tokensMatchedInThisSubmission   = new DefaultDictionary <Tuple <int, SnippetType>, HashSet <int> >();
            var tokensMatchedInOtherSubmissions = new DefaultDictionary <Tuple <int, SnippetType>, HashSet <int> >();

            var maxSnippetsCount   = configuration.PlagiarismDetector.CountOfColdestSnippetsUsedToSearch;
            var snippetsOccurences = await snippetsRepo.GetSnippetsOccurencesForSubmissionAsync(submission, maxSnippetsCount);

            var snippetsStatistics = await snippetsRepo.GetSnippetsStatisticsAsync(submission.ClientId, submission.TaskId, snippetsOccurences.Select(o => o.SnippetId));

            var authorsCount = await submissionsRepo.GetAuthorsCountAsync(submission.ClientId, submission.TaskId);

            var matchedSnippets = new DefaultDictionary <int, List <MatchedSnippet> >();

            foreach (var snippetOccurence in snippetsOccurences)
            {
                var otherOccurences = await snippetsRepo.GetSnippetsOccurencesAsync(
                    snippetOccurence.SnippetId,
                    /* Filter only snippet occurences in submissions BY THIS client, THIS task, THIS language and NOT BY THIS author */
                    o => o.Submission.ClientId == submission.ClientId &&
                    o.Submission.TaskId == submission.TaskId &&
                    o.Submission.Language == submission.Language &&
                    o.Submission.AuthorId != submission.AuthorId
                    );

                var snippet     = snippetOccurence.Snippet;
                var snippetType = snippet.SnippetType;

                foreach (var otherOccurence in otherOccurences)
                {
                    for (var i = 0; i < snippet.TokensCount; i++)
                    {
                        var tokenIndexInThisSubmission  = snippetOccurence.FirstTokenIndex + i;
                        var tokenIndexInOtherSubmission = otherOccurence.FirstTokenIndex + i;
                        tokensMatchedInThisSubmission[Tuple.Create(otherOccurence.SubmissionId, snippetType)].Add(tokenIndexInThisSubmission);
                        tokensMatchedInOtherSubmissions[Tuple.Create(otherOccurence.SubmissionId, snippetType)].Add(tokenIndexInOtherSubmission);
                    }

                    matchedSnippets[otherOccurence.SubmissionId].Add(new MatchedSnippet
                    {
                        SnippetType = snippetType,
                        TokensCount = snippet.TokensCount,
                        OriginalSubmissionFirstTokenIndex   = snippetOccurence.FirstTokenIndex,
                        PlagiarismSubmissionFirstTokenIndex = otherOccurence.FirstTokenIndex,
                        SnippetFrequency = GetSnippetFrequency(snippetsStatistics[snippet.Id], authorsCount),
                    });
                }
            }

            var plagiateSubmissionIds = tokensMatchedInOtherSubmissions.Keys.Select(tuple => tuple.Item1).ToList();
            var plagiateSubmissions   = await submissionsRepo.GetSubmissionsByIdsAsync(plagiateSubmissionIds);

            var plagiarisms = new List <Plagiarism>();

            var allSnippetTypes      = GetAllSnippetTypes();
            var thisSubmissionLength = submission.TokensCount;

            foreach (var plagiarismSubmission in plagiateSubmissions)
            {
                var unionLength = 0;
                foreach (var snippetType in allSnippetTypes)
                {
                    var submissionIdWithSnippetType = Tuple.Create(plagiarismSubmission.Id, snippetType);
                    if (!tokensMatchedInThisSubmission.ContainsKey(submissionIdWithSnippetType))
                    {
                        continue;
                    }

                    unionLength += tokensMatchedInThisSubmission[submissionIdWithSnippetType].Count;
                    unionLength += tokensMatchedInOtherSubmissions[submissionIdWithSnippetType].Count;
                }

                var plagiateSubmissionLength = plagiarismSubmission.TokensCount;
                var totalLength = thisSubmissionLength + plagiateSubmissionLength;
                var weight      = ((double)unionLength) / totalLength;
                /* Normalize weight */
                weight /= allSnippetTypes.Count;

                if (weight < suspicionLevels.FaintSuspicion)
                {
                    continue;
                }

                plagiarisms.Add(BuildPlagiarismInfo(plagiarismSubmission, weight, matchedSnippets[plagiarismSubmission.Id]));
            }

            return(plagiarisms);
        }
Example #27
0
 internal MetaDateModifiedCheck(Submission submission) : base(submission)
 {
     Flag            = new Flag(submission.Config.CheckMetaDateModifiedWeight);
     _localReference = submission.MetaDateModified.ToString();
 }
        private void SeedSubmissionsAndTestRuns(OjsDbContext context)
        {
            foreach (var submission in context.Submissions)
            {
                context.Submissions.Remove(submission);
            }

            foreach (var testRun in context.TestRuns)
            {
                context.TestRuns.Remove(testRun);
            }

            foreach (var participantToDelete in context.Participants)
            {
                context.Participants.Remove(participantToDelete);
            }

            Random random = new Random();

            List <TestRun> testRuns = new List <TestRun>();

            var test = new Test
            {
                IsTrialTest = false,
                OrderBy     = 1
            };

            for (int i = 0; i < 1000; i++)
            {
                testRuns.Add(new TestRun
                {
                    TimeUsed   = (random.Next() % 10) + 1,
                    MemoryUsed = (random.Next() % 1500) + 200,
                    ResultType = (TestRunResultType)(random.Next() % 5),
                    Test       = test
                });
            }

            var contest = new Contest
            {
                Name      = "Contest batka 2",
                StartTime = DateTime.Now.AddDays(1),
                EndTime   = DateTime.Now.AddDays(2),
                IsDeleted = false,
                IsVisible = true,
                OrderBy   = 1
            };

            var problemGroup = new ProblemGroup
            {
                OrderBy = 0,
                Contest = contest
            };

            var problem = new Problem
            {
                ProblemGroup  = problemGroup,
                Name          = "Problem",
                MaximumPoints = 100,
                MemoryLimit   = 100,
                OrderBy       = 1
            };

            var user = new UserProfile
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            var participant = new Participant
            {
                Contest    = contest,
                IsOfficial = false,
                User       = user
            };

            for (int i = 0; i < 100; i++)
            {
                var submission = new Submission
                {
                    Problem     = problem,
                    Participant = participant
                };

                for (int j = 0; j < (random.Next() % 20) + 5; j++)
                {
                    submission.TestRuns.Add(testRuns[random.Next() % 1000]);
                }

                context.Submissions.Add(submission);
            }
        }
 private void LoadSavedImage(Submission currentSub)
 {
     String filename = currentSub.ImageName + ".jpg";
     BitmapImage image = new BitmapImage();
     try
     {
         using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
         {
             using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("MyScience/Images/" + filename, FileMode.Open, FileAccess.Read))
             {
                 image.SetSource(fileStream);
             }
         }
         Photo.Source = image;
     }
     catch (Exception e) { 
         //should load a place holder image here instead
     }
 }
Example #30
0
 static extern int TuningFork_setAggregationStrategyInterval(Submission method, UInt32 intervalMsOrCount);
Example #31
0
        private static object CreateSubmission(ScriptInfo scriptInfo, Type modelType, ScriptEngine scriptEngine,
                                               out Submission<object> submission)
        {
            var submissionModel = Activator.CreateInstance(modelType);
            var session = scriptEngine.CreateSession(submissionModel, modelType);

            // INFO: Compile Rolsyn Script Submission
            submission = session.CompileSubmission<object>(scriptInfo.Script);

            return submissionModel;
        }
Example #32
0
 public int GetIndex(Submission submission)
 {
     return(_context.Submissions.AsNoTracking()
            .Count(s => s.SubmitterId.Equals(submission.SubmitterId) && s.AssignmentId == submission.AssignmentId) - 1);
 }
Example #33
0
 public NuisanceManager([InjectOptional] Submission submission, PluginConfig pluginConfig, DSAssetLoader assetLoader)
 {
     _submission   = submission;
     _pluginConfig = pluginConfig;
     _assetLoader  = assetLoader;
 }
Example #34
0
        Submission getSubmission()
        {
            Project app = App.applist[App.currentIndex];
            List<Field> fields = GetFormField(app.Form);
            /*Get the values of all the fields*/
            int cur = 0;
            for (int i = 0; i < fields.Count; i++)
            {
                switch (fields[i].type)
                {
                    case "Question":
                        TextBox newTextBox = DynamicPanel.Children[cur + 1] as TextBox;
                        fields[i].value = newTextBox.Text;
                        cur += 2;
                        break;
                    case "RadioButton":
                        String[] Options = fields[i].value.Split('|');
                        cur = cur + 1;
                        for (int j = 0; j < Options.Length; j++)
                        {
                            RadioButton RButton = DynamicPanel.Children[cur] as RadioButton;
                            if (RButton.IsChecked == true)
                            {
                                fields[i].value = RButton.Content.ToString();
                            }
                            cur++;
                        }
                        break;
                    case "CheckBox":
                        String[] Choices = fields[i].value.Split('|');
                        fields[i].value = "";
                        cur = cur + 1;
                        for (int j = 0; j < Choices.Length; j++)
                        {
                            CheckBox CBox = DynamicPanel.Children[cur] as CheckBox;
                            if (CBox.IsChecked == true)
                            {
                                if (fields[i].value == "")
                                {
                                    fields[i].value = CBox.Content.ToString();
                                }
                                else
                                {
                                    fields[i].value = fields[i].value + "|" + CBox.Content.ToString();
                                }
                            }
                            cur++;
                        }
                        break;
                    case "SliderBar":
                        cur = cur + 1;
                        Slider SliderBar = DynamicPanel.Children[cur] as Slider;
                        fields[i].value = SliderBar.Value.ToString();
                        break;
                }

            }
            Image photo = DynamicPanel.Children.OfType<Image>().First() as Image;
            WriteableBitmap image = (WriteableBitmap)photo.Source;

            if (!App.locationServicesOn)
            {
                //TextBlock message = new TextBlock();
                displayPopup(popupTitle1, popupContent5);
                return null;
            }
            if (image != null)
            {

                /*Parse the fields list into Json String*/
                String data = GetJsonString(fields);
                DateTime time = DateTime.Now;
                Submission newsubmission = new Submission
                {
                    ID = 0,
                    ProjectID = App.applist[App.currentIndex].ID,
                    ProjectName = App.applist[App.currentIndex].Name,
                    UserID = App.currentUser.ID,
                    Data = data,
                    Location = lat.ToString() + "," + lng.ToString(),
                    Time = time,
                    ImageName = App.currentUser.ID.ToString() + "-" + time.ToFileTime().ToString(),
                    LowResImageName = App.currentUser.ID.ToString() + "-" + time.ToFileTime().ToString()
                };
                return newsubmission;
            }
            else
            {
                TextBlock message = new TextBlock();
                displayPopup(popupTitle1, popupContent3);
                return null;
            }
        }
Example #35
0
        public static void loadSubmission(String txtDirectory, List<Submission> sublist)
        {
            sublist.Clear();
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!myIsolatedStorage.DirectoryExists(txtDirectory)) return;

                txtDirectory += "/";
                String[] txtfiles = myIsolatedStorage.GetFileNames(txtDirectory + "*.txt");
                sublist.Clear();
                foreach (String txtfile in txtfiles)
                {
                    var fileStream = myIsolatedStorage.OpenFile(txtDirectory + txtfile, FileMode.Open, FileAccess.Read);
                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        Submission submn = new Submission();
                        submn.ID = 0;
                        submn.ProjectID = Convert.ToInt32(reader.ReadLine());
                        submn.ProjectName = reader.ReadLine();
                        submn.UserID = App.currentUser.ID;
                        submn.Data = reader.ReadLine();
                        submn.Location = reader.ReadLine();
                        submn.Time = Convert.ToDateTime(reader.ReadLine());
                        submn.ImageName = reader.ReadLine();
                        submn.LowResImageName = reader.ReadLine();
                        sublist.Add(submn);
                    }
                }
            }
        }
 private void LoadSubmittedImage(Submission currentSub)
 {
     String filename = currentSub.ImageName;
     if (NetworkInterface.GetIsNetworkAvailable())
     {
         Binding tmpBinding = new Binding();
         tmpBinding.Source = new Uri(filename);
         Photo.SetBinding(Image.SourceProperty, tmpBinding);
     }
     else
     {
         currentSub.ImageName = currentSub.ImageName.Substring(currentSub.ImageName.LastIndexOf("/"));
         LoadSavedImage(currentSub);
     }
     
 }
Example #37
0
 public GameplayManager(PluginConfig config, SiraLog logger, Submission submission)
 {
     _config     = config;
     _logger     = logger;
     _submission = submission;
 }
        private void LoadContent(Submission currentSub)
        {
            PageTitle.Text = currentSub.ProjectName;
            

            TimeBlock.Text = "   " + currentSub.Time.ToString();
            LocationBlock.Text = "  " + currentSub.Location;

            List<Field> fields = GetFormField(currentSub.Data);

            for (int i = 0; i < fields.Count; i++)
            {
                switch (fields[i].type)
                {
                    case "Question":
                        //TODO:add a numerical checker for number answers
                        var QBlock = new TextBlock { Name = "Question" + i.ToString(), Text = fields[i].label, FontSize=30 };
                        QBlock.Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0x6C, 0x16));
                        var ABlock = new TextBlock { Name = "Answer" + i.ToString(), Text = "    " + fields[i].value, FontSize = 24 };
                        DynamicPanel.Children.Add(QBlock);
                        DynamicPanel.Children.Add(ABlock);
                        break;
                    case "RadioButton":
                        //TODO: type is RadioButton, label is question, value is options
                        //      In value, different options are seperated by "|"
                        var RBTextBlock = new TextBlock { Name = "Question" + i.ToString(), Text = fields[i].label, FontSize=30 };
                        RBTextBlock.Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0x6C, 0x16));
                        DynamicPanel.Children.Add(RBTextBlock);
                        string[] Options = fields[i].value.Split('|');
                        for (int j = 0; j < Options.Length; j++)
                        {
                            var RBABlock = new TextBlock { Text = "  " + Options[j], FontSize = 24};
                            DynamicPanel.Children.Add(RBABlock);
                        }
                        break;
                    case "CheckBox":
                        //TODO: same as RadioButton
                        var CBTextBlock = new TextBlock { Name = "Question" + i.ToString(), Text = fields[i].label, FontSize = 30 };
                        CBTextBlock.Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0x6C, 0x16));
                        DynamicPanel.Children.Add(CBTextBlock);
                        string[] Choices = fields[i].value.Split('|');
                        for (int j = 0; j < Choices.Length; j++)
                        {
                            var CBABlock = new TextBlock { Text = "  " + Choices[j], FontSize = 24 };
                            DynamicPanel.Children.Add(CBABlock);
                        }
                        break;
                    case "SliderBar":
                        //TODO: same as RadioButton except value is the max and min values
                        var SBTextBlock = new TextBlock { Name = "Question" + i.ToString(), Text = fields[i].label +  fields[i].value, FontSize = 30};
                        SBTextBlock.Foreground = new SolidColorBrush(Color.FromArgb(0xFF, 0xFF, 0x6C, 0x16));
                        DynamicPanel.Children.Add(SBTextBlock);
                        break;
                }

            }

        }
Example #39
0
 public static int GetTotalNumberOfRows(object filter)
 {
     return(Submission.GetSubmissionsCount((SubmissionsFilter)filter));
 }
Example #40
0
		private async void ProcessInput()
		{
			var source = Interlocked.Exchange (ref this.submission, null);

			if (source != null)
				source.Cancel();

			if (String.IsNullOrEmpty (input) || String.IsNullOrEmpty (TestCode))
				return;

			int id = Interlocked.Increment (ref this.submissionId);

			Either<string, Error> result = await Instantly.Instrument (input, id);
			string instrumented = result.Fold (i => i, e => null);
			if (instrumented == null)
				return;

			Project project = new Project();
			project.Sources.Add (Either<FileInfo, string>.B (instrumented));

			Submission s = null;
			var sink = new MemoryInstrumentationSink (() => s.IsCanceled);
			s = new Submission (id, project, sink, TestCode);

			if (DebugTree)
				Debug = instrumented;

			this.evaluator.PushSubmission (s);
		}
Example #41
0
        /// <summary>
        /// Adds a submission to the given assignment for the given student
        /// The submission should use the current time as its DateTime
        /// You can get the current time with DateTime.Now
        /// The score of the submission should start as 0 until a Professor grades it
        /// If a Student submits to an assignment again, it should replace the submission contents
        /// and the submission time (the score should remain the same).
        /// Does *not* automatically reject late submissions.
        /// </summary>
        /// <param name="subject">The course subject abbreviation</param>
        /// <param name="num">The course number</param>
        /// <param name="season">The season part of the semester for the class the assignment belongs to</param>
        /// <param name="year">The year part of the semester for the class the assignment belongs to</param>
        /// <param name="category">The name of the assignment category in the class</param>
        /// <param name="asgname">The new assignment name</param>
        /// <param name="uid">The student submitting the assignment</param>
        /// <param name="contents">The text contents of the student's submission</param>
        /// <returns>A JSON object containing {success = true/false}.</returns>
        public IActionResult SubmitAssignmentText(string subject, int num, string season, int year,
                                                  string category, string asgname, string uid, string contents)
        {
            try
            {
                var query = from cour in db.Courses
                            join cla in db.Classes on cour.CourseId equals cla.CourseId
                            into classes
                            from c in classes.DefaultIfEmpty()
                            join assignCat in db.AssignmentCategories on c.ClassId equals assignCat.ClassId
                            into assignCategories
                            from a in assignCategories.DefaultIfEmpty()
                            join assignm in db.Assignments on a.AssignCatId equals assignm.AssignCatId
                            into assignments
                            from assi in assignments.DefaultIfEmpty()
                            where cour.SubjectAbbr == subject
                            where cour.CourseNumber == (uint)num
                            where c.Semester == season + " " + year
                            where a.Name == category
                            where assi.Name == asgname
                            select
                            new
                {
                    id = assi.AssignmentId
                };

                var assgnId = query.First().id;

                var prevSubmission = from sub in db.Submission
                                     where sub.AssignmentId == assgnId
                                     where sub.UId == uid
                                     select
                                     new
                {
                    id = sub.AssignmentId
                };

                Submission submission = new Submission
                {
                    AssignmentId = assgnId,
                    UId          = uid,
                    Contents     = contents,
                    Time         = DateTime.Now
                };

                // update old submission
                if (prevSubmission.Count() > 0)
                {
                    db.Submission.Update(submission);
                }
                // add new submission
                else
                {
                    db.Submission.Add(submission);
                }

                db.SaveChanges();

                return(Json(new { success = true }));
            }
            catch (Exception)
            {
                return(Json(new { success = false }));
            }
        }
Example #42
0
		private async Task Execute (ITextSnapshot snapshot, CancellationToken cancelToken)
		{
			this.statusbar.SetText ("Evaluating...");

			int id = Interlocked.Increment (ref submissionId);

			string original = snapshot.GetText();
			bool error = false;
			var result = await Instantly.Instrument (original, id);
			string text = result.Fold (
				s => s,
				e =>
				{
					error = true;
					return String.Format ("L{0}: {1}", e.Region.BeginLine, e.Message);
				});

			if (cancelToken.IsCancellationRequested)
			{
				this.statusbar.SetText ("Evaluation canceled.");
				return;
			}

			if (error)
			{
				this.statusbar.SetText (text);
				return;
			}

			IProject project = this.dte.GetProject (this.document, text);

			Submission submission = null;
			var sink = new MemoryInstrumentationSink (() => submission.IsCanceled);
			submission = new Submission (id, project, sink, this.context.TestCode);
			submission.Tag = new Tuple<ITextSnapshot, string> (snapshot, original);

			this.evaluator.PushSubmission (submission);
		}
        private async Task UpdateSnippetsFromSubmissionAsync(ISnippetsRepo snippetsRepo, Submission submission)
        {
            var occurences = new HashSet <Tuple <int, int> >(
                (await snippetsRepo.GetSnippetsOccurencesForSubmissionAsync(submission))
                .Select(o => Tuple.Create(o.SnippetId, o.FirstTokenIndex))
                );

            foreach (var(firstTokenIndex, snippet) in submissionSnippetsExtractor.ExtractSnippetsFromSubmission(submission))
            {
                var foundSnippet = await snippetsRepo.GetOrAddSnippetAsync(snippet);

                if (!occurences.Contains(Tuple.Create(foundSnippet.Id, firstTokenIndex)))
                {
                    logger.Information($"Информация о сниппете #{foundSnippet.Id} в решении #{submission.Id} не найдена, добавляю");
                    try
                    {
                        await snippetsRepo.AddSnippetOccurenceAsync(submission, foundSnippet, firstTokenIndex);
                    }
                    catch (Exception e)
                    {
                        logger.Error(e, $"Ошибка при добавлении сниппета #{foundSnippet.Id} в решении #{submission.Id}");
                    }
                }
            }
        }
 public bool Create(Submission submission)
 {
     dbContext.Add(submission);
     dbContext.SaveChanges();
     return(true);
 }
 public void Update(Submission submission) =>
 _submissions.ReplaceOne(sub => sub.Id == submission.Id, submission);