public void TestCountSimiliarVsEmpty() { Assert.AreEqual(Ex1.CountSimilar(Ex4), 0); Assert.AreEqual(Ex2.CountSimilar(Ex4), 0); Assert.AreEqual(Ex3.CountSimilar(Ex4), 0); Assert.AreEqual(Ex4.CountSimilar(Ex4), 0); }
public static void CallGoogleInterview() { var case1 = new[] { 1, 2, 3, 9 }; var case2 = new[] { 1, 2, 4, 4 }; var sum = 8; var result0Case1 = Ex0.Solve(case1, sum); var result0Case2 = Ex0.Solve(case2, sum); var result1Case1 = Ex1.Solve(case1, sum); var result1Case2 = Ex1.Solve(case2, sum); var result2case1 = Ex2.Solve(case1, sum); var result2case2 = Ex2.Solve(case2, sum); }
public void Ex2TestDecreaseDelta() { double oldResult = 0; double delta = double.MaxValue; double result = 0; for (long i = 10; i < 10000000000; i *= 10) { result = Ex2.GetPI(1.0 / i); if (delta <= Math.Abs(result - oldResult)) { Assert.Fail(); return; } delta = Math.Abs(result - oldResult); oldResult = result; } }
static void Main(string[] args) { //Начало цикла string end = ""; do { double k = Convert.ToDouble(GetInput()[0]); if (k <= 0) { k = 0.0000000000001; } Console.WriteLine("result: " + Ex2.GetPI(k)); Console.WriteLine("PI: " + Math.PI); //Вывод результата и конец цикла Console.WriteLine("#Любой символ для завершения"); end = Console.ReadLine(); } while (end == "" || end.Length > 1); }
static void Main(string[] args) { Console.WriteLine("Desenvolvido por: Leandro Rocha de Brito"); var exerc1 = new Ex1(); var exerc2 = new Ex2(); /* var exerc3 = new Exerc3(); * var exerc4 = new Exerc4(); * var exerc5 = new Exerc5(); * var exerc6 = new Exerc6(); * var exerc7 = new Exerc7(); * var exerc8 = new Exerc8(); * var exerc9 = new Exerc9(); * var exerc10 = new Exerc10();*/ Byte _opition; do { System.Console.WriteLine($"\n\n Digite o número do exercicio que desejar entre {exercInicial} a {exercFinal}, ou número 0 pra sair"); _opition = Convert.ToByte(System.Console.ReadLine()); System.Console.WriteLine($"Você escolheu o exercício {_opition}:"); switch (_opition) { case 1: exerc1.Main(); break; case 2: exerc2.Main(); break; /* case 3: exerc3.exe(); break; * case 4: exerc4.exe(); break; * case 5: exerc5.exe(); break; * case 6: exerc6.exe(); break; * case 7: exerc7.exe(); break; * case 8: exerc8.exe(); break; * case 9: exerc9.exe(); break; * case 10: exerc10.exe(); break;*/ default: _opition = 0; break; } } while ((_opition != 0) && (_opition <= exercFinal)); System.Console.WriteLine("Nº do exercício não encontrado"); }
public void Task_2Catch__FirstMatchesAndRethrow_SecondMatches() { var mock1 = new Mock <IAfter>(); var mock2 = new Mock <IAfter>(); var ex1 = new Ex1(); var ex2 = new Ex2(); mock1.Setup(then => then.CatchExceptionHandler(ex1)).Throws(ex2); Task task = SimpleTaskFactory .Run(() => { throw ex1; }) .Catch <Ex1>(exception => mock1.Object.CatchExceptionHandler(exception)) .Catch <Ex2>(exception => mock2.Object.CatchExceptionHandler(exception)); task.Wait(); mock1.Verify(then => then.CatchExceptionHandler(ex1), Times.Once); mock2.Verify(then => then.CatchExceptionHandler(ex2), Times.Once); Assert.Pass(); }
static void Main( string[] args ) { // Read args ParseArgs(args); // Start up the GUI thread InitGUIThread(); AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, "Starting up SwarmAgent ..." ); AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent with remoting service" ); // Register the local agent singleton RemotingConfiguration.RegisterWellKnownServiceType( typeof( Agent ), "SwarmAgent", WellKnownObjectMode.Singleton ); AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... registering SwarmAgent network channels" ); // We're going to have two channels for the Agent: one for the actual Agent // application (IPC with infinite timeout) and one for all other remoting // traffic (TCP with infinite timeout that we monitor for drops) IpcChannel AgentIPCChannel = null; TcpChannel AgentTCPChannel = null; while( ( Ticking == true ) && ( ( AgentIPCChannel == null ) || ( AgentTCPChannel == null ) ) ) { try { if( AgentIPCChannel == null ) { // Register the IPC connection to the local agent string IPCChannelPortName = String.Format( "127.0.0.1:{0}", Properties.Settings.Default.AgentRemotingPort ); AgentIPCChannel = new IpcChannel( IPCChannelPortName ); ChannelServices.RegisterChannel( AgentIPCChannel, false ); } if( AgentTCPChannel == null ) { // Register the TCP connection to the local agent AgentTCPChannel = new TcpChannel( Properties.Settings.Default.AgentRemotingPort ); ChannelServices.RegisterChannel( AgentTCPChannel, false ); } } catch (RemotingException Ex) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Channel already registered, suggesting another SwarmAgent or client is running."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] If you feel this is in error, check your running process list for additional copies of"); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] SwarmAgent or UnrealLightmass (or other client) and consider killing them."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, "[ERROR] Sleeping for a few seconds and trying again..."); AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, string.Format("[ERROR] Channel registration failed. Reason: {0}\n, Callstack: {1}.", Ex.Message, Ex.StackTrace)); Thread.Sleep(3000); } catch (Exception Ex) { AgentApplication.Log(EVerbosityLevel.Informative, ELogColour.Orange, string.Format("[ERROR] Channel registration failed. Reason: {0}\n, Callstack: {1}.", Ex.Message, Ex.StackTrace)); Thread.Sleep(3000); } } // if we're still ticking, we should have both of our channels initialized if( Ticking ) { Debug.Assert( AgentIPCChannel != null ); Debug.Assert( AgentTCPChannel != null ); } else { // Otherwise, we can simply return to exit return; } // Get the agent interface object using the IPC channel string LocalAgentURL = String.Format( "ipc://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() ); LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL ); AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initializing SwarmAgent" ); // Init the local agent object (if this is the first call to it, it will be created now) bool AgentInitializedSuccessfully = false; try { AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id ); } catch( Exception Ex ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with an IPC channel! Falling back to TCP..." ); AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex.ToString() ); // Try again with the TCP channel, which is slower but should work LocalAgentURL = String.Format( "tcp://127.0.0.1:{0}/SwarmAgent", Properties.Settings.Default.AgentRemotingPort.ToString() ); LocalAgent = ( Agent )Activator.GetObject( typeof( Agent ), LocalAgentURL ); try { AgentInitializedSuccessfully = LocalAgent.Init( Process.GetCurrentProcess().Id ); if( AgentInitializedSuccessfully ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] RECOVERED by using TCP channel!" ); } } catch( Exception Ex2 ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] Local agent failed to initialize with a TCP channel! Fatal error." ); AgentApplication.Log( EVerbosityLevel.Verbose, ELogColour.Red, "[ERROR] Exception details: " + Ex2.ToString() ); ChannelServices.UnregisterChannel( AgentTCPChannel ); ChannelServices.UnregisterChannel( AgentIPCChannel ); return; } } // Only continue if we have a fully initialized agent if( ( LocalAgent != null ) && AgentInitializedSuccessfully ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Green, " ... initialization successful, SwarmAgent now running" ); // Loop until a quit/restart event has been requested while( !LocalAgent.ShuttingDown() ) { try { // If we've stopped ticking, notify the agent that we want to shutdown if( !Ticking ) { LocalAgent.RequestShutdown(); } // Maintain the agent itself LocalAgent.MaintainAgent(); // Maintain any running active connections LocalAgent.MaintainConnections(); // Maintain the Agent's cache if( CacheRelocationRequested ) { LocalAgent.RequestCacheRelocation(); CacheRelocationRequested = false; } if( CacheClearRequested ) { LocalAgent.RequestCacheClear(); CacheClearRequested = false; } if( CacheValidateRequested ) { LocalAgent.RequestCacheValidate(); CacheValidateRequested = false; } LocalAgent.MaintainCache(); // Maintain any running jobs LocalAgent.MaintainJobs(); // If this is a deployed application which is configured to auto-update, // we'll check for any updates and, if there are any, request a restart // which will install them prior to restarting #if !__MonoCS__ if( ( AgentApplication.DeveloperOptions.UpdateAutomatically ) && ( ApplicationDeployment.IsNetworkDeployed ) && (DateTime.UtcNow > NextUpdateCheckTime)) { if( CheckForUpdates() ) { LocalAgent.RequestRestart(); } NextUpdateCheckTime = DateTime.UtcNow + TimeSpan.FromMinutes(1); } #endif } catch( Exception Ex ) { AgentApplication.Log( EVerbosityLevel.Informative, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.Message ); AgentApplication.Log( EVerbosityLevel.ExtraVerbose, ELogColour.Red, "[ERROR] UNHANDLED EXCEPTION: " + Ex.ToString() ); } // Sleep for a little bit Thread.Sleep( 500 ); } // Let the GUI destroy itself RequestQuit(); bool AgentIsRestarting = LocalAgent.Restarting(); // Do any required cleanup LocalAgent.Destroy(); ChannelServices.UnregisterChannel( AgentTCPChannel ); ChannelServices.UnregisterChannel( AgentIPCChannel ); // Now that everything is shut down, restart if requested if( AgentIsRestarting ) { ClearCache(); InstallAllUpdates(); Application.Restart(); } } }
private static void Solution2() { Ex2 ex2 = new Ex2(3.54, 6); Console.WriteLine(ex2); }
public void ReceiveImage() { int GetImageLength; int GetImageArea; int RealImageLength; MemoryStream ms = new MemoryStream(); IPBindPoint_ForImage = new IPEndPoint(ServerIP, sPort + 1); IPBindPoint_ForImage = new IPEndPoint(((IPEndPoint)Client[0].RemoteEndPoint).Address, sPort + 1); senderp = (IPEndPoint)IPBindPoint_ForImage; Bitmap GetImageBit; //Thread.Sleep(10000); try { ImageServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500); while (Client[0].Connected) { //Get Image Size //ImageServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0); Client[0].Receive(GetImageSize, 0, 4, SocketFlags.None); RealImageLength = BitConverter.ToInt32(GetImageSize, 0); Client[0].Receive(GetImageSize, 0, 4, SocketFlags.None); GetImageLength = BitConverter.ToInt32(GetImageSize, 0); if (GetImageLength == 0) { continue; } //Get Image Area /*ImageClient.Receive(GetImageAreaByte, 0, 4, SocketFlags.None); * GetImageArea = BitConverter.ToInt32(GetImageAreaByte, 0);*/ GetImageBytes = new byte[GetImageLength]; //ImageServer.Receive(GetImageBytes, 0, GetImageLength, SocketFlags.None); //ImageServer.ReceiveFrom(GetImageBytes, 0, GetImageLength, SocketFlags.None, ref senderp); int count = 0; int icount = 0; sw = false; do { try { GetByte = new byte[SizeForOne + 4]; for (int i = icount; i < GetImageLength / SizeForOne; i++) { //ChatBoxAdd(ImageServer.ReceiveFrom(GetByte, 0, SizeForOne + 4, SocketFlags.None, ref senderp).ToString()); ImageServer.BeginReceiveFrom(GetByte, 0, SizeForOne + 4, SocketFlags.None, ref senderp, new AsyncCallback(MessageCallBack), Tuple.Create(GetByte, 0, GetImageLength)); } Client[0].Send(new byte[4]); Client[0].Receive(new byte[4]); if (GetImageLength % SizeForOne != 0) { ImageServer.ReceiveFrom(GetImageBytes, GetImageLength - (GetImageLength % SizeForOne), GetImageLength % SizeForOne, SocketFlags.None, ref senderp); } sw = true; Client[0].Send(BitConverter.GetBytes(-1)); } catch (Exception Ex3) { ChatBoxAdd(Ex3.ToString()); ChatBoxAdd("UDP 데이터 소실 발생."); sw = false; icount = 0; Client[0].Send(BitConverter.GetBytes(-1)); break; Client[0].Send(BitConverter.GetBytes(icount)); } } while (!sw); try { if (sw == false) { throw new Exception(); } ms = new MemoryStream(); ms.Write(GetImageBytes, 0, (int)GetImageBytes.Length); ms.Position = 0; GetImageBytes = new byte[RealImageLength]; //var DecompressStream = new DeflateStream(ms, CompressionMode.Decompress,true); var DecompressStream = new GZipStream(ms, CompressionMode.Decompress, true); var DecompressedStream = new MemoryStream(); DecompressStream.CopyTo(DecompressedStream); DecompressStream.Close(); DecompressedStream.Position = 0; Bitmap Image = new Bitmap(DecompressedStream); //Bitmap Image = new Bitmap(ms); ChatBoxAdd("Success!"); MainPicture.MainPictureChange(Image); //pictureBox1Change(Image); Orginal_Image = Image; ms.Close(); DecompressedStream.Close(); ImageServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0); Client[0].Send(new byte[4]); sw = true; } catch (Exception ex) { ChatBoxAdd(ex.ToString()); ImageServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 0); Client[0].Send(new byte[4]); sw = true; } GetImageBytes = null; //Thread.Sleep(100); GetImageBit = null; GC.Collect(0); GC.Collect(1); } } catch (Exception Ex2) { ChatBoxAdd(Ex2.ToString()); } }
public void TaskT_2Catch__FirstMatchesAndRethrow_SecondMatches() { var mock1 = new Mock<IAfter>(); var mock2 = new Mock<IAfter>(); var ex1 = new Ex1(); var ex2 = new Ex2(); mock1.Setup(then => then.CatchExceptionHandlerWithOutput(ex1)).Throws(ex2); Task<int> task = SimpleTaskFactory .Run(() => { throw ex1; return default(int); }) .Catch<int, Ex1>(exception => mock1.Object.CatchExceptionHandlerWithOutput(exception)) .Catch<int, Ex2>(exception => mock2.Object.CatchExceptionHandlerWithOutput(exception)); task.Wait(); mock1.Verify(then => then.CatchExceptionHandlerWithOutput(ex1), Times.Once); mock2.Verify(then => then.CatchExceptionHandlerWithOutput(ex2), Times.Once); Assert.Pass(); }
public void Ex2Test2() { Assert.AreEqual(Math.PI, Ex2.GetPI(0.00000000000000001), 0.00000001); }
public static DateTime DtTm(String Str) { DateTime Value = DateTime.MinValue; if (Str != "") { try { Value = Convert.ToDateTime(Str); } catch (Exception Ex) { Ex.GetType(); int Year = 0; int Month = 0; int Day = 0; int Hour = 0; int Min = 0; int Sec = 0; Char[] Separators = { ' ', '/', ':', '.' }; Str = Str.Trim().ToUpper(); String[] Parts = Str.Split(Separators); for (int iParts = 0; iParts < Parts.Length; iParts++) { switch (iParts) { case 0: Month = Num(Parts[iParts]); break; case 1: Day = Num(Parts[iParts]); break; case 2: Year = Num(Parts[iParts]); break; case 3: Hour = Num(Parts[iParts]); break; case 4: Min = Num(Parts[iParts]); break; case 5: Sec = Num(Parts[iParts]); break; } } if (Hour > 0 && Hour <= 12) { String Last = Parts[Parts.Length - 1]; if (Last.IndexOf('P') > -1) { Hour += 12; } } if (Year < 99) { Year += 2000; } if (Month == 0) { Month = 1; } if (Month > 12) { Month = 12; } if (Day == 0) { Day = 1; } if (Day > 31) { Day = 31; } if (Month == 2 && Day > 29) { Day = 29; } if (Hour > 24) { Hour = 24; } if (Min > 59) { Min = 59; } if (Sec > 59) { Sec = 59; } if (Year > 0 && Month > 0 && Day > 0) { try { Value = new DateTime(Year, Month, Day, Hour, Min, Sec); } catch (Exception Ex1) { Ex1.GetType(); Day--; try { Value = new DateTime(Year, Month, Day, Hour, Min, Sec); } catch (Exception Ex2) { Ex2.GetType(); } } } } } return(Value); }
private void toolStripButton1_Click(object sender, EventArgs e) { if (goodInput && !loading) { loading = true; toolStripButton1.Enabled = false; if (iterations >= 100000) { DialogResult option = MessageBox.Show("Running " + iterations + " simulations will " + "take approximately: " + getTime() + "\nDo you wish to continue?", "Alert", MessageBoxButtons.OKCancel); if (option == DialogResult.Cancel) { goto Done; } } try { if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } } catch (Exception Ex0) { var nullErrorMessageBox = MessageBox.Show ("ERROR disposing old image file! \nOutput: " + Ex0.ToString(), "Alert", MessageBoxButtons.OK); } RscriptWriter(); userInputScript = rPathDest; Console.WriteLine("userInputScript: " + userInputScript); outputLocation = RpathFinder(); Console.WriteLine("outputLocation: " + outputLocation); try { RunFromCmd(userInputScript, userInputCSV, outputLocation, iterations.ToString(), distributionType); } catch (Exception Ex1) { var nullErrorMessageBox = MessageBox.Show ("ERROR on CMD process! \nOutput: " + Ex1.ToString(), "Alert", MessageBoxButtons.OK); } try { Cursor.Current = Cursors.WaitCursor; toolStripButton1.BackColor = Color.GreenYellow; if (iterations >= 10000000) { Thread.Sleep(Convert.ToInt32(iterations * 0.10)); } else if (iterations >= 100000 && iterations < 10000000) { Thread.Sleep(Convert.ToInt32(iterations * 0.30)); } else if (iterations >= 10000 && iterations < 100000) { Thread.Sleep(Convert.ToInt32(iterations * 0.50)); } else { Thread.Sleep(2500); } } catch (Exception Ex2) { var nullErrorMessageBox = MessageBox.Show ("ERROR waiting for process to complete! \nOuput: " + Ex2.ToString(), "Alert", MessageBoxButtons.OK); } try { pictureBox1.Image = Image.FromFile(RpathFinder() + @"\output.png"); } catch (Exception Ex3) { var nullErrorMessageBox = MessageBox.Show ("ERROR loading the image file! \nOuput: " + Ex3.ToString(), "Alert", MessageBoxButtons.OK); } Done: try { if (!string.IsNullOrWhiteSpace(userInputScript)) { DeleteTempFile(userInputScript); } //if (!string.IsNullOrWhiteSpace(userInputScript)) //DeleteTempFile(RpathFinder() + @"\output.png"); loading = false; maxWarning = false; minWarning = false; } catch (Exception Ex4) { var nullErrorMessageBox = MessageBox.Show ("ERROR on cleanup process! \nOutput: " + Ex4.ToString(), "Alert", MessageBoxButtons.OK); } } }
public void TestCountSimilarCasewise() { Assert.AreEqual(Ex1.CountSimilar(Ex2), 3); Assert.AreEqual(Ex2.CountSimilar(Ex3), 1); Assert.AreEqual(Ex1.CountSimilar(Ex3), 1); }
public void TestCountSimilarVsSelf() { Assert.AreEqual(Ex1.CountSimilar(Ex1), Ex1.Count); Assert.AreEqual(Ex2.CountSimilar(Ex2), Ex2.Count); Assert.AreEqual(Ex3.CountSimilar(Ex3), Ex3.Count); }
private async void button1_Click(object sender, EventArgs e) { listView1.Items.Clear(); this.ct = new CancellationTokenSource(); string path = Dir.Text; int numberOfFiles = 1; if (!Directory.Exists(path)) { listView1.Items.Add(new ListViewItem { Text = "Invalid Directory" }); return; } try { numberOfFiles = Int32.Parse(NumberOfFIles.Text); } catch (Exception) { listView1.Items.Clear(); ListViewItem toAdd = new ListViewItem(); toAdd.Text = "Invalid number."; listView1.Items.Add(toAdd); return; } this.progressTask.Value = 0; listView1.Items.Add(new ListViewItem { Text = "Running... " }); try { ResultParallel res = await Ex2.processDirAsync(path, numberOfFiles, ct.Token, (progress, totalItems) => { SetValue((Int32)((((float)(int)progress) / (float)(int)totalItems) * 100f)); }); listView1.Items.Clear(); listView1.Items.Add(new ListViewItem { Text = "Number of files processed " + res.numberOfFiles }); listView1.Items.AddRange(res.list.ConvertAll <ListViewItem>((item) => { return(new ListViewItem { Text = item }); }).ToArray()); } catch (OperationCanceledException ex) { listView1.Items.Clear(); listView1.Items.Add(new ListViewItem { Text = "Cancelled...." }); } catch (Exception ex) { listView1.Items.Clear(); listView1.Items.Add(new ListViewItem { Text = "Error: " + ex.Message }); } finally { this.ct.Dispose(); } }