private static void printParenth(int left, int right, System.Collections.ArrayList arr) { if (left == 0 && right == 0) { foreach (var item in arr) { System.Console.Write(item + " "); } System.Console.WriteLine(); //return arr; } if (left > 0) { System.Collections.ArrayList new_arr = (System.Collections.ArrayList)arr.Clone(); new_arr.Add("("); //return printParenth(left - 1, right, new_arr); } if (left < right) { System.Collections.ArrayList new_arr = (System.Collections.ArrayList)arr.Clone(); new_arr.Add(")"); //return printParenth(left, right - 1, new_arr); } //return null; }
private static void printParenth(int RemainingLeft, int RemainingRight, System.Collections.ArrayList arr) { if (RemainingLeft == 0 && RemainingRight == 0) { for (int i = 0; i < arr.Count; i++) { System.Console.Write(arr[i] + " "); } System.Console.WriteLine(); } if (RemainingLeft > 0) { System.Collections.ArrayList arr2 = (System.Collections.ArrayList)arr.Clone(); arr2.Add("["); printParenth(RemainingLeft - 1, RemainingRight, arr2); } if (RemainingLeft < RemainingRight) { System.Collections.ArrayList arr2 = (System.Collections.ArrayList)arr.Clone(); arr2.Add("]"); printParenth(RemainingLeft, RemainingRight - 1, arr2); } }
private static void RunArrayRotation() { var inputArray = new[] { 1, 2, 3, 4, 5, 6 }; var positions = 2; Console.WriteLine($"Input: {Utils.FormatArray(inputArray)}, rotate by: {positions}"); var arrayCopy = (int[])inputArray.Clone(); ArrayRotation.Rotate(arrayCopy, positions); Console.WriteLine($"Rotate: {Utils.FormatArray(arrayCopy)}"); arrayCopy = (int[])inputArray.Clone(); ArrayRotation.Rotate_Reverse(arrayCopy, positions); Console.WriteLine($"Rotate by using array reverse: {Utils.FormatArray(arrayCopy)}"); }
public void CloneWorks() { var arr = new[] { "x", "y" }; var arr2 = arr.Clone(); Assert.IsFalse(arr == arr2); Assert.AreEqual(arr, arr2); }
public Image(System.Drawing.Bitmap bitmap) { this.bitmap = (System.Drawing.Bitmap)bitmap.Clone(); this.width = this.bitmap.Width; this.height = this.bitmap.Height; }
/// <summary> /// Resizes and rotates an image, keeping the original aspect ratio. Does not dispose the original /// Image instance. /// </summary> /// <param name="image">Image instance</param> /// <param name="width">desired width</param> /// <param name="height">desired height</param> /// <param name="rotateFlipType">desired RotateFlipType</param> /// <returns>new resized/rotated Image instance</returns> public static System.Drawing.Image Resize(System.Drawing.Image image, int width, int height, RotateFlipType rotateFlipType) { // clone the Image instance, since we don't want to resize the original Image instance var rotatedImage = image.Clone() as System.Drawing.Image; //rotatedImage.RotateFlip(rotateFlipType); var newSize = CalculateResizedDimensions(rotatedImage, width, height); var resizedImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb); resizedImage.SetResolution(72, 72); using (var graphics = Graphics.FromImage(resizedImage)) { // set parameters to create a high-quality thumbnail graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; // use an image attribute in order to remove the black/gray border around image after resize // (most obvious on white images), see this post for more information: // http://www.codeproject.com/KB/GDI-plus/imgresizoutperfgdiplus.aspx using (var attribute = new ImageAttributes()) { attribute.SetWrapMode(WrapMode.TileFlipXY); // draws the resized image to the bitmap graphics.DrawImage(rotatedImage, new Rectangle(new Point(0, 0), newSize), 0, 0, rotatedImage.Width, rotatedImage.Height, GraphicsUnit.Pixel, attribute); } } return resizedImage; }
internal P4FormRecordSet(string FormCommand, System.Text.Encoding encoding) { // clone this so we don't hold a reference to another object's encoding object // preventing it from Garbage collecting. _encoding = (System.Text.Encoding) encoding.Clone(); _FormCommand = FormCommand; }
/// <summary> /// Initializes a new DirectXTexture class. /// </summary> /// <param name="bmp">The Bitmap.</param> internal DirectXTexture(System.Drawing.Bitmap bmp) { RawBitmap = (System.Drawing.Bitmap) bmp.Clone(); _width = bmp.Width; _height = bmp.Height; var sourceArea = new Rectangle(0, 0, bmp.Width, bmp.Height); var bitmapProperties = new BitmapProperties( new PixelFormat(Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied), 96, 96); var size = new Size2(bmp.Width, bmp.Height); int stride = bmp.Width*sizeof (int); using (var tempStream = new DataStream(bmp.Height*stride, true, true)) { BitmapData bitmapData = bmp.LockBits(sourceArea, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); for (int y = 0; y < bmp.Height; y++) { int offset = bitmapData.Stride*y; for (int x = 0; x < bmp.Width; x++) { byte b = Marshal.ReadByte(bitmapData.Scan0, offset++); byte g = Marshal.ReadByte(bitmapData.Scan0, offset++); byte r = Marshal.ReadByte(bitmapData.Scan0, offset++); byte a = Marshal.ReadByte(bitmapData.Scan0, offset++); int rgba = r | (g << 8) | (b << 16) | (a << 24); tempStream.Write(rgba); } } bmp.UnlockBits(bitmapData); tempStream.Position = 0; _bmp = new Bitmap(DirectXHelper.RenderTarget, size, tempStream, stride, bitmapProperties); } }
public System.Collections.ArrayList Recombine(System.Collections.ArrayList maleGenes, System.Collections.ArrayList femaleGenes) { ArrayList child; if (maleGenes.Count < femaleGenes.Count) { child = femaleGenes.Clone() as ArrayList; for (int i = 0; i < maleGenes.Count; i++) { if (!Convert.ToBoolean(i % 2)) child[i] = maleGenes[i]; // Deep Copy child[i] = (child[i] as IGene).Clone(); } } else { child = maleGenes.Clone() as ArrayList; for (int i = 0; i < femaleGenes.Count; i++) { if (!Convert.ToBoolean(i % 2)) child[i] = femaleGenes[i]; // Deep Copy child[i] = (child[i] as IGene).Clone(); } } return child; }
public VersionAttribute(System.Version version) { if (version == null) { throw new ArgumentNullException(); } this.Version = (System.Version) version.Clone(); }
public void SortingWithoutChanges() { var array = new[] { 1, 2, 3, 4, 5 }; var arrayCopy = (int[])array.Clone(); array.HeapSort(); CollectionAssert.AreEqual(arrayCopy, array); }
public void SortingSomeArray() { var array = new[] { -5, 5, -10, -4, 11, 0, 1, -9, 9, 7 }; var arrayCopy = (int[])array.Clone(); array.HeapSort(); Array.Sort(arrayCopy); CollectionAssert.AreEqual(arrayCopy, array); }
internal P4Form(string FormCommand, string specDef, Dictionary<string, string> S, System.Text.Encoding encoding) : base(S) { _specdef = specDef; // clone this so we don't hold a reference to another object's encoding object // preventing it from Garbage collecting. _encoding = (System.Text.Encoding) encoding.Clone(); _spec = new p4dn.Spec(specDef, encoding); _formCommand = FormCommand; }
public void SortingBadArray() { var array = new[] { 5, 4, 3, 2, 1 }; var arrayCopy = (int[])array.Clone(); array.HeapSort(); Array.Sort(arrayCopy); CollectionAssert.AreEqual(arrayCopy, array); }
public void SortingSomeArrayWhenMaxComparerUsing() { var array = new[] { -5, 5, -10, -4, 11, 0, 1, -9, 9, 7 }; var arrayCopy = (int[])array.Clone(); var comparer = new MyIntComparer(); array.HeapSort(comparer); Array.Sort(arrayCopy, comparer); CollectionAssert.AreEqual(arrayCopy, array); }
public void SendLiveImage(System.Drawing.Image img) { lock (this.locker) { if (this.images.Count < 2) { this.images.Enqueue((System.Drawing.Image) img.Clone()); this.go.Set(); } } }
public static void DrawAdaptiveString(this System.Drawing.Graphics g, string Text, System.Drawing.Font Font, System.Drawing.Brush Brush, System.Drawing.RectangleF Where, System.Drawing.StringFormat Format) { System.Drawing.Font curFont = (System.Drawing.Font)Font.Clone(); System.Drawing.SizeF curSize; do { curSize = g.MeasureString(Text, curFont); if (curSize.Width > Where.Width || curSize.Height > Where.Height) curFont = new System.Drawing.Font(curFont.FontFamily, curFont.Size - 1); } while ((curSize.Width > Where.Width || curSize.Height > Where.Height)); g.DrawString(Text, curFont, Brush, Where, Format); }
public void should_return_shallow_copy_of_an_array_using_clone() { var array = new[] {new RefTypeClass(1)}; var cloned = (RefTypeClass[])array.Clone(); array[0].Value = 5; // change the variable value to correct one. const int expectedResult = 1; Assert.Equal(expectedResult, cloned[0].Value); }
public void SimpleCloneEquality() { var source = new[] { "test0", "test1", "test2" }; var target = (string[])source.Clone(); Assert.AreNotSame(source, target); for (int i = 0; i < source.Length; i++) { Assert.AreSame(source[i], target[i]); } }
private static void CreateNewImage(ref System.Drawing.Image refImage, int r, int g, int b) { Image newImage = (Image)refImage.Clone(); // Convert to gif with new color Core.GifImage.ConverToGifImageWithNewColor(ref newImage, refImage.Palette, victim, Color.FromArgb(255, r, g, b)); // Sage this gif image SaveGifImage(ref newImage, r, g, b); // Free up resources newImage.Dispose(); newImage = null; }
/// <summary> /// 获取表里某页的数据 /// </summary> /// <param name="data">表数据</param> /// <param name="PageIndex">当前页</param> /// <param name="PageSize">分页大小</param> /// <param name="AllPage">返回总页数</param> /// <returns>返回当页表数据</returns> public static System.Data.DataTable GetPage(System.Data.DataTable data, int PageIndex, int PageSize, out int AllPage) { AllPage = data.Rows.Count / PageSize; AllPage += data.Rows.Count % PageSize == 0 ? 0 : 1; System.Data.DataTable Ntable = data.Clone(); int startIndex = PageIndex * PageSize; int endIndex = startIndex + PageSize > data.Rows.Count ? data.Rows.Count : startIndex + PageSize; if (startIndex < endIndex) for (int i = startIndex; i < endIndex; i++) { Ntable.ImportRow(data.Rows[i]); } return Ntable; }
public void Compare_Test2() { var dt0 = new DateTimeOffset(1582, 10, 15, 0, 0, 0, TimeSpan.Zero); var arr = new [] { TimeUuid.NewId(dt0.AddTicks(0x00000000007fffL)), TimeUuid.NewId(dt0.AddTicks(0x00ff0000000000L)), TimeUuid.NewId(dt0.AddTicks(0x07ff0000000000L)), TimeUuid.NewId(dt0.AddTicks(0x07ff0000ff0000L)) }; var actual = (TimeUuid[])arr.Clone(); Array.Sort(actual); CollectionAssert.AreEqual(arr, actual); }
internal OperatingSystem(PlatformID platform, System.Version version, string servicePack) { if ((platform < PlatformID.Win32S) || (platform > PlatformID.MacOSX)) { throw new ArgumentException(Environment.GetResourceString("Arg_EnumIllegalVal", new object[] { (int) platform }), "platform"); } if (version == null) { throw new ArgumentNullException("version"); } this._platform = platform; this._version = (System.Version) version.Clone(); this._servicePack = servicePack; }
public MovablePictureBox(int x, int y, System.Drawing.Image image, Model.SoundPosition soundPosition, Controller.StaveController staveController) { this.threadRunning = true; this.Location = new Point(x, y); this.Width = 32; this.Height = 32; this.staveController = staveController; this.Image = (System.Drawing.Image) image.Clone(); this.Cursor = System.Windows.Forms.Cursors.SizeAll; this.soundPosition = soundPosition; InitializeComponent(); this.IsSelected = false; this.threadRunning = false; }
private static long CheckCycleAt0(System sys0) { System sys = sys0.Clone(); long t2 = 0; while (true) { Timestep2(sys.moons); t2++; if (sys == sys0) { break; } } Console.WriteLine($"Found cycle at {t2}"); return(t2); }
/// <summary> /// Convertir a escala de grises, es necesario optimizarlo con LockBitmap /// </summary> /// <param name="Bitmap"></param> /// <returns></returns> public static Bitmap GrayScale(System.Drawing.Bitmap Bitmap) { System.Drawing.Bitmap bitmap = (System.Drawing.Bitmap)Bitmap.Clone(); System.Drawing.Color color; for (System.Int32 i = 0; i < bitmap.Width; i++) { for (System.Int32 j = 0; j < bitmap.Height; j++) { color = bitmap.GetPixel(i, j); color = ColorToGrey(color); Bitmap.SetPixel(i, j, color); } } return Bitmap; }
public bool Apply(System.Drawing.Bitmap srcBitmap, double value) { if (value < -255 || value > 255) return false; _image = (Bitmap)srcBitmap.Clone(); // GDI+ still lies to us - the return format is BGR, NOT RG_image. BitmapData bmData = _image.LockBits(new Rectangle(0, 0, _image.Width, _image.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int stride = bmData.Stride; System.IntPtr Scan0 = bmData.Scan0; int nVal = 0; unsafe { byte* p = (byte*)(void*)Scan0; int nOffset = stride - _image.Width * 3; int nWidth = _image.Width * 3; for (int y = 0; y < _image.Height; ++y) { for (int x = 0; x < nWidth; ++x) { nVal = (int)(p[0] + value); if (nVal < 0) nVal = 0; if (nVal > 255) nVal = 255; p[0] = (byte)nVal; ++p; } p += nOffset; } } _image.UnlockBits(bmData); return true; }
/// <summary> /// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source /// </summary> /// <param name="bitmap">The Source Bitmap</param> /// <returns>The equivalent BitmapSource</returns> public static BitmapSource ToBitmapSource(System.Drawing.Bitmap bitmap) { if (bitmap == null) return null; using (System.Drawing.Bitmap source = (System.Drawing.Bitmap)bitmap.Clone()) { IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap( ptr, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); NativeMethods.DeleteObject(ptr); //release the HBitmap bs.Freeze(); return bs; } }
public override void fillRowsToOtherDataset(System.Data.DataTable table, System.Collections.ArrayList rows, System.Data.DataSet data, System.Data.IDbTransaction tran) { int contador = 0; StringBuilder s = new StringBuilder(); data.Tables.Add(table.Clone()); string baseSelectCommand = SqlSyntax.CreateSelectCommandText(table, "WHERE {0}", DBAbstractDataLayer.DataAccessRules.Syntax.DataDeletionStatus.All); using (SqlDataAdapter da = new SqlDataAdapter(new SqlCommand("", (SqlConnection)tran.Connection, (SqlTransaction)tran))) { // por cada linha da tabela modified ou deleted (as marcadas como added nao estao sujeitas a conflitos de concorrencia foreach (DataRow dr in rows) { contador++; s.Append("("); s.Append(buildFilter(table, dr).ToString()); s.Append(")"); // impedir que na query entre 1 "or" a mais if (contador % 200 != 0 && contador < rows.Count) s.Append(" OR "); // se ja tiverem sido obtidos 200 IDs, completar a query e executa-la e na base de dados if (contador % 200 == 0 || contador == rows.Count) { // executar comando sql obtido try { //System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(new System.Data.SqlClient.SqlCommand("", (System.Data.SqlClient.SqlConnection) tran.Connection, (System.Data.SqlClient.SqlTransaction) tran)); //da.SelectCommand.CommandText = SqlSyntax.CreateSelectCommand(table, string.Format("where {0}", s), DBAbstractDataLayer.DataAccessRules.SqlClient.SqlSyntax.DataDeletionStatus.All); da.SelectCommand.CommandText = string.Format(baseSelectCommand, s); da.Fill(data, table.TableName); // limpar filtro para o voltar a encher com os proximos 50 s = new System.Text.StringBuilder(); } catch (Exception ex) { Trace.WriteLine(string.Format("Erro ({0}): {1}", table.TableName, ex)); throw; } } } } }
protected RunspaceBase(PSHost host, System.Management.Automation.Runspaces.InitialSessionState initialSessionState) { this._version = PSVersionInfo.PSVersion; this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(System.Management.Automation.Runspaces.RunspaceState.BeforeOpen); this._syncRoot = new object(); this._runspaceEventQueue = new Queue<RunspaceEventQueueItem>(); this.RunspaceOpening = new ManualResetEventSlim(false); this._runningPipelines = new ArrayList(); if (host == null) { throw PSTraceSource.NewArgumentNullException("host"); } if (initialSessionState == null) { throw PSTraceSource.NewArgumentNullException("initialSessionState"); } this._host = host; this._initialSessionState = initialSessionState.Clone(); base.ApartmentState = initialSessionState.ApartmentState; this.ThreadOptions = initialSessionState.ThreadOptions; }
/*filtra la tabla origen con los elementos de la columa clave de la tabla filtro*/ public System.Data.DataTable Filter(System.Data.DataTable filtro, System.Data.DataTable origen, string clave) { int i = 0; System.Data.DataTable dtfiltrado = origen.Clone(); while (i < filtro.Rows.Count) { string svalor = filtro.Rows[i][0].ToString(); System.Data.DataRow[] drseleccionados = origen.Select(clave + "='" + svalor + "'"); /*if (drseleccionados.Length == 0) { System.Data.DataRow drmissing = dtfiltrado.NewRow(); drmissing["id_mostra"] = svalor; dtfiltrado.Rows.Add(drmissing); }*/ foreach (System.Data.DataRow dr in drseleccionados) { dtfiltrado.ImportRow(dr); } i++; } return dtfiltrado; }
public static void Day12() { Console.WriteLine("Day12: "); Moon[] moons = File.ReadAllLines("Aoc2019\\Day12\\input.txt").Select(s => Regex.Replace(s, "[<>xyz= ]", "")).Select(s => { var xyz = s.Split(',').Select(s => int.Parse(s)).ToArray(); return(new Moon(xyz)); }).ToArray(); System sys0 = new System(moons); // part 1 System sys = sys0.Clone(); for (int t = 0; t < 1000; t++) { Timestep2(sys.moons); } Console.WriteLine(sys.TotalEnergy()); //part 2 System sysX = sys0.Clone(); for (int i = 0; i < sysX.moons.Length; i++) { sysX.moons[i].y = 0; sysX.moons[i].z = 0; } System sysY = sys0.Clone(); for (int i = 0; i < sysY.moons.Length; i++) { sysY.moons[i].x = 0; sysY.moons[i].z = 0; } System sysZ = sys0.Clone(); for (int i = 0; i < sysZ.moons.Length; i++) { sysZ.moons[i].x = 0; sysZ.moons[i].y = 0; } long xcyc = CheckCycleAt0(sysX); long ycyc = CheckCycleAt0(sysY); long zcyc = CheckCycleAt0(sysZ); long x = 0, y = 0, z = 0; // this is the answer, just to speed up running this program. Comment these three lines to recalculate. x = 374307970285176 - xcyc; y = 374307970285176 - ycyc; z = 374307970285176 - zcyc; // A faster way than this loop would be to calculate the Least Common Multiple of xcyc, ycyc, zcyc while (true) { if (x < y) { if (x < z) { x += xcyc; } else { z += zcyc; } } else { if (y < z) { y += ycyc; } else { z += zcyc; } } if (x == y && y == z) { break; } } Console.WriteLine(x); }
// this version checks for cycles that might start after position 0. private static long CheckCycle(System sys0) { Dictionary <int, (long, System)> possible_matches = new Dictionary <int, (long, System)>(); System sys = sys0.Clone(); long t2 = 0; long check_step = 10000000; long deltastep; while (true) { Timestep2(sys.moons); t2++; int hash = sys.GetHashCode(); if (possible_matches.TryGetValue(hash, out var prevt)) { //Console.WriteLine($"Found possible previous cycle at {prevt.Item1}"); if (prevt.Item2 == sys) { Console.WriteLine($"Found cycle at {t2} with time-delta {t2 - prevt.Item1}"); deltastep = t2 - prevt.Item1; break; } } if (t2 % check_step == 0) { possible_matches.Add(hash, (t2, sys.Clone())); Console.WriteLine(t2 + " " + possible_matches.Count); } } sys = sys0.Clone(); t2 = 0; foreach (var prev in possible_matches) { if (prev.Value.Item1 < deltastep && t2 < prev.Value.Item1) { t2 = prev.Value.Item1; sys = prev.Value.Item2.Clone(); Console.WriteLine($"Advancing system to prev {t2}"); } } while (t2 < deltastep) { Timestep2(sys.moons); t2++; if (t2 % check_step == 0) { Console.WriteLine($"Advancing system to {t2}"); } } var sys1 = sys0.Clone(); while (sys1 != sys) { Timestep2(sys.moons); Timestep2(sys1.moons); t2++; if (t2 % check_step == 0) { Console.WriteLine($"Advancing delta systems to {t2}"); } } Console.WriteLine($"Cycle starts at {t2 - deltastep} repeating at {t2}"); return(deltastep); }