public void Sort(MyCollection <Trial> first, out MyCollection <Trial> sorted) { int max = -1; Trial maxTr = new Trial(); foreach (Trial item in first.myList) { if (item.Mark >= max) { max = item.Mark; } } //находим испытание с максиимальной оценкой sorted = new MyCollection <Trial>(); //первый элемент - найденный (т.к. впоследствии окажется последним) foreach (Trial item in first.myList) { if (item.Mark == max) { sorted.myList.Add(item);//добавляем элементы с оценками = максимуму в начало } } max--; do { foreach (Trial item in first.myList) { if (item.Mark == max) { sorted.myList.Add(item); // добавляем все элементы с оценками на 1 ниже } } max--; } while (max != -1); }
/// <summary> /// Called when the app comes back to life. I put this in so when the trial is over, and the user is directed to the store, if /// the user purchases the app it will be activated when he / she comes back. If the app is not activated, and the user just presses /// the back button, we'll de-activate the app and go to the "Purchase" screen. /// </summary> internal void AppActivated() { try { if ((Application.Current as App).IsTrial) { if (Trial.IsTrialExpired()) //if (true) { try { Dispatcher.BeginInvoke(() => { NavigationService.Navigate(new Uri("/TrialExpired.xaml", UriKind.Relative)); }); } catch (Exception ex) { } } } else { EnableApp(true); } } catch (Exception ex) { } }
public void TargetHit(TargetController target) { Trial currentTrial = session.CurrentTrial; currentTrial.result["correct"] = target.isCorrect; currentTrial.End(); }
public int GetDaysLeftInTrial() { int returnValue = 0; returnValue = Trial.GetDaysLeftInTrial(); return(returnValue); }
public void NextTrial() { // We try to load the next trial variables try { Trial t = _experiment.LoadNextTrial(); } catch (AllTrialsPerformedException e) { ExperienceFinished(); return; //info temporary } _experiment.StartTrial(); currentTrialIndex = _experiment.GetCurrentTrialIndex(); Debug.Log("<color=#E91E63>Current trial : " + currentTrialIndex + "</color>"); // We read the value of the CSV : int color = int.Parse(_experiment.GetParameterData("Color")); string shape = _experiment.GetParameterData("Shape"); // Here you start your trial based on what you get : Debug.Log("Loading the shape " + shape + " with the color id " + color); }
public void RefreshSessionTree() { if (trvSession.Nodes.Count != 0) { trvSession.Nodes.Clear(); } TreeNode topNode = new TreeNode(Session.Instance.Name); topNode.Tag = NodeType.Session; trvSession.Nodes.Add(topNode); trvSession.TopNode = topNode; for (int i = 0; i < Session.Instance.Trials.Count; i++) { Trial t = (Trial)Session.Instance.Trials[i]; TreeNode trialNode = new TreeNode(t.Name); trialNode.Tag = NodeType.Trial; topNode.Nodes.Add(trialNode); for (int j = 0; j < t.Templates.Count; j++) { Template tp = (Template)t.Templates[j]; TreeNode templateNode = new TreeNode(tp.Name); templateNode.Tag = NodeType.Template; trialNode.Nodes.Add(templateNode); } } trvSession.ExpandAll(); if (Session.Instance.CurrentTrial != null) { trvSession.SelectedNode = trvSession.TopNode.Nodes[Session.Instance.CurrentTrialIndex]; } }
public void SetupTargets(Trial trial) // can be called from OnTrialBegin in the Session inspector { TargetPosition correctTargetPosition = (TargetPosition)trial.settings.GetObject("correct_target_position"); leftTarget.Setup(correctTargetPosition == TargetPosition.Left); rightTarget.Setup(correctTargetPosition == TargetPosition.Right); bool inverted = trial.settings.GetBool("inverted"); if (inverted) { // light up the opposite target if (correctTargetPosition == TargetPosition.Left) { rightTarget.Highlight(); } if (correctTargetPosition == TargetPosition.Right) { leftTarget.Highlight(); } } else { // light up the correct target if (correctTargetPosition == TargetPosition.Left) { leftTarget.Highlight(); } if (correctTargetPosition == TargetPosition.Right) { rightTarget.Highlight(); } } }
public void EndIfLastTrial(Trial trial) { if (trial == trial.session.LastTrial) { trial.session.End(); } }
public void RunTrial(Trial t) { currentTrial = t; _challengeIndex = -1; builder = new ResultBuilder(); AdvanceChallenge(); }
private Trial[] createTrials(int numTrials, bool practice) { Trial[] result = new Trial[numTrials]; if (practice == true) { int index = 0; // create a set of practice trials - 1 trial each of span 3, 5, and 7 for (int span = 3; span <= 7; span += 2) { result[index].spanLength = span; result[index++].correct = false; } } else { // create the trials for the official test int numRepeats = numTrials / 5; int index = 0; for (int i = 1; i <= numRepeats; i++) { for (int span = 3; span <= 7; span++) { result[index].spanLength = span; result[index++].correct = false; } } } randomizeTrials(ref result); return(result); }
void UpdateProgressPanel() { string runningText = runner.Running ? "Running" : "Not Running"; runningText = !runner.Ended ? runningText : "Ended"; RunningStatusText.text = $"Runner is {runningText}."; var design = runner.RunnableDesign; int currentTrial = (design.TotalTrials / design.BlockCount) * (currentBlockIndex) + currentTrialIndex + 1; if (currentTrial > design.TotalTrials) { currentTrial = design.TotalTrials; } string blockText = ""; if (design.HasBlocks) { blockText = $" (Block {currentBlockIndex} / {design.BlockCount})"; } CurrentTrialText.text = ($"Running Trial: {currentTrial} of {design.TotalTrials} total{blockText}."); Image progressPanelImage = ProgressPanel.GetComponent <Image>(); if (ended) { progressPanelImage.color = Color.red; } else { progressPanelImage.color = Color.green; } }
private bool SaveData() { var item = ScreenToClassMap(); var trial = _context.Trials.Find(_Id); if (trial == null) { trial = new Trial(); } else { trial.Id = _Id; } trial.Measurement = item.Measurement; trial.Name = item.Name; trial.QuantityAthletes = item.QuantityAthletes; if (_Id == 0) { _context.Trials.Add(trial); } var regs = _context.SaveChanges(); return(regs > 0); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="trialId">Id of the trial to be graduated.</param> public void Run(AdWordsUser user, long trialId) { // Get the TrialService and BudgetService. TrialService trialService = (TrialService)user.GetService( AdWordsService.v201609.TrialService); BudgetService budgetService = (BudgetService)user.GetService( AdWordsService.v201609.BudgetService); try { // To graduate a trial, you must specify a different budget from the // base campaign. The base campaign (in order to have had a trial based // on it) must have a non-shared budget, so it cannot be shared with // the new independent campaign created by graduation. Budget budget = new Budget() { name = "Budget #" + ExampleUtilities.GetRandomString(), amount = new Money() { microAmount = 50000000L }, deliveryMethod = BudgetBudgetDeliveryMethod.STANDARD }; BudgetOperation budgetOperation = new BudgetOperation() { @operator = Operator.ADD, operand = budget }; // Add budget. long budgetId = budgetService.mutate( new BudgetOperation[] { budgetOperation }).value[0].budgetId; Trial trial = new Trial() { id = trialId, budgetId = budgetId, status = TrialStatus.GRADUATED }; TrialOperation trialOperation = new TrialOperation() { @operator = Operator.SET, operand = trial }; // Update the trial. trial = trialService.mutate(new TrialOperation[] { trialOperation }).value[0]; // Graduation is a synchronous operation, so the campaign is already // ready. If you promote instead, make sure to see the polling scheme // demonstrated in AddTrial.cs to wait for the asynchronous operation // to finish. Console.WriteLine("Trial ID {0} graduated. Campaign ID {1} was given a new budget " + "ID {1} and is no longer dependent on this trial.", trial.id, trial.trialCampaignId, budgetId); } catch (Exception e) { throw new System.ApplicationException("Failed to graduate trial.", e); } }
public void TestTrialInitial() { var trial = new Trial(Orientations.Upright, 0.0f); Assert.AreEqual(0.0f, trial.NormalizedFitnessDuration); Assert.AreEqual(0.0f, trial.NormalizedFitnessHistory); Assert.AreEqual(0.0f, trial.Fitness); }
private IEnumerator TrialRoutine(Trial trial) { fixationDot.SetActive(true); SetEnforcedHeadTransform(); //resets head location at the beginning of each trial IsPausable = true; yield return(WaitForFixation(sessionSettings.fixationTime, Mathf.Tan(sessionSettings.fixationErrorTolerance * Mathf.PI / 180 * sessionSettings.stimulusDepth))); IsPausable = false; var trialDuration = GetTrialDuration(); var outerStimulusRoutine = StartCoroutine(OuterStimulusRoutine()); var innerStimulusRoutine = StartCoroutine(InnerStimulusRoutine()); var inputRoutine = StartCoroutine(InputRoutine()); var fixationBreakCheckRoutine = StartCoroutine(FixationBreakCheckRoutine()); var headStabilityCheckRoutine = StartCoroutine(HeadStabilityCheckRoutine()); var attentionCueRoutine = AttentionCueRoutine(); if (sessionSettings.sessionType == SessionSettings.SessionType.Training) { StartCoroutine(attentionCueRoutine); } var elapsedTime = 0.0f; while (!_isFixationBroken && elapsedTime < trialDuration / 1000) { elapsedTime += Time.deltaTime; yield return(null); } StopCoroutine(outerStimulusRoutine); StopCoroutine(innerStimulusRoutine); StopCoroutine(inputRoutine); if (fixationBreakCheckRoutine != null) { StopCoroutine(fixationBreakCheckRoutine); } StopCoroutine(attentionCueRoutine); StopCoroutine(headStabilityCheckRoutine); outerStimulus.SetActive(false); innerStimulus.SetActive(false); stimulusSpacer.SetActive(false); attentionCue.SetActive(false); laserManager.DeactivateBothLasers(); // Start trial over if fixation was broken if (_isFixationBroken) { BeginTrial(trial); yield break; } trial.End(); }
// Constructor public MainPage() { _mainPageInstance = this; string hasAppBeenRated = string.Empty; if (Rate.HasAppBeenRated().ToUpper() == "YES") { _rated = true; } else { _rated = false; } InitializeComponent(); //Initially show the msft control, if it fails, show google. AdvertisingVisibility = Visibility.Visible; GoogleAdVisibility = Visibility.Collapsed; MyAdControl.CountryOrRegion = RegionInfo.CurrentRegion.TwoLetterISORegionName; BuildLocalizedApplicationBar(_rated); SetLockScreenSetting(); MyAdControl.ErrorOccurred += MyAdControl_ErrorOccurred; GoogleAdControl.FailedToReceiveAd += GoogleAdControl_FailedToReceiveAd; this.DataContext = this; Trial.SaveStartDateOfTrial(); if (IS.GetSetting(RATED) != null) { if ((bool)IS.GetSetting(RATED)) { _rated = true; } } if (IS.GetSetting(NUMBEROFTIMESOPENED) == null) { IS.SaveSetting(NUMBEROFTIMESOPENED, 0); } else { IS.SaveSetting(NUMBEROFTIMESOPENED, (int)IS.GetSetting(NUMBEROFTIMESOPENED) + 1); _numberOfTimesOpened = (int)IS.GetSetting(NUMBEROFTIMESOPENED); } if (!(Application.Current as App).IsFreeVersion) { PaidAppInitialization(); } else { FreeAppInitialIzation(); } }
private void SaveTrial(Trial target, bool saveAs) { string fileName = string.Empty; if (target.WasSaved && !saveAs) { fileName = target.FileName; } else { SaveFileDialog sfd = new SaveFileDialog(); sfd.Title = Resources.SaveTrialAs; sfd.Filter = Resources.TrialFileFilter; sfd.FileName = target.Name; if (sfd.ShowDialog() == DialogResult.OK) { fileName = sfd.FileName; target.Name = Path.GetFileNameWithoutExtension(fileName); } } if (string.IsNullOrEmpty(fileName)) { return; } using (StreamWriter sw = new StreamWriter(fileName)) { target.FileName = fileName; target.Save(sw, fileName); } }
/// <summary> /// Adds a result to the SessionData for the given trial. /// Stores the accuracy of the marker position when player responded. /// </summary> protected override void AddResult(Trial t, float xPos) { TrialResult r = new TrialResult(t); r.accuracy = GetAccuracy(xPos); int score = GetScore(xPos); if (IsHighResponse(score)) { DisplayFeedback(HIGH_RESPONSE, RESPONSE_COLOR_HIGH, score); r.success = true; GUILog.Log("EXCELLENT! Score = {0}", score); } else if (IsMediumResponse(score)) { DisplayFeedback(MEDIUM_RESPONSE, RESPONSE_COLOR_MEDIUM, score); r.success = true; GUILog.Log("Good! Score = {0}", score); } else if (IsLowResponse(score)) { DisplayFeedback(LOW_RESPONSE, RESPONSE_COLOR_LOW, score); r.success = true; GUILog.Log("Ok. Score = {0}", score); } else { DisplayFeedback(LOWEST_RESPONSE, RESPONSE_COLOR_LOWEST, score); r.success = false; GUILog.Log("Bad... Score = {0}", score); } sessionData.results.Add(r); }
private void trvSession_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { if (string.IsNullOrEmpty(e.Label)) { Util.ShowError(Resources.EmptyNameError); } else { switch ((NodeType)e.Node.Tag) { case NodeType.Session: Session.Instance.Name = e.Label; trvSession.TopNode.Text = Session.Instance.Name; break; case NodeType.Trial: Trial target = (Trial)Session.Instance.Trials[e.Node.Index]; target.Name = e.Label; e.Node.Text = target.Name; break; case NodeType.Template: Trial tgt = (Trial)Session.Instance.Trials[e.Node.Parent.Index]; Template template = (Template)tgt.Templates[e.Node.Index]; template.Name = e.Label; e.Node.Text = template.Name; break; } } e.CancelEdit = true; }
/// <summary> /// Called at the beginning of each Trial. /// </summary> protected virtual void StartTrial(Trial t) { currentTrial = t; trialInProgress = true; playerResponded = false; OnStartTrial(); }
private void resetTrial() { switch (dockingStateType) { case DockingStateType.toStart: currentTrial.timesStartFailed++; Debug.Log("currentTrial.timesStartFailed: " + currentTrial.timesStartFailed); playSound("Error"); break; case DockingStateType.toEnd: currentTrial.timesEndFailed++; Debug.Log("currentTrial.timesEndFailed: " + currentTrial.timesEndFailed); playSound("Error"); //save it for later if they failed because of //saccade allows them to remember position deferredTrials.Add(currentTrial); deferredTrials.Shuffle(); //Fetch new one if (trials.Count == 0 && deferredTrials.Count == 0) { advanceState(); } if (trials.Count == 0 && deferredTrials.Count > 0) { currentTrial = deferredTrials[0]; deferredTrials.RemoveAt(0); Debug.Log("Advanced, remaining : " + trials.Count + deferredTrials.Count); //move target to new position target.transform.localPosition = currentTrial.start; //target.transform.localPosition = currentTrial.translation.start; dockingStateType = DockingStateType.toStart; cursor.GetComponent <MeshRenderer>().enabled = true; //trialCount++; } if (trials.Count > 0) { currentTrial = trials[0]; trials.RemoveAt(0); Debug.Log("Advanced, remaining : " + trials.Count); Debug.Log("Deferred remaining : " + deferredTrials.Count); //move target to new position target.transform.localPosition = currentTrial.start; //target.transform.localPosition = currentTrial.translation.start; dockingStateType = DockingStateType.toStart; cursor.GetComponent <MeshRenderer>().enabled = true; //trialCount++; } break; } cursor.GetComponent <MeshRenderer>().enabled = true; timeLast = Time.time; }
public virtual void Awake() { trial = this; practice_rounds = new bool[total_rounds]; survey_rounds = new bool[total_rounds]; default_time_limit = time_limit; PopulateInputDelays(); }
public void TestTrialInitial() { var trial = new Trial(Orientations.Upright, 0.0f); Assert.AreEqual(0.0f, trial.NormalizedFitnessDuration); Assert.AreEqual(0.0f, trial.NormalizedFitnessHistory); Assert.AreEqual(0.0f, trial.Fitness); }
public ExportSettingsForm(Trial trial) { MdiParent = null; InitializeComponent(); this.trial = trial; txtExportStart.Text = 0.ToString(); txtExportEnd.Text = trial.Duration.ToString(); }
void StartRunningTrial(Trial trial) { currentlyRunningTrial = trial; TuxLog.Log($"{TuxLog.FormatOrange("Starting")} {currentlyRunningTrial.TrialText}"); ExperimentEvents.StartPart(trial); ExperimentEvents.TrialHasStarted(trial); }
public ExportSettingsForm(Trial trial) { MdiParent = null; InitializeComponent(); this.trial = trial; txtExportStart.Text = 0.ToString(); txtExportEnd.Text = trial.Duration.ToString(); }
public TrialTreeNode(Trial trial) : base(trial.Name) { this.Trial = trial; foreach (Series s in Trial.Series) { Nodes.Add(new SeriesTreeNode(s)); } }
public DateTime GetStartDateOfTrial() { DateTime returnValue = DateTime.Today; returnValue = Trial.GetStartDateOfTrial(); return(returnValue); }
public void EndIfLastTrial(Trial trial) { if (trial == trial.session.LastTrial) { Debug.Log(trial.session.blocks); trial.session.End(); } }
private Dictionary <String, String> MapObject(Trial item) { Dictionary <String, String> mappedObject = new Dictionary <string, string>(); mappedObject.Add("trialName", item.Name); mappedObject.Add("trialDifficulty", item.Difficulty.ToString()); return(mappedObject); }
public FmInputLink(ref Trial tr, DataService service) { InitializeComponent(); StartPosition = FormStartPosition.CenterScreen; trial = tr; this.service = service; }
private bool IsTrialExpired() { bool trialExpired = false; trialExpired = Trial.IsTrialExpired(); return(trialExpired); }
public BehavioralTestTemplateTrialControl(Session session, int trialIndex, ErrorProvider errorProvider) { _Trial = session.Trials[trialIndex]; InitializeComponent(); _ErrorProvider = errorProvider; //cmbTrialCount.SelectedIndex = 0; txtDuration.Text = _Trial.Duration.ToString(); gbTrial.Text = String.Format("Trial: {0}", _Trial.Name); txtName.Text = _Trial.Name; txtName.Enabled = (session.Trials.Count == 1) ? false : true; }
public int currentTrialForEdit = 0; // keeps track of which trial index is currently being edited while in Fitness/Mini-game Panels // For Each Trial: // MiniGame Class to store gametype and settings // Fitness Function Class w/ Fitness component list and settings // Constructor Functions: public Player() { DebugBot.DebugFunctionCall("Player; Player() Constructor!; ", debugFunctionCalls); InitializeNewPopulation(); masterTrialsList = new List<Trial>(); Trial newTrial = new Trial(this); // make trials list one member long, with a None mini-game value masterTrialsList.Add(newTrial); masterCupid = new CrossoverManager(); dataManager = new DataManager(this); graphKing = new TheGraphKing(); //newTrial.playerRef = this; }
public void TestTrialWorst() { var trial = new Trial(Orientations.Upright, 0.0f); for (int i = 0; i < 100; i++) { trial.Update(180.0f, 180.0f, 180.0f, 180.0f, 6.0f, 6.0f); } Assert.AreEqual(0.1f, trial.NormalizedFitnessDuration); Assert.AreEqual(0.001f, trial.NormalizedFitnessHistory, 0.001f); Assert.AreEqual(0.0109f, trial.Fitness, 0.001f); }
public void BeginTrial(Orientations orientation, float startTime) { this.startTime = startTime; this.orientation = orientation; SetRotation(orientation); currentTrial = new Trial(orientation, startTime); if (Phenotype != null) { Phenotype.AddTrial(currentTrial); } }
public void TestTrialDuration() { var trialLong = new Trial(Orientations.Upright, 0.0f); var trialShort = new Trial(Orientations.Upright, 0.0f); for (int i = 0; i < 1000; i++) { trialLong.Update(90.0f, 30.0f, 90.0f, 30.0f, 3.0f, 1.0f); } for (int i = 0; i < 100; i++) { trialShort.Update(90.0f, 30.0f, 90.0f, 30.0f, 3.0f, 1.0f); } Assert.That(trialLong.Fitness > trialShort.Fitness); }
public ExportSettings(Trial trial, int timeBinDuration = -1, int exportStart = -1, int exportEnd = -1) { if (timeBinDuration != -1 && (timeBinDuration > trial.Duration || timeBinDuration <= 0)) throw new IndexOutOfRangeException(); if (exportStart != -1 && exportStart > trial.Duration) throw new IndexOutOfRangeException(); if (exportEnd != -1 && exportStart > trial.Duration) throw new IndexOutOfRangeException(); if (exportEnd != -1 && exportEnd <= exportStart) throw new Exception("Invalid Export Range"); if (exportEnd == -1) exportEnd = trial.Duration; if (exportStart == -1) exportStart = 0; this.TimeBinDuration = timeBinDuration; this.UseTimeBins = this.TimeBinDuration > 0; this.ExportStart = exportStart; this.ExportEnd = exportEnd; }
public void export(Trial trial) { ExportRun exportRun = ExportRun.Create(trial.Runs[0], exportSettings); List<string> dataRows = new List<string>(); string headerRow = String.Join<String>("\t", exportRun.Headers()); foreach (Run run in trial.Runs) { exportRun = ExportRun.Create(run, exportSettings); if (run.Status == Run.RunStatus.Complete) { Run.ValidationResult runValidationResult = run.Validate(); if (runValidationResult.IsValid) { dataRows.Add(String.Join<String>("\t", exportRun.RunData())); } } } string exportFilename = exportPath(trial); string exportDirectory = Path.GetDirectoryName(exportFilename); if (!Directory.Exists(exportDirectory)) { Directory.CreateDirectory(exportDirectory); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(exportFilename)) { file.WriteLine(headerRow); foreach (string dataRow in dataRows) { file.WriteLine(dataRow); } } }
public static Project CreateDefaultEpm(Researcher researcher, String name) { if (researcher == null) { Logger.logError("Invalid Researcher"); return null; } var project = new Project { Name = name }; var test = new BehavioralTest { Name = "test", BehavioralTestType = BehavioralTestType.Epm, }; project.AddBehavioralTest(test); Researcher.Current.AddProject(project); var testSession = new Session { Name = "", }; test.AddSession(testSession); var testTrial = new Trial { Name = "", Duration = 300, }; testSession.AddTrial(testTrial); Researcher.Current.Save(); return project; }
/// <summary> /// The <see cref="Form.Load"/> event handler. /// Initializes the form on the presentation screen, /// then initializes flash stimulus handling, /// starts the timing control and then /// loads first stimulus. /// </summary> /// <param name="sender"> /// Source of the event. /// </param> /// <param name="e"> /// An empty <see cref="EventArgs"/> /// </param> private void PresenterModuleLoad(object sender, EventArgs e) { try { if (this.trials == null || this.trials.Count == 0) { this.Close(); return; } // Add already navigated browser slide subnode to the trial collection TrialsIncludingNavigatedWebpages = (TrialCollection)this.trials.Clone(); foreach (var trial in this.trials) { if (trial[0].IsBrowserSlide) { var browserNode = Document.ActiveDocument.ExperimentSettings.SlideShow.GetNodeByID(trial.ID); foreach (var visitedPageNode in browserNode.Nodes) { // Also add all visited page trials for this browser slide // this can be only be one step deep var subCollectionNode = visitedPageNode as SlideshowTreeNode; if (subCollectionNode != null) { var slide = subCollectionNode.Slide; if (slide == null || slide.IsDisabled) { continue; } var subtrial = new Trial(subCollectionNode.Text, Slideshow.GetIdOfNode(subCollectionNode)); subtrial.Add(slide); TrialsIncludingNavigatedWebpages.Add(subtrial); } } } } // Show presentation on secondary screen if possible, // otherwise maximise on primary screen PresentationScreen.PutFormOnPresentationScreen(this, true); // Some slides may have a hidden cursor. this.hiddenCursor = false; // Initializes the timer this.watch = new Stopwatch(); this.watch.Start(); // Start UserCamera if (this.userCameraProperties != null) { this.InitializeUserCamera(this.userCameraProperties); if (this.userCamera != null && this.userCamera.Properties.CaptureMode != CaptureMode.None) { AsyncHelper.FireAsync(new MethodInvoker(this.userCamera.RunGraph)); } } if (this.screenCaptureProperties != null && this.screenCaptureProperties.CaptureMode != CaptureMode.None) { this.InitializeScreenCapture(this.screenCaptureProperties); } this.presentationBounds = PresentationScreen.GetPresentationWorkingArea(); // Loads first slide, or closes form if there are no slides to display. this.trialCounter = -1; this.InitializeFirstTrial(); } catch (Exception ex) { ExceptionMethods.HandleException(ex); this.Close(); } }
/////////////////////////////////////////////////////////////////////////////// // Methods and Eventhandling for Background tasks // /////////////////////////////////////////////////////////////////////////////// #region BACKGROUNDWORKER #endregion //BACKGROUNDWORKER /////////////////////////////////////////////////////////////////////////////// // Methods for doing main class job // /////////////////////////////////////////////////////////////////////////////// #region METHODS /// <summary> /// This method loads the <see cref="Trial"/> with the given ID /// into the <see cref="Picture"/> by displaying its first <see cref="Slide"/> /// if there is any. /// </summary> /// <param name="trialID">An <see cref="Int32"/> with the trial ID.</param> /// <returns><strong>True</strong> if successful, otherwise <strong>false</strong>.</returns> protected bool LoadTrialStimulus(int trialID) { this.currentTrial = Document.ActiveDocument.ExperimentSettings.SlideShow.GetTrialByID(trialID); if (this.currentTrial == null) { return false; } Slide initialSlide = this.currentTrial[0]; this.LoadSlide(initialSlide, ActiveXMode.BehindPicture); ((MainForm)this.MdiParent).StatusLabel.Text = "Ready ..."; return true; }
public bool recordTrialBlock(TrialBlockData results) { DataClasses1DataContext database = new DataClasses1DataContext(); StudiesUser x = (from su in database.StudiesUsers where su.StudyID == results.studyID && su.UserID == results.userID select su).Single(); TrialBlock newBlock = new TrialBlock(); newBlock.StudyID = results.studyID; newBlock.StartTime = results.taken; newBlock.UserID = results.userID; newBlock.TrialTypeID = results.typeID; newBlock.WordListID = x.WordListID; newBlock.WordSublistID = x.WordSublistID; database.TrialBlocks.InsertOnSubmit(newBlock); database.SubmitChanges(); int trialcount = results.clickID1s.Length; for (int i = 0; i < trialcount; i++) { Trial newTrial = new Trial(); newTrial.TrialBlockID = newBlock.ID; newTrial.WordID = results.words[i]; newTrial.TimeFirstIDpresented = results.showID1s[i]; newTrial.TimeFirstIDclicked = results.clickID1s[i]; newTrial.TimeSecondIDpresented = results.showID2s[i]; newTrial.TimeSecondIDclicked = results.clickID2s[i]; newTrial.TimeOptionsPresented = results.optionsShown[i]; newTrial.Option1ID = results.optionIDs[i][0]; newTrial.Option2ID = results.optionIDs[i][1]; newTrial.Option3ID = results.optionIDs[i][2]; newTrial.TimeOptionClicked = results.clickOptionTimes[i]; newTrial.OptionIDClicked = results.optionIDsClicked[i]; database.Trials.InsertOnSubmit(newTrial); database.SubmitChanges(); } return evalPerformance(database, newBlock.ID, newBlock.Study.TargetWordsPerMinute, results.studyID, results.userID); }
private void runTrial() { try { drawBoard(); CurrentTrial = new Trial(); CurrentTrialCount++; mainTimer.Start(); } catch (Exception e) { MessageBox.Show("Error occurred while starting trial: " + e.Message); throw e; } }
static void MainMenu() { Menu DifficultyMenu = new Menu("Select Difficulty", null, new List<Menu>{ new Menu("Beginner",(s)=>{s["Difficulty"]=Board.Difficulty.Beginner;}), new Menu("Intermediate",(s)=>{s["Difficulty"]=Board.Difficulty.Intermediate;}), new Menu("Advanced",(s)=>{s["Difficulty"]=Board.Difficulty.Advanced;}) }); Action<Dictionary<string, object>> todo = (s) => Console.Out.WriteLine("TODO"); var menu = new Menu("Main Menu", null, new List<Menu> { new Menu("Play a Game",null,new List<Menu>{ DifficultyMenu, new Menu("Play Game",(s)=>{ Board.Difficulty difficulty; if(!Menu.Load(s,"Difficulty", out difficulty)) return; new HumanPlayer(difficulty).Play(); })}), new Menu("AI Tools",null,new List<Menu>{ new Menu("View Trial",null,new List<Menu>{ new Menu("Display Stats",s=> { Trial<RuleSetSpecimen> trial; if(!Menu.Load(s,"Trial",out trial)) return; Console.WriteLine("Generation: " + trial.Generation); Console.WriteLine("Population Size: " + trial.TrialConfig.PopulationSize); Console.WriteLine("Mutation Rate: " + trial.TrialConfig.PopulationSize); Console.WriteLine("Carryover Rate: " + trial.TrialConfig.CarryoverRate); }), new Menu("Evolve",s=> { Trial<RuleSetSpecimen> trial; if(!Menu.Load(s,"Trial",out trial)) return; trial.Evolve(Menu.PromptFor<Int32>("How many generations?")); }), new Menu("Load Best",null,new List<Menu>{ new Menu ("Best Living",s=>{ Trial<RuleSetSpecimen> trial; if(!Menu.Load(s,"Trial",out trial)) return; s["Best"] = trial.GetBestLiving(); }), new Menu("Best Ever",s=>{ Trial<RuleSetSpecimen> trial; if(!Menu.Load(s,"Trial",out trial)) return; s["Best"] = trial.GetBestLiving(); }) }), new Menu("Run Best",null,new List<Menu>{ new Menu("Fast",s=>{ RuleSetSpecimen best; if(!Menu.Load(s,"Best",out best)) return; Board board = new AutoBoard(Board.Difficulty.Beginner); SmartPlayer player = new SmartPlayer(best.RuleSet, board); player.Play(); Console.Out.WriteLine(player); Console.Out.WriteLine(player.GetCurrentState()); }), new Menu("Slow",s=>{ RuleSetSpecimen best; if(!Menu.Load(s,"Best",out best)) return; Board board = new AutoBoard(Board.Difficulty.Beginner); SmartPlayer player = new SmartPlayer(best.RuleSet, board); bool halt; do { halt = player.Step(); Console.Out.WriteLine(player); Console.Out.WriteLine("Current State: "+player.GetCurrentState()); Console.Out.WriteLine("Steps Since Reveal: "+player.StepsSinceReveal); Console.ReadLine(); } while (!halt && player.GetCurrentState() == Board.State.Playing && player.StepsSinceReveal < 10); }), new Menu("Manual",todo) }) }), new Menu("New Trial",(s)=> { s["Trial"] = new Trial<RuleSetSpecimen>( Menu.PromptFor<string>("Enter Name"), new TrialConfiguration<RuleSetSpecimen> { CarryoverRate = Menu.PromptFor<Double>("Enter Carryover Rate"), MutationRate = Menu.PromptFor<Double>("Enter Mutation Rate"), PopulationSize = Menu.PromptFor<Int32>("Enter Population Size"), Stringer = new RuleSetSpecimenStringer() } ); }), new Menu("Load Trial",s=> { s["Trial"] = new Trial<RuleSetSpecimen>( Menu.PromptFor<string>("Enter Name"), new RuleSetSpecimenStringer()); }) }) }); var state = new Dictionary<string, object>(); menu.Display(state); }
public void Selector_SelectFiles() { Directory.SetCurrentDirectory(TopLevelDir); Trial[] trials = new Trial[] { new Trial { Label = "name", C1 = "name = *.txt", C2 = "name = *.bin" }, new Trial { Label = "name (shorthand)", C1 = "*.txt", C2 = "*.bin" }, new Trial { Label = "size", C1 = "size < 7500", C2 = "size >= 7500" }, new Trial { Label = "size", C1 = "size = 8080", C2 = "size != 8080" }, new Trial { Label = "name & size", C1 = "name = *.bin AND size > 7500", C2 = "name != *.bin OR size <= 7500", }, new Trial { Label = "name XOR name", C1 = "name = *.bin XOR name = *4.*", C2 = "(name != *.bin OR name = *4.*) AND (name = *.bin OR name != *4.*)", }, new Trial { Label = "name XOR size", C1 = "name = *.bin XOR size > 100k", C2 = "(name != *.bin OR size > 100k) AND (name = *.bin OR size <= 100k)", }, new Trial { Label = "mtime", C1 = String.Format("mtime < {0}", twentyDaysAgo.ToString("yyyy-MM-dd")), C2 = String.Format("mtime >= {0}", twentyDaysAgo.ToString("yyyy-MM-dd")), }, new Trial { Label = "ctime", C1 = String.Format("mtime < {0}", threeDaysAgo.ToString("yyyy-MM-dd")), C2 = String.Format("mtime >= {0}", threeDaysAgo.ToString("yyyy-MM-dd")), }, new Trial { Label = "atime", C1 = String.Format("mtime < {0}", yesterdayAtMidnight.ToString("yyyy-MM-dd")), C2 = String.Format("mtime >= {0}", yesterdayAtMidnight.ToString("yyyy-MM-dd")), }, new Trial { Label = "size (100k)", C1="size > 100k", C2="size <= 100kb", }, new Trial { Label = "size (1mb)", C1="size > 1m", C2="size <= 1mb", }, new Trial { Label = "size (1gb)", C1="size > 1g", C2="size <= 1gb", }, new Trial { Label = "attributes (Hidden)", C1 = "attributes = H", C2 = "attributes != H" }, new Trial { Label = "attributes (ReadOnly)", C1 = "attributes = R", C2 = "attributes != R" }, new Trial { Label = "attributes (System)", C1 = "attributes = S", C2 = "attributes != S" }, new Trial { Label = "attributes (Archive)", C1 = "attributes = A", C2 = "attributes != A" }, }; string zipFileToCreate = Path.Combine(TopLevelDir, "Selector_SelectFiles.zip"); Assert.IsFalse(File.Exists(zipFileToCreate), "The zip file '{0}' already exists.", zipFileToCreate); int count1, count2; //String filename = null; SetupFiles(); var topLevelFiles = Directory.GetFiles(fodderDirectory, "*.*", SearchOption.TopDirectoryOnly); for (int m = 0; m < trials.Length; m++) { Ionic.FileSelector ff = new Ionic.FileSelector(trials[m].C1); var list = ff.SelectFiles(fodderDirectory); TestContext.WriteLine("======================================================="); TestContext.WriteLine("Selector: " + ff.ToString()); TestContext.WriteLine("Criteria({0})", ff.SelectionCriteria); TestContext.WriteLine("Count({0})", list.Count); count1 = 0; foreach (string s in list) { switch (m) { case 0: case 1: Assert.IsTrue(s.EndsWith(".txt")); break; case 2: { FileInfo fi = new FileInfo(s); Assert.IsTrue(fi.Length < 7500); } break; case 4: { FileInfo fi = new FileInfo(s); bool x = s.EndsWith(".bin") && fi.Length > 7500; Assert.IsTrue(x); } break; } count1++; } ff = new Ionic.FileSelector(trials[m].C2); list = ff.SelectFiles(fodderDirectory); TestContext.WriteLine("- - - - - - - - - - - - - - - - - - - - - - - - - - - -"); TestContext.WriteLine("Criteria({0})", ff.SelectionCriteria); TestContext.WriteLine("Count({0})", list.Count); count2 = 0; foreach (string s in list) { switch (m) { case 0: case 1: Assert.IsTrue(s.EndsWith(".bin")); break; case 2: { FileInfo fi = new FileInfo(s); Assert.IsTrue(fi.Length >= 7500); } break; case 4: { FileInfo fi = new FileInfo(s); bool x = !s.EndsWith(".bin") || fi.Length <= 7500; Assert.IsTrue(x); } break; } count2++; } Assert.AreEqual<Int32>(topLevelFiles.Length, count1 + count2); } }
/// <summary> /// This method iterates recursively through the tree to return only the trials /// contained in the tree. /// </summary> /// <param name="trials">Ref. The output <see cref="TrialCollection"/> of trials.</param> /// <param name="node">The <see cref="TreeNode"/> to parse.</param> private void ParseNodeForTrials(ref TrialCollection trials, TreeNode node) { Trial trial = null; // Add trial if this node is marked to be a trial if (node.Tag != null && node.Tag.ToString() == "Trial") { trial = new Trial(node.Text, Slideshow.GetIdOfNode(node)); trials.Add(trial); } foreach (TreeNode subNode in node.Nodes) { SlideshowTreeNode subSlideNode = subNode as SlideshowTreeNode; Slide slide = subSlideNode.Slide; if (slide != null) { // By default use a new trial for each slide trial = new Trial(subNode.Text, Slideshow.GetIdOfNode(subNode)); // If parent is already marked as trial use this // instead. if (subNode.Parent != null && subNode.Parent.Tag != null && subNode.Parent.Tag.ToString() == "Trial") { trial = trials[trials.Count - 1]; } // Add slide to correct trial trial.Add(slide); } // Iterate through the tree. this.ParseNodeForTrials(ref trials, subNode); // If a trial was found, add it to the list. if (trial != null && !trials.Contains(trial)) { trials.Add(trial); } } }
/////////////////////////////////////////////////////////////////////////////// // Construction and Initializing methods // /////////////////////////////////////////////////////////////////////////////// #region CONSTRUCTION /// <summary> /// Initializes a new instance of the TrialChangedEventArgs class. /// </summary> /// <param name="newFinishedTrial">Finished trial.</param> /// <param name="newNextTrial">Next trial.</param> /// <param name="newResponse">The response of type <see cref="StopCondition"/> /// that ended the trial.</param> /// <param name="newCategory">A <see cref="string"/> with the /// slides category.</param> /// <param name="newTrialCounter">The index of the current visible trial /// in the current trial list.</param> /// <param name="newWebcamTime">The time in milliseconds of the begin of the /// webcams video section.</param> public TrialChangedEventArgs( Trial newFinishedTrial, Trial newNextTrial, StopCondition newResponse, string newCategory, int newTrialCounter, long newWebcamTime) { this.finishedTrial = newFinishedTrial; this.nextTrial = newNextTrial; this.response = newResponse; this.category = newCategory; this.trialCounter = newTrialCounter; this.webcamTime = newWebcamTime; }
/// <summary> /// The <see cref="PresenterModule.TrialChanged"/> event handler. /// Stores the trial information into the database /// and updates the live viewer with the new slide. /// </summary> /// <param name="sender"> /// Source of the event. /// </param> /// <param name="e"> /// A <see cref="TrialChangedEventArgs"/> with the event data. /// </param> private void ObjPresenterTrialChanged(object sender, TrialChangedEventArgs e) { // Set time critical values long currentTime = this.counterChangedTime; this.xScrollOffset = 0; this.yScrollOffset = 0; // If the last trial was a disabled trial (PreFixationSlide) // Only update start times if (e.FinishedTrial[e.FinishedTrial.Count - 1].IsDisabled) { // Update new trial this.currentTrialStarttime = currentTime - this.recordingStarttime; if (this.chbRecordAudio.Checked || this.chbRecordVideo.Checked) { this.currentTrialVideoStartTime = e.WebcamTime; } this.Invoke(this.delegateNewSlideAvailable); return; } if (e.FinishedTrial.Name != "DummyTrial") { // Update current trial this.precedingTrial = e.FinishedTrial; // When rawData list exceeds sample limit or this was the last trial // write the samples into the database if (this.rawDataLists[this.listCounter].Count > MINSAMPLESFORWRITINGTODATABASE || e.NextTrial == null) { // Stop recording if this was the last trial or cancelled if (e.NextTrial == null) { // Stop tracking this.currentTracker.Stop(); // Give the presentation thread time to close. Application.DoEvents(); } // switch to next raw data list for writing lock (this) { // Save copy to dataset table in new thread AsyncHelper.FireAndForget( new WaitCallback(StoreRecordsInDataSetTable), new DataToTable(this.rawDataLists[this.listCounter], this.subjectRawDataTable)); // Clear list, cause its content was copied during creation of DataToTable this.rawDataLists[this.listCounter].Clear(); this.listCounter++; if (this.listCounter == NUMWRITINGTHREADS) { this.listCounter = 0; } } } // Write new trial information var trialData = new TrialsData { SubjectName = this.currentTracker.Subject.SubjectName, TrialName = this.precedingTrial.Name, TrialSequence = this.trialSequenceCounter - 1, TrialID = this.precedingTrial.ID, Category = this.precedingTrial[0].Category, TrialStartTime = this.currentTrialStarttime, Duration = (int)(currentTime - this.recordingStarttime - this.currentTrialStarttime) }; if (this.trialSequenceCounter > 0) { this.trialDataList.Add(trialData); } // Store usercam start event if applicable if (this.chbRecordAudio.Checked || this.chbRecordVideo.Checked) { var usercamVideoEvent = new MediaEvent { EventID = this.trialEventList.Count, Param = this.currentTrialVideoStartTime.ToString(CultureInfo.InvariantCulture), Task = MediaEventTask.Start, Time = 0, Type = EventType.Usercam, SubjectName = this.currentTracker.Subject.SubjectName, TrialSequence = this.trialSequenceCounter - 1 }; if (this.trialSequenceCounter > 0) { this.trialEventList.Add(usercamVideoEvent); } } // Store subjects response event var inputEvent = new InputEvent { EventID = this.trialEventList.Count, SubjectName = this.currentTracker.Subject.SubjectName, Task = InputEventTask.SlideChange, Time = trialData.Duration, TrialSequence = this.trialSequenceCounter - 1, Type = EventType.Response }; if (e.Response != null) { inputEvent.Param = e.Response.ToString(); } if (this.trialSequenceCounter >= 0) { this.trialEventList.Add(inputEvent); } } // Update new trial this.currentTrialStarttime = currentTime - this.recordingStarttime; if (this.chbRecordAudio.Checked || this.chbRecordVideo.Checked) { this.currentTrialVideoStartTime = e.WebcamTime; } // Update recorder modules viewer var updateLiveViewerThread = new Thread(this.NewSlideAvailable); updateLiveViewerThread.SetApartmentState(ApartmentState.STA); updateLiveViewerThread.Start(); }
/////////////////////////////////////////////////////////////////////////////// // Eventhandler // /////////////////////////////////////////////////////////////////////////////// #region EVENTS /////////////////////////////////////////////////////////////////////////////// // Eventhandler for UI, Menu, Buttons, Toolbars etc. // /////////////////////////////////////////////////////////////////////////////// #region WINDOWSEVENTHANDLER #endregion //WINDOWSEVENTHANDLER /////////////////////////////////////////////////////////////////////////////// // Eventhandler for Custom Defined Events // /////////////////////////////////////////////////////////////////////////////// #region CUSTOMEVENTHANDLER #endregion //CUSTOMEVENTHANDLER #endregion //EVENTS /////////////////////////////////////////////////////////////////////////////// // Methods and Eventhandling for Background tasks // /////////////////////////////////////////////////////////////////////////////// #region BACKGROUNDWORKER #endregion //BACKGROUNDWORKER /////////////////////////////////////////////////////////////////////////////// // Methods for doing main class job // /////////////////////////////////////////////////////////////////////////////// #region PRIVATEMETHODS /// <summary> /// This method does the main job of drawing the given <see cref="Trial"/> /// in the given <see cref="Rectangle"/> using the given <see cref="Graphics"/> object. /// It calls the various drawing methods from the base class <see cref="CustomRenderer"/>. /// </summary> /// <param name="trial">The <see cref="Trial"/> to be rendered.</param> /// <param name="thumbRect">A <see cref="Rectangle"/> with the bounds for the node.</param> /// <param name="g">The <see cref="Graphics"/> to be used.</param> private void DrawTrialInRect(Trial trial, Rectangle thumbRect, Graphics g) { int slidesCount = trial.Count; Rectangle newBounds = thumbRect; newBounds.Inflate(-2, -2); int newWidth = newBounds.Width; int newHeight = newBounds.Height; if (slidesCount == 0) { StringFormat sf = new StringFormat(); sf.Alignment = StringAlignment.Center; sf.LineAlignment = StringAlignment.Center; g.DrawString("No slides defined ...", SystemFonts.MenuFont, Brushes.Black, newBounds, sf); } else if (slidesCount == 1) { Slide slide = trial[0]; g.DrawImage(slide.Thumb, newBounds); } else if (slidesCount <= 4) { g.DrawRectangle(Pens.DarkGray, newBounds); newWidth = (int)((newBounds.Width - 1) / 2f); newHeight = (int)((newBounds.Height - 1) / 2f); Rectangle subItemRect = new Rectangle(newBounds.Location, new Size(newWidth, newHeight)); for (int i = 0; i < slidesCount; i++) { Slide slide = trial[i]; g.DrawImage(slide.Thumb, subItemRect); if (i % 2 == 0) { subItemRect.Offset(newWidth + 1, 0); } else { subItemRect.Offset(-newWidth - 1, newHeight + 1); } } } else { g.DrawRectangle(Pens.DarkGray, newBounds); newWidth = (int)((newBounds.Width - 2) / 3f); newHeight = (int)((newBounds.Height - 2) / 3f); Rectangle subItemRect = new Rectangle(newBounds.Location, new Size(newWidth, newHeight)); for (int i = 0; i <= Math.Min(9, slidesCount - 1); i++) { if (i == 8 && slidesCount > 9) { int itemsLeft = slidesCount - i; g.DrawString(itemsLeft.ToString() + " more", SystemFonts.MenuFont, Brushes.Red, subItemRect); return; } Slide slide = trial[i]; g.DrawImage(slide.Thumb, subItemRect); if (i == 2 || i == 5) { subItemRect.Offset(-newWidth * 2 - 2, newHeight + 1); } else { subItemRect.Offset(newWidth + 1, 0); } } } }
private static void SerializeTest(string[] args) { BehavioralTest test = new BehavioralTest(); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(test.GetType()); FileStream stream; if (args.Length >= 2 && args[1] == "u") { stream = new FileStream("a.xml", FileMode.Open); test = (BehavioralTest)x.Deserialize(stream); foreach (Session s in test.SessionsForSerialization) { test.Sessions.Add(s); foreach (Trial t in s.TrialsForSerialization) { s.Trials.Add(t); } } stream.Close(); return; } Project project = new Project(); test.BehavioralTestType = BehavioralTestType.Fst; Session session = new Session(); Trial trial = new Trial(); trial.Duration = 360; session.TrialsForSerialization.Add(trial); test.SessionsForSerialization.Add(session); stream = new FileStream("a.xml", FileMode.Create); x.Serialize(stream, test); stream.Close(); }
private void cmbSessionCount_SelectedIndexChanged(object sender, EventArgs e) { ComboBox control = (ComboBox)sender; int sessionCount = Int32.Parse(control.SelectedItem.ToString()); RemoveSessionControls(); if (sessionCount == 0) { return; } for (int i = 0; i < sessionCount; i++) { Session session = new Session(); session.Name = String.Format("S{0}", i+1); if (_BehavioralTestTemplate != null) { if (_BehavioralTestTemplate.Sessions.Count > i) { session = _BehavioralTestTemplate.Sessions[i]; } else { Trial trial = new Trial(); trial.Name = String.Format("T{0}", 1); session.Trials.Add(trial); _BehavioralTestTemplate.Sessions.Add(session); } } else { Trial trial = new Trial(); trial.Name = String.Format("T{0}", 1); session.Trials.Add(trial); _BehavioralTestTemplate.Sessions.Add(session); } } if (_BehavioralTestTemplate.Sessions.Count > sessionCount) { for (int i = sessionCount; i < _BehavioralTestTemplate.Sessions.Count; i++) { _BehavioralTestTemplate.Sessions.Remove(_BehavioralTestTemplate.Sessions[i]); } } for (int i = 0; i < _BehavioralTestTemplate.Sessions.Count; i++) { AddSessionControl(_BehavioralTestTemplate.Sessions[i], i); } }
/// <summary> /// This static method creates a slide with a sized image /// for each trial and adds it to the slideshow. /// </summary> /// <param name="detectonSettings"> /// The <see cref="DetectionSettings"/> /// used in this import. /// </param> /// <param name="mainWindow"> /// The <see cref="MainForm"/> to get access to the status label. /// </param> public static void GenerateOgamaSlideshowTrials(DetectionSettings detectonSettings, MainForm mainWindow) { // Stores found stimuli files List<string> trialNames = Document.ActiveDocument.ExperimentSettings.SlideShow.GetTrialNames(); foreach (KeyValuePair<int, int> kvp in detectonSettings.TrialSequenceToTrialIDAssignments) { int trialID = kvp.Value; string file = string.Empty; if (detectonSettings.TrialIDToImageAssignments.ContainsKey(trialID)) { file = detectonSettings.TrialIDToImageAssignments[trialID]; } string filename = Path.GetFileNameWithoutExtension(file); // Create slide var stopConditions = new StopConditionCollection { new MouseStopCondition( MouseButtons.Left, true, string.Empty, null, Point.Empty) }; VGImage stimulusImage = null; if (file != string.Empty) { stimulusImage = new VGImage( ShapeDrawAction.None, Pens.Black, Brushes.Black, SystemFonts.MenuFont, Color.White, Path.GetFileName(file), Document.ActiveDocument.ExperimentSettings.SlideResourcesPath, ImageLayout.Zoom, 1f, Document.ActiveDocument.PresentationSize, VGStyleGroup.None, filename, string.Empty, true) { Size = Document.ActiveDocument.PresentationSize }; } var newSlide = new Slide( filename, Color.White, null, stopConditions, null, string.Empty, Document.ActiveDocument.PresentationSize) { Modified = true, MouseCursorVisible = true }; // Only add stimulus if an image exists if (file != string.Empty) { newSlide.VGStimuli.Add(stimulusImage); } else { newSlide.Name = "No stimulus detected"; } // Create trial if (Document.ActiveDocument.ExperimentSettings.SlideShow.GetNodeByID(trialID) != null) { // trialID = int.Parse(Document.ActiveDocument.ExperimentSettings.SlideShow.GetUnusedNodeID()); // var message = string.Format("The trial with the ID:{0} exists already in the slideshow so it will not be created." // + Environment.NewLine + "Delete the trial with this ID in the slideshow design module if you want it to be newly created by the importer, or assign a new ID to the imported data.", trialID); // ExceptionMethods.ProcessMessage("This trial exists already", message); continue; } var newTrial = new Trial(filename, trialID) { Name = filename }; newTrial.Add(newSlide); if (trialNames.Contains(filename) || (filename == string.Empty && trialNames.Contains("No stimulus detected"))) { // Trial already exists continue; } trialNames.Add(filename); // Create slide node var slideNode = new SlideshowTreeNode(newSlide.Name) { Name = trialID.ToString(CultureInfo.InvariantCulture), Slide = newSlide }; // Add slide node to slideshow Document.ActiveDocument.ExperimentSettings.SlideShow.Nodes.Add(slideNode); Document.ActiveDocument.Modified = true; } mainWindow.StatusLabel.Text = "Saving slideshow to file ..."; if (!Document.ActiveDocument.SaveSettingsToFile(Document.ActiveDocument.ExperimentSettings.DocumentFilename)) { ExceptionMethods.ProcessErrorMessage("Couldn't save slideshow to experiment settings."); } mainWindow.StatusLabel.Text = "Refreshing context panel ..."; mainWindow.RefreshContextPanelImageTabs(); mainWindow.StatusLabel.Text = "Ready ..."; mainWindow.StatusProgressbar.Value = 0; }
public void Selector_AddSelectedFiles() { Directory.SetCurrentDirectory(TopLevelDir); Trial[] trials = new Trial[] { new Trial { Label = "name", C1 = "name = *.txt", C2 = "name = *.bin" }, new Trial { Label = "name (shorthand)", C1 = "*.txt", C2 = "*.bin" }, new Trial { Label = "attributes (Hidden)", C1 = "attributes = H", C2 = "attributes != H" }, new Trial { Label = "attributes (ReadOnly)", C1 = "attributes = R", C2 = "attributes != R" }, new Trial { Label = "mtime", C1 = "mtime < 2007-01-01", C2 = "mtime > 2007-01-01" }, new Trial { Label = "atime", C1 = "atime < 2007-01-01", C2 = "atime > 2007-01-01" }, new Trial { Label = "ctime", C1 = "ctime < 2007-01-01", C2 = "ctime > 2007-01-01" }, new Trial { Label = "size", C1 = "size < 7500", C2 = "size >= 7500" }, new Trial { Label = "name & size", C1 = "name = *.bin AND size > 7500", C2 = "name != *.bin OR size <= 7500", }, new Trial { Label = "name, size & attributes", C1 = "name = *.bin AND size > 8kb and attributes = H", C2 = "name != *.bin OR size <= 8kb or attributes != H", }, new Trial { Label = "name, size, time & attributes.", C1 = "name = *.bin AND size > 7k and mtime < 2007-01-01 and attributes = H", C2 = "name != *.bin OR size <= 7k or mtime > 2007-01-01 or attributes != H", }, }; _txrx = TestUtilities.StartProgressMonitor("AddSelectedFiles", "AddSelectedFiles", "starting up..."); string[] zipFileToCreate = { Path.Combine(TopLevelDir, "Selector_AddSelectedFiles-1.zip"), Path.Combine(TopLevelDir, "Selector_AddSelectedFiles-2.zip") }; Assert.IsFalse(File.Exists(zipFileToCreate[0]), "The zip file '{0}' already exists.", zipFileToCreate[0]); Assert.IsFalse(File.Exists(zipFileToCreate[1]), "The zip file '{0}' already exists.", zipFileToCreate[1]); int count1, count2; SetupFiles(); var topLevelFiles = Directory.GetFiles(fodderDirectory, "*.*", SearchOption.TopDirectoryOnly); string currentDir = Directory.GetCurrentDirectory(); _txrx.Send(String.Format("pb 0 max {0}", 2 * (trials.Length + 1))); _txrx.Send("pb 0 step"); for (int m = 0; m < trials.Length; m++) { _txrx.Send("test AddSelectedFiles"); _txrx.Send("pb 1 max 4"); _txrx.Send(String.Format("status test {0}/{1}: creating zip #1/2", m + 1, trials.Length)); TestContext.WriteLine("==============================================="); TestContext.WriteLine("AddSelectedFiles() [{0}]", trials[m].Label); using (ZipFile zip1 = new ZipFile()) { zip1.AddSelectedFiles(trials[m].C1, fodderDirectory, ""); zip1.Save(zipFileToCreate[0]); } count1 = TestUtilities.CountEntries(zipFileToCreate[0]); TestContext.WriteLine("C1({0}) Count({1})", trials[m].C1, count1); _txrx.Send("pb 1 step"); System.Threading.Thread.Sleep(100); _txrx.Send("pb 0 step"); _txrx.Send(String.Format("status test {0}/{1}: creating zip #2/2", m + 1, trials.Length)); using (ZipFile zip1 = new ZipFile()) { zip1.AddSelectedFiles(trials[m].C2, fodderDirectory, ""); zip1.Save(zipFileToCreate[1]); } count2 = TestUtilities.CountEntries(zipFileToCreate[1]); TestContext.WriteLine("C2({0}) Count({1})", trials[m].C2, count2); Assert.AreEqual<Int32>(topLevelFiles.Length, count1 + count2); _txrx.Send("pb 1 step"); /// ======================================================= /// Now, select entries from that ZIP _txrx.Send(String.Format("status test {0}/{1}: selecting zip #1/2", m + 1, trials.Length)); using (ZipFile zip1 = ZipFile.Read(zipFileToCreate[0])) { var selected1 = zip1.SelectEntries(trials[m].C1); Assert.AreEqual<Int32>(selected1.Count, count1); } _txrx.Send("pb 1 step"); _txrx.Send(String.Format("status test {0}/{1}: selecting zip #2/2", m + 1, trials.Length)); using (ZipFile zip1 = ZipFile.Read(zipFileToCreate[1])) { var selected2 = zip1.SelectEntries(trials[m].C2); Assert.AreEqual<Int32>(selected2.Count, count2); } _txrx.Send("pb 1 step"); _txrx.Send("pb 0 step"); } }
/// <summary> /// The web browser_ navigating lock. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void WebBrowserNavigatingLock(object sender, WebBrowserNavigatingEventArgs e) { try { // Get WebBrowser object var browser = sender as WebBrowser; // Check if website has frames which leads to multiple // calls to navigated for each frame if (this.isWebbrowserClicked) { // Reset flag to avoid multiple trial notifications on frame loading this.isWebbrowserClicked = false; // Disable navigation, if max browse depth is reached this.numberOfTimesNavigated++; if (this.numberOfTimesNavigated >= this.maxBrowseDepth) { if (browser != null) { browser.AllowNavigation = false; } } // Get slideshow var documentsSlideshow = Document.ActiveDocument.ExperimentSettings.SlideShow; // Make screenshot of newly navigated web page in // separate thread, if it is not already there. var screenshotFilename = BrowserDialog.GetFilenameFromUrl(e.Url); // WebsiteScreenshot.Instance.ScreenshotFilename = screenshotFilename; if (!this.currentBrowserTreeNode.UrlToID.ContainsKey(screenshotFilename)) { // This webpage has never been visited before, so get a new id // and create slide and slideshownode for the slideshow var newTrialId = Convert.ToInt32(documentsSlideshow.GetUnusedNodeID()); this.currentBrowserTreeNode.UrlToID.Add(screenshotFilename, newTrialId); // Create new trial var newName = Path.GetFileNameWithoutExtension(screenshotFilename); var newWebpageTrial = new Trial(newName, newTrialId); // Create VGScrollImageSlide var newWebpageSlide = (Slide)this.shownSlideContainer.Slide.Clone(); newWebpageSlide.Modified = true; if (!newWebpageSlide.IsThumbNull) { newWebpageSlide.Thumb.Dispose(); newWebpageSlide.Thumb = null; } newWebpageSlide.Name = newName; newWebpageSlide.ActiveXStimuli.Clear(); newWebpageSlide.VGStimuli.Clear(); var baseUrlScreenshot = new VGScrollImage( ShapeDrawAction.None, Pens.Transparent, Brushes.Black, SystemFonts.DefaultFont, Color.Black, Path.GetFileName(screenshotFilename), Document.ActiveDocument.ExperimentSettings.SlideResourcesPath, ImageLayout.None, 1f, Document.ActiveDocument.PresentationSize, VGStyleGroup.None, newWebpageSlide.Name, string.Empty); newWebpageSlide.VGStimuli.Add(baseUrlScreenshot); // Finish creating new trial newWebpageTrial.Add(newWebpageSlide); // Update trial lists with new trial TrialsIncludingNavigatedWebpages.Add(newWebpageTrial); // Now update slideshow with new trial // Create node var slideNode = new SlideshowTreeNode(newName); slideNode.Name = newTrialId.ToString(CultureInfo.InvariantCulture); slideNode.Slide = newWebpageSlide; // Add node to slideshow at browser tree node subgroup this.currentBrowserTreeNode.Nodes.Add(slideNode); documentsSlideshow.IsModified = true; Document.ActiveDocument.Modified = true; } if (this.getTimeMethod != null) { this.getTimeMethod(); } // Get the corrent trial ID // use the existing, if we have already a screenshot of this url var trialID = this.currentBrowserTreeNode.UrlToID[screenshotFilename]; var trialIndex = TrialsIncludingNavigatedWebpages.GetIndexOfTrialByID(trialID); var trial = TrialsIncludingNavigatedWebpages[trialIndex]; // Reset slide counter // but do not increase trial counter, otherwise // we would have wrong counting in CheckForSlideChange // instead note the trials added this.slideCounter = 0; this.trialsAdded++; // Send counter changed event to increase trial sequence // and update recorders control view this.OnCounterChanged(new CounterChangedEventArgs(trialID, this.slideCounter)); var webcamTime = this.userCamera != null ? this.userCamera.GetCurrentTime() : -1; var navigatedCondition = new NavigatedStopCondition(e.Url); this.OnTrialChanged( new TrialChangedEventArgs( this.shownSlideContainer.Trial, trial, navigatedCondition, "Webpage", this.trialCounter + this.trialsAdded, webcamTime)); // Update shown slide container this.shownSlideContainer.Trial = trial; this.shownSlideContainer.Slide = trial[0]; var fullFile = Path.Combine(Document.ActiveDocument.ExperimentSettings.SlideResourcesPath, screenshotFilename); if (!File.Exists(fullFile)) { // Create screenshot on Document completed event using // the filename stated above var navigateThread = new Thread(this.NavigateMirror); navigateThread.SetApartmentState(ApartmentState.STA); var parameters = new object[2]; parameters[0] = e; parameters[1] = fullFile; navigateThread.Start(parameters); } } } catch (Exception ex) { ExceptionMethods.HandleException(ex); } }
/// <summary> /// This method iterates the slideshow recursively to find the /// trial with the given ID. /// </summary> /// <param name="trialID">An <see cref="Int32"/> with the trial id to search for.</param> /// <returns>The <see cref="Trial"/> that matches the trial id.</returns> public Trial GetTrialByID(int trialID) { SlideshowTreeNode trialNode = IterateTreeNodes(trialID.ToString(), this, true); if (trialNode != null) { Trial trial = new Trial(trialNode.Text, trialID); if (trialNode.Slide != null) { if (trialNode.Parent.Tag != null && trialNode.Parent.Tag.ToString() == "Trial") { trial = new Trial(trialNode.Parent.Text, Convert.ToInt32(trialNode.Parent.Name)); foreach (SlideshowTreeNode slideNode in trialNode.Parent.Nodes) { trial.Add((Slide)slideNode.Slide.Clone()); } } else { trial.Add((Slide)trialNode.Slide.Clone()); } } else if (trialNode.Nodes.Count > 0 && (trialNode.Tag != null && trialNode.Tag.ToString() == "Trial")) { foreach (SlideshowTreeNode slideNode in trialNode.Nodes) { trial.Add((Slide)slideNode.Slide.Clone()); } } return trial; } return null; }
/////////////////////////////////////////////////////////////////////////////// // Eventhandler for Custom Defined Events // /////////////////////////////////////////////////////////////////////////////// /// <summary> /// The <see cref="PresenterModule.CounterChanged"/> event handler. /// Indicates a slide change in the presenter, so update trial and slide /// counter and the live viewer. /// </summary> /// <param name="sender"> /// Source of the event. /// </param> /// <param name="e"> /// A <see cref="CounterChangedEventArgs"/> with the event data. /// </param> private void ObjPresenterCounterChanged(object sender, CounterChangedEventArgs e) { this.counterChangedTime = this.GetCurrentTime(); if (this.counterChangedTime < 0) { throw new ArgumentException("Tracking had not been started"); } if (this.recordingStarttime == -5) { this.recordingStarttime = this.counterChangedTime; this.recordTimerWatch.Start(); this.tmrRecordClock.Start(); // Start update timer of control panel viewer this.Picture.StartAnimation(); } lock (this) { this.slideCounter = e.SlideCounter; // Don´t use presenters trialCounter // Because of using links between trials. // and care of trials with multiple slides // don´t increase trial sequence counter on this. if (this.slideCounter == 0) { this.trialSequenceCounter++; } // Set current trial if (e.TrialID == -5) { this.currentTrial = null; } else { var trialIndex = this.trials.GetIndexOfTrialByID(e.TrialID); if (trialIndex < 0) { // The trial is not in the default trial list, so it might has been created during recording // or is a subtrial of a browsing trial trialIndex = PresenterModule.TrialsIncludingNavigatedWebpages.GetIndexOfTrialByID(e.TrialID); this.currentTrial = (Trial)PresenterModule.TrialsIncludingNavigatedWebpages[trialIndex].Clone(); } else { this.currentTrial = this.trials[trialIndex]; } } // Set current slide this.currentSlide = this.currentTrial != null ? this.currentTrial[this.slideCounter] : null; } }
/// <summary> /// Inserts the pre slide trials. /// </summary> /// <param name="trials">The trials.</param> private void InsertPreSlideTrials(ref TrialCollection trials) { var trialsWithPreSlideTrials = new TrialCollection(); foreach (var trial in trials) { foreach (var slideobject in trial) { // if we have a preslide fixation trial add this trial before var preSlideTrialID = slideobject.IdOfPreSlideFixationTrial; if (preSlideTrialID != -1) { var preSlideNode = this.GetNodeByID(preSlideTrialID); var preTrial = new Trial(preSlideNode.Text, preSlideTrialID); preTrial.AddRange(this.GetPreSlideTrialSlides(preSlideNode)); trialsWithPreSlideTrials.Add(preTrial); } } trialsWithPreSlideTrials.Add(trial); } trials = trialsWithPreSlideTrials; }
/// <summary> /// This method resets the recording module by calling /// <see cref="ITracker.Stop()" /> for the current tracker. /// </summary> private void ResetRecordInterface() { this.currentTracker.Stop(); ((MainForm)this.MdiParent).StatusLabel.Text = "Ready..."; this.currentSlide = null; // Reset counters this.trialSequenceCounter = -1; this.slideCounter = 0; this.recordingStarttime = -5; this.lastTimeStamp = -1; this.currentTrial = null; this.currentSlide = DefaultSlide; this.recordTimerWatch.Reset(); this.tmrRecordClock.Stop(); this.tmrRecordClock.Dispose(); this.tmrRecordClock = new System.Windows.Forms.Timer { Interval = 1000 }; this.tmrRecordClock.Tick += this.TmrRecordClockTick; // Stop updating viewer this.Picture.StopAnimation(); this.Picture.ResetPicture(); // Redraw panel this.NewSlideAvailable(); // this.forcePanelViewerUpdate = true; this.forcePanelViewerUpdate = false; }
/// <summary> /// This method iterates recursively through the tree to return a /// shuffled trial collection. /// </summary> /// <param name="node">The <see cref="TreeNode"/> to parse.</param> /// <returns>A <see cref="List{Object}"/> with the shuffled trials separated in /// shuffle groups.</returns> private List<object> ParseNodeForRandomizedTrials(TreeNode node) { var items = new List<object>(); var parentNode = node as SlideshowTreeNode; if (this.shuffling.UseThisCustomShuffling) { if (Convert.ToInt32(parentNode.Name) == this.shuffling.ShuffleSectionsParentNodeID) { return this.ParseNodeForCustomShuffledTrials(node); } } if (parentNode.Tag != null && parentNode.Tag.ToString() == "Trial") { var trial = new Trial(parentNode.Text, GetIdOfNode(parentNode)); foreach (SlideshowTreeNode subNode in parentNode.Nodes) { var slide = subNode.Slide; if (slide != null && !slide.IsDisabled) { //// if we have a preslide fixation trial add the slides before //var preSlideTrialID = slide.IdOfPreSlideFixationTrial; //if (preSlideTrialID != -1) //{ // var preSlideNode = this.GetNodeByID(preSlideTrialID); // trial.AddRange(this.GetPreSlideTrialSlides(preSlideNode)); //} trial.Add(slide); } } if (trial.Count > 0) { items.Add(trial); } } else { foreach (TreeNode subNode in node.Nodes) { var subCollectionNode = subNode as SlideshowTreeNode; if (subCollectionNode is BrowserTreeNode) { var trial = new Trial(subNode.Text, GetIdOfNode(subNode)); var browserSlide = this.CreateBrowserSlide(subCollectionNode as BrowserTreeNode); if (!browserSlide.IsDisabled) { //// if we have a preslide fixation trial add this trial before //var preSlideTrialID = browserSlide.IdOfPreSlideFixationTrial; //if (preSlideTrialID != -1) //{ // var preSlideNode = this.GetNodeByID(preSlideTrialID); // var preTrial = new Trial(preSlideNode.Text, preSlideTrialID); // preTrial.AddRange(this.GetPreSlideTrialSlides(preSlideNode)); // items.Add(preTrial); //} trial.Add(browserSlide); items.Add(trial); } } else { var slide = subCollectionNode.Slide; if (slide != null && !slide.IsDisabled) { var trial = new Trial(subNode.Text, GetIdOfNode(subNode)); //// if we have a preslide fixation trial add this trial before //var preSlideTrialID = slide.IdOfPreSlideFixationTrial; //if (preSlideTrialID != -1) //{ // var preSlideNode = this.GetNodeByID(preSlideTrialID); // var preTrial = new Trial(preSlideNode.Text, preSlideTrialID); // preTrial.AddRange(this.GetPreSlideTrialSlides(preSlideNode)); // items.Add(preTrial); //} trial.Add(slide); items.Add(trial); } else { items.Add(this.ParseNodeForRandomizedTrials(subNode)); } } } if (parentNode.Randomize) { items = (List<object>)CollectionUtils<object>.Shuffle(items); if (parentNode.NumberOfItemsToUse != 0) { items.RemoveRange(parentNode.NumberOfItemsToUse, items.Count - parentNode.NumberOfItemsToUse); } } } return items; }