コード例 #1
0
ファイル: Server.cs プロジェクト: 89sos98/iveely
 /// <summary>
 /// 带处理过程的构造方法
 /// </summary>
 /// <param name="host">IP地址</param>
 /// <param name="port">端口号</param>
 /// <param name="processing">数据处理过程</param>
 /// <param name="maxVisitThread"></param>
 public Server(string host, int port, Processing processing, int maxVisitThread = 1)
 {
     _isListening = false;
     _address = host;
     _port = port;
     _processing = processing;
     _maxVisitThread = maxVisitThread;
 }
コード例 #2
0
ファイル: OrgProcessing.cs プロジェクト: Garreye/meticumedia
        /// <summary>
        /// Constructor with processing method to apply to OrgPath items during run.
        /// </summary>
        /// <param name="process">Delegate for processing OrgPath items during run</param>
        public OrgProcessing(Processing process)
        {
            // Store process
            this.process = process;

            // Set process number
            lock (totalLock)
                this.ProcessNumber = OrgProcessing.totalProcesses++;
        }
コード例 #3
0
        public Boolean InitialProc(string sIDNo)
        {
            PhilipGoldIron.Bll.Processing proc = new Processing();
            bool result = false;

            //Verify ID Number
            bool test = proc.VerifyPeopleID(sIDNo);

            return result;
        }
コード例 #4
0
ファイル: FadeManager.cs プロジェクト: Kuvo/Primary
    /// <summary>
    /// フェードイン、フェードアウトでシーンを切り替える
    /// </summary>
    /// <param name='scene'>シーン名</param>
    /// <param name='interval'>暗転にかかる時間(秒)</param>
    public void Fade(string scene, float interval = 0.5f, Processing processing = null)
    {
        if (IsFading)
        {
            Debug.Log("フェード中です。");
            return;
        }

        StartCoroutine(TransScene(scene, interval, processing));
    }
コード例 #5
0
		/// <summary>
		/// Initializes internal variables used to read the message
		/// </summary>
		private void InitVars()
		{
			// reset our internal vars
			_state = Processing.FirstLine;
			_chunk = null;
			_chunkedBody = null;
            _parser = new HttpByteParser();
			_receivedBytes = null;
			_headerOffsetStart = -1;
			_headerOffsetEnd = -1;			
		}
コード例 #6
0
ファイル: NextAnalysis.cs プロジェクト: Nefarin/DadmProject
 public void Process(Processing process, out IProcessingState timeoutState)
 {
     process.Modules.CurrentAnalysisIndex++;
     if (process.Modules.CurrentAnalysisIndex < process.Modules.Amount())
     {
         timeoutState = new ProcessAnalysis();
     }
     else
     {
         timeoutState = new Idle(5);
     }
 }
コード例 #7
0
 static void Main(string[] args)
 {
     if (checkParams(args))
       {
     readInputFile(args[0]);
     var prozessingHelper = new Processing(items[0].FileName);
     //var slide = prozessingHelper.Slide;
       }
       else
       {
     Console.WriteLine("Eine Alternative Eingabe wählen:");
     Console.WriteLine("StromaDetection.exe <eingabe.csv> <ausgabe.csv>");
     Console.WriteLine("StromaDetection.exe <eingabe.png> <ausgabe.csv>");
       }
 }
コード例 #8
0
        private static void ExtendHomeLocation(Location homeLocation)
        {
            if (homeLocation == null)
                return;

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (homeLocation.Longitude == 0 || homeLocation.Latitude == 0)
                return;

            var location = Processing.SetLocationDetails(homeLocation.Latitude, homeLocation.Longitude);

            homeLocation.Name = location.Name;
            homeLocation.City = location.City;
            homeLocation.Country = location.Country;
            homeLocation.CountryIsoCode = location.CountryIsoCode;
            homeLocation.County = location.County;
        }
コード例 #9
0
        public void CropImage_When_Passed_An_Image_With_Coordinates_TopLeft_And_A_New_Size_4_Pixels_Different_Than_Original_Size_Returns_Message_Dimensions_Invalid_And_Returns_Original_Image()
        {
            //Arrange
            Bitmap    originalImage  = new Bitmap(@"C:\Users\Public\test_224_299_Image.bmp");
            int       oldImageWidth  = originalImage.Width;
            int       oldImageHeight = originalImage.Height;
            Rectangle size           = new Rectangle(0, 0, oldImageWidth - 4, oldImageHeight - 4);

            //Act
            Dictionary <string, Image> result = Processing.CropImage(originalImage, size);
            Bitmap croppedImage        = (Bitmap)result.FirstOrDefault().Value;
            string croppedImageMessage = result.FirstOrDefault().Key;

            //Assert
            Assert.AreEqual(croppedImage, originalImage);
            Assert.AreEqual(croppedImageMessage, "Crop Dimensions invalid, Please choose new valid values");
        }
コード例 #10
0
        public async void CancelTask()
        {
            var cts = new CancellationTokenSource();

            try
            {
                await Task.WhenAll(
                    CancellableMethodAsync(cts.Token),
                    CancelAfter2Sec(cts));

                Processing.SetState(1, "Le traitement est terminé.", false);
            }
            catch (OperationCanceledException)
            {
                Processing.SetState(Processing.Progress, "Le traitement a été annulé.", false);
            }
        }
コード例 #11
0
        public void GetCenter_TestImage_EqualsReference()
        {
            testImg.New("Quarters", new int[] { 20, 20 });
            byte[,] slice   = testImg.Image.ToByte();
            byte[,,] volume = new byte[20, 20, 1];
            for (int i = 0; i < slice.GetLength(0); i++)
            {
                for (int j = 0; j < slice.GetLength(1); j++)
                {
                    volume[i, j, 0] = slice[i, j];
                }
            }

            int[] center = Processing.GetCenter(volume, 3);

            Assert.Equal(new int[] { 14, 14 }, center);
        }
コード例 #12
0
ファイル: App.xaml.cs プロジェクト: MadManLabs/VideoConvert
        private void ApplicationStartup(object sender, StartupEventArgs e)
        {
            bool savedFirstStart = AppSettings.FirstStart;

            if (savedFirstStart)
            {
                AppSettings.Upgrade();
// ReSharper disable ConditionIsAlwaysTrueOrFalse
                AppSettings.FirstStart = savedFirstStart;
// ReSharper restore ConditionIsAlwaysTrueOrFalse
            }

            ReconfigureLogger();
            ReconfigureLanguage(AppSettings.UseLanguage);

            Log.InfoFormat("Use Language: {0:s}", AppSettings.UseLanguage);
            Log.InfoFormat("VideoConvert v{0:s} started", AppSettings.GetAppVersion().ToString(4));
            Log.InfoFormat("OS-Version: {0:s}", Environment.OSVersion.VersionString);
            Log.InfoFormat("CPU-Count: {0:g}", Environment.ProcessorCount);
            Log.InfoFormat(".NET Version: {0:s}", Environment.Version.ToString(4));
            Log.InfoFormat("System Uptime: {0:s}", TimeSpan.FromMilliseconds(Environment.TickCount).ToString("c"));

            bool elevated = false;

            try
            {
                elevated = Processing.IsProcessElevated();
            }
            catch (Exception)
            {
                Log.Error("Could not determine process elevation status");
            }

            if (Environment.OSVersion.Version.Major >= 6)
            {
                Log.InfoFormat("Process Elevated: {0:s}", elevated.ToString(Cinfo));
            }

            Extensions supExt = new Extensions();

            CpuExtensions.GetExtensions(out supExt);
            InspectCpuExtensions(supExt);

            ReconfigureRenderMode();
        }
コード例 #13
0
        /// <summary>
        /// Aktualisiert ein vorhandenes Foto mit dem übergebenen
        /// </summary>
        /// <param name="imageStream">Stream des Fotos</param>
        /// <param name="existingPhoto">Daten es existierenden Fotos</param>
        /// <returns></returns>
        public Photo UpdatePhoto(Stream imageStream, Photo existingPhoto)
        {
            try
            {
                var folderId = existingPhoto.Folder;
                existingPhoto.DirectLinks.Clear();
                BackupExistingFiles(folderId);

                ReadMetaInformation(imageStream, existingPhoto);

                if (Processing.CorrectImageRotation(ref imageStream, existingPhoto.Exif) !=
                    RotateFlipType.RotateNoneFlipNone)
                {
                    CorrectPhotoInformation(existingPhoto);
                }

                imageStream.Seek(0, SeekOrigin.Begin);
                var fileId = UploadFile(folderId, FullsizeFileName, imageStream, true);
                var link   = GetContentLink(fileId);

                CreateThumbNails(imageStream, folderId, existingPhoto);

                var domColor = Processing.GetDominantColor(imageStream);
                existingPhoto.Color = domColor;

                imageStream.Close();
                imageStream.Dispose();

                existingPhoto.DirectLinks.Add(new DirectLink {
                    Size = 0, Url = link
                });
                CheckForExistingLocation(existingPhoto);
                ExtractCategoriesAndTopics(existingPhoto);

                DeleteBackupedFiles(folderId);

                return(existingPhoto);
            }
            catch
            {
                ProcessGlitch(imageStream, existingPhoto.Name, true);
                //Der Fehler muss nach oben gereicht werden, damit er in der obersten Ebene behandelt wird
                throw;
            }
        }
コード例 #14
0
            private void OnNewCandles(CandleSeries series, IEnumerable <Candle> candles)
            {
                if (!_series.Contains(series))
                {
                    return;
                }

                foreach (var c in candles)
                {
                    var candle = c.Clone();

                    candle.State = CandleStates.Active;
                    Processing?.Invoke(series, candle);

                    candle.State = CandleStates.Finished;
                    Processing?.Invoke(series, candle);
                }
            }
コード例 #15
0
ファイル: PreProcessor.cs プロジェクト: Donaldpherman/OOPIE
        public PreProcessor()
        {
            // By default we are preprocessing input
            Processing.Push(true);

            // Grab what's defined from the command line
            string[] args = Environment.GetCommandLineArgs();
            for (int n = 0; n < args.Length; ++n)
            {
                if (args[n] == "-D")
                {
                    if ((n + 1) < args.Length)
                    {
                        MacroDefines.Add(args[n + 1], string.Empty);
                    }
                }
            }
        }
コード例 #16
0
            private void ProcessCandle(SeriesInfo info, CandleMessage candleMsg)
            {
                if (info.CurrentCandle != null && info.CurrentCandle.OpenTime == candleMsg.OpenTime)
                {
                    if (info.CurrentCandle.State == CandleStates.Finished)
                    {
                        return;
                    }

                    info.CurrentCandle.Update(candleMsg);
                }
                else
                {
                    info.CurrentCandle = candleMsg.ToCandle(info.Series);
                }

                Processing?.Invoke(info.Series, info.CurrentCandle);
            }
コード例 #17
0
 public void BindBatches()
 {
     if (!string.IsNullOrEmpty(Convert.ToString(drpFaculty.Text)))
     {
         Processing term = new Processing();
         drp_Batch.DataSource     = term.BindBatch(0, "", Convert.ToInt32(drpFaculty.SelectedValue), 0, 0, 0, Convert.ToInt32(DrpTerm.SelectedValue), "SelectByFaculty", 0, DateTime.Now, DateTime.Now, DateTime.Now, "");
         drp_Batch.DataTextField  = "BatchCode";
         drp_Batch.DataValueField = "Batch_id";
         drp_Batch.DataBind();
         drp_Batch.Items.Insert(0, new ListItem("Select", "0"));
     }
     else
     {
         drp_Batch.DataSource = null;
         drp_Batch.DataBind();
         drp_Batch.Items.Insert(0, new ListItem("Select", "0"));
     }
 }
コード例 #18
0
        // General Purpose Functions //


        // Also saves current selected customer values if chosen
        private void Save(bool displayMessage)
        {
            //Takes what is currently in sidepanel and appends to customer's data
            customers[selected_customer_index].accountNumber = CI_AccountNumber.Text;
            customers[selected_customer_index].address       = CI_Address.Text;
            customers[selected_customer_index].comment       = CI_Comment.Text;
            customers[selected_customer_index].phoneNumber   = CI_Phone.Text;
            customers[selected_customer_index].name          = CI_Name.Text;
            customers[selected_customer_index].town          = CI_Town.Text;

            //Once done appending new data save to file
            Processing.SaveData(customers, savePath, displayMessage);

            //Save user prefs
            Processing.SavePrefs(savePrefsPath, themeIndex);

            //Processing.Encrypt(savePath, "test");
        }
コード例 #19
0
        public void CropImage_When_Passed_An_Image_With_Coordinates_TopLeft_And_A_New_Size_Of_265_198_Returns_Message_Success_And_Returns_Correct_New_Width_And_Height_Within_A_Tolerance_Of_7_Pixels()
        {
            //Arrange
            Bitmap    originalImage = new Bitmap(@"C:\Users\Public\test_224_299_Image.bmp");
            Rectangle size          = new Rectangle(0, 0, 265, 198);

            //Act
            Dictionary <string, Image> result = Processing.CropImage(originalImage, size);
            Bitmap croppedImage        = (Bitmap)result.FirstOrDefault().Value;
            string croppedImageMessage = result.FirstOrDefault().Key;
            int    newWidth            = croppedImage.Width;
            int    newHeight           = croppedImage.Height;

            //Assert
            Assert.IsTrue(272 > newWidth && newWidth > 258);
            Assert.IsTrue(205 > newHeight && newHeight > 190);
            Assert.AreEqual(croppedImageMessage, "Success");
        }
コード例 #20
0
 private void UserControlLoaded(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrEmpty(AppSettings.ToolsPath))
     {
         string msg = Processing.GetResourceString("update_error_encpath");
         Xceed.Wpf.Toolkit.MessageBox.Show(msg, "Error",
                                           MessageBoxButton.OK, MessageBoxImage.Error);
     }
     else
     {
         BackgroundWorker checkUpdate = new BackgroundWorker {
             WorkerReportsProgress = true, WorkerSupportsCancellation = true
         };
         checkUpdate.RunWorkerCompleted += CheckUpdateRunWorkerCompleted;
         checkUpdate.DoWork             += CheckUpdateDoWork;
         checkUpdate.RunWorkerAsync();
     }
 }
コード例 #21
0
        private async Task PossiblySynchronousMethodAsync(bool shouldBeSynchronous)
        {
            if (shouldBeSynchronous)
            {
                // Sur ce chemin d'exécution, aucun await n'est fait,
                // donc le traitement est effectué de manière synchrone.
                Processing.WriteText("Le traitement est synchrone.");
                Processing.DoSomeHeavyProcessing();
                Processing.WriteText("Fin du traitement synchrone.");
            }
            else
            {
                Processing.WriteText("Le traitement est asynchrone.");
                await Processing.DoSomeHeavyProcessingAsync();

                Processing.WriteText("Fin du traitement asynchrone.");
            }
        }
コード例 #22
0
    protected void BindDropdownList()
    {
        try
        {
            Processing P = new Processing();
            DrpSemester.DataSource     = P.BindSem();
            DrpSemester.DataValueField = "Semester_RefID";
            DrpSemester.DataTextField  = "Semester_Desc";
            DrpSemester.DataBind();

            PopulateBatchCode();

            populateBatchSession();
        }
        catch (Exception ex)
        {
        }
    }
コード例 #23
0
    /// <summary>
    /// 実際にフェードアウトを実行
    /// </summary>
    /// <param name="interval">暗転にかかる時間(秒)</param>
    /// <param name="sortOrder">フェードを掛ける面</param>
    /// <param name="startColor">色</param>
    /// <param name="processing">フェードアウト完了時に実行する処理</param>
    /// <returns></returns>
    private IEnumerator TransScene(float interval, int sortOrder, Color startColor, Processing processing)
    {
        fadeCanvas = Instantiate(fadeCanvasPrefab).GetComponent <Canvas>();
        // シーン遷移が行われても問題なく動作するように、破棄しないようにする
        DontDestroyOnLoad(fadeCanvas.gameObject);
        fadeImage       = fadeCanvas.GetComponentInChildren <Image>();
        fadeImage.color = startColor;

        //だんだん暗く
        IsFading = true;
        float time = 0;

        while (time <= interval)
        {
            //this.FadeAlpha = Mathf.Lerp(0f, 1f, time / interval);
            var c = fadeImage.color;
            c.a             = Mathf.Lerp(0f, 1f, time / interval);
            fadeImage.color = c;
            time           += Time.deltaTime;
            yield return(0);
        }

        // フェード中に実行する処理
        if (processing != null)
        {
            processing();
        }

        //だんだん明るく
        time = 0;
        while (time <= interval)
        {
            //this.FadeAlpha = Mathf.Lerp(1.0f, 0.0f, time / interval);
            var c = fadeImage.color;
            c.a             = Mathf.Lerp(1.0f, 0.0f, time / interval);
            fadeImage.color = c;

            time += Time.deltaTime;
            yield return(0);
        }

        Destroy(fadeCanvas.gameObject);
        IsFading = false;
    }
コード例 #24
0
        private void DoEncodeAudio(EncodeInfo job)
        {
            FfMpeg     ffmpeg = new FfMpeg();
            OggEnc     oggEnc = new OggEnc();
            Lame       lame   = new Lame();
            NeroAACEnc aacEnc = new NeroAACEnc();

            switch (job.AudioProfile.Type)
            {
            case ProfileType.AC3:
                ffmpeg.SetJob(job);
                _worker.DoWork += ffmpeg.DoEncodeAc3;
                Log.Info("ffmpeg.DoEncodeAC3()");
                break;

            case ProfileType.OGG:
                oggEnc.SetJob(job);
                _worker.DoWork += oggEnc.DoEncode;
                Log.Info("oggenc.DoEncode()");
                break;

            case ProfileType.AAC:
                aacEnc.SetJob(job);
                _worker.DoWork += aacEnc.DoEncode;
                Log.Info("NeroAacEnc.DoEncode()");
                break;

            case ProfileType.MP3:
                lame.SetJob(job);
                _worker.DoWork += lame.DoEncode;
                Log.Info("lame.DoEncode()");
                break;

            case ProfileType.Copy:
                if (job.EncodingProfile.OutFormat == OutputType.OutputDvd &&
                    !Processing.CheckAudioDvdCompatible(job.AudioStreams[job.StreamId]))
                {
                    ffmpeg.SetJob(job);
                    _worker.DoWork += ffmpeg.DoEncodeAc3;
                    Log.Info("ffmpeg.DoEncodeAC3()");
                }
                break;
            }
        }
コード例 #25
0
        /// <summary>
        /// 根据文章对象(及flowxml)获取审核信息
        /// </summary>
        /// <param name="articleID"></param>
        /// <returns></returns>
        public Processing GetArticleProcess(Article a)
        {
            if (a == null)
            {
                return(null);
            }
            else
            {
                Processing p = new Processing();
                if (string.IsNullOrEmpty(a.ProcessState))
                {
                    p.CurLayerNO = "0";
                }
                else
                {
                    p.CurLayerNO = a.ProcessState;
                }

                p.ProcessDirection = a.ProcessDirection;
                p.ObjectID         = a.ID;
                p.FromOtherSite    = false;
                p.ArticleState     = (ArticleStates)a.State;
                if (We7Helper.IsNumber(a.ProcessState) && ((ProcessStates)int.Parse(a.ProcessState)) == ProcessStates.Unaudit)
                {
                    p.ArticleState = ArticleStates.Stopped;
                }

                Channel ch = ChannelHelper.GetChannel(a.OwnerID, null);
                if (ch != null)
                {
                    if (!string.IsNullOrEmpty(ch.ProcessEnd) && We7Helper.IsNumber(ch.ProcessEnd))
                    {
                        p.ProcessEndAction = (ProcessEnding)(int.Parse(ch.ProcessEnd));
                    }
                    if (!string.IsNullOrEmpty(ch.ProcessLayerNO) && We7Helper.IsNumber(ch.ProcessLayerNO))
                    {
                        p.ProcessTotalLayer = int.Parse(ch.ProcessLayerNO);
                    }
                }

                p = FillDataByFlowXml(p, (ProcessObject)a);
                return(p);
            }
        }
コード例 #26
0
ファイル: MainLogin.cs プロジェクト: whztt07/GameS_old
    // Update is called once per frame
    void Update()
    {
        //Stopwatch sw = new Stopwatch ();
        //sw.Start ();
        float dTime = Time.deltaTime;

        //for (int i = 0; i < 1; i++)
        //	Instantiate (testPrefab,Vector3.zero,Quaternion.Euler(Vector3.zero));
        ClickUPD();
        if (Processing.Work())
        {
            Processing.UPDConnect(dTime);
            UI.UIUpd(dTime);
            AnimationC.AnimationUPD();
        }

        //sw.Stop ();
//		print ("res:"+sw.ElapsedMilliseconds.ToString ());
    }
コード例 #27
0
        public void ApplyGain(double dbGain, bool applyToWindow = false)
        {
            FFTs stft = parentRef.GetSTFT();
            SelectedWindowIndices indices = parentRef.GetSelectedWindowIndices();

            if (applyToWindow)
            {
                if (!indices.Exists())
                {
                    MessageBox.Show("There is no window selected!");
                    return;
                }
                Processing.AddGain(stft, dbGain, indices, dB: true);
            }
            else
            {
                Processing.AddGain(stft, dbGain, dB: true);
            }
        }
コード例 #28
0
        public void CropImage_When_Passed_An_Image_With_Coordinates_TopLeft_And_A_New_Negative_Size_Returns_Message_Out_Of_Memory_And_Returns_Original_Image()
        {
            //Arrange
            Bitmap    originalImage  = new Bitmap(@"C:\Users\Public\test_224_299_Image.bmp");
            int       oldImageWidth  = originalImage.Width;
            int       oldImageHeight = originalImage.Height;
            Rectangle size           = new Rectangle(0, 0, -oldImageWidth, -oldImageHeight);

            //Act
            Dictionary <string, Image> result = Processing.CropImage(originalImage, size);
            Bitmap croppedImage        = (Bitmap)result.FirstOrDefault().Value;
            string croppedImageMessage = result.FirstOrDefault().Key;

            System.Console.WriteLine(croppedImageMessage);

            //Assert
            Assert.AreEqual(croppedImage, originalImage);
            Assert.AreEqual(croppedImageMessage, "Exception caught: Out of memory.");
        }
コード例 #29
0
        static void Main()
        {
            Processing.ReadCsv();
            botClient = new TelegramBotClient(Configuration.BotToken);
            me        = botClient.GetMeAsync().Result;

            Console.WriteLine($"Hello, World! I am user {me.Id} and my name is {me.FirstName}.");

            //botClient.OnMessage += Bot_FirstOnMessage;
            botClient.OnMessage += Bot_OnMessage;
            botClient.StartReceiving();

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();

            botClient.StopReceiving();

            Console.ReadKey();
        }
コード例 #30
0
        // GET: Patients/Edit/5
        public async Task <IActionResult> Edit(int?id)
        {
            var patientObject = Processing.db.Patients.First(a => a.PatientEmail == User.Identity.Name);

            if (id == null)
            {
                id = patientObject.PatientID;
                //return NotFound();
            }

            var patient = Processing.ReturnIndividualPatient(patientObject.PatientID);

            //var patient = await _context.Patients.FindAsync(id);
            if (patient == null)
            {
                return(NotFound());
            }
            return(View(patient));
        }
コード例 #31
0
        public void ComputeTreatment()
        {
            Service s    = Collaborator.Service;
            Roles   role = Collaborator.Role;

            switch (role)
            {
            case Roles.USER:
                if (s.Name.Contains("Compta"))
                {
                    // Coll compta => double val DF
                    Treatment = Processing.FINANCIAL_DIRECTOR;
                }
                else
                {
                    // Cas classique
                    Treatment = Processing.CLASSIC;
                }
                break;

            case Roles.CHIEF:
                if (s.Name.Contains("Compta"))
                {
                    // CDS compta => double val PDG
                    Treatment = Processing.CEO;
                }
                else if (s.Name.Contains("RH"))
                {
                    // CDS RH => double val compta
                    Treatment = Processing.COMPTA;
                }
                else if (s.Name.Contains("Direction"))
                {
                    // PDG => double val DF
                    Treatment = Processing.FINANCIAL_DIRECTOR;
                }
                else
                {
                    Treatment = Processing.COMPTA;
                }
                break;
            }
        }
コード例 #32
0
    private Color?GetColour()
    {
        byte red = 0, green = 0, blue = 0;

        try
        {
            red = byte.Parse(redAmount.Text);

            green = byte.Parse(greenAmount.SelectedItem.Value);

            blue = byte.Parse(blueAmount.SelectedItem.Value);
        }
        catch
        {
            return(null);
        }

        return(Processing.MakeColour(red, green, blue, grayscale.Checked));
    }
コード例 #33
0
ファイル: ArticleEdit.aspx.cs プロジェクト: jiaping/JPCMS
        protected void Page_Load(object sender, EventArgs e)
        {
            Article a = ArticleHelper.GetArticle(ArticleID);

            if (a != null &&
                !String.IsNullOrEmpty(a.ModelName) &&
                !Constants.ArticleModelName.Equals(a.ModelName, StringComparison.OrdinalIgnoreCase) &&
                String.Compare(a.ModelName, "Article", true) == 0)
            {
                Response.Redirect(String.Format("~/Admin/Addins/ModelEditor.aspx?notiframe={2}&model={0}&ID={1}", a.ModelName, a.ID, Request["notiframe"]), true);
            }

            if (a != null)
            {
                Channel ch = ChannelHelper.GetChannel(OwnerID, null);
                if (ch != null &&
                    !String.IsNullOrEmpty(ch.ModelName) &&
                    String.Compare(ch.ModelName, "Article", true) != 0 &&
                    String.Compare(ch.ModelName, Constants.ArticleModelName) != 0)
                {
                    Response.Redirect(String.Format("~/Admin/Addins/ModelEditor.aspx?notiframe={3}&model={0}&ID={1}&oid={2}", ch.ModelName, We7Helper.CreateNewID(), ch.ID, Request["notiframe"]), true);
                }

                Processing    p        = ProcessHelper.GetArticleProcess(a);
                List <string> contents = AccountHelper.GetPermissionContents(AccountID, a.OwnerID);
                if (a != null && a.AccountID != AccountID && a.State == (int)ArticleStates.Checking && !contents.Contains(p.CurLayerNOToChannel))
                {
                    MessageLiteral.Text = "<p class='alertInfo' >本篇文章正在审核流程中,您不能进行编辑。</p>";
                    //Response.End();
                }
                else
                {
                    MenuTabLabel.Text = BuildNavString();
                }
            }
            else
            {
                MenuTabLabel.Text = BuildNavString();
            }

            PagePathLiteral.Text = BuildPagePath();
        }
コード例 #34
0
    protected void ButtonSaveColour_Click(object sender, EventArgs e)
    {
        Color?tempColour = GetColour();

        //Can't make our colour
        if (tempColour == null)
        {
            StatusBar.ForeColor = Color.Red;
            StatusBar.Text      = "Can not make colour.";
            return;
        }

        //Our colour is valid, save it as a colour
        Color validColour = (Color)tempColour;

        //Colour is already saved
        if (Processing.checkColourInListBox(validColour, SavedColours))
        {
            StatusBar.ForeColor = Color.Red;
            StatusBar.Text      = "Colour is already saved.";
            return;
        }

        //Don't have a name for our colour
        if (ColourNameInput.Text.Length == 0)
        {
            StatusBar.ForeColor = Color.Red;
            StatusBar.Text      = "Need a name for the colour";
            return;
        }
        //We don't have that name in our list box
        else if (Processing.checkNameInListBox(ColourNameInput.Text, SavedColours))
        {
            StatusBar.ForeColor = Color.Red;
            StatusBar.Text      = "Name already saved.";
            return;
        }

        SavedColours.Items.Add(new ListItem(ColourNameInput.Text, validColour.ToArgb().ToString()));
        StatusBar.ForeColor = Color.Green;
        StatusBar.Text      = $"Colour - {ColourNameInput.Text} : Saved Successfully";
    }
コード例 #35
0
 public override void mTokens()
 {
     base.mTokens();
     // if we aren't processing, skip this token
     // if the Count is 0, we are in a bad state.
     if (Processing.Count > 0)
     {
         if (!Processing.Peek())
         {
             state.channel = Hidden;
         }
     }
     else if (_warn)
     {
         // Don't warn every token
         _warn = false;
         Debug.Assert(Processing.Count > 0, "Stack underflow preprocessing.  mTokens");
         Console.WriteLine("Found unexpected else.");
     }
 }
コード例 #36
0
 public void DoneProcessingFile(List <AnalogyLogMessage> messages, string filename)
 {
     lock (_lockObject)
     {
         if (Processing.Contains(filename))
         {
             Processing.Remove(filename);
         }
         if (ProcessedFileNames.Contains(filename))
         {
             ProcessedFileNames.Remove(filename);
         }
         ProcessedFileNames.Add(filename);
         if (Messages.ContainsKey(filename))
         {
             Messages.Remove(filename);
         }
         Messages.Add(filename, messages);
     }
 }
コード例 #37
0
        /// <summary>
        /// 通过文章ID返回权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetCurLayerNOText(string id)
        {
            Criteria       c = new Criteria(CriteriaType.Equals, "ID", id);
            List <Article> a = Assistant.List <Article>(c, null);

            if (a.Count > 0)
            {
                Processing p        = GetArticleProcess(a[0]);
                string     mysiteID = SiteConfigs.GetConfig().SiteID;
                if (p.CurrentSiteID == mysiteID || string.IsNullOrEmpty(p.CurrentSiteID) && string.IsNullOrEmpty(mysiteID))
                {
                    return(p.CurLayerNOToChannel);
                }
                else
                {
                    return("");
                }
            }
            return("");
        }
コード例 #38
0
ファイル: MgfService.cs プロジェクト: xpaperclip/tlpdtools
    public void Colourize(bool resolveReferences)
    {
        if (resolveReferences)
            tb.ClearStyle(FastColoredTextBoxNS.StyleIndex.All);
        else
            tb.ClearStyle(tb.GetStyleIndexMask(new Style[] { preprocStyle, linkStyle, commentStyle }));

        players.Clear();
        maps.Clear();
        seriesOrder.Clear();

        var p = new Processing(this);
        using (var sr = new StringReader(tb.Text))
        {
            p.Do(sr, true, resolveReferences, null);
        }
    }
コード例 #39
0
        private static void processInput()
        {
            int Radius = 2;
              int NoiseLevel = 10;

              Console.WriteLine("Processing Input...");
              foreach (var import in importItems)
              {
            Console.WriteLine();
            Console.WriteLine(import.FileName);

            Console.WriteLine("Slide extrahieren...");
            var processingHelper = new Processing(import.FileName);
            var slide = processingHelper.Slide;

            Console.WriteLine("Ausschnitt aus Slide extrahieren mit originaler Auflösung...");
            int partImageWidth = import.LowerRight.X - import.UpperLeft.X;
            int partImageHeight = import.LowerRight.Y - import.UpperLeft.Y;
            Bitmap partImage = slide.GetImagePart(
              import.UpperLeft.X, import.UpperLeft.Y,
              partImageWidth, partImageHeight,
              partImageWidth, partImageHeight
            );

            #region global tissue detection
            Console.WriteLine("Gewebe suchen und in separatem Layer speichern...");
            var bitmapProcessor = new BitmapProcessor(partImage);
            ObjectLayer overviewLayer = new TissueDetector().Execute(bitmapProcessor, Radius, NoiseLevel);
            bitmapProcessor.Dispose();

            Console.WriteLine("Gewebe-Layer in Ausschnitt zeichnen + speichern...");
            DrawObjectsToImage(partImage, overviewLayer, Color.Black);
            partImage.Save(processingHelper.DataPath + "ImagePartTissue.png");
            #endregion global tissue detection

            #region Deconvolution
            Console.WriteLine("Execute deconvolution 3...");
            var gpX = new ColorDeconvolution().Get3rdStain(partImage, ColorDeconvolution.KnownStain.HaematoxylinEosin);
            gpX.Dispose();
            Bitmap gpX_bmp = gpX.Bitmap;
            gpX_bmp.Save(processingHelper.DataPath + "ImagePartColor3.png");

            Console.WriteLine("Execute deconvolution 2...");
            var gpE = new ColorDeconvolution().Get2ndStain(partImage, ColorDeconvolution.KnownStain.HaematoxylinEosin);
            gpE.Dispose();
            Bitmap gpE_bmp = gpE.Bitmap;
            gpE_bmp.Save(processingHelper.DataPath + "ImagePartColor2.png");

            Console.WriteLine("Execute deconvolution 1...");
            var gpH = new ColorDeconvolution().Get1stStain(partImage, ColorDeconvolution.KnownStain.HaematoxylinEosin);
            gpH.Dispose();
            Bitmap gpH_bmp = gpH.Bitmap;
            gpH_bmp.Save(processingHelper.DataPath + "ImagePartColor1.png");
            #endregion Deconvolution

            #region execute edge detection
            Console.WriteLine("Execute edge detection...");
            SobelResponse responseH = Filtering.ExecuteSobel(gpH_bmp);
            SobelResponse responseE = Filtering.ExecuteSobel(gpE_bmp);
            var substracted = new double[responseH.Size.Width, responseH.Size.Height];
            var substractedRange = new Range<double>();
            for (var x = 0; x < responseH.Size.Width; x++)
            {
              for (var y = 0; y < responseH.Size.Height; y++)
              {
            var value = Math.Max(0, responseE.Gradient[x, y] - responseH.Gradient[x, y]);
            substracted[x, y] = value;
            substractedRange.Add(value);
              }
            }
            double[,] nonMaximumSupression = Filtering.ExecuteNonMaximumSupression(substracted, responseE.Orientation);
            Bitmap edges = Visualization.Visualize(nonMaximumSupression, Visualization.CreateColorizing(substractedRange.Maximum));
            edges.Save(processingHelper.DataPath + "ImagePartEdges.png");
            #endregion execute edge detection

            exportItems.Add(
              new Ausgabe {
            Identify = import.Identify,
            Result = false,
            Message = "kein Fehler"
              }
            );
              }
        }
コード例 #40
0
ファイル: Init.cs プロジェクト: Nefarin/DadmProject
 public void Process(Processing process, out IProcessingState timeoutState)
 {
     timeoutState = new Idle(5);
 }
コード例 #41
0
 protected override void OnImageFileOpened(EventArgs e)
 {
     base.OnImageFileOpened(e);
       this._widthRatio = null;
       this._heightRatio = null;
       if (null == this.ImageFile) return;
       this.dataHolder = new Processing(this.ImageFile.Url);
       this.comboBox.Items.Clear();
       this.heatMapNames.Clear();
       if (null != this.heatMap) this.heatMap.Dispose();
       this.heatMap = null;
       if (null != this.pictureBox.Image) this.pictureBox.Image.Dispose();
       this.pictureBox.Image = null;
       WsiInterop.Navigation.Changed += this.wsiInteropNavigationChanged;
       foreach (var hm in Directory.GetFiles(this.dataHolder.DataPath, "*.png"))
       {
     var i1 = hm.LastIndexOf('\\');
     var n = hm.Substring(i1 + 1);
     var i2 = n.LastIndexOf('.');
     n = n.Remove(i2);
     this.heatMapNames.Add(n, hm);
     this.comboBox.Items.Add(n);
       }
 }
コード例 #42
0
ファイル: FadeManager.cs プロジェクト: Kuvo/Primary
    // シーン遷移用コルーチン
    IEnumerator TransScene(string scene, float interval, Processing processing)
    {
        //だんだん暗く
        this.isFading = true;
        float time = 0;
        while (time <= interval)
        {
            this.FadeAlpha = Mathf.Lerp(0f, 1f, time / interval);
            time += Time.deltaTime;
            yield return 0;
        }

        // フェード中に実行する処理
        if(processing != null)
        {
            processing();
        }

        //だんだん明るく
        time = 0;
        while (time <= interval)
        {
            this.FadeAlpha = Mathf.Lerp(1.0f, 0.0f, time / interval);
            time += Time.deltaTime;
            yield return 0;
        }

        this.isFading = false;
    }
コード例 #43
0
		/// <summary>
		/// Tries to parse some chunk data for the message
		/// </summary>
		/// <returns></returns>
		private bool TryAndParseChunkData(ref HttpMessage message, EventHandler<HttpMessageProgressEventArgs> onProgress, object stateObject)
		{
			// get bytes, and update the index...
			int waitingOn = _chunk.Size;
			int received = _receivedBytes.Length - 2 - _parser.Index;
			
			// if we received enough data to pull in a chunk, do that now
			if (received >= waitingOn)
			{
				// copy the end of the data out as chunk data
				byte[] data = HttpUtils.Clone(_receivedBytes, _parser.Index, _chunk.Size);

				// bump the parser past the end of the next \r\n
				_parser.Index += _chunk.Size + 2;

				// create a new chunked body
				if (_chunkedBody == null)
					_chunkedBody = new HttpChunkedBody();

				// assign the data to the chunk
				_chunk.Data = data;

				// todo: 

				// add the chunk to the body
				_chunkedBody.Chunks.Add(_chunk);

				// if the chunk is empty, it's the last chunk		
				bool empty = _chunk.IsEmpty;
				
				// destroy the chunk
				_chunk = null;

				if (empty)
				{
					// change state to processing chunk data
					_state = Processing.ChunkTrailerHeaderLine;
				}
				else
				{
					// go back to processing a chunk size line
					_state = Processing.ChunkSizeLine;
				}

				return true;				
			}

			return false;
		}
コード例 #44
0
		/// <summary>
		/// Tries to parse a chunk size line for the message
		/// </summary>
		/// <returns></returns>
		private bool TryAndParseChunkSizeLine(ref HttpMessage message, EventHandler<HttpMessageProgressEventArgs> onProgress, object stateObject)
		{
			// try and parse a token from the data
			HttpByteParserToken token = _parser.GetNextToken();						
			if (token == null)
				return false;
			
			// the first line of any message is never empty
			if (token.IsEmpty)
				return false;

			// success! this line is a header
			string line = token.ToString(HttpUtils.Encoding);

			// parse the size line
			HttpChunkSizeLine chunkSizeLine = HttpChunkSizeLine.Parse(line);

			// create a new chunk
			_chunk = new HttpChunk(chunkSizeLine, null);
			
			// change state to processing chunk data
			_state = Processing.ChunkData;

			return true;
		}
コード例 #45
0
ファイル: MgfService.cs プロジェクト: xpaperclip/tlpdtools
    public string Process()
    {
        players.Clear();
        maps.Clear();
        unknownPlayers.Clear();
        unknownMaps.Clear();
        seriesOrder.Clear();

        var p = new Processing(this);
        using (var sr = new StringReader(tb.Text))
        using (var sw = new StringWriter())
        {
            p.Do(sr, false, true, sw);

            using (var headerWriter = new StringWriter())
            {
                if (unknownMaps.Count > 0)
                {
                    headerWriter.WriteLine("; unknown maps");
                    int maxlength = (from map in unknownMaps select map.Length).Max();
                    foreach (string map in unknownMaps)
                        headerWriter.WriteLine("$map {0} = {1}", map.PadRight(maxlength, ' '), map);
                    headerWriter.WriteLine();
                }

                if (unknownPlayers.Count > 0)
                {
                    headerWriter.WriteLine("; unknown players");
                    int maxlength = (from player in unknownPlayers select player.Length).Max();
                    foreach (string player in unknownPlayers)
                        headerWriter.WriteLine("$player {0} = {1}", player.PadRight(maxlength, ' '), player);
                    headerWriter.WriteLine();
                }

                headerWriter.WriteLine(sw.ToString());
                return headerWriter.ToString();
            }
        }
    }
コード例 #46
0
        private static void Main(string[] args)
        {
            #region init
              if (0 == args.Length)
              {
            Console.WriteLine("no slide name");
            return;
              }
              var slideName = args[0];
              var processinHelper = new Processing(slideName);
              var slide = processinHelper.Slide;
              #endregion init

              TiledProcessInformation<uint[]> haematoxylinHistogram;
              TiledProcessInformation<uint[]> eosinHistogram;

              if (!File.Exists(processinHelper.DataPath + "haematoxylinHistogram.tpi") || !File.Exists(processinHelper.DataPath + "eosinHistogram.tpi"))
              {
            if (!Directory.Exists(processinHelper.DataPath + "deconvolution")) Directory.CreateDirectory(processinHelper.DataPath + "deconvolution");
            var tissueData = TiledProcessInformation<bool>.FromFile(processinHelper.DataPath + "tissueData.tpi");
            haematoxylinHistogram = new TiledProcessInformation<uint[]>(tissueData.Partitioner, tissueData.WsiUri);
            eosinHistogram = new TiledProcessInformation<uint[]>(tissueData.Partitioner, tissueData.WsiUri);
            var partitioner = tissueData.Partitioner;
            var dict = new Dictionary<Point, WsiRect>();
            foreach (var tile in tissueData.Partitioner)
              dict.Add(tissueData.Partitioner.CurrentIndices, tile);
            var stopwatch = new Stopwatch();
            foreach (var tile in partitioner)
            {
              var tissueTile = dict[partitioner.CurrentIndices];
              if (!tissueData[tissueTile]) continue;
              stopwatch.Start();
              using (var tileImage = slide.GetImagePart(tile))
              {
            var hHistogramValue = new uint[256];
            var hValues = new List<double>();
            using (var gpH = new ColorDeconvolution().Get1stStain(tileImage, ColorDeconvolution.KnownStain.HaematoxylinEosin))
            {
              foreach (var intensity in gpH.GetPixels())
              {
                hHistogramValue[intensity]++;
                hValues.Add(intensity);
              }
              haematoxylinHistogram.AddDataToCurrentTile(hHistogramValue);
              gpH.Dispose();
              gpH.Bitmap.Save(processinHelper.DataPath + "deconvolution\\" + partitioner.CurrentIndices + ".h.png");
            }
            var eHistogramValue = new uint[256];
            var eValues = new List<double>();
            using (var gpE = new ColorDeconvolution().Get2ndStain(tileImage, ColorDeconvolution.KnownStain.HaematoxylinEosin))
            {
              foreach (var intensity in gpE.GetPixels())
              {
                eHistogramValue[intensity]++;
                eValues.Add(intensity);
              }
              eosinHistogram.AddDataToCurrentTile(eHistogramValue);
              gpE.Dispose();
              gpE.Bitmap.Save(processinHelper.DataPath + "deconvolution\\" + partitioner.CurrentIndices + ".e.png");
            }
            NumericVector hHistogram = RConnector.Engine.CreateNumericVector(hValues);
            RConnector.Engine.SetSymbol("hHistogram", hHistogram);
            NumericVector eHistogram = RConnector.Engine.CreateNumericVector(eValues);
            RConnector.Engine.SetSymbol("eHistogram", eHistogram);
            var handle = RConnector.StartOutput();
            RConnector.Engine.Evaluate("hist(eHistogram, col=rgb(1,0,0,0.5),xlim=c(0,255), main=\"" + partitioner.CurrentIndices + "\", xlab=\"HE\")");
            RConnector.Engine.Evaluate("hist(hHistogram, col=rgb(0,0,1,0.5), add=T)");
            var output = RConnector.EndOutput(handle);
            output.Save(processinHelper.DataPath + "deconvolution\\histogram" + partitioner.CurrentIndices + ".png");
              }
              stopwatch.Stop();
              Console.WriteLine(partitioner.CurrentIndices + ":" + (stopwatch.ElapsedMilliseconds / 1000d) + "s");
              stopwatch.Reset();
            }
            haematoxylinHistogram.ToFile(processinHelper.DataPath + "haematoxylinHistogram.tpi");
            eosinHistogram.ToFile(processinHelper.DataPath + "eosinHistogram.tpi");
              }
              else
              {
            haematoxylinHistogram = TiledProcessInformation<uint[]>.FromFile(processinHelper.DataPath + "haematoxylinHistogram.tpi");
            eosinHistogram = TiledProcessInformation<uint[]>.FromFile(processinHelper.DataPath + "eosinHistogram.tpi");
              }

              var hRange = new Range<uint>();
              foreach (var tile in haematoxylinHistogram.Partitioner)
              {
            if (null == haematoxylinHistogram[tile]) continue;
            uint sum = 0;
            for (uint i = 0; i < 256; i++)
            {
              sum += haematoxylinHistogram[tile][i] * (255 - i);
            }
            hRange.Add(sum);
              }
              Func<uint[], Color> h2pixel = h =>
              {
            if (null == h) return Color.Gray;
            uint sum = 0;
            for (uint i = 0; i < 256; i++)
            {
              sum += h[i] * (255 - i);
            }
            var ratio = (double)sum / hRange.Maximum;
            return Color.FromArgb(0, 0, (int)Math.Round(255.0 * ratio));
              };
              var eRange = new Range<uint>();
              foreach (var tile in eosinHistogram.Partitioner)
              {
            if (null == eosinHistogram[tile]) continue;
            uint sum = 0;
            for (uint i = 0; i < 256; i++)
            {
              sum += eosinHistogram[tile][i] * (255 - i);
            }
            eRange.Add(sum);
              }
              Func<uint[], Color> e2pixel = e =>
              {
            if (null == e) return Color.Gray;
            uint sum = 0;
            for (uint i = 0; i < 256; i++)
            {
              sum += e[i] * (255 - i);
            }
            var ratio = (double)sum / eRange.Maximum;
            return Color.FromArgb((int)Math.Round(255.0 * ratio), 0, 0);
              };
              using (Bitmap b = haematoxylinHistogram.GenerateHeatMap(h2pixel))
            b.Save(processinHelper.DataPath + "haematoxylinHistogram.png");
              using (Bitmap b = eosinHistogram.GenerateHeatMap(e2pixel))
            b.Save(processinHelper.DataPath + "eosinHistogram.png");
              Console.WriteLine("done");
              Console.ReadKey();
        }
コード例 #47
0
		/// <summary>
		/// Tries to parse the first line for the message
		/// </summary>
		/// <returns></returns>
        private bool TryAndParseFirstLine(ref HttpMessage message, EventHandler<HttpMessageProgressEventArgs> onProgress, object stateObject)
		{
			// try and parse a token from the data
			HttpByteParserToken token = _parser.GetNextToken();						
			if (token == null)
				return false;
			
			// the first line of any message is never empty
			if (token.IsEmpty)
				return false; 

			// success! store the first line of the message
			message._firstLine = token.ToString(HttpUtils.Encoding);

			// save the offset into the data where the headers start
			_headerOffsetStart = _parser.Index;

			// change state to processing headers!
			_state = Processing.HeaderLine;
			
			return true;
		}
コード例 #48
0
        static void Main(string[] args)
        {
            #region init
              if (0 == args.Length)
              {
            Console.WriteLine("no slide name");
            return;
              }
              var slideName = args[0];
              var processinHelper = new Processing(slideName);
              var slide = processinHelper.Slide;
              #endregion init

              var part = new WsiPartitioner(new Rectangle(new Point(0, 0), slide.Size), new Size(1000, 1000), new Size(0, 0), 1.0);
              var tissueData = new TiledProcessInformation<bool>(part, slideName);

              #region global tissue detection
              int overviewImageWidth = slide.Size.Width / OverviewTileSize;
              int overviewImageHeight = slide.Size.Height / OverviewTileSize;

              Bitmap overviewImage = slide.GetImagePart(0, 0, slide.Size.Width, slide.Size.Height, overviewImageWidth, overviewImageHeight);

              var bitmapProcessor = new BitmapProcessor(overviewImage);

              ObjectLayer overviewLayer = new TissueDetector().Execute(bitmapProcessor, Radius, NoiseLevel);

              bitmapProcessor.Dispose();

              DrawObjectsToImage(overviewImage, overviewLayer, Color.Black);
              overviewImage.Save(processinHelper.DataPath + "tissueDetectionOverview.png");
              #endregion global tissue detection

              //part.Tiles[]
              foreach (var tile in part)
              {
            #region global tissue detection
            var rect = tile.SourceRect;
            int overviewX = rect.X / OverviewTileSize;
            int overviewY = rect.Y / OverviewTileSize;
            int windowSize = rect.Width / OverviewTileSize;

            bool tileInObject = true;
            int partsOutside = 0;

            for (int y = 0; y < windowSize; y++)
            {
              for (int x = 0; x < windowSize; x++)
              {
            int newX = overviewX + x;
            int newY = overviewY + y;

            if (newX < 0 || newX >= overviewLayer.Map.Width || newY < 0 || newY >= overviewLayer.Map.Height) { continue; }

            uint id = overviewLayer.Map[newX, newY];
            if (id != 0) continue;
            partsOutside++;
            if (!(partsOutside >= Math.Pow(windowSize + 1, 2) * 0.75)) continue;
            tileInObject = false;
            break;
              }
              if (!tileInObject) { break; }
            }
            tissueData.AddDataToCurrentTile(tileInObject);
            #endregion global tissue detection
            if (tileInObject) Console.WriteLine(tile.SourceRect + ":" + partsOutside);
              }
              tissueData.ToFile(processinHelper.DataPath + "tissueData.tpi");
              using (Bitmap b = tissueData.GenerateHeatMap(tissue => tissue ? Color.Green : Color.Red))
            b.Save(processinHelper.DataPath + "tissueData.png");

              Console.WriteLine("done");
              Console.ReadKey();
        }
コード例 #49
0
		/// <summary>
		/// Tries to parse a header line for the message
		/// </summary>
		/// <returns></returns>
		private bool TryAndParseHeaderLine(ref HttpMessage message, EventHandler<HttpMessageProgressEventArgs> onProgress, object stateObject)
		{
			// try and parse a token from the data
			HttpByteParserToken token = _parser.GetNextToken();						
			if (token == null)
				return false;
			
			// the first line of any message is never empty
			if (token.IsEmpty)
			{
				// save the offset into the data where the headers end
				_headerOffsetEnd = _parser.Index;

				// determine if the body is chunked, as we have all the headers now we can determine how the message is going to come in
				if (message.IsChunked)
					// change state to processing a chunk size line
					_state = Processing.ChunkSizeLine;
				else
					// change state to processing the body
					_state = Processing.Body;

				// notify the callback that we have received the headers
				this.OnProgress(onProgress, this, new HttpMessageProgressEventArgs(message, true, new byte[] {}, _receivedBytes.Length, stateObject));							
				
				// we're done with the headers
				return true; 
			}

			// success! this line is a header
			string line = token.ToString(HttpUtils.Encoding);

			// parse the line into a new header
			HttpHeader header = HttpHeader.Parse(line);

			// save the header
			message.Headers.Add(header);

			return true;
		}
コード例 #50
0
ファイル: MgfService.cs プロジェクト: xpaperclip/tlpdtools
        public void Do(TextReader sr, bool doColour, bool resolveReferences, TextWriter writer)
        {
            if (doColour)
            {
                tb = svc.tb;
                this.doColour = doColour;
            }
            bool generateOutput = false;
            if (writer != null)
            {
                // if we are generating output, then force references to be resolved
                resolveReferences = true;
                generateOutput = true;
            }

            while ((line = sr.ReadLine()) != null)
            {
                linenum++;

                // syntax colour comments
                int commentidx = line.IndexOf(';');
                if (commentidx >= 0)
                {
                    if (doColour) tb.GetRange(new Place(commentidx, linenum), new Place(line.Length, linenum)).SetStyle(svc.commentStyle);
                    line = line.Substring(0, commentidx);
                }

                // trim line
                TrimLine(true);

                // if nothing left, skip line
                if (line.Length == 0) continue;

                // termination
                if (IsCommand("$end", svc.preprocStyle))
                {
                    // terminate further processing and colour as a comment
                    if (doColour) tb.GetRange(new Place(linestart, linenum), tb.Range.End).SetStyle(svc.commentStyle);
                    break;
                }

                // include file
                if (IsCommand("$include", svc.preprocStyle))
                {
                    ColourToEnd(0, svc.linkStyle);
                    if (resolveReferences)
                    {
                        string filename = svc.ResolveIncludeFile(line);

                        if (filename == null)
                        {
                            // doesn't exist
                            ColourToEnd(0, svc.wavyError);
                        }
                        else
                        {
                            // open included file and process it
                            var psub = new Processing(svc);
                            psub.processingFilename = filename;
                            using (var subreader = new StreamReader(filename))
                            {
                                psub.Do(subreader, false, true, writer);
                            }
                        }
                    }
                    continue;
                }

                // print line
                if (IsCommand("$print", svc.preprocStyle))
                {
                    if (generateOutput)
                        writer.WriteLine(line);
                    continue;
                }

                // tlpd line
                if (line.StartsWith("[tlpd#"))
                {
                    int endidx;
                    TlpdEntity entity = Tlpd.Parse(line, false, out endidx);
                    if (endidx > 0)
                    {
                        ColourLength(0, endidx, svc.linkTlpdStyle);
                        if (!entity.IsValid || string.IsNullOrWhiteSpace(entity.Name))
                            ColourLength(0, endidx, svc.wavyError);
                        switch (entity.Type)
                        {
                            case TlpdEntityType.Map: svc.maps[entity.Name] = entity; break;
                            case TlpdEntityType.Player: svc.players[entity.Name] = entity; break;
                        }
                    }
                    if (endidx < line.Length)
                        Colour(endidx, line.Length, svc.wavyError);
                    continue;
                }

                // map line
                if (IsCommand("$map", svc.entityStyle))
                {
                    if (!line.Contains("="))
                    {
                        ErrorLine("Syntax error: Try '$map name = [tlpd#maps#000#db]' instead.");
                        continue;
                    }

                    // $map Name = [tlpd#]
                    int equalsidx = line.IndexOf("=");
                    string name = line.Substring(0, equalsidx);
                    string tlpd = line.Substring(equalsidx + 1);

                    int namestart, nameend;
                    name = name.Trim(out namestart, out nameend);
                    if (resolveReferences)
                    {
                        if (svc.maps.ContainsKey(name))
                            Colour(namestart, nameend, svc.wavyRedefined);
                    }

                    int tlpdstart, tlpdend;
                    tlpd = tlpd.Trim(out tlpdstart, out tlpdend);
                    int endidx;
                    TlpdEntity entity = Tlpd.Parse(tlpd, true, out endidx);
                    if (endidx > 0)
                    {
                        ColourLength(equalsidx + 1 + tlpdstart, endidx, svc.linkTlpdStyle);
                        if (entity.Type == TlpdEntityType.Map)
                        {
                            entity.Name = name;
                            svc.maps[entity.Name] = entity;
                        }
                        else
                        {
                            ColourLength(equalsidx + 1 + tlpdstart, endidx, svc.wavyError);
                        }
                    }
                    if (endidx < line.Length) Colour(equalsidx + 1 + tlpdstart + endidx, line.Length - 1, svc.wavyError);

                    //if (resolveReferences)
                    //{
                    //    svc.maps[name] = Tlpd.Parse(tlpd);
                    //    Colour(namestart, nameend, svc.mapStyle);
                    //}
                    continue;
                }

                // player line
                if (IsCommand("$player", svc.entityStyle))
                {
                    if (!line.Contains("="))
                    {
                        ErrorLine("Syntax error: Try '$player name = [tlpd#players#0#T#db]' instead.");
                        continue;
                    }

                    // $map Name = [tlpd#]
                    int equalsidx = line.IndexOf("=");
                    string name = line.Substring(0, equalsidx);
                    string tlpd = line.Substring(equalsidx + 1);

                    int namestart, nameend;
                    name = name.Trim(out namestart, out nameend);
                    if (resolveReferences)
                    {
                        if (svc.players.ContainsKey(name))
                            Colour(namestart, nameend, svc.wavyRedefined);
                    }

                    int tlpdstart, tlpdend;
                    tlpd = tlpd.Trim(out tlpdstart, out tlpdend);
                    int endidx;
                    TlpdEntity entity = Tlpd.Parse(tlpd, true, out endidx);
                    if (endidx > 0)
                    {
                        ColourLength(equalsidx + 1 + tlpdstart, endidx, svc.linkTlpdStyle);
                        if (entity.Type == TlpdEntityType.Player)
                        {
                            entity.Name = name;
                            svc.players[entity.Name] = entity;
                        }
                        else
                        {
                            ColourLength(equalsidx + 1 + tlpdstart, endidx, svc.wavyError);
                        }
                    }
                    if (endidx < line.Length) Colour(equalsidx + 1 + tlpdstart + endidx, line.Length - 1, svc.wavyError);

                    //if (resolveReferences)
                    //{
                    //    svc.players[name] = Tlpd.Parse(tlpd);
                    //    Colour(namestart, nameend, ColourPlayer(svc.players[name]));
                    //}
                    continue;
                }

                // series line
                if (IsCommand("$series", svc.seriesStyle))
                {
                    svc.seriesOrder.Clear();
                    int startidx = 0;
                    while (startidx < line.Length)
                    {
                        int idx = line.IndexOf(",", startidx);
                        if (idx < 0) idx = line.Length;

                        string map = line.Substring(startidx, idx - startidx);
                        int mapstart, mapend;
                        map = map.Trim(out mapstart, out mapend);
                        svc.seriesOrder.Add(map);
                        if (resolveReferences)
                        {
                            if (!svc.maps.ContainsKey(map))
                                Colour(startidx + mapstart, startidx + mapend, svc.wavyUndefined);
                            else
                                Colour(startidx + mapstart, startidx + mapend, svc.mapStyle);
                        }

                        startidx = idx + 1;
                    }

                    continue;
                }

                // winner > loser : map
                // winner < loser : map
                if (line.Contains(":"))
                {
                    int colonidx = line.IndexOf(":");
                    string players = line.Substring(0, colonidx);
                    string map = line.Substring(colonidx + 1);

                    Colour(colonidx, colonidx, svc.operatorStyle);

                    int mapstart, mapend;
                    map = map.Trim(out mapstart, out mapend);
                    if (resolveReferences)
                    {
                        if (!svc.maps.ContainsKey(map))
                            Colour(colonidx + 1 + mapstart, colonidx + 1 + mapend, svc.wavyUndefined);
                        else
                            Colour(colonidx + 1 + mapstart, colonidx + 1 + mapend, svc.mapStyle);
                    }

                    int playersstart, playersend;
                    players = players.Trim(out playersstart, out playersend);

                    int arrowidx = 0;
                    bool leftwinner;
                    if (players.Contains(">"))
                    {
                        arrowidx = players.IndexOf(">");
                        leftwinner = true;
                    }
                    else if (players.Contains("<"))
                    {
                        arrowidx = players.IndexOf("<");
                        leftwinner = false;
                    }
                    else
                    {
                        Error(playersstart, playersend, "No winner specified.");
                        continue;
                    }

                    string left = players.Substring(0, arrowidx);
                    string right = players.Substring(arrowidx + 1);
                    Colour(arrowidx, arrowidx, svc.operatorStyle);

                    int leftstart, leftend;
                    left = left.Trim(out leftstart, out leftend);
                    if (resolveReferences)
                    {
                        if (!svc.players.ContainsKey(left))
                            Colour(leftstart, leftend, svc.wavyUndefined);
                        else
                            Colour(leftstart, leftend, ColourPlayer(svc.players[left]));
                    }

                    int rightstart, rightend;
                    right = right.Trim(out rightstart, out rightend);
                    if (resolveReferences)
                    {
                        if (!svc.players.ContainsKey(right))
                            Colour(arrowidx + 1 + rightstart, arrowidx + 1 + rightend, svc.wavyUndefined);
                        else
                            Colour(arrowidx + 1 + rightstart, arrowidx + 1 + rightend, ColourPlayer(svc.players[right]));
                    }

                    if (generateOutput)
                        WriteGame(writer, left, right, map, leftwinner);

                    continue;
                }

                // map @ winner loser
                if (line.Contains("@"))
                {
                    int atidx = line.IndexOf("@");
                    string map = line.Substring(0, atidx);
                    string players = line.Substring(atidx + 1);

                    Colour(atidx, atidx, svc.operatorStyle);

                    int mapstart, mapend;
                    map = map.Trim(out mapstart, out mapend);
                    if (resolveReferences)
                    {
                        if (!svc.maps.ContainsKey(map))
                            Colour(mapstart, mapend, svc.wavyUndefined);
                        else
                            Colour(mapstart, mapend, svc.mapStyle);
                    }

                    int playersstart, playersend;
                    players = players.Trim(out playersstart, out playersend);
                    line = line.Substring(atidx + 1 + playersstart);
                    linestart += atidx + 1 + playersstart;

                    int spaceidx = players.IndexOf(" ");
                    if (spaceidx < 0)
                    {
                        Error(playersstart, playersend, "No winner specified.");
                        continue;
                    }

                    string left = players.Substring(0, spaceidx);
                    string right = players.Substring(spaceidx + 1);

                    int leftstart, leftend;
                    left = left.Trim(out leftstart, out leftend);
                    if (resolveReferences)
                    {
                        if (!svc.players.ContainsKey(left))
                            Colour(leftstart, leftend, svc.wavyUndefined);
                        else
                            Colour(leftstart, leftend, ColourPlayer(svc.players[left]));
                    }

                    int rightstart, rightend;
                    right = right.Trim(out rightstart, out rightend);
                    if (resolveReferences)
                    {
                        if (!svc.players.ContainsKey(right))
                            Colour(spaceidx + 1 + rightstart, spaceidx + 1 + rightend, svc.wavyUndefined);
                        else
                            Colour(spaceidx + 1 + rightstart, spaceidx + 1 + rightend, ColourPlayer(svc.players[right]));
                    }

                    if (generateOutput)
                        WriteGame(writer, left, right, map);

                    continue;
                }

                // 2-0 left right
                if (line.Contains("-"))
                {
                    int atidx = line.IndexOf(" ");
                    if (atidx < 0)
                    {
                        ErrorLine("Syntax error");
                        continue;
                    }

                    string score = line.Substring(0, atidx);
                    string players = line.Substring(atidx + 1);

                    Colour(atidx, atidx, svc.operatorStyle);

                    int scorestart, scoreend;
                    score = score.Trim(out scorestart, out scoreend);

                    // parse scores
                    int dashidx = score.IndexOf("-");
                    if (dashidx < 0)
                    {
                        ErrorLine("Syntax error");
                        continue;
                    }

                    int scoreleft, scoreright;
                    bool errorfree = true;
                    if (!int.TryParse(score.Substring(0, dashidx), out scoreleft))
                    {
                        Error(scorestart, scorestart + dashidx - 1, "Error");
                        errorfree = false;
                    }
                    if (!int.TryParse(score.Substring(dashidx + 1), out scoreright))
                    {
                        Error(scorestart + dashidx + 1, scoreend, "Error");
                        errorfree = false;
                    }
                    Colour(scorestart + dashidx, scorestart + dashidx, svc.operatorStyle);
                    if (errorfree)
                    {
                        Colour(scorestart, scorestart + dashidx - 1, (scoreleft > scoreright) ? svc.winnerStyle : svc.loserStyle);
                        Colour(scorestart + dashidx + 1, scoreend, (scoreleft < scoreright) ? svc.winnerStyle : svc.loserStyle);
                    }

                    // parse players
                    int playersstart, playersend;
                    players = players.Trim(out playersstart, out playersend);
                    line = line.Substring(atidx + 1 + playersstart);
                    linestart += atidx + 1 + playersstart;

                    int spaceidx = players.IndexOf(" ");
                    if (spaceidx < 0)
                    {
                        Error(playersstart, playersend, "No winner specified.");
                        continue;
                    }

                    string left = players.Substring(0, spaceidx);
                    string right = players.Substring(spaceidx + 1);

                    int leftstart, leftend;
                    left = left.Trim(out leftstart, out leftend);
                    if (resolveReferences)
                    {
                        if (!svc.players.ContainsKey(left))
                            Colour(leftstart, leftend, svc.wavyUndefined);
                        else
                            Colour(leftstart, leftend, ColourPlayer(svc.players[left]));
                    }

                    int rightstart, rightend;
                    right = right.Trim(out rightstart, out rightend);
                    if (resolveReferences)
                    {
                        if (!svc.players.ContainsKey(right))
                            Colour(spaceidx + 1 + rightstart, spaceidx + 1 + rightend, svc.wavyUndefined);
                        else
                            Colour(spaceidx + 1 + rightstart, spaceidx + 1 + rightend, ColourPlayer(svc.players[right]));
                    }

                    if (generateOutput)
                    {
                        bool alternate = (scoreleft > scoreright);
                        int mapsdone = 0;
                        while (scoreleft + scoreright > 0)
                        {
                            bool leftwinner = true;
                            if (alternate)
                                leftwinner = (scoreleft > 0);
                            else
                                leftwinner = !(scoreright > 0);
                            alternate = !alternate;
                            if (leftwinner)
                                scoreleft--;
                            else
                                scoreright--;

                            string map = "";
                            if (mapsdone < svc.seriesOrder.Count) map = svc.seriesOrder[mapsdone];
                            mapsdone++;
                            
                            WriteGame(writer, left, right, map, leftwinner);
                        }
                    }

                    continue;
                }

                // wlw winner loser
                int satidx = line.IndexOf(" ");
                if (satidx >= 0)
                {
                    string score = line.Substring(0, satidx);
                    string players = line.Substring(satidx + 1);

                    int scorestart, scoreend;
                    score = score.Trim(out scorestart, out scoreend);

                    // parse scores
                    bool[] leftwinner = new bool[score.Length];
                    bool errorfree = true;
                    for (int i = 0; i < score.Length; i++)
                    {
                        char c = score[i];
                        if (c == 'w' || c == 'W')
                        {
                            leftwinner[i] = true;
                        }
                        else if (c == 'l' || c == 'L')
                        {
                            leftwinner[i] = false;
                        }
                        else
                        {
                            errorfree = false;
                            break;
                        }
                    }
                    if (!errorfree)
                    {
                        ErrorLine("Syntax error");
                        continue;
                    }
                    for (int i = 0; i < score.Length; i++)
                    {
                        ColourLength(scorestart + i, 1, leftwinner[i] ? svc.winnerStyle : svc.loserStyle);
                    }

                    // parse players
                    int playersstart, playersend;
                    players = players.Trim(out playersstart, out playersend);
                    line = line.Substring(satidx + 1 + playersstart);
                    linestart += satidx + 1 + playersstart;

                    int spaceidx = players.IndexOf(" ");
                    if (spaceidx < 0)
                    {
                        Error(playersstart, playersend, "No winner specified.");
                        continue;
                    }

                    string left = players.Substring(0, spaceidx);
                    string right = players.Substring(spaceidx + 1);

                    int leftstart, leftend;
                    left = left.Trim(out leftstart, out leftend);
                    if (resolveReferences)
                    {
                        if (!svc.players.ContainsKey(left))
                            Colour(leftstart, leftend, svc.wavyUndefined);
                        else
                            Colour(leftstart, leftend, ColourPlayer(svc.players[left]));
                    }

                    int rightstart, rightend;
                    right = right.Trim(out rightstart, out rightend);
                    if (resolveReferences)
                    {
                        if (!svc.players.ContainsKey(right))
                            Colour(spaceidx + 1 + rightstart, spaceidx + 1 + rightend, svc.wavyUndefined);
                        else
                            Colour(spaceidx + 1 + rightstart, spaceidx + 1 + rightend, ColourPlayer(svc.players[right]));
                    }

                    if (generateOutput)
                    {
                        int mapsdone = 0;
                        for (int i = 0; i < leftwinner.Length; i++)
                        {
                            string map = "";
                            if (mapsdone < svc.seriesOrder.Count) map = svc.seriesOrder[mapsdone];
                            mapsdone++;

                            WriteGame(writer, left, right, map, leftwinner[i]);
                        }
                    }

                    continue;
                }

                // unrecognised line
                ErrorLine("unrecognised command");
            }
        }
コード例 #51
0
		/// <summary>
		/// Tries to parse the body for the message
		/// </summary>
		/// <returns></returns>
		private bool TryAndParseBody(ref HttpMessage message, EventHandler<HttpMessageProgressEventArgs> onProgress, object stateObject)
		{
			// determine the content length of the message's entity
			int contentLength = message.ContentLength;

			// the number of bytes we have received thus far would be determined by looking at the different between what we have and where the header's stopped
			int postedBytesLength = _receivedBytes.Length - _headerOffsetEnd;

			// we could have potentially received more than just one message so the extra data would be denoted by the difference between the content length and the body which we received
			int extraBytesReceived = postedBytesLength - contentLength;

			// if we received extra bytes that do not belong to this message
			if (extraBytesReceived > 0)
			{				
				// create a new buffer to hold the exra
				_previouslyReceivedBytes = new byte[extraBytesReceived];

				// copy the tail of the message off as extra bytes
				Buffer.BlockCopy(_receivedBytes, _headerOffsetEnd + contentLength, _previouslyReceivedBytes, 0, extraBytesReceived);

				// now shrink the bytes received to be exactly what comprises the bytes that make up this message
				byte[] tempBuffer = new byte[_headerOffsetEnd + contentLength];
				Buffer.BlockCopy(_receivedBytes, 0, tempBuffer, 0, tempBuffer.Length);				
				_receivedBytes = tempBuffer;
			}

			// if we've read in enough data to get the body, or there's no body coming
			if ( (postedBytesLength >= contentLength && contentLength > 0) || (contentLength == 0))
			{				
				// change state to finished
				_state = Processing.Finished;		

				// we want to kick out of the processing loop
				return false;
			}

			// otherwise we simply need to wait on the socket to receive more data
			return false;
		}
コード例 #52
0
ファイル: Abort.cs プロジェクト: Nefarin/DadmProject
 public void Process(Processing process, out IProcessingState timeoutState)
 {
     timeoutState = new Abort();
     process.Communication.SendProcessingEvent(new AnalysisEnded());
     process.Stop = true;
 }
コード例 #53
0
ファイル: Lite.cs プロジェクト: cvronmin/resource-helper
 private void initTooMuchPixels()
 {
     this.designPanel.Controls.Clear();
     frame = new Processing("Rendering " + pixels.GetLength(0) + "x" + pixels.GetLength(1) + " Image");
     frame.ShowInTaskbar = false;
     frame.Show();
     frame.Activate();
     frame.Focus();
     frame.changeStatus("creating pixel - part 1");
     for (int x = 0; x < pixels.GetLength(1) / 4; x++)
     {
         for (int y = 0; y < pixels.GetLength(0); y++)
         {
             frame.changeStatus("creating pixel" + x + "," + y);
             pixels[y, x] = new PixelButton();
             pixels[y, x].BackColor = System.Drawing.Color.Transparent;
             pixels[y, x].FlatStyle = System.Windows.Forms.FlatStyle.Flat;
             pixels[y, x].FlatAppearance.BorderSize = 0;
             pixels[y, x].Location = new System.Drawing.Point(0, 0);
             pixels[y, x].Margin = new System.Windows.Forms.Padding(0);
             pixels[y, x].Name = "pixel";
             pixels[y, x].Size = new System.Drawing.Size(4, 4);
             pixels[y, x].UseVisualStyleBackColor = false;
             pixels[y, x].setXY(y, x);
             pixels[y, x].Click += new System.EventHandler(this.pixels_Click);
             pixels[y, x].BackColorChanged += new System.EventHandler(this.pixels_Changed);
             this.designPanel.Controls.Add(pixels[y, x]);
         }
     }
     this.designPanel.Size = new Size(514, 258);
     setSizeLabel();
     redrawTooMuchPixels();
     waitTimer.Start();
 }
コード例 #54
0
ファイル: Idle.cs プロジェクト: Nefarin/DadmProject
 public void Process(Processing process, out IProcessingState timeoutState)
 {
     timeoutState = new Idle(5);
     Thread.Sleep(_sleepTime);
 }
コード例 #55
0
		/// <summary>
		/// Tries to parse a trailer header for the message
		/// </summary>
		/// <returns></returns>
		private bool TryAndParseTrailerHeaderLine(ref HttpMessage message, EventHandler<HttpMessageProgressEventArgs> onProgress, object stateObject)
		{
			// try and parse a token from the data
			HttpByteParserToken token = _parser.GetNextToken();						
			if (token == null)
			{
				// change state to processing the body
				_state = Processing.Finished;

				// we're done with the headers
				return true; 
			}
			
			// the first line of any message is never empty
			if (token.IsEmpty)
			{
				// change state to processing the body
				_state = Processing.Finished;

				// we're done with the headers
				return true; 
			}

			// success! this line is a header
			string line = token.ToString(HttpUtils.Encoding);

			// parse the line into a new header
			HttpHeader header = HttpHeader.Parse(line);

			// save the header in the chunked body trailers
			_chunkedBody.TrailerHeaders.Add(header);

			return true;
		}