qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
76,464 |
<p>I'd like to create a module in DNN that, similar to the Announcements control, offers a template that the portal admin can modify for formatting. I have a control that currently uses a Repeater control with templates. Is there a way to override the contents of the repeater ItemTemplate, HeaderTemplate, and FooterTemplate properties? </p>
|
[
{
"answer_id": 5629954,
"author": "swajak",
"author_id": 100258,
"author_profile": "https://Stackoverflow.com/users/100258",
"pm_score": 1,
"selected": false,
"text": "GroupBox box = new GroupBox();\n[...]\nbox.Paint += delegate(object o, PaintEventArgs p)\n{\n p.Graphics.Clear(someColorHere);\n};\n"
},
{
"answer_id": 5827166,
"author": "Mick Bruno",
"author_id": 730366,
"author_profile": "https://Stackoverflow.com/users/730366",
"pm_score": 6,
"selected": true,
"text": "groupBox1.Paint += PaintBorderlessGroupBox;\n\nprivate void PaintBorderlessGroupBox(object sender, PaintEventArgs p)\n{\n GroupBox box = (GroupBox)sender;\n p.Graphics.Clear(SystemColors.Control);\n p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0);\n}\n"
},
{
"answer_id": 13653500,
"author": "Andy",
"author_id": 1867592,
"author_profile": "https://Stackoverflow.com/users/1867592",
"pm_score": 3,
"selected": false,
"text": " private void UserControl1_Paint(object sender, PaintEventArgs e)\n {\n ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, Color.Red, ButtonBorderStyle.Solid);\n\n }\n"
},
{
"answer_id": 20042058,
"author": "user1944617",
"author_id": 1944617,
"author_profile": "https://Stackoverflow.com/users/1944617",
"pm_score": 5,
"selected": false,
"text": " private void groupBox1_Paint(object sender, PaintEventArgs e)\n {\n GroupBox box = sender as GroupBox;\n DrawGroupBox(box, e.Graphics, Color.Red, Color.Blue);\n }\n\n\n private void DrawGroupBox(GroupBox box, Graphics g, Color textColor, Color borderColor)\n {\n if (box != null)\n {\n Brush textBrush = new SolidBrush(textColor);\n Brush borderBrush = new SolidBrush(borderColor);\n Pen borderPen = new Pen(borderBrush);\n SizeF strSize = g.MeasureString(box.Text, box.Font);\n Rectangle rect = new Rectangle(box.ClientRectangle.X,\n box.ClientRectangle.Y + (int)(strSize.Height / 2),\n box.ClientRectangle.Width - 1,\n box.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n // Draw text\n g.DrawString(box.Text, box.Font, textBrush, box.Padding.Left, 0);\n\n // Drawing Border\n //Left\n g.DrawLine(borderPen, rect.Location, new Point(rect.X, rect.Y + rect.Height));\n //Right\n g.DrawLine(borderPen, new Point(rect.X + rect.Width, rect.Y), new Point(rect.X + rect.Width, rect.Y + rect.Height));\n //Bottom\n g.DrawLine(borderPen, new Point(rect.X, rect.Y + rect.Height), new Point(rect.X + rect.Width, rect.Y + rect.Height));\n //Top1\n g.DrawLine(borderPen, new Point(rect.X, rect.Y), new Point(rect.X + box.Padding.Left, rect.Y));\n //Top2\n g.DrawLine(borderPen, new Point(rect.X + box.Padding.Left + (int)(strSize.Width), rect.Y), new Point(rect.X + rect.Width, rect.Y));\n }\n }\n"
},
{
"answer_id": 50451872,
"author": "George",
"author_id": 5077953,
"author_profile": "https://Stackoverflow.com/users/5077953",
"pm_score": 1,
"selected": false,
"text": " private void groupSchitaCentru_Paint(object sender, PaintEventArgs e)\n {\n Pen blackPen = new Pen(Color.Black, 2);\n Point pointTopLeft = new Point(0, 7);\n Point pointBottomLeft = new Point(0, groupSchitaCentru.ClientRectangle.Height);\n Point pointTopRight = new Point(groupSchitaCentru.ClientRectangle.Width, 7);\n Point pointBottomRight = new Point(groupSchitaCentru.ClientRectangle.Width, groupSchitaCentru.ClientRectangle.Height);\n\n e.Graphics.DrawLine(blackPen, pointTopLeft, pointBottomLeft);\n e.Graphics.DrawLine(blackPen, pointTopLeft, pointTopRight);\n e.Graphics.DrawLine(blackPen, pointBottomRight, pointTopRight);\n e.Graphics.DrawLine(blackPen, pointBottomLeft, pointBottomRight);\n }\n"
},
{
"answer_id": 51663475,
"author": "NetXpert",
"author_id": 1542024,
"author_profile": "https://Stackoverflow.com/users/1542024",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\nnamespace BorderedGroupBox\n{\n public class BorderedGroupBox : GroupBox\n {\n private Color _borderColor = Color.Black;\n private int _borderWidth = 2;\n private int _borderRadius = 5;\n private int _textIndent = 10;\n\n public BorderedGroupBox() : base()\n {\n InitializeComponent();\n this.Paint += this.BorderedGroupBox_Paint;\n }\n\n public BorderedGroupBox(int width, float radius, Color color) : base()\n {\n this._borderWidth = Math.Max(1,width);\n this._borderColor = color;\n this._borderRadius = Math.Max(0,radius);\n InitializeComponent();\n this.Paint += this.BorderedGroupBox_Paint;\n }\n\n public Color BorderColor\n {\n get => this._borderColor;\n set\n {\n this._borderColor = value;\n DrawGroupBox();\n }\n }\n\n public int BorderWidth\n {\n get => this._borderWidth;\n set\n {\n if (value > 0)\n {\n this._borderWidth = Math.Min(value, 10);\n DrawGroupBox();\n }\n }\n }\n\n public int BorderRadius\n {\n get => this._borderRadius;\n set\n { // Setting a radius of 0 produces square corners...\n if (value >= 0)\n {\n this._borderRadius = value;\n this.DrawGroupBox();\n }\n }\n }\n\n public int LabelIndent\n {\n get => this._textIndent;\n set\n {\n this._textIndent = value;\n this.DrawGroupBox();\n }\n }\n\n private void BorderedGroupBox_Paint(object sender, PaintEventArgs e) =>\n DrawGroupBox(e.Graphics);\n\n private void DrawGroupBox() =>\n this.DrawGroupBox(this.CreateGraphics());\n\n private void DrawGroupBox(Graphics g)\n {\n Brush textBrush = new SolidBrush(this.ForeColor);\n SizeF strSize = g.MeasureString(this.Text, this.Font);\n\n Brush borderBrush = new SolidBrush(this.BorderColor);\n Pen borderPen = new Pen(borderBrush,(float)this._borderWidth);\n Rectangle rect = new Rectangle(this.ClientRectangle.X,\n this.ClientRectangle.Y + (int)(strSize.Height / 2),\n this.ClientRectangle.Width - 1,\n this.ClientRectangle.Height - (int)(strSize.Height / 2) - 1);\n\n Brush labelBrush = new SolidBrush(this.BackColor);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n // Drawing Border (added \"Fix\" from Jim Fell, Oct 6, '18)\n int rectX = (0 == this._borderWidth % 2) ? rect.X + this._borderWidth / 2 : rect.X + 1 + this._borderWidth / 2;\n int rectHeight = (0 == this._borderWidth % 2) ? rect.Height - this._borderWidth / 2 : rect.Height - 1 - this._borderWidth / 2;\n // NOTE DIFFERENCE: rectX vs rect.X and rectHeight vs rect.Height\n g.DrawRoundedRectangle(borderPen, rectX, rect.Y, rect.Width, rectHeight, (float)this._borderRadius);\n\n // Draw text\n if (this.Text.Length > 0)\n {\n // Do some work to ensure we don't put the label outside\n // of the box, regardless of what value is assigned to the Indent:\n int width = (int)rect.Width, posX;\n posX = (this._textIndent < 0) ? Math.Max(0-width,this._textIndent) : Math.Min(width, this._textIndent);\n posX = (posX < 0) ? rect.Width + posX - (int)strSize.Width : posX;\n g.FillRectangle(labelBrush, posX, 0, strSize.Width, strSize.Height);\n g.DrawString(this.Text, this.Font, textBrush, posX, 0);\n }\n }\n\n #region Component Designer generated code\n /// <summary>Required designer variable.</summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>Clean up any resources being used.</summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n components.Dispose();\n\n base.Dispose(disposing);\n }\n\n /// <summary>Required method for Designer support - Don't modify!</summary>\n private void InitializeComponent() => components = new System.ComponentModel.Container();\n #endregion\n }\n}\n static class GraphicsExtension\n{\n private static GraphicsPath GenerateRoundedRectangle(\n this Graphics graphics,\n RectangleF rectangle,\n float radius)\n {\n float diameter;\n GraphicsPath path = new GraphicsPath();\n if (radius <= 0.0F)\n {\n path.AddRectangle(rectangle);\n path.CloseFigure();\n return path;\n }\n else\n {\n if (radius >= (Math.Min(rectangle.Width, rectangle.Height)) / 2.0)\n return graphics.GenerateCapsule(rectangle);\n diameter = radius * 2.0F;\n SizeF sizeF = new SizeF(diameter, diameter);\n RectangleF arc = new RectangleF(rectangle.Location, sizeF);\n path.AddArc(arc, 180, 90);\n arc.X = rectangle.Right - diameter;\n path.AddArc(arc, 270, 90);\n arc.Y = rectangle.Bottom - diameter;\n path.AddArc(arc, 0, 90);\n arc.X = rectangle.Left;\n path.AddArc(arc, 90, 90);\n path.CloseFigure();\n }\n return path;\n }\n\n private static GraphicsPath GenerateCapsule(\n this Graphics graphics,\n RectangleF baseRect)\n {\n float diameter;\n RectangleF arc;\n GraphicsPath path = new GraphicsPath();\n try\n {\n if (baseRect.Width > baseRect.Height)\n {\n diameter = baseRect.Height;\n SizeF sizeF = new SizeF(diameter, diameter);\n arc = new RectangleF(baseRect.Location, sizeF);\n path.AddArc(arc, 90, 180);\n arc.X = baseRect.Right - diameter;\n path.AddArc(arc, 270, 180);\n }\n else if (baseRect.Width < baseRect.Height)\n {\n diameter = baseRect.Width;\n SizeF sizeF = new SizeF(diameter, diameter);\n arc = new RectangleF(baseRect.Location, sizeF);\n path.AddArc(arc, 180, 180);\n arc.Y = baseRect.Bottom - diameter;\n path.AddArc(arc, 0, 180);\n }\n else path.AddEllipse(baseRect);\n }\n catch { path.AddEllipse(baseRect); }\n finally { path.CloseFigure(); }\n return path;\n }\n\n /// <summary>\n /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius\n /// for the arcs that make the rounded edges.\n /// </summary>\n /// <param name=\"brush\">System.Drawing.Pen that determines the color, width and style of the rectangle.</param>\n /// <param name=\"x\">The x-coordinate of the upper-left corner of the rectangle to draw.</param>\n /// <param name=\"y\">The y-coordinate of the upper-left corner of the rectangle to draw.</param>\n /// <param name=\"width\">Width of the rectangle to draw.</param>\n /// <param name=\"height\">Height of the rectangle to draw.</param>\n /// <param name=\"radius\">The radius of the arc used for the rounded edges.</param>\n public static void DrawRoundedRectangle(\n this Graphics graphics,\n Pen pen,\n float x,\n float y,\n float width,\n float height,\n float radius)\n {\n RectangleF rectangle = new RectangleF(x, y, width, height);\n GraphicsPath path = graphics.GenerateRoundedRectangle(rectangle, radius);\n SmoothingMode old = graphics.SmoothingMode;\n graphics.SmoothingMode = SmoothingMode.AntiAlias;\n graphics.DrawPath(pen, path);\n graphics.SmoothingMode = old;\n }\n\n /// <summary>\n /// Draws a rounded rectangle specified by a pair of coordinates, a width, a height and the radius\n /// for the arcs that make the rounded edges.\n /// </summary>\n /// <param name=\"brush\">System.Drawing.Pen that determines the color, width and style of the rectangle.</param>\n /// <param name=\"x\">The x-coordinate of the upper-left corner of the rectangle to draw.</param>\n /// <param name=\"y\">The y-coordinate of the upper-left corner of the rectangle to draw.</param>\n /// <param name=\"width\">Width of the rectangle to draw.</param>\n /// <param name=\"height\">Height of the rectangle to draw.</param>\n /// <param name=\"radius\">The radius of the arc used for the rounded edges.</param>\n\n public static void DrawRoundedRectangle(\n this Graphics graphics,\n Pen pen,\n int x,\n int y,\n int width,\n int height,\n int radius)\n {\n graphics.DrawRoundedRectangle(\n pen,\n Convert.ToSingle(x),\n Convert.ToSingle(y),\n Convert.ToSingle(width),\n Convert.ToSingle(height),\n Convert.ToSingle(radius));\n }\n}\n"
},
{
"answer_id": 68691524,
"author": "compound eye",
"author_id": 133507,
"author_profile": "https://Stackoverflow.com/users/133507",
"pm_score": 0,
"selected": false,
"text": " Rectangle rect = new Rectangle(this.ClientRectangle.X,\n this.ClientRectangle.Y + (int)(strSize.Height / 2),\n this.ClientRectangle.Width,\n this.ClientRectangle.Height - (int)(strSize.Height / 2));\n\n Brush labelBrush = new SolidBrush(this.BackColor);\n\n // Clear text and border\n g.Clear(this.BackColor);\n\n\n int drawX = rect.X;\n int drawY = rect.Y;\n int drawWidth = rect.Width;\n int drawHeight = rect.Height;\n\n if (this._borderWidth > 0)\n {\n drawX += this._borderWidth / 2;\n drawY += this._borderWidth / 2;\n\n drawWidth -= this._borderWidth;\n drawHeight -= this._borderWidth;\n \n if (this._borderWidth % 2 == 0)\n {\n drawX -= 1;\n drawWidth += 1;\n\n drawY -= 1;\n drawHeight += 1;\n }\n }\n\n g.DrawRoundedRectangle(borderPen, drawX, drawY, drawWidth, drawHeight, (float)this._borderRadius);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13100/"
] |
76,472 |
<p>Is there a way in Ruby to find the version of a file, specifically a .dll file?</p>
|
[
{
"answer_id": 77447,
"author": "AShelly",
"author_id": 10396,
"author_profile": "https://Stackoverflow.com/users/10396",
"pm_score": 4,
"selected": false,
"text": "require \"Win32API\"\nFILENAME = \"c:/ruby/bin/ruby.exe\" #your filename here\ns=\"\"\nvsize=Win32API.new('version.dll', 'GetFileVersionInfoSize', \n ['P', 'P'], 'L').call(FILENAME, s)\np vsize\nif (vsize > 0)\n result = ' '*vsize\n Win32API.new('version.dll', 'GetFileVersionInfo', \n ['P', 'L', 'L', 'P'], 'L').call(FILENAME, 0, vsize, result)\n rstring = result.unpack('v*').map{|s| s.chr if s<256}*''\n r = /FileVersion..(.*?)\\000/.match(rstring)\n puts \"FileVersion = #{r ? r[1] : '??' }\"\nelse\n puts \"No Version Info\"\nend\n"
},
{
"answer_id": 142578,
"author": "Tom Lahti",
"author_id": 22902,
"author_profile": "https://Stackoverflow.com/users/22902",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/ruby\n\ns = File.read(ARGV[0])\nx = s.match(/F\\0i\\0l\\0e\\0V\\0e\\0r\\0s\\0i\\0o\\0n\\0*(.*?)\\0\\0\\0/)\n\nif x.class == MatchData\n ver=x[1].gsub(/\\0/,\"\")\nelse\n ver=\"No version\"\nend\n\nputs ver\n"
},
{
"answer_id": 17068756,
"author": "Pete",
"author_id": 131887,
"author_profile": "https://Stackoverflow.com/users/131887",
"pm_score": 2,
"selected": false,
"text": "DL version_dll = Fiddle.dlopen('version.dll')\n\ns=''\nvsize = Fiddle::Function.new(version_dll['GetFileVersionInfoSize'],\n [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP],\n Fiddle::TYPE_LONG).call(filename, s)\n\nraise 'Unable to determine the version number' unless vsize > 0\n\nresult = ' '*vsize\nFiddle::Function.new(version_dll['GetFileVersionInfo'],\n [Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG,\n Fiddle::TYPE_LONG, Fiddle::TYPE_VOIDP],\n Fiddle::TYPE_VOIDP).call(filename, 0, vsize, result)\n\nrstring = result.unpack('v*').map{|s| s.chr if s<256}*''\nr = /FileVersion..(.*?)\\000/.match(rstring)\n\nputs r[1]\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,482 |
<p>I have a file saved as UCS-2 Little Endian I want to change the encoding so I ran the following code:</p>
<pre><code>cat tmp.log -encoding UTF8 > new.log
</code></pre>
<p>The resulting file is still in UCS-2 Little Endian. Is this because the pipeline is always in that format? Is there an easy way to pipe this to a new file as UTF8?</p>
|
[
{
"answer_id": 76734,
"author": "driis",
"author_id": 13627,
"author_profile": "https://Stackoverflow.com/users/13627",
"pm_score": 5,
"selected": false,
"text": "get-content tmp.log -encoding Unicode | set-content new.log -encoding UTF8\n"
},
{
"answer_id": 76808,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 7,
"selected": true,
"text": "Get-Content tmp.log | Out-File -Encoding UTF8 new.log\n"
},
{
"answer_id": 31521946,
"author": "sba923",
"author_id": 1808955,
"author_profile": "https://Stackoverflow.com/users/1808955",
"pm_score": 1,
"selected": false,
"text": "$xml = New-Object -Typename XML\n$xml.load('foo.xml')\n"
},
{
"answer_id": 67678498,
"author": "Geordie",
"author_id": 796634,
"author_profile": "https://Stackoverflow.com/users/796634",
"pm_score": 0,
"selected": false,
"text": "$myString = [IO.File]::ReadAllText($filePath, [Text.Encoding]::GetEncoding(1252))\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2582/"
] |
76,488 |
<p>Can't find anything relevant about Entity Framework/MySQL on Google so I'm hoping someone knows about it.</p>
|
[
{
"answer_id": 16254132,
"author": "oware",
"author_id": 1322781,
"author_profile": "https://Stackoverflow.com/users/1322781",
"pm_score": 1,
"selected": false,
"text": "create table person(\n Id tinyint unsigned primary key auto_increment,\n Name varchar(30)\n);\n Person p;\np = new Person();\np.Name = 'Oware'\ncontext.Person.Add(p);\ncontext.SaveChanges();\n Referencia a objeto no establecida como instancia de un objeto.:\n en MySql.Data.Entity.ListFragment.WriteSql(StringBuilder sql)\n en MySql.Data.Entity.SelectStatement.WriteSql(StringBuilder sql)\n en MySql.Data.Entity.InsertStatement.WriteSql(StringBuilder sql)\n en MySql.Data.Entity.SqlFragment.ToString()\n en MySql.Data.Entity.InsertGenerator.GenerateSQL(DbCommandTree tree)\n en MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)\n en System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree)\n en System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree)\n en System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)\n en System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues)\n en System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)\n en System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)\n en System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)\n en System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)\n en System.Data.Entity.Internal.InternalContext.SaveChanges()\n en System.Data.Entity.Internal.LazyInternalContext.SaveChanges()\n en System.Data.Entity.DbContext.SaveChanges()\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13594/"
] |
76,522 |
<p>We make infrastructure services (data retrieval and storage) and small smart client applications (fancy reporting mostly) for a commercial bank. Our team is large, 40 odd contractual employees that are C# .NET programmers. We support 50 odd applications and systems that we have developed. </p>
<p>A few members of the team began making <a href="http://en.wikipedia.org/wiki/Windows_Presentation_Foundation" rel="nofollow noreferrer">WPF</a>, <a href="http://en.wikipedia.org/wiki/Windows_Workflow_Foundation" rel="nofollow noreferrer">WF</a> and <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation" rel="nofollow noreferrer">WCF</a> based applications. Given that they are the first, most members do not understand these technologies. What benefits do they convey that would overcome the cost of retraining the team?</p>
|
[
{
"answer_id": 531146,
"author": "helifreak",
"author_id": 52565,
"author_profile": "https://Stackoverflow.com/users/52565",
"pm_score": 2,
"selected": false,
"text": "Paint() Paint() ControlTemplates"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76522",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,549 |
<p>An array of ints in java is stored as a block of 32-bit values in memory. How is an array of Integer objects stored? i.e.</p>
<pre><code>int[] vs. Integer[]
</code></pre>
<p>I'd imagine that each element in the Integer array is a reference to an Integer object, and that the Integer object has object storage overheads, just like any other object.</p>
<p>I'm hoping however that the JVM does some magical cleverness under the hood given that Integers are immutable and stores it just like an array of ints.</p>
<p>Is my hope woefully naive? Is an Integer array much slower than an int array in an application where every last ounce of performance matters?</p>
|
[
{
"answer_id": 76720,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Integer foo = new Integer();\nfoo = null; \n int int bar = Integer.MAX_VALUE;\nbar++;\n foo = Integer.MAX_VALUE;\nfoo++;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
] |
76,564 |
<p>All I want is to be able to change the color of a bullet in a list to a light gray. It defaults to black, and I can't figure out how to change it.</p>
<p>I know I could just use an image; I'd rather not do that if I can help it.</p>
|
[
{
"answer_id": 76603,
"author": "Jonathan Arkell",
"author_id": 11052,
"author_profile": "https://Stackoverflow.com/users/11052",
"pm_score": 3,
"selected": false,
"text": "<ul>\n <li style=\"color: #888;\"><span style=\"color: #000\">test</span></li>\n</ul>\n"
},
{
"answer_id": 76616,
"author": "ahockley",
"author_id": 8209,
"author_profile": "https://Stackoverflow.com/users/8209",
"pm_score": -1,
"selected": false,
"text": "ul.colored {list-style: color: green;}\n"
},
{
"answer_id": 76620,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": -1,
"selected": false,
"text": "<li style='color:#e0e0e0'>something</li>\n"
},
{
"answer_id": 76626,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 8,
"selected": true,
"text": "<ul>\n <li><span>item #1</span></li>\n <li><span>item #2</span></li>\n <li><span>item #3</span></li>\n</ul>\n li {\n color: red; /* bullet color */\n}\nli span {\n color: black; /* text color */\n}\n"
},
{
"answer_id": 76639,
"author": "NerdFury",
"author_id": 6146,
"author_profile": "https://Stackoverflow.com/users/6146",
"pm_score": -1,
"selected": false,
"text": "<ul style=\"color: red;\">\n<li>One</li>\n<li>Two</li>\n<li>Three</li>\n</ul>\n"
},
{
"answer_id": 76707,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li style=\"color:#ddd;\"><span style=\"color:#000;\">List Item</span></li>\n</ul>\n"
},
{
"answer_id": 1083559,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "li { color: red; }\nli b { color: black; font_weight: normal; }\n.c1 { color: red; }\n.c2 { color: blue; }\n.c3 { color: green; }\n <ul>\n<li><b>Text 1</b></li>\n<li><b>Text 2</b></li>\n<li><b>Text 3</b></li>\n</ul>\n <ul>\n <li class=\"c1\"><b>Text 1</b></li>\n <li class=\"c2\"><b>Text 2</b></li>\n <li class=\"c3\"><b>Text 3</b></li>\n </ul>\n"
},
{
"answer_id": 4288573,
"author": "Marc",
"author_id": 496015,
"author_profile": "https://Stackoverflow.com/users/496015",
"pm_score": 6,
"selected": false,
"text": ":before <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n<html>\n<head>\n <style type=\"text/css\">\n li {\n list-style: none;\n }\n\n li:before {\n /* For a round bullet */\n content:'\\2022';\n /* For a square bullet */\n /*content:'\\25A0';*/\n display: block;\n position: relative;\n max-width: 0px;\n max-height: 0px;\n left: -10px;\n top: -0px;\n color: green;\n font-size: 20px;\n }\n </style>\n</head>\n\n<body>\n <ul>\n <li>foo</li>\n <li>bar</li>\n </ul>\n</body>\n</html>\n"
},
{
"answer_id": 10237554,
"author": "ghr",
"author_id": 387558,
"author_profile": "https://Stackoverflow.com/users/387558",
"pm_score": 2,
"selected": false,
"text": "list-style-image ul {\n list-style-image:url('gray-bullet.gif');\n}\n"
},
{
"answer_id": 14176134,
"author": "alaasdk",
"author_id": 501602,
"author_profile": "https://Stackoverflow.com/users/501602",
"pm_score": 0,
"selected": false,
"text": "$(\"li\").each(function(){\nvar content = $(this).html();\nvar myDiv = $(\"<div />\")\nmyDiv.css(\"color\", \"red\"); //color of text.\nmyDiv.html(content);\n$(this).html(myDiv).css(\"color\", \"yellow\"); //color of bullet\n});\n"
},
{
"answer_id": 16040621,
"author": "Ky -",
"author_id": 453435,
"author_profile": "https://Stackoverflow.com/users/453435",
"pm_score": 4,
"selected": false,
"text": "::marker <ul>\n <li>item #1</li>\n <li>item #2</li>\n <li>item #3</li>\n</ul>\n\nli::marker {\n color: red; /* bullet color */\n}\nli {\n color: black /* text color */\n}\n"
},
{
"answer_id": 33908171,
"author": "eggy",
"author_id": 1890236,
"author_profile": "https://Stackoverflow.com/users/1890236",
"pm_score": 0,
"selected": false,
"text": "text-success fa-ul fa-li <link href=\"https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css\" rel=\"stylesheet\" />\n<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\" rel=\"stylesheet\" />\n\n<ul class=\"fa-ul\">\n <li><i class=\"fa-li fa fa-circle\"></i>List icons</li>\n <li><i class=\"fa-li fa fa-check-square text-success\"></i>can be used</li>\n <li><i class=\"fa-li fa fa-spinner fa-spin text-primary\"></i>as bullets</li>\n <li><i class=\"fa-li fa fa-square text-danger\"></i>in lists</li>\n</ul>"
},
{
"answer_id": 44568145,
"author": "Mohammed",
"author_id": 4657565,
"author_profile": "https://Stackoverflow.com/users/4657565",
"pm_score": 0,
"selected": false,
"text": "<article class=\"event-item\">\n <p>Black text here</p>\n</article>\n\n.event-item{\n list-style-type: disc;\n display: list-item;\n color: #ff6f9a;\n margin-left: 25px;\n}\n.event-item p {\n margin: 0;\n color: initial;\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7072/"
] |
76,571 |
<p>In JavaScript, using the Prototype library, the following functional construction is possible:</p>
<pre><code>var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"];
words.pluck('length');
//-> [7, 8, 5, 16, 4]
</code></pre>
<p>Note that this example code is equivalent to</p>
<pre><code>words.map( function(word) { return word.length; } );
</code></pre>
<p>I wondered if something similar is possible in F#:</p>
<pre><code>let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"]
//val words: string list
List.pluck 'Length' words
//int list = [7; 8; 5; 16; 4]
</code></pre>
<p>without having to write:</p>
<pre><code>List.map (fun (s:string) -> s.Length) words
</code></pre>
<p>This would seem quite useful to me because then you don't have to write functions for every property to access them.</p>
|
[
{
"answer_id": 79511,
"author": "Gavin",
"author_id": 2377,
"author_profile": "https://Stackoverflow.com/users/2377",
"pm_score": 1,
"selected": false,
"text": "pluck object.method() object[method] String.Length #r \"FSharp.PowerPack.dll\" \nopen Microsoft.FSharp.Compatibility\nwords |> List.map String.length \n Compatibility"
},
{
"answer_id": 86084,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "type Microsoft.FSharp.Collections.List<'a> with\n member list.pluck property = \n try \n let prop = typeof<'a>.GetProperty property \n [for elm in list -> prop.GetValue(elm, [| |])]\n with e-> \n [box <| \"Error: Property '\" + property + \"'\" + \n \" not found on type '\" + typeof<'a>.Name + \"'\"]\n\nlet a = [\"aqueous\"; \"strength\"; \"hated\"; \"sesquicentennial\"; \"area\"]\n\na.pluck \"Length\" \na.pluck \"Unknown\"\n <pre"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6264/"
] |
76,581 |
<p>There's an MSDN article <a href="http://msdn.microsoft.com/en-us/library/aa919730.aspx" rel="nofollow noreferrer">here</a>, but I'm not getting very far:</p>
<pre><code>p = 139;
g = 5;
CRYPT_DATA_BLOB pblob;
pblob.cbData = sizeof( ULONG );
pblob.pbData = ( LPBYTE ) &p;
CRYPT_DATA_BLOB gblob;
gblob.cbData = sizeof( ULONG );
gblob.pbData = ( LPBYTE ) &g;
HCRYPTKEY hKey;
if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF,
CRYPT_PREGEN, &hKey ) )
{
::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &pblob, 0 );
</code></pre>
<p>Fails here with <code>NTE_BAD_DATA</code>. I'm using <code>MS_DEF_DSS_DH_PROV</code>. What gives?</p>
|
[
{
"answer_id": 78156,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 1,
"selected": false,
"text": "KP_P KP_G KP_Q KP_PUB_PARAMS DATA_BLOB DHPUBKEY_VER3 KP_PUB_PARAMS"
},
{
"answer_id": 78537,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 3,
"selected": true,
"text": "BYTE p[64] = { 139 }; // little-endian, all other bytes set to 0\nBYTE g[64] = { 5 };\n\nCRYPT_DATA_BLOB pblob;\npblob.cbData = sizeof( p);\npblob.pbData = p;\n\nCRYPT_DATA_BLOB gblob;\ngblob.cbData = sizeof( g );\ngblob.pbData = g;\n\nHCRYPTKEY hKey;\nif ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF,\n ( 512 << 16 ) | CRYPT_PREGEN, &hKey ) )\n{\n ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &pblob, 0 );\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,591 |
<p>I'm trying to load test data into a test DB during a maven build for integration testing. persistence.xml is being copied to <code>target/test-classes/META-INF/</code> correctly, but I get this exception when the test is run.</p>
<blockquote>
<p>javax.persistence.PersistenceException:
No Persistence provider for
EntityManager named aimDatabase</p>
</blockquote>
<p>It looks like it's not finding or loading persistence.xml.</p>
|
[
{
"answer_id": 232105,
"author": "stevemac",
"author_id": 20150,
"author_profile": "https://Stackoverflow.com/users/20150",
"pm_score": 2,
"selected": false,
"text": "<provider>oracle.toplink.essentials.PersistenceProvider</provider>"
},
{
"answer_id": 1380292,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": " <dependency>\n <groupId>org.hibernate</groupId>\n <artifactId>hibernate-entitymanager</artifactId>\n <version>3.4.0.GA</version>\n </dependency> \n"
},
{
"answer_id": 2131109,
"author": "jhumble",
"author_id": 217829,
"author_profile": "https://Stackoverflow.com/users/217829",
"pm_score": 4,
"selected": false,
"text": "src/main/java src/main/resources META-INF/persistence.xml target/classes META-INF/persistence.xml src/main/java"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
76,601 |
<p>I've got a client that sees the "Page can not be displayed" (nothing else) whenever they perform a certain action in their website. I don't get the error, ever. I've tried IE, FF, Chrome, and I do not see the error. The client sees the error on IE.</p>
<p>The error occurs when they press a form submit button that has only hidden fields.</p>
<p>I'm thinking this could be some kind of anti-malware / virus issue. has anyone ever dealt with this issue?</p>
|
[
{
"answer_id": 76671,
"author": "Loren Segal",
"author_id": 6436,
"author_profile": "https://Stackoverflow.com/users/6436",
"pm_score": 0,
"selected": false,
"text": "C:\\windows\\hosts C:\\windows\\system32\\hosts"
},
{
"answer_id": 49221946,
"author": "Webb Lu",
"author_id": 4838119,
"author_profile": "https://Stackoverflow.com/users/4838119",
"pm_score": 0,
"selected": false,
"text": "TLS 1.0"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13666/"
] |
76,624 |
<p>Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.</p>
<p>For some reason I thought the following might work:</p>
<pre><code>enum MY_ENUM : unsigned __int64
{
LARGE_VALUE = 0x1000000000000000,
};
</code></pre>
|
[
{
"answer_id": 76661,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 0,
"selected": false,
"text": "enum MY_ENUM\n{\n CHAR_VALUE = 'c',\n};\n enum MY_ENUM\n{\n LARGE_VALUE = 0x1000000000000000,\n};\n"
},
{
"answer_id": 76683,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 5,
"selected": true,
"text": "const __int64 LARGE_VALUE = 0x1000000000000000L;\n enum class MY_ENUM : unsigned __int64 {\n LARGE_VALUE = 0x1000000000000000ULL\n};\n LARGE_VALUE MY_ENUM::LARGE_VALUE"
},
{
"answer_id": 76705,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 1,
"selected": false,
"text": "const __int64 LARVE_VALUE = ...\n"
},
{
"answer_id": 76756,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 2,
"selected": false,
"text": "namespace MyNamespace {\nconst uint64 LARGE_VALUE = 0x1000000000000000;\n};\n MyNamespace::LARGE_VALUE \n using MyNamespace;\n....\nval = LARGE_VALUE;\n"
},
{
"answer_id": 76980,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 4,
"selected": false,
"text": "enum class Enum2 : __int64 {Val1, Val2, val3};\n"
},
{
"answer_id": 81531,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "__int64 __int64"
},
{
"answer_id": 2630851,
"author": "mloskot",
"author_id": 151641,
"author_profile": "https://Stackoverflow.com/users/151641",
"pm_score": 3,
"selected": false,
"text": "enum MyEnum\n{\n Undefined = 0xffffffffffffffffULL\n};\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
76,637 |
<p>I have an linux app that uses cups for printing, but I've noticed that if I print and then quit my app right away my printout never appears. So I assume that my app has to wait for it to actually come out of the printer before quitting, so does anyone know how to tell when it's finished printing??</p>
<p>I'm using libcups to print a postscript file that my app generates. So I use the command to print the file and it then returns back to my app. So my app thinks that the document is off to the printer queue when I guess it has not made it there yet. So rather than have all my users have to look on the screen for the printer icon in the system tray I would rather have a solution in code, so if they try and quit before it has really been sent off I can alert them to the fact. Also the file I generate is a temporary file so it would be nice to know when it is finished with so I can delete it.</p>
|
[
{
"answer_id": 190892,
"author": "hendry",
"author_id": 4534,
"author_profile": "https://Stackoverflow.com/users/4534",
"pm_score": 1,
"selected": false,
"text": "lpr lpq"
},
{
"answer_id": 3022250,
"author": "Kurt Pfeifle",
"author_id": 359307,
"author_profile": "https://Stackoverflow.com/users/359307",
"pm_score": 1,
"selected": false,
"text": "/var/spool/cups/ lp lpr $? cupsSendRequest cupsGetResponse"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76637",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
76,650 |
<p>This has me puzzled. This code worked on another server, but it's failing on Perl v5.8.8 with <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> loaded from CPAN today.</p>
<pre><code>Warning:
Use of uninitialized value in numeric lt (<) at /home/downside/lib/Date/Manip.pm line 3327.
at dailyupdate.pl line 13
main::__ANON__('Use of uninitialized value in numeric lt (<) at
/home/downsid...') called at
/home/downside/lib/Date/Manip.pm line 3327
Date::Manip::Date_SecsSince1970GMT(09, 16, 2008, 00, 21, 22) called at
/home/downside/lib/Date/Manip.pm line 1905
Date::Manip::UnixDate('today', '%Y-%m-%d') called at
TICKER/SYMBOLS/updatesymbols.pm line 122
TICKER::SYMBOLS::updatesymbols::getdate() called at
TICKER/SYMBOLS/updatesymbols.pm line 439
TICKER::SYMBOLS::updatesymbols::updatesymbol('DBI::db=HASH(0x87fcc34)',
'TICKER::SYMBOLS::symbol=HASH(0x8a43540)') called at
TICKER/SYMBOLS/updatesymbols.pm line 565
TICKER::SYMBOLS::updatesymbols::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at
dailyupdate.pl line 149
EDGAR::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at
dailyupdate.pl line 180
EDGAR::dailyupdate() called at dailyupdate.pl line 193
</code></pre>
<p>The code that's failing is simply:</p>
<pre><code>sub getdate()
{ my $err; ## today
&Date::Manip::Date_Init('TZ=EST5EDT');
my $today = Date::Manip::UnixDate('today','%Y-%m-%d'); ## today's date
####print "Today is ",$today,"\n"; ## ***TEMP***
return($today);
}
</code></pre>
<p>That's right; <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> is failing for <code>"today"</code>.</p>
<p>The line in <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> that is failing is:</p>
<pre><code> my($tz)=$Cnf{"ConvTZ"};
$tz=$Cnf{"TZ"} if (! $tz);
$tz=$Zone{"n2o"}{lc($tz)} if ($tz !~ /^[+-]\d{4}$/);
my($tzs)=1;
$tzs=-1 if ($tz<0); ### ERROR OCCURS HERE
</code></pre>
<p>So <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> is assuming that <code>$Cnf</code> has been initialized with elements <code>"ConvTZ"</code> or <code>"TZ"</code>. Those are initialized in <code>Date_Init</code>, so that should have been taken care of.</p>
<p>It's only failing in my large program. If I just extract "<code>getdate()</code>" above
and run it standalone, there's no error. So there's something about the
global environment that affects this.</p>
<p>This seems to be a known, but not understood problem. If you search Google for
"Use of uninitialized value date manip" there are about 2400 hits.
This error has been reported with <a href="http://www.lemis.com/grog/videorecorder/mythsetup-sep-2006.html" rel="nofollow noreferrer">MythTV</a> and <a href="http://www.cpan.org/modules/by-module/Mail/grepmail-4.51.readme" rel="nofollow noreferrer">grepmail</a>.</p>
|
[
{
"answer_id": 167314,
"author": "schwerwolf",
"author_id": 7045,
"author_profile": "https://Stackoverflow.com/users/7045",
"pm_score": 2,
"selected": false,
"text": "Date::Manip::Date_Init(\"ConvTZ=IGNORE\");\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,651 |
<p>Where may one find references on implementing an algorithm for calculating a "dirty rectangle" for minimizing frame buffer updates? A display model that permits arbitrary edits and computes the minimal set of "bit blit" operations required to update the display.</p>
|
[
{
"answer_id": 78222,
"author": "Martin W",
"author_id": 14199,
"author_profile": "https://Stackoverflow.com/users/14199",
"pm_score": 2,
"selected": false,
"text": "#!/usr/bin/env python\nimport pygame\n\nclass DirtyRectSprite(pygame.sprite.Sprite):\n \"\"\"Sprite with image and rect attributes.\"\"\"\n def __init__(self, some_image, *groups):\n pygame.sprite.Sprite.__init__(self, *groups)\n self.image = pygame.image.load(some_image).convert()\n self.rect = self.image.get_rect()\n def update(self):\n pass #do something here\n\ndef main():\n screen = pygame.display.set_mode((640, 480))\n background = pygame.image.load(open(\"some_bg_image.png\")).convert()\n render_group = pygame.sprite.RenderUpdates()\n dirty_rect_sprite = DirtyRectSprite(open(\"some_image.png\"))\n render_group.add(dirty_rect_sprite)\n\n while True:\n dirty_rect_sprite.update()\n render_group.clear(screen, background)\n pygame.display.update(render_group.draw(screen))\n"
},
{
"answer_id": 309213,
"author": "Bob Cross",
"author_id": 5812,
"author_profile": "https://Stackoverflow.com/users/5812",
"pm_score": 2,
"selected": false,
"text": "Area Shape getBound2D()"
},
{
"answer_id": 6520903,
"author": "Charles Goodwin",
"author_id": 546060,
"author_profile": "https://Stackoverflow.com/users/546060",
"pm_score": 2,
"selected": false,
"text": "public class DirtyList {\n\n /** The dirty regions (each one is an int[4]). */\n private int[] dirties = new int[10 * 4]; // gets grown dynamically\n\n /** The number of dirty regions */\n private int numdirties = 0;\n\n ...\n\n /** \n * Pseudonym for running a new dirty() request against the entire dirties list\n * (x,y) represents the topleft coordinate and (w,h) the bottomright coordinate \n */\n public final void dirty(int x, int y, int w, int h) { dirty(x, y, w, h, 0); }\n\n /** \n * Add a new rectangle to the dirty list; returns false if the\n * region fell completely within an existing rectangle or set of\n * rectangles (i.e. did not expand the dirty area)\n */\n private void dirty(int x, int y, int w, int h, int ind) {\n int _n;\n if (w<x || h<y) {\n return;\n }\n for (int i=ind; i<numdirties; i++) {\n _n = 4*i;\n // invalid dirties are marked with x=-1\n if (dirties[_n]<0) {\n continue;\n }\n\n int _x = dirties[_n];\n int _y = dirties[_n+1];\n int _w = dirties[_n+2];\n int _h = dirties[_n+3];\n\n if (x >= _w || y >= _h || w <= _x || h <= _y) {\n // new region is outside of existing region\n continue;\n }\n\n if (x < _x) {\n // new region starts to the left of existing region\n\n if (y < _y) {\n // new region overlaps at least the top-left corner of existing region\n\n if (w > _w) {\n // new region overlaps entire width of existing region\n\n if (h > _h) {\n // new region contains existing region\n dirties[_n] = -1;\n continue;\n }// else {\n // new region contains top of existing region\n dirties[_n+1] = h;\n continue;\n\n } else {\n // new region overlaps to the left of existing region\n\n if (h > _h) {\n // new region contains left of existing region\n dirties[_n] = w;\n continue;\n }// else {\n // new region overlaps top-left corner of existing region\n dirty(x, y, w, _y, i+1);\n dirty(x, _y, _x, h, i+1);\n return;\n\n }\n } else {\n // new region starts within the vertical range of existing region\n\n if (w > _w) {\n // new region horizontally overlaps existing region\n\n if (h > _h) {\n // new region contains bottom of existing region\n dirties[_n+3] = y;\n continue;\n }// else {\n // new region overlaps to the left and right of existing region\n dirty(x, y, _x, h, i+1);\n dirty(_w, y, w, h, i+1);\n return;\n\n } else {\n // new region ends within horizontal range of existing region\n\n if (h > _h) {\n // new region overlaps bottom-left corner of existing region\n dirty(x, y, _x, h, i+1);\n dirty(_x, _h, w, h, i+1);\n return;\n }// else {\n // existing region contains right part of new region\n w = _x;\n continue;\n }\n }\n } else {\n // new region starts within the horizontal range of existing region\n\n if (y < _y) {\n // new region starts above existing region\n\n if (w > _w) {\n // new region overlaps at least top-right of existing region\n\n if (h > _h) {\n // new region contains the right of existing region\n dirties[_n+2] = x;\n continue;\n }// else {\n // new region overlaps top-right of existing region\n dirty(x, y, w, _y, i+1);\n dirty(_w, _y, w, h, i+1);\n return;\n\n } else {\n // new region is horizontally contained within existing region\n\n if (h > _h) {\n // new region overlaps to the above and below of existing region\n dirty(x, y, w, _y, i+1);\n dirty(x, _h, w, h, i+1);\n return;\n }// else {\n // existing region contains bottom part of new region\n h = _y;\n continue;\n }\n } else {\n // new region starts within existing region\n\n if (w > _w) {\n // new region overlaps at least to the right of existing region\n\n if (h > _h) {\n // new region overlaps bottom-right corner of existing region\n dirty(x, _h, w, h, i+1);\n dirty(_w, y, w, _h, i+1);\n return;\n }// else {\n // existing region contains left part of new region\n x = _w;\n continue;\n } else {\n // new region is horizontally contained within existing region\n\n if (h > _h) {\n // existing region contains top part of new region\n y = _h;\n continue;\n }// else {\n // new region is contained within existing region\n return;\n }\n }\n }\n }\n\n // region is valid; store it for rendering\n _n = numdirties*4;\n size(_n);\n dirties[_n] = x;\n dirties[_n+1] = y;\n dirties[_n+2] = w;\n dirties[_n+3] = h;\n numdirties++;\n }\n\n ...\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,680 |
<p>I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; <code>messages (id, body)</code> and <code>messages_read (user_id, message_id)</code>.</p>
<p>Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 76702,
"author": "cynicalman",
"author_id": 410,
"author_profile": "https://Stackoverflow.com/users/410",
"pm_score": 3,
"selected": false,
"text": "SELECT id FROM messages m WHERE m.id NOT IN(\n SELECT message_id FROM messages_read WHERE user_id = ?)\n"
},
{
"answer_id": 76733,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 0,
"selected": false,
"text": "SELECT id, body FROM messages LEFT JOIN\n (SELECT message_id FROM messages_read WHERE user_id = ?)\n ON id=message_id WHERE message_id IS NULL \n"
},
{
"answer_id": 78715,
"author": "Bennor McCarthy",
"author_id": 14451,
"author_profile": "https://Stackoverflow.com/users/14451",
"pm_score": 3,
"selected": true,
"text": "SELECT id, message\nFROM messages\nLEFT JOIN messages_read\n ON messages_read.message_id = messages.id\n AND messages_read.[user_id] = @user_id\nWHERE\n messages_read.message_id IS NULL\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13636/"
] |
76,700 |
<p>I'm looking for a little shell script that will take anything piped into it, and dump it to a file.. for email debugging purposes. Any ideas?</p>
|
[
{
"answer_id": 76721,
"author": "Stephen Deken",
"author_id": 7154,
"author_profile": "https://Stackoverflow.com/users/7154",
"pm_score": 6,
"selected": true,
"text": "man tee\n"
},
{
"answer_id": 76731,
"author": "Commodore Jaeger",
"author_id": 4659,
"author_profile": "https://Stackoverflow.com/users/4659",
"pm_score": 4,
"selected": false,
"text": "cat > FILENAME\n"
},
{
"answer_id": 76736,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 3,
"selected": false,
"text": "echo \"hello, world!\" > the-file.txt\n"
},
{
"answer_id": 76741,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 0,
"selected": false,
"text": ">> ~file echo \"Foobar\" >> /home/mo/dumpfile\n"
},
{
"answer_id": 76742,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 1,
"selected": false,
"text": "while /bin/true; do\n read LINE\n echo $LINE > $OUTPUT\ndone\n"
},
{
"answer_id": 76748,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "cat - > filename\n cat > filename\n"
},
{
"answer_id": 76754,
"author": "sirprize",
"author_id": 12902,
"author_profile": "https://Stackoverflow.com/users/12902",
"pm_score": 1,
"selected": false,
"text": "#!/bin/sh\nexec cat >/path/to/file\n"
},
{
"answer_id": 78515,
"author": "Scott",
"author_id": 7399,
"author_profile": "https://Stackoverflow.com/users/7399",
"pm_score": 1,
"selected": false,
"text": "<<command>> | tee <<file>> <<command>> <<file>>"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12624/"
] |
76,724 |
<p>I need to return a list of record id's from a table that may/may not have multiple entries with that record id on the same date. The same date criteria is key - if a record has three entries on 09/10/2008, then I need all three returned. If the record only has one entry on 09/12/2008, then I don't need it.</p>
|
[
{
"answer_id": 76783,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 3,
"selected": false,
"text": "SELECT id, datefield, count(*) FROM tablename GROUP BY datefield\n HAVING count(*) > 1\n"
},
{
"answer_id": 76785,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "GROUP BY HAVING select id, count(*) from records group by date having count(*) > 1\n"
},
{
"answer_id": 76798,
"author": "Manu",
"author_id": 2133,
"author_profile": "https://Stackoverflow.com/users/2133",
"pm_score": 1,
"selected": false,
"text": "select id from tbl where date in\n(select date from tbl group by date having count(*)>1)\n"
},
{
"answer_id": 76799,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 1,
"selected": false,
"text": "select * from Table\nwhere id in (\n select alias1.id from Table alias1, Table alias2\n where alias1.id != alias2.id\n and datediff(day, alias1.date, alias2.date) = 0\n)\n"
},
{
"answer_id": 76815,
"author": "Travis",
"author_id": 7316,
"author_profile": "https://Stackoverflow.com/users/7316",
"pm_score": 1,
"selected": false,
"text": "select\n recordID\nfrom\n tablewithrecords as a\n left join (\n select\n count(recordID) as recordcount\n from\n tblwithrecords\n where\n recorddate='9/10/08'\n ) as b on a.recordID=b.recordID\nwhere\n b.recordcount>1\n"
},
{
"answer_id": 76840,
"author": "Sparr",
"author_id": 13675,
"author_profile": "https://Stackoverflow.com/users/13675",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM the_table WHERE ROW(record_id,date) IN \n ( SELECT record_id, date FROM the_table \n GROUP BY record_id, date WHERE COUNT(*) > 1 )\n"
},
{
"answer_id": 76849,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 2,
"selected": false,
"text": "select * from table\ninner join (\n select id, date\n from table \n group by id, date \n having count(*) > 1) grouped \n on table.id = grouped.id and table.date = grouped.date\n"
},
{
"answer_id": 76875,
"author": "jkramer",
"author_id": 12523,
"author_profile": "https://Stackoverflow.com/users/12523",
"pm_score": 1,
"selected": false,
"text": "SELECT id, COUNT(*) AS same_date FROM foo GROUP BY id, date HAVING same_date = 3;\n"
},
{
"answer_id": 76879,
"author": "Chris Wuestefeld",
"author_id": 10082,
"author_profile": "https://Stackoverflow.com/users/10082",
"pm_score": 1,
"selected": false,
"text": "SELECT CAST(FLOOR(CAST(CURRENT_TIMESTAMP AS float)) AS DATETIME)\n"
},
{
"answer_id": 76901,
"author": "Dave Lievense",
"author_id": 13679,
"author_profile": "https://Stackoverflow.com/users/13679",
"pm_score": 1,
"selected": false,
"text": "select record_id, \n convert(varchar, date_created, 101) as log date, \n count(distinct date_created) as num_of_entries\nfrom record_log_table\ngroup by convert(varchar, date_created, 101), record_id\nhaving count(distinct date_created) > 1\n"
},
{
"answer_id": 77304,
"author": "Bob Probst",
"author_id": 12424,
"author_profile": "https://Stackoverflow.com/users/12424",
"pm_score": 2,
"selected": false,
"text": "declare @duplicates table (\nid int,\ndatestamp datetime,\nipsum varchar(200))\n\ninsert into @duplicates (id,datestamp,ipsum) values (1,'9/12/2008','ipsum primis in faucibus')\ninsert into @duplicates (id,datestamp,ipsum) values (1,'9/12/2008','Vivamus consectetuer. ')\ninsert into @duplicates (id,datestamp,ipsum) values (2,'9/12/2008','condimentum posuere, quam.')\ninsert into @duplicates (id,datestamp,ipsum) values (2,'9/13/2008','Donec eu sapien vel dui')\ninsert into @duplicates (id,datestamp,ipsum) values (3,'9/12/2008','In velit nulla, faucibus sed')\n\nselect a.* from @duplicates a\ninner join (select id,datestamp, count(1) as number\n from @duplicates\n group by id,datestamp\n having count(1) > 1) b\n on (a.id = b.id and a.datestamp = b.datestamp)\n"
},
{
"answer_id": 98368,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "SELECT RecordID\nFROM aTable\nWHERE SameDate IN\n (SELECT SameDate\n FROM aTable\n GROUP BY SameDate\n HAVING COUNT(SameDate) > 1)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,760 |
<p>fellow anthropoids and lily pads and paddlewheels!</p>
<p>I'm developing a Windows desktop app in C#/.NET/WPF, using VS 2008. The app is required to install and run on Vista and XP machines. I'm working on a Setup/Windows Installer Project to install the app.</p>
<p>My app requires read/modify/write access to a SQLCE database file (.sdf) and some other database-type files related to a third-party control I'm using. These files should be shared among all users/log-ins on the PC, none of which can be required to be an Administrator. This means, of course, that the files can't go in the program's own installation directory (as such things often did before the arrival of Vista, yes, yes!).</p>
<p>I had expected the solution to be simple. <strong>Vista and XP both have shared-application-data folders intended for this purpose.</strong> ("\ProgramData" in Vista, "\Documents and Settings\All Users\Application Data" in XP.) The .NET Environment.GetFolderPath(SpecialFolder.CommonApplicationData) call exists to find the paths to these folders on a given PC, yes, yes!</p>
<p><strong>But I can't figure out how to specify the shared-application-data folder as a target in the Setup project.</strong></p>
<p>The Setup project offers a "Common Files" folder, but that's intended for shared program components (not data files), is usually located under "\Program Files," and has the same security restrictions anything else in "\Program files" does, yes, yes!</p>
<p>The Setup project offers a "User's Application Data" folder, but that's a per-user folder, which is exactly what I'm trying to avoid, yes, yes!</p>
<p>Is it possible to add files to the shared-app-data folder in a robust, cross-Windows-version way from a VS 2008 setup project? Can anyone tell me how?</p>
|
[
{
"answer_id": 374293,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "[CommonAppDataFolder]\\[Manufacturer]\\[ProductName]"
},
{
"answer_id": 741763,
"author": "cdonner",
"author_id": 58880,
"author_profile": "https://Stackoverflow.com/users/58880",
"pm_score": 1,
"selected": false,
"text": "Form_Load(object sender, EventArgs e)\n{\n // Set the db directory to the common app data folder\n AppDomain.CurrentDomain.SetData(\"DataDirectory\", \n System.Environment.GetFolderPath\n (System.Environment.SpecialFolder.CommonApplicationData));\n}\n Data Source=|DataDirectory|\\YourDatabase.sdf\n"
},
{
"answer_id": 4392394,
"author": "ejwipp",
"author_id": 171655,
"author_profile": "https://Stackoverflow.com/users/171655",
"pm_score": 3,
"selected": false,
"text": "\nstatic void Main(string[] args)\n{\n if (args != null && args.Length > 0 && args[0] == \"Install\")\n {\n ApplicationData.SetPermissions();\n }\n else\n {\n // Execute app \"normally\"\n }\n}\n \npublic static void SetPermissions()\n{\n String path = GetPath();\n try\n {\n // Create security idenifier for all users (WorldSid)\n SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);\n DirectoryInfo di = new DirectoryInfo(path);\n DirectorySecurity ds = di.GetAccessControl();\n // add a new file access rule w/ write/modify for all users to the directory security object\n ds.AddAccessRule(new FileSystemAccessRule(sid, \n FileSystemRights.Write | FileSystemRights.Modify,\n InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, // all sub-dirs to inherit\n PropagationFlags.None,\n AccessControlType.Allow)); // Turn write and modify on\n // Apply the directory security to the directory\n di.SetAccessControl(ds);\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message);\n }\n}\n"
},
{
"answer_id": 10657695,
"author": "Ahmad",
"author_id": 1404032,
"author_profile": "https://Stackoverflow.com/users/1404032",
"pm_score": 1,
"selected": false,
"text": "string userAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);\nstring commonAppData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13726/"
] |
76,781 |
<p>I need to create a custom membership user and provider for an ASP.NET mvc app and I'm looking to use TDD. I have created a User class which inherits from the MembershipUser class, but when I try to test it I get an error that I can't figure out. How do I give it a valid provider name? Do I just need to add it to web.config? But I'm not even testing the web app at this point.</p>
<p>[failure] UserTests.SetUp.UserShouldHaveMembershipUserProperties
TestCase 'UserTests.SetUp.UserShouldHaveMembershipUserProperties'
failed: The membership provider name specified is invalid.
Parameter name: providerName
System.ArgumentException
Message: The membership provider name specified is invalid.
Parameter name: providerName
Source: System.Web</p>
|
[
{
"answer_id": 243844,
"author": "ddc0660",
"author_id": 16027,
"author_profile": "https://Stackoverflow.com/users/16027",
"pm_score": 4,
"selected": true,
"text": " <connectionStrings>\n <remove name=\"LocalSqlServer\"/>\n <add name=\"LocalSqlServer\" connectionString=\"<connection string>\" providerName=\"System.Data.SqlClient\"/>\n </connectionStrings>\n <system.web>\n <membership defaultProvider=\"provider\">\n <providers>\n <add name=\"provider\" applicationName=\"MyApp\" type=\"System.Web.Security.SqlMembershipProvider\" connectionStringName=\"LocalSqlServer\" minRequiredPasswordLength=\"6\" minRequiredNonalphanumericCharacters=\"0\" requiresQuestionAndAnswer=\"false\" maxInvalidPasswordAttempts=\"3\" passwordAttemptWindow=\"15\"/>\n </providers>\n </membership>\n </system.web>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9938/"
] |
76,793 |
<p>I'm working on a set of classes that will be used to serialize to XML. The XML is not controlled by me and is organized rather well. Unfortunately, there are several sets of nested nodes, the purpose of some of them is just to hold a collection of their children. Based on my current knowledge of XML Serialization, those nodes require another class.</p>
<p>Is there a way to make a class serialize to a set of XML nodes instead of just one. Because I feel like I'm being as clear as mud, say we have the xml:</p>
<pre><code><root>
<users>
<user id="">
<firstname />
<lastname />
...
</user>
<user id="">
<firstname />
<lastname />
...
</user>
</users>
<groups>
<group id="" groupname="">
<userid />
<userid />
</group>
<group id="" groupname="">
<userid />
<userid />
</group>
</groups>
</root>
</code></pre>
<p>Ideally, 3 classes would be best. A class <code>root</code> with collections of <code>user</code> and <code>group</code> objects. However, best I can figure is that I need a class for <code>root</code>, <code>users</code>, <code>user</code>, <code>groups</code> and <code>group</code>, where <code>users</code> and <code>groups</code> contain only collections of <code>user</code> and <code>group</code> respectively, and <code>root</code> contains a <code>users</code>, and <code>groups</code> object.</p>
<p>Anyone out there who knows better than me? (don't lie, I know there are).</p>
|
[
{
"answer_id": 76826,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 4,
"selected": true,
"text": "[XmlArray(\"users\"),\nXmlArrayItem(\"user\")]\npublic List<User> Users\n{\n get { return _users; }\n}\n"
},
{
"answer_id": 77259,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": " [XmlElement(\"Name\")]\n public string Name { get { return name; } set{ name = value; } }\n\n public static void Main(String[] args)\n {\n Employee e = new Employee();\n XmlObjectSerializer.Save(\"c:\\steve.xml\", e);\n }\n <Employee>\n <Name>Steve</Name>\n</Employee>\n using System;\nusing System.IO;\nusing System.Xml.Serialization;\n\nnamespace Utilities\n{\n /// <summary>\n /// Opens and Saves objects to Xml\n /// </summary>\n /// <projectIndependent>True</projectIndependent>\n public static class XmlObjectSerializer\n {\n /// <summary>\n /// Serializes and saves data contained in obj to an XML file located at filePath <para></para> \n /// </summary>\n /// <param name=\"filePath\">The file path to save to</param>\n /// <param name=\"obj\">The object to save</param>\n /// <exception cref=\"System.IO.IOException\">Thrown if an error occurs while saving the object. See inner exception for details</exception>\n public static void Save(String filePath, Object obj)\n {\n // allows access to the file\n StreamWriter oWriter = null;\n\n try\n {\n // Open a stream to the file path\n oWriter = new StreamWriter(filePath);\n\n // Create a serializer for the object's type\n XmlSerializer oSerializer = new XmlSerializer(obj.GetType());\n\n // Serialize the object and write to the file\n oSerializer.Serialize(oWriter.BaseStream, obj);\n }\n catch (Exception ex)\n {\n // throw any errors as IO exceptions\n throw new IOException(\"An error occurred while saving the object\", ex);\n }\n finally\n {\n // if a stream is open\n if (oWriter != null)\n {\n // close it\n oWriter.Close();\n }\n }\n }\n\n /// <summary>\n /// Deserializes saved object data of type T in an XML file\n /// located at filePath \n /// </summary>\n /// <typeparam name=\"T\">Type of object to deserialize</typeparam>\n /// <param name=\"filePath\">The path to open the object from</param>\n /// <returns>An object representing the file or the default value for type T</returns>\n /// <exception cref=\"System.IO.IOException\">Thrown if the file could not be opened. See inner exception for details</exception>\n public static T Open<T>(String filePath)\n {\n // gets access to the file\n StreamReader oReader = null;\n\n // the deserialized data\n Object data;\n\n try\n {\n // Open a stream to the file\n oReader = new StreamReader(filePath);\n\n // Create a deserializer for the object's type\n XmlSerializer oDeserializer = new XmlSerializer(typeof(T));\n\n // Deserialize the data and store it\n data = oDeserializer.Deserialize(oReader.BaseStream);\n\n //\n // Return the deserialized object\n // don't cast it if it's null\n // will be null if open failed\n //\n if (data != null)\n {\n return (T)data;\n }\n else\n {\n return default(T);\n }\n }\n catch (Exception ex)\n {\n // throw error\n throw new IOException(\"An error occurred while opening the file\", ex);\n }\n finally\n {\n // Close the stream\n oReader.Close();\n }\n }\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
76,796 |
<p>What are some general tips to make sure I don't leak memory in C++ programs? How do I figure out who should free memory that has been dynamically allocated?</p>
|
[
{
"answer_id": 76820,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 5,
"selected": false,
"text": "int main()\n{ \n Object* obj = new Object();\n //...\n delete obj;\n}\n int main()\n{\n boost::shared_ptr<Object> obj(new Object());\n //...\n // destructor destroys when reference count is zero\n}\n void foo()\n{\n boost::shared_ptr<Object> obj(new Object()); \n\n // Simplified here\n PostThreadMessage(...., (LPARAM)ob.get());\n // Destructor destroys! pointer sent to PostThreadMessage is invalid! Zohnoes!\n}\n"
},
{
"answer_id": 76876,
"author": "Seth Morris",
"author_id": 13434,
"author_profile": "https://Stackoverflow.com/users/13434",
"pm_score": 2,
"selected": false,
"text": "allocate\nif allocation succeeded:\n{ //scope)\n deallocate()\n}\n"
},
{
"answer_id": 76906,
"author": "Seth Morris",
"author_id": 13434,
"author_profile": "https://Stackoverflow.com/users/13434",
"pm_score": -1,
"selected": false,
"text": "new a()\nif (Bad()) {delete a; return;}\nnew b()\nif (Bad()) {delete a; delete b; return;}\n... // etc.\n"
},
{
"answer_id": 76961,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 0,
"selected": false,
"text": "#define DEBUG_DELETE PrepareDelete(__LINE__,__FILE__); delete\n#define delete DEBUG_DELETE\n"
},
{
"answer_id": 77035,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 4,
"selected": false,
"text": "create a thing\nuse that thing\ndestroy that thing\n"
},
{
"answer_id": 77893,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 7,
"selected": false,
"text": "void doSandwich()\n{\n T * p = new T() ;\n // do something with p\n delete p ; // leak if the p processing throws or return\n}\n\nvoid doRAIIDynamic()\n{\n std::auto_ptr<T> p(new T()) ; // you can use other smart pointers, too\n // do something with p\n // WON'T EVER LEAK, even in case of exceptions, returns, breaks, etc.\n}\n\nvoid doRAIIStatic()\n{\n T p ;\n // do something with p\n // WON'T EVER LEAK, even in case of exceptions, returns, breaks, etc.\n}\n new new try finally terminate exit"
},
{
"answer_id": 78019,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "Object* x = new Object;\n shared_ptr<Object> x(new Object);\n Object x;\n"
},
{
"answer_id": 81039,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "struct myparams {\nint x;\nstd::vector<double> z;\n}\n\nstd::auto_ptr<myparams> param(new myparams(x, ...));\n// Release the ownership in case thread creation is successfull\nif (0 == pthread_create(&th, NULL, th_func, param.get()) param.release();\n...\n extern \"C\" void* th_func(void* p) {\n try {\n std::auto_ptr<myparams> param((myparams*)p);\n ...\n } catch(...) {\n }\n return 0;\n}\n param.release();\n"
},
{
"answer_id": 81082,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 1,
"selected": false,
"text": "#ifdef _DEBUG\n#define new DEBUG_NEW\n#endif\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,809 |
<p>Is anyone out there* using <a href="http://web2py.com/" rel="noreferrer">web2py</a>?</p>
<p>Specifically:</p>
<ul>
<li>In production?</li>
<li>With what database?</li>
<li><p>With Google Application Engine?</p>
<ul>
<li>by "out there" I mean at stackoverflow.</li>
</ul></li>
</ul>
|
[
{
"answer_id": 178937,
"author": "Andre Bossard",
"author_id": 21027,
"author_profile": "https://Stackoverflow.com/users/21027",
"pm_score": 4,
"selected": false,
"text": "dba.users.name.requires=IS_NOT_EMPTY()\ndba.users.email.requires=[IS_EMAIL(), IS_NOT_IN_DB(dba,'users.email')]\ndba.dogs.owner_id.requires=IS_IN_DB(dba,'users.id','users.name')\ndba.dogs.name.requires=IS_NOT_EMPTY()\ndba.dogs.type.requires=IS_IN_SET(['small','medium','large'])\ndba.purchases.buyer_id.requires=IS_IN_DB(dba,'users.id','users.name')\ndba.purchases.product_id.requires=IS_IN_DB(dba,'products.id','products.name')\ndba.purchases.quantity.requires=IS_INT_IN_RANGE(0,10)\n"
},
{
"answer_id": 196705,
"author": "massimo",
"author_id": 24489,
"author_profile": "https://Stackoverflow.com/users/24489",
"pm_score": 7,
"selected": false,
"text": "BR DIV SPAN IS_IN_SET IS_INT_IN_RANGE"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/479/"
] |
76,812 |
<p>What factors determine which approach is more appropriate?</p>
|
[
{
"answer_id": 76869,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 2,
"selected": false,
"text": "GetTotalPriceofThings();\n Cart.getTotal();\n"
},
{
"answer_id": 76904,
"author": "Chris Comeaux",
"author_id": 2748,
"author_profile": "https://Stackoverflow.com/users/2748",
"pm_score": 0,
"selected": false,
"text": "Thing Thing Thing Thing"
},
{
"answer_id": 76960,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 0,
"selected": false,
"text": "Collection.Add(Thing)\n Thing.AddSelfToCollection(Collection)\n"
},
{
"answer_id": 76977,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": true,
"text": "DoSomethingToThing(Thing n) Thing.DoSomething() fileHandle.close();\n string x = \"Hello World\";\nsubmitHttpRequest( x );\n submitHttpRequst(x) x.submitViaHttp() networkConnection.submitHttpRequest(x)\n"
},
{
"answer_id": 76997,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 2,
"selected": false,
"text": "// Form 1: \"File handle, close.\"\nfileHandle.close(); \n\n// Form 2: \"(Computer,) close the file handle.\"\nclose(fileHandle);\n\n// Form 3: \"File handle, write the contents of another file handle.\"\nfileHandle.writeContentsOf(anotherFileHandle);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
76,855 |
<p>Each of our production web servers maintains its own cache for separate web sites (ASP.NET Web Applications). Currently to clear a cache we log into the server and "touch" the web.config file. </p>
<p>Does anyone have an example of a safe/secure way to <strong>remotely</strong> reset the cache for a specific web application? Ideally we'd be able to say "clear the cache for app X running on all servers" but also "clear the cache for app X running on server Y".</p>
<p>Edits/Clarifications: </p>
<ul>
<li><p>I should probably clarify that doing this via the application itself isn't really an option (i.e. some sort of log in to the application, surf to a specific page or handler that would clear the cache). In order to do something like this we'd need to disable/bypass logging and stats tracking code, or mess up our stats.</p></li>
<li><p>Yes, the cache expires regularly. What I'd like to do though is setup something so I can expire a specific cache on demand, usually after we change something in the database (we're using SQL 2000). We can do this now but only by logging in to the servers themselves.</p></li>
</ul>
|
[
{
"answer_id": 77860,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 2,
"selected": false,
"text": "Context.Application.Lock()\nContext.Session.Abandon()\nContext.Application.RemoveAll()\nContext.Application.UnLock()\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12842/"
] |
76,870 |
<p>I want to load a different properties file based upon one variable.</p>
<p>Basically, if doing a dev build use this properties file, if doing a test build use this other properties file, and if doing a production build use yet a third properties file.</p>
|
[
{
"answer_id": 78583,
"author": "Tim",
"author_id": 10363,
"author_profile": "https://Stackoverflow.com/users/10363",
"pm_score": 3,
"selected": false,
"text": "include if include <include buildfile=\"devPropertyFile.build\" if=\"${buildEnvironment == 'DEV'}\"/>\n<include buildfile=\"testPropertyFile.build\" if=\"${buildEnvironment == 'TEST'}\"/>\n<include buildfile=\"prodPropertyFile.build\" if=\"${buildEnvironment == 'PROD'}\"/>\n"
},
{
"answer_id": 87752,
"author": "scott.caligan",
"author_id": 14814,
"author_profile": "https://Stackoverflow.com/users/14814",
"pm_score": 6,
"selected": true,
"text": "<property name=\"environment\" value=\"local\" />\n <target name=\"config\">\n <!-- configuration logic goes here -->\n</target>\n\n<target name=\"buildmyproject\" depends=\"config\">\n <!-- this target builds your project, but runs the config target first -->\n</target>\n <target name=\"config\">\n <property name=\"configFile\" value=\"${environment}.config.xml\" />\n <if test=\"${file::exists(configFile)}\">\n <echo message=\"Loading ${configFile}...\" />\n <include buildfile=\"${configFile}\" />\n </if>\n <if test=\"${not file::exists(configFile) and environment != 'local'}\">\n <fail message=\"Configuration file '${configFile}' could not be found.\" />\n </if>\n</target>\n"
},
{
"answer_id": 180438,
"author": "Ryan Taylor",
"author_id": 19977,
"author_profile": "https://Stackoverflow.com/users/19977",
"pm_score": 3,
"selected": false,
"text": "<target name=\"dev\">\n <property name=\"environment\" value=\"dev\"/>\n <call target=\"importProperties\" cascade=\"false\"/>\n</target>\n\n<target name=\"test\">\n <property name=\"environment\" value=\"test\"/>\n <call target=\"importProperties\" cascade=\"false\"/>\n</target>\n\n<target name=\"stage\">\n <property name=\"environment\" value=\"stage\"/>\n <call target=\"importProperties\" cascade=\"false\"/>\n</target>\n\n<target name=\"importProperties\">\n <property name=\"propertiesFile\" value=\"properties.${environment}.build\"/>\n <if test=\"${file::exists(propertiesFile)}\">\n <include buildfile=\"${propertiesFile}\"/>\n </if>\n <if test=\"${not file::exists(propertiesFile)}\">\n <fail message=\"Properties file ${propertiesFile} could not be found.\"/>\n </if>\n</target>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9052/"
] |
76,882 |
<p>I have written a lot of code in Python, and I am very used to the syntax, object structure, and so forth of Python because of it.</p>
<p>What is the best online guide or resource site to provide me with the basics, as well as a comparison or lookup guide with equivalent functions/features in VBA versus Python.</p>
<p>For example, I am having trouble equating a simple List in Python to VBA code. I am also have issues with data structures, such as dictionaries, and so forth. </p>
<p>What resources or tutorials are available that will provide me with a guide to porting python functionality to VBA, or just adapting to the VBA syntax from a strong OOP language background?</p>
|
[
{
"answer_id": 185390,
"author": "molasses",
"author_id": 11293,
"author_profile": "https://Stackoverflow.com/users/11293",
"pm_score": 1,
"selected": false,
"text": "' An array with 3 elements\n'' The number inside the brackets represents the upper bound index\n'' ie. the last index you can access\n'' So a(2) means you can access a(0), a(1), and a(2) '\n\nDim a(2) As String\na(0) = \"a\"\na(1) = \"b\"\na(2) = \"c\"\n\nDim i As Integer\nFor i = 0 To UBound(a)\n MsgBox a(i)\nNext\n ' Declare a \"dynamic\" array '\n\nDim a() As Variant\n\n' Set the array size to 3 elements '\n\nReDim a(2)\na(0) = 1\na(1) = 2\n\n' Set the array size to 2 elements\n'' If you dont use Preserve then you will lose\n'' the existing data in the array '\n\nReDim Preserve a(1)\n Set cars = CreateObject(\"Scripting.Dictionary\")\ncars.Add \"a\", \"Alvis\"\ncars.Add \"b\", \"Buick\"\ncars.Add \"c\", \"Cadillac\" \n"
},
{
"answer_id": 186583,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": false,
"text": "list dict list Collection VBA dim alist as New Collection .Add(item) .Count .Item(i) .Remove(i) ReDim dict Dim adict As New Dictionary .Add(key, item) .Exists(key) .Items() .Keys()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,925 |
<p>DOING THE POST IS NOT THE PROBLEM! Formatting the message so that I get a response is the problem.</p>
<p>Ideally I'd be able to construct a message and use WinHTTP to perform a post to a WCF service (hosted in IIS) and get a response, but so far I've been unable to construct something that works properly.</p>
<p>Does anyone have an example of doing this that is straightforward?</p>
<p>In the 2.0 Web Service world this was as easy as putting a setting in the web.config to get the service to respond to a post and then calling the appropriate web method with the right parameters. There seems to be no analogue for this in the WCF world.</p>
<p>As of now there is no option for me to convert the consumer (the vbscript end) into .NET.</p>
<p>Assume at this point that at the endpoint I can convert to using whatever bindings are available right up to whatever is supported in .NET 3.5, but at the same time if this can be done using WsHttpBinding or BasicHttpBinding then the proper answer to this would be to describe how to format the message for either of those bindings in the context of VBScript or if there is no way to do that then just say, you can't do it. If this can be done using WebHTTPBinding then I have not found a way to make it happen as I've already investigated the WebInvoke attribute and been unable to create a test from VBScript to WCF that worked properly.</p>
<p>Assume that the posted data type is a string and the response is also a string.</p>
<p>Also this question is not WinHTTP related. I already know how to perform the post using WinHTTP it's the construction of the message that the WCF service will respond to that is the problem.</p>
<p>While I could use something other than WinHTTP to perform the post from ASP over to the WCF service such as XMLHTTP I still have the problem of constructing an XML message that the WCF service will respond to. I've tried variations on this and still am unable to fathom what sort of format I need to use to make this happen.</p>
<p>I know theoretically that all the WCF service needs is a properly formatted message. I'm just unable to construct the message properly and usually while everyone has some suggestion on how to send the message I have yet to see someone give an actual example of what the proper message format would be in this situation since everyone is so used to using .NET to send the message and it's all done for you in that context.</p>
|
[
{
"answer_id": 77115,
"author": "Spike",
"author_id": 13111,
"author_profile": "https://Stackoverflow.com/users/13111",
"pm_score": 0,
"selected": false,
"text": "Sub ExportToHTTPPOST()\nDim sURL, sExtraParams\nConst ForReading = 1, ForWriting = 2, ForAppending = 3\n\nSet rs = CreateObject(\"Scripting.FileSystemObject\")\nSet r = rs.OpenTextFile(\"y:\\test.xml\", ForReading)\n\nSet Ws = CreateObject(\"Scripting.FileSystemObject\")\nSet w = Ws.OpenTextFile(\"Y:\\test2.xml\", ForWriting, True)\n\nDo Until r.AtEndOfStream\n\n sData = sData & r.readline\n\nLoop\n\nsURL = \"http://MyServer/MyWebApp.asp\"\n\nsData = \"payload=\" & sData\n\n Set objHTTP = New WinHttp.WinHttpRequest\n\n objHTTP.Open \"POST\", sURL, False\n objHTTP.setRequestHeader \"Content-Type\", \"application/x-www-form-urlencoded\"\n objHTTP.send sData\n w.writeline objHTTP.ResponseText\n Set objHTTP = Nothing\n w.Close\n r.Close\nEnd Sub\n"
},
{
"answer_id": 95307,
"author": "Skyhigh",
"author_id": 13387,
"author_profile": "https://Stackoverflow.com/users/13387",
"pm_score": 1,
"selected": false,
"text": "Set objXML = CreateObject(\"MSXML2.ServerXMLHTTP.6.0\")\nobjXML.open \"POST\", url, false\nobjXML.setRequestHeader \"Content-Type\", \"application/x-www-form-urlencoded\"\nobjXML.send(\"key=\"& Server.URLEncode(xmlvalue))\nSet responseXML = objXML.responseXML\nSet objXML = nothing\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10004/"
] |
76,930 |
<p><strong>Scenario:</strong> Several people go on holiday together, armed with digital cameras, and snap away. Some people remembered to adjust their camera clocks to local time, some left them at their home time, some left them at local time of the country they were born in, and some left their cameras on factory time.</p>
<p><strong>The Problem:</strong> Timestamps in the EXIF metadata of photos will not be synchronised, making it difficult to aggregate all the photos into one combined collection.</p>
<p><strong>The Question:</strong> Assuming that you have discovered the deltas between all of the camera clocks, What is the <em>simplest</em> way to correct these timestamp differences in Windows Vista?</p>
|
[
{
"answer_id": 77123,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "exiftool \"-DateTimeOriginal+=5:10:2 10:48:0\" DIR\n\nexiftool -AllDates-=1 DIR\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5975/"
] |
76,939 |
<p>Is it possible to install the x86 Remote Debugger as a Service on a 64bit machine? I need to attach a debugger to managed code in a Session 0 process. The process runs 32bit but the debugger service that gets installed is 64bit and wont attach to the 32bit process. </p>
<p>I tried creating the Service using the SC command, and was able to get the service to start, and verified that it was running in Task manager processes. However, when I tried to connect to it with visual studio, it said that the remote debugger monitor wasn't enabled. When I stopped the x86 service, and started the x64 service and it was able to find the monitor, but still got an error.</p>
<p>Here is the error when I try to use the remote debugger:
Unable to attach to the process. The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) cannot debug 32-bit processes or 32-bit dumps. Please use the 32-bit version instead.</p>
<p>Here is the error when I try to attach locally:
Attaching to a process in a different terminal server session is not supported on this computer. Try remote debugging to the machine and running the Microsoft Visual Studio Remote Debugging Monitor in the process's session.</p>
<p>If I try to run the 32bit remote debugger as an application, it wont work attach b/c the Remote Debugger is running in my session and not in session 0.</p>
|
[
{
"answer_id": 77920,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "sc create \"Remote Debugger\" binpath= \"C:\\use\\short\\filename\\in\\the\\path\\x86\\msvsmon.exe /service msvsmon90\"\n"
},
{
"answer_id": 445514,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "sc stop msvsmon90\nsc config msvsmon90 binPath= \"C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\Remote Debugger\\x86\\msvsmon.exe /service msvsmon90\"\nsc start msvsmon90\n"
},
{
"answer_id": 26037339,
"author": "GreatDane",
"author_id": 1796802,
"author_profile": "https://Stackoverflow.com/users/1796802",
"pm_score": 0,
"selected": false,
"text": "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\Common7\\IDE\\Remote Debugger msvsmon.exe x86 x64"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3291/"
] |
76,963 |
<p>I am a MFC programmer who is new to C# and am looking for a simple control that will allow number entry and range validation.</p>
|
[
{
"answer_id": 77853,
"author": "Ricardo Amores",
"author_id": 10136,
"author_profile": "https://Stackoverflow.com/users/10136",
"pm_score": 1,
"selected": false,
"text": "private string ComputeRegexPattern()\n{\n StringBuilder builder = new StringBuilder();\n if (this._forcePositives)\n {\n builder.Append(\"([+]|[-])?\");\n }\n builder.Append(@\"[\\d]*((\");\n if (!this._useIntegers)\n {\n for (int i = 0; i < this._numericSeparator.Length; i++)\n {\n builder.Append(\"[\").Append(this._numericSeparator[i]).Append(\"]\");\n if ((this._numericSeparator.Length > 0) && (i != (this._numericSeparator.Length - 1)))\n {\n builder.Append(\"|\");\n }\n }\n }\n builder.Append(@\")[\\d]*)?\");\n return builder.ToString();\n}\n private bool CheckValidNumber()\n{\n if (Regex.Match(this.Text, this.RegexPattern).Value != this.Text)\n {\n this._errorProvider.SetError(this, this.ValidationError);\n return false;\n }\n this._errorProvider.Clear();\n return true;\n}\n\nprotected override void OnValidating(CancelEventArgs e)\n{\n bool flag = this.CheckValidNumber();\n if (!flag)\n {\n e.Cancel = true;\n this.Text = \"0\";\n }\n base.OnValidating(e);\n if (!flag)\n {\n this.ValidationFail(this, EventArgs.Empty);\n }\n}\n protected override void OnKeyPress(KeyPressEventArgs e)\n{\n if ((!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar)) && (!this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._numericSeparator.Contains(e.KeyChar.ToString())))\n {\n e.Handled = true;\n }\n if (this._numberSymbols.Contains(e.KeyChar.ToString()) && !this._forcePositives)\n {\n e.Handled = true;\n }\n if (this._numericSeparator.Contains(e.KeyChar.ToString()) && this._useIntegers)\n {\n e.Handled = true;\n }\n base.OnKeyPress(e);\n}\n protected override void OnKeyUp(KeyEventArgs e)\n{\n this.CheckValidNumber();\n base.OnKeyUp(e);\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,967 |
<p>I know that that is not a question... erm anyway HERE is the question.</p>
<p>I have inherited a database that has 1(one) table in that looks much like this. Its aim is to record what species are found in the various (200 odd) countries.</p>
<pre><code>ID
Species
Afghanistan
Albania
Algeria
American Samoa
Andorra
Angola
....
Western Sahara
Yemen
Zambia
Zimbabwe
</code></pre>
<p>A sample of the data would be something like this</p>
<pre><code>id Species Afghanistan Albania American Samoa
1 SP1 null null null
2 SP2 1 1 null
3 SP3 null null 1
</code></pre>
<p>It seems to me this is a typical many to many situation and I want 3 tables.
Species, Country, and SpeciesFoundInCountry</p>
<p>The link table (SpeciesFoundInCountry) would have foreign keys in both the species and Country tables.</p>
<p>(It is hard to draw the diagram!)</p>
<pre><code>Species
SpeciesID SpeciesName
Country
CountryID CountryName
SpeciesFoundInCountry
CountryID SpeciesID
</code></pre>
<p>Is there a magic way I can generate an insert statement that will get the CountryID from the new Country table based on the column name and the SpeciesID where there is a 1 in the original mega table?</p>
<p>I can do it for one Country (this is a select to show what I want out)</p>
<pre><code>SELECT Species.ID, Country.CountryID
FROM Country, Species
WHERE (((Species.Afghanistan)=1)) AND (((Country.Country)="Afghanistan"));
</code></pre>
<p>(the mega table is called species)</p>
<p>But using this strategy I would need to do the query for each column in the original table. </p>
<p>Is there a way of doing this in sql?</p>
<p>I guess I can OR a load of my where clauses together and write a script to make the sql, seems inelegant though!</p>
<p>Any thoughts (or clarification required)?</p>
|
[
{
"answer_id": 77054,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 1,
"selected": false,
"text": "select \n 'SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.' + \n c.name + \n ')=1)) AND (((Country.Country)=\"' +\n c.name + \n '\"))'\nfrom syscolumns c\ninner join sysobjects o\non o.id = c.id\nwhere o.name = 'old_table_name'\n"
},
{
"answer_id": 77610,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Public Sub CreateRelationshipRecords()\n\n Dim rstSource as DAO.Recordset\n Dim rstDestination as DAO.Recordset\n Dim fld as DAO.Field\n dim strSQL as String\n Dim lngSpeciesID as Long\n\n strSQL = \"SELECT * FROM [ORIGINALTABLE]\"\n Set rstSource = CurrentDB.OpenRecordset(strSQL)\n set rstDestination = CurrentDB.OpenRecordset(\"SpeciesFoundInCountry\")\n\n rstSource.MoveFirst\n\n ' Step through each record in the original table\n Do Until rstSource.EOF\n lngSpeciesID = rstSource.ID\n ' Now step through the fields(columns). If the field\n ' value is one (1), then create a relationship record\n ' using the field name as the Country Name\n For Each fld in rstSource.Fields\n If fld.Value = 1 then\n with rstDestination\n .AddNew\n .Fields(\"CountryID\").Value = Null\n .Fields(\"CountryName\").Value = fld.Name\n .Fields(\"SpeciesID\").Value = lngSpeciesID\n .Update\n End With\n End IF\n Next fld \n rstSource.MoveNext\n Loop\n\n ' Clean up\n rstSource.Close\n Set rstSource = nothing\n ....\n\nEnd Sub\n"
},
{
"answer_id": 78130,
"author": "CindyH",
"author_id": 12897,
"author_profile": "https://Stackoverflow.com/users/12897",
"pm_score": 1,
"selected": false,
"text": "cout>>\"I don't know C\"\ncout>>\"Hello World\"\n"
},
{
"answer_id": 78249,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": "Dim db As Database\nDim tdf As TableDef\n\nSet db = CurrentDb\n\nSet tdf = db.TableDefs(\"SO\")\n\nstrSQL = \"SELECT ID, Species, \"\"\" & tdf.Fields(2).Name _\n & \"\"\" AS Country, [\" & tdf.Fields(2).Name & \"] AS CountryValue FROM SO \"\n\nFor i = 3 To tdf.Fields.Count - 1\n strSQL = strSQL & vbCrLf & \"UNION SELECT ID, Species, \"\"\" & tdf.Fields(i).Name _\n & \"\"\" AS Country, [\" & tdf.Fields(i).Name & \"] AS CountryValue FROM SO \"\nNext\n\ndb.CreateQueryDef \"UnionSO\", strSQL\n"
},
{
"answer_id": 78348,
"author": "Gaurav",
"author_id": 13492,
"author_profile": "https://Stackoverflow.com/users/13492",
"pm_score": 1,
"selected": false,
"text": "SELECT * FROM ugly_table;\nwhile(row)\nforeach(row as field => value)\nif(value == 1)\nSELECT country_id from country_table WHERE country_name = field;\n\nif(field == 'Species')\nSELECT species_id from species_table WHERE species_name = value;\n\nINSERT INTO better_table (...)\n"
},
{
"answer_id": 78464,
"author": "user14336",
"author_id": 14336,
"author_profile": "https://Stackoverflow.com/users/14336",
"pm_score": 1,
"selected": false,
"text": "where substring(new_column,country_code) = '1'\n where a.species_name = b.species_name\n"
},
{
"answer_id": 197683,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 1,
"selected": false,
"text": "/* if you have N countries */\nCREATE TABLE Country\n(id int, \n name varchar(50)) \n\nINSERT Country\n SELECT 1, 'Afghanistan'\nUNION SELECT 2, 'Albania', \nUNION SELECT 3, 'Algeria' ,\nUNION SELECT 4, 'American Samoa' ,\nUNION SELECT 5, 'Andorra' ,\nUNION SELECT 6, 'Angola' ,\n...\nUNION SELECT N-3, 'Western Sahara', \nUNION SELECT N-2, 'Yemen', \nUNION SELECT N-1, 'Zambia', \nUNION SELECT N, 'Zimbabwe', \n\n\n\nCREATE TABLE #tmp\n(key varchar(N), \n country_id int) \n/* \"key\" field needs to be as long as N */ \n\n\nINSERT #tmp \nSELECT '1________ ... _', 'Afghanistan' \n/* '1' followed by underscores to make the length = N */\n\nUNION SELECT '_1_______ ... ___', 'Albania'\nUNION SELECT '__1______ ... ___', 'Algeria'\n...\nUNION SELECT '________ ... _1_', 'Zambia'\nUNION SELECT '________ ... __1', 'Zimbabwe'\n\nCREATE TABLE new_table\n(country_id int, \nspecies_id int) \n\nINSERT new_table\nSELECT species.id, country_id\nFROM species s , \n #tmp t\nWHERE isnull( s.Afghanistan, ' ' ) + \n isnull( s.Albania, ' ' ) + \n ... + \n isnull( s.Zambia, ' ' ) + \n isnull( s.Zimbabwe, ' ' ) like t.key \n INSERT new_table SELECT Species.ID, 1 FROM Species WHERE Species.Afghanistan = 1 \nINSERT new_table SELECT Species.ID, 2 FROM Species WHERE Species.Albania= 1 \n...\nINSERT new_table SELECT Species.ID, 999 FROM Species WHERE Species.Zambia= 1 \nINSERT new_table SELECT Species.ID, 1000 FROM Species WHERE Species.Zimbabwe= 1 \n"
},
{
"answer_id": 225462,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 1,
"selected": false,
"text": "SELECT Species.ID, Country.CountryID\nFROM Country, Species\nWHERE (((Species.%PAR1%)=1)) AND (((Country.Country)=\"%PAR1%\"))\nUNION\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76967",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5552/"
] |
76,976 |
<p>Is it possible to get the progress of an XMLHttpRequest (bytes uploaded, bytes downloaded)? </p>
<p>This would be useful to show a progress bar when the user is uploading a large file. The standard API doesn't seem to support it, but maybe there's some non-standard extension in any of the browsers out there? It seems like a pretty obvious feature to have after all, since the client knows how many bytes were uploaded/downloaded.</p>
<p>note: I'm aware of the "poll the server for progress" alternative (it's what I'm doing right now). the main problem with this (other than the complicated server-side code) is that typically, while uploading a big file, the user's connection is completely hosed, because most ISPs offer poor upstream. So making extra requests is not as responsive as I'd hoped. I was hoping there'd be a way (maybe non-standard) to get this information, which the browser has at all times.</p>
|
[
{
"answer_id": 3360576,
"author": "Markus Peröbner",
"author_id": 404522,
"author_profile": "https://Stackoverflow.com/users/404522",
"pm_score": 3,
"selected": false,
"text": "var progressBar = document.getElementById(\"p\"),\n client = new XMLHttpRequest()\nclient.open(\"GET\", \"magical-unicorns\")\nclient.onprogress = function(pe) {\n if(pe.lengthComputable) {\n progressBar.max = pe.total\n progressBar.value = pe.loaded\n }\n}\nclient.onloadend = function(pe) {\n progressBar.value = pe.loaded\n}\nclient.send()\n"
},
{
"answer_id": 3694435,
"author": "albanx",
"author_id": 354881,
"author_profile": "https://Stackoverflow.com/users/354881",
"pm_score": 7,
"selected": false,
"text": "xhr.upload.onprogress xhr.responseText Content-Length $filesize=filesize('test.zip');\n\nheader(\"Content-Length: \" . $filesize); // set header length\n// if the headers is not set then the evt.loaded will be 0\nreadfile('test.zip');\nexit 0;\n function updateProgress(evt) \n{\n if (evt.lengthComputable) \n { // evt.loaded the bytes the browser received\n // evt.total the total bytes set by the header\n // jQuery UI progress bar to show the progress on screen\n var percentComplete = (evt.loaded / evt.total) * 100; \n $('#progressbar').progressbar( \"option\", \"value\", percentComplete );\n } \n} \nfunction sendreq(evt) \n{ \n var req = new XMLHttpRequest(); \n $('#progressbar').progressbar(); \n req.onprogress = updateProgress;\n req.open('GET', 'test.php', true); \n req.onreadystatechange = function (aEvt) { \n if (req.readyState == 4) \n { \n //run any callback here\n } \n }; \n req.send(); \n}\n"
},
{
"answer_id": 35080857,
"author": "Forums Lover",
"author_id": 5283607,
"author_profile": "https://Stackoverflow.com/users/5283607",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<p id=\"demo\">result</p>\n<button type=\"button\" onclick=\"get_post_ajax();\">Change Content</button>\n<script type=\"text/javascript\">\n function update_progress(e)\n {\n if (e.lengthComputable)\n {\n var percentage = Math.round((e.loaded/e.total)*100);\n console.log(\"percent \" + percentage + '%' );\n }\n else \n {\n console.log(\"Unable to compute progress information since the total size is unknown\");\n }\n }\n function transfer_complete(e){console.log(\"The transfer is complete.\");}\n function transfer_failed(e){console.log(\"An error occurred while transferring the file.\");}\n function transfer_canceled(e){console.log(\"The transfer has been canceled by the user.\");}\n function get_post_ajax()\n {\n var xhttp;\n if (window.XMLHttpRequest){xhttp = new XMLHttpRequest();}//code for modern browsers} \n else{xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");}// code for IE6, IE5 \n xhttp.onprogress = update_progress;\n xhttp.addEventListener(\"load\", transfer_complete, false);\n xhttp.addEventListener(\"error\", transfer_failed, false);\n xhttp.addEventListener(\"abort\", transfer_canceled, false); \n xhttp.onreadystatechange = function()\n {\n if (xhttp.readyState == 4 && xhttp.status == 200)\n {\n document.getElementById(\"demo\").innerHTML = xhttp.responseText;\n }\n };\n xhttp.open(\"GET\", \"http://it-tu.com/ajax_test.php\", true);\n xhttp.send();\n }\n</script>\n</body>\n</html>"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
76,988 |
<p>I have seen another program provide traceroute functionality within it but without needing root (superuser) privileges? I've always assumed that raw sockets need to be root, but is there some other way? (I think somebody mentioned "supertrace" or "tracepath"?) Thanks!</p>
|
[
{
"answer_id": 77205,
"author": "James Antill",
"author_id": 10314,
"author_profile": "https://Stackoverflow.com/users/10314",
"pm_score": -1,
"selected": false,
"text": "\nint opt_on = 1;\nint opt_off = 0;\n\nfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)\nsetsockopt(fd, SOL_IP, IP_MTU_DISCOVER, &opt_off, sizeof int)\nsetsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &opt_on, sizeof int)\nsetsockopt(fd, SOL_IP, IP_RECVTTL, &opt_on, sizeof int)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13817/"
] |
76,993 |
<p>How can I set the protected <code>DoubleBuffered</code> property of the controls on a form that are suffering from flicker?</p>
|
[
{
"answer_id": 77023,
"author": "Arno",
"author_id": 13685,
"author_profile": "https://Stackoverflow.com/users/13685",
"pm_score": 4,
"selected": false,
"text": "public void EnableDoubleBuffering()\n{\n this.SetStyle(ControlStyles.DoubleBuffer | \n ControlStyles.UserPaint | \n ControlStyles.AllPaintingInWmPaint,\n true);\n this.UpdateStyles();\n}\n"
},
{
"answer_id": 77041,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 4,
"selected": false,
"text": "System.Reflection.PropertyInfo aProp = typeof(System.Windows.Forms.Control)\n .GetProperty(\"DoubleBuffered\", System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\naProp.SetValue(ListView1, true, null);\n"
},
{
"answer_id": 77071,
"author": "Jeff Hubbard",
"author_id": 8844,
"author_profile": "https://Stackoverflow.com/users/8844",
"pm_score": 3,
"selected": false,
"text": "class Foo : Panel\n{\n public Foo() { DoubleBuffered = true; }\n}\n"
},
{
"answer_id": 77233,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 8,
"selected": true,
"text": "public static void SetDoubleBuffered(System.Windows.Forms.Control c)\n{\n //Taxes: Remote Desktop Connection and painting\n //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx\n if (System.Windows.Forms.SystemInformation.TerminalServerSession)\n return;\n\n System.Reflection.PropertyInfo aProp = \n typeof(System.Windows.Forms.Control).GetProperty(\n \"DoubleBuffered\", \n System.Reflection.BindingFlags.NonPublic | \n System.Reflection.BindingFlags.Instance);\n\n aProp.SetValue(c, true, null); \n}\n"
},
{
"answer_id": 89125,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 6,
"selected": false,
"text": "protected override CreateParams CreateParams {\n get {\n var cp = base.CreateParams;\n cp.ExStyle |= 0x02000000; // Turn on WS_EX_COMPOSITED\n return cp;\n } \n}\n"
},
{
"answer_id": 1643053,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 3,
"selected": false,
"text": "protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= 0x02000000;\n return cp;\n }\n}\n"
},
{
"answer_id": 14282267,
"author": "MajesticRa",
"author_id": 548894,
"author_profile": "https://Stackoverflow.com/users/548894",
"pm_score": 3,
"selected": false,
"text": "public static class ControlExtentions\n{\n /// <summary>\n /// Turn on or off control double buffering (Dirty hack!)\n /// </summary>\n /// <param name=\"control\">Control to operate</param>\n /// <param name=\"setting\">true to turn on double buffering</param>\n public static void MakeDoubleBuffered(this Control control, bool setting)\n {\n Type controlType = control.GetType();\n PropertyInfo pi = controlType.GetProperty(\"DoubleBuffered\", BindingFlags.Instance | BindingFlags.NonPublic);\n pi.SetValue(control, setting, null);\n }\n}\n DataGridView _grid = new DataGridView();\n// ...\n_grid.MakeDoubleBuffered(true);\n"
},
{
"answer_id": 17279923,
"author": "dnennis",
"author_id": 2386550,
"author_profile": "https://Stackoverflow.com/users/2386550",
"pm_score": 2,
"selected": false,
"text": "protected override CreateParams CreateParams\n{\n get\n {\n CreateParams cp = base.CreateParams;\n cp.ExStyle |= 0x02000000;\n return cp;\n }\n}\n private void myPanel_SizeChanged(object sender, EventArgs e)\n{\n Application.DoEvents();\n}\n"
},
{
"answer_id": 39343123,
"author": "Flip70",
"author_id": 6799147,
"author_profile": "https://Stackoverflow.com/users/6799147",
"pm_score": 2,
"selected": false,
"text": "Protected Overrides ReadOnly Property CreateParams() As CreateParams\n Get\n Dim cp As CreateParams = MyBase.CreateParams\n cp.ExStyle = cp.ExStyle Or &H2000000\n Return cp\n End Get\nEnd Property\n"
},
{
"answer_id": 67273198,
"author": "Gregor y",
"author_id": 4496560,
"author_profile": "https://Stackoverflow.com/users/4496560",
"pm_score": -1,
"selected": false,
"text": "SetStyle function Set-DoubleBuffered{\n<#\n.SYNOPSIS\nTurns on double buffering for a [System.Windows.Forms.Control] object\n.DESCRIPTION\nUses the Non-Public method 'SetStyle' on the control to set the three\nstyle flags recomend for double buffering: \n UserPaint\n AllPaintingInWmPaint\n DoubleBuffer\n.INPUTS\n[System.Windows.Forms.Control]\n.OUTPUTS\nNone\n.COMPONENT \nSystem.Windows.Forms.Control\n.FUNCTIONALITY\nSet Flag, DoubleBuffering, Graphics\n.ROLE\nWinForms Developer\n.NOTES\nThrows an exception when trying to double buffer a control on a terminal \nserver session becuase doing so will cause lots of data to be sent across \nthe line\n.EXAMPLE\n#A simple WinForm that uses double buffering to reduce flicker\nAdd-Type -AssemblyName System.Windows.Forms\n[System.Windows.Forms.Application]::EnableVisualStyles()\n\n$Pen = [System.Drawing.Pen]::new([System.Drawing.Color]::FromArgb(0xff000000),3)\n\n$Form = New-Object System.Windows.Forms.Form\nSet-DoubleBuffered $Form\n$Form.Add_Paint({\n param(\n [object]$sender,\n [System.Windows.Forms.PaintEventArgs]$e\n )\n [System.Windows.Forms.Form]$f = $sender\n $g = $e.Graphics\n $g.SmoothingMode = 'AntiAlias'\n $g.DrawLine($Pen,0,0,$f.Width/2,$f.Height/2)\n})\n$Form.ShowDialog()\n\n.LINK\nhttps://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.setstyle?view=net-5.0\n.LINK\nhttps://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.controlstyles?view=net-5.0\n#>\n param(\n [parameter(mandatory=$true,ValueFromPipeline=$true)]\n [ValidateScript({$_ -is [System.Windows.Forms.Control]})]\n #The WinForms control to set to double buffered\n $Control,\n \n [switch]\n #Override double buffering on a terminal server session(not recomended)\n $Force\n )\n begin{try{\n if([System.Windows.Forms.SystemInformation]::TerminalServerSession -and !$Force){\n throw 'Double buffering not set on terminal server session.'\n }\n \n $SetStyle = ([System.Windows.Forms.Control]).GetMethod('SetStyle',\n [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance\n )\n $UpdateStyles = ([System.Windows.Forms.Control]).GetMethod('UpdateStyles',\n [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance\n )\n }catch {$PSCmdlet.ThrowTerminatingError($PSItem)}\n }process{try{\n $SetStyle.Invoke($Control,@(\n ([System.Windows.Forms.ControlStyles]::UserPaint -bor\n [System.Windows.Forms.ControlStyles]::AllPaintingInWmPaint -bor\n [System.Windows.Forms.ControlStyles]::DoubleBuffer\n ),\n $true\n ))\n $UpdateStyles.Invoke($Control,@())\n }catch {$PSCmdlet.ThrowTerminatingError($PSItem)}}\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/76993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
77,005 |
<p>I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.</p>
<p>My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using <code>gcc</code>).</p>
<p>I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?</p>
|
[
{
"answer_id": 76867,
"author": "mana",
"author_id": 12016,
"author_profile": "https://Stackoverflow.com/users/12016",
"pm_score": 3,
"selected": false,
"text": "ulimit -c unlimited\n"
},
{
"answer_id": 76937,
"author": "Brian Mitchell",
"author_id": 13716,
"author_profile": "https://Stackoverflow.com/users/13716",
"pm_score": 5,
"selected": false,
"text": "backtrace() __builtin_frame_address __builtin_return_address __builtin_frame_address"
},
{
"answer_id": 76962,
"author": "Stéphane",
"author_id": 13022,
"author_profile": "https://Stackoverflow.com/users/13022",
"pm_score": 3,
"selected": false,
"text": "#include <exeinfo.h>\nint backtrace(void **buffer, int size);\n"
},
{
"answer_id": 76986,
"author": "Benson",
"author_id": 13816,
"author_profile": "https://Stackoverflow.com/users/13816",
"pm_score": 4,
"selected": false,
"text": "$ g++ -g prog.cpp -o prog\n $ gdb ./prog\n... gdb startup output ...\n(gdb) run\n... program runs and crashes ...\n(gdb) where\n... gdb outputs your stack trace ...\n"
},
{
"answer_id": 77272,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "ulimit -c <value> ulimit ulimit -a SIGSEGV"
},
{
"answer_id": 77336,
"author": "Todd Gamblin",
"author_id": 9122,
"author_profile": "https://Stackoverflow.com/users/9122",
"pm_score": 10,
"selected": true,
"text": "execinfo.h SIGSEGV stderr baz() #include <stdio.h>\n#include <execinfo.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n\nvoid handler(int sig) {\n void *array[10];\n size_t size;\n\n // get void*'s for all entries on the stack\n size = backtrace(array, 10);\n\n // print out all the frames to stderr\n fprintf(stderr, \"Error: signal %d:\\n\", sig);\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n exit(1);\n}\n\nvoid baz() {\n int *foo = (int*)-1; // make a bad pointer\n printf(\"%d\\n\", *foo); // causes segfault\n}\n\nvoid bar() { baz(); }\nvoid foo() { bar(); }\n\n\nint main(int argc, char **argv) {\n signal(SIGSEGV, handler); // install our handler\n foo(); // this will call foo, bar, and baz. baz segfaults.\n}\n -g -rdynamic $ gcc -g -rdynamic ./test.c -o test\n $ ./test\nError: signal 11:\n./test(handler+0x19)[0x400911]\n/lib64/tls/libc.so.6[0x3a9b92e380]\n./test(baz+0x14)[0x400962]\n./test(bar+0xe)[0x400983]\n./test(foo+0xe)[0x400993]\n./test(main+0x28)[0x4009bd]\n/lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb]\n./test[0x40086a]\n main main foo bar baz"
},
{
"answer_id": 1925461,
"author": "jschmier",
"author_id": 203667,
"author_profile": "https://Stackoverflow.com/users/203667",
"pm_score": 7,
"selected": false,
"text": "#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#ifndef __USE_GNU\n#define __USE_GNU\n#endif\n\n#include <execinfo.h>\n#include <signal.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ucontext.h>\n#include <unistd.h>\n\n/* This structure mirrors the one found in /usr/include/asm/ucontext.h */\ntypedef struct _sig_ucontext {\n unsigned long uc_flags;\n ucontext_t *uc_link;\n stack_t uc_stack;\n sigcontext_t uc_mcontext;\n sigset_t uc_sigmask;\n} sig_ucontext_t;\n\nvoid crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)\n{\n void * array[50];\n void * caller_address;\n char ** messages;\n int size, i;\n sig_ucontext_t * uc;\n\n uc = (sig_ucontext_t *)ucontext;\n\n /* Get the address at the time the signal was raised */\n#if defined(__i386__) // gcc specific\n caller_address = (void *) uc->uc_mcontext.eip; // EIP: x86 specific\n#elif defined(__x86_64__) // gcc specific\n caller_address = (void *) uc->uc_mcontext.rip; // RIP: x86_64 specific\n#else\n#error Unsupported architecture. // TODO: Add support for other arch.\n#endif\n\n fprintf(stderr, \"signal %d (%s), address is %p from %p\\n\", \n sig_num, strsignal(sig_num), info->si_addr, \n (void *)caller_address);\n\n size = backtrace(array, 50);\n\n /* overwrite sigaction with caller's address */\n array[1] = caller_address;\n\n messages = backtrace_symbols(array, size);\n\n /* skip first stack frame (points here) */\n for (i = 1; i < size && messages != NULL; ++i)\n {\n fprintf(stderr, \"[bt]: (%d) %s\\n\", i, messages[i]);\n }\n\n free(messages);\n\n exit(EXIT_FAILURE);\n}\n\nint crash()\n{\n char * p = NULL;\n *p = 0;\n return 0;\n}\n\nint foo4()\n{\n crash();\n return 0;\n}\n\nint foo3()\n{\n foo4();\n return 0;\n}\n\nint foo2()\n{\n foo3();\n return 0;\n}\n\nint foo1()\n{\n foo2();\n return 0;\n}\n\nint main(int argc, char ** argv)\n{\n struct sigaction sigact;\n\n sigact.sa_sigaction = crit_err_hdlr;\n sigact.sa_flags = SA_RESTART | SA_SIGINFO;\n\n if (sigaction(SIGSEGV, &sigact, (struct sigaction *)NULL) != 0)\n {\n fprintf(stderr, \"error setting signal handler for %d (%s)\\n\",\n SIGSEGV, strsignal(SIGSEGV));\n\n exit(EXIT_FAILURE);\n }\n\n foo1();\n\n exit(EXIT_SUCCESS);\n}\n signal 11 (Segmentation fault), address is (nil) from 0x8c50\n[bt]: (1) ./test(crash+0x24) [0x8c50]\n[bt]: (2) ./test(foo4+0x10) [0x8c70]\n[bt]: (3) ./test(foo3+0x10) [0x8c8c]\n[bt]: (4) ./test(foo2+0x10) [0x8ca8]\n[bt]: (5) ./test(foo1+0x10) [0x8cc4]\n[bt]: (6) ./test(main+0x74) [0x8d44]\n[bt]: (7) /lib/libc.so.6(__libc_start_main+0xa8) [0x40032e44]\n uc_mcontext.arm_pc uc_mcontext.eip"
},
{
"answer_id": 2526298,
"author": "jschmier",
"author_id": 203667,
"author_profile": "https://Stackoverflow.com/users/203667",
"pm_score": 7,
"selected": false,
"text": "backtrace() c++filt abi::__cxa_demangle c++filt __cxa_demangle c++filt class foo\n{\npublic:\n foo() { foo1(); }\n\nprivate:\n void foo1() { foo2(); }\n void foo2() { foo3(); }\n void foo3() { foo4(); }\n void foo4() { crash(); }\n void crash() { char * p = NULL; *p = 0; }\n};\n\nint main(int argc, char ** argv)\n{\n // Setup signal handler for SIGSEGV\n ...\n\n foo * f = new foo();\n return 0;\n}\n ./test signal 11 (Segmentation fault), address is (nil) from 0x8048e07\n[bt]: (1) ./test(crash__3foo+0x13) [0x8048e07]\n[bt]: (2) ./test(foo4__3foo+0x12) [0x8048dee]\n[bt]: (3) ./test(foo3__3foo+0x12) [0x8048dd6]\n[bt]: (4) ./test(foo2__3foo+0x12) [0x8048dbe]\n[bt]: (5) ./test(foo1__3foo+0x12) [0x8048da6]\n[bt]: (6) ./test(__3foo+0x12) [0x8048d8e]\n[bt]: (7) ./test(main+0xe0) [0x8048d18]\n[bt]: (8) ./test(__libc_start_main+0x95) [0x42017589]\n[bt]: (9) ./test(__register_frame_info+0x3d) [0x8048981]\n ./test 2>&1 | c++filt signal 11 (Segmentation fault), address is (nil) from 0x8048e07\n[bt]: (1) ./test(foo::crash(void)+0x13) [0x8048e07]\n[bt]: (2) ./test(foo::foo4(void)+0x12) [0x8048dee]\n[bt]: (3) ./test(foo::foo3(void)+0x12) [0x8048dd6]\n[bt]: (4) ./test(foo::foo2(void)+0x12) [0x8048dbe]\n[bt]: (5) ./test(foo::foo1(void)+0x12) [0x8048da6]\n[bt]: (6) ./test(foo::foo(void)+0x12) [0x8048d8e]\n[bt]: (7) ./test(main+0xe0) [0x8048d18]\n[bt]: (8) ./test(__libc_start_main+0x95) [0x42017589]\n[bt]: (9) ./test(__register_frame_info+0x3d) [0x8048981]\n abi::__cxa_demangle void crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)\n{\n sig_ucontext_t * uc = (sig_ucontext_t *)ucontext;\n\n void * caller_address = (void *) uc->uc_mcontext.eip; // x86 specific\n\n std::cerr << \"signal \" << sig_num \n << \" (\" << strsignal(sig_num) << \"), address is \" \n << info->si_addr << \" from \" << caller_address \n << std::endl << std::endl;\n\n void * array[50];\n int size = backtrace(array, 50);\n\n array[1] = caller_address;\n\n char ** messages = backtrace_symbols(array, size); \n\n // skip first stack frame (points here)\n for (int i = 1; i < size && messages != NULL; ++i)\n {\n char *mangled_name = 0, *offset_begin = 0, *offset_end = 0;\n\n // find parantheses and +address offset surrounding mangled name\n for (char *p = messages[i]; *p; ++p)\n {\n if (*p == '(') \n {\n mangled_name = p; \n }\n else if (*p == '+') \n {\n offset_begin = p;\n }\n else if (*p == ')')\n {\n offset_end = p;\n break;\n }\n }\n\n // if the line could be processed, attempt to demangle the symbol\n if (mangled_name && offset_begin && offset_end && \n mangled_name < offset_begin)\n {\n *mangled_name++ = '\\0';\n *offset_begin++ = '\\0';\n *offset_end++ = '\\0';\n\n int status;\n char * real_name = abi::__cxa_demangle(mangled_name, 0, 0, &status);\n\n // if demangling is successful, output the demangled function name\n if (status == 0)\n { \n std::cerr << \"[bt]: (\" << i << \") \" << messages[i] << \" : \" \n << real_name << \"+\" << offset_begin << offset_end \n << std::endl;\n\n }\n // otherwise, output the mangled function name\n else\n {\n std::cerr << \"[bt]: (\" << i << \") \" << messages[i] << \" : \" \n << mangled_name << \"+\" << offset_begin << offset_end \n << std::endl;\n }\n free(real_name);\n }\n // otherwise, print the whole line\n else\n {\n std::cerr << \"[bt]: (\" << i << \") \" << messages[i] << std::endl;\n }\n }\n std::cerr << std::endl;\n\n free(messages);\n\n exit(EXIT_FAILURE);\n}\n"
},
{
"answer_id": 6599348,
"author": "jhclark",
"author_id": 758067,
"author_profile": "https://Stackoverflow.com/users/758067",
"pm_score": 7,
"selected": false,
"text": "$ catchsegv program -o hai\n $ LD_PRELOAD=/lib/libSegFault.so program -o hai\n $ gcc -g1 -lSegFault -o program program.cc\n$ program -o hai\n $ export SEGFAULT_SIGNALS=\"all\" # \"all\" signals\n$ export SEGFAULT_SIGNALS=\"bus abrt\" # SIGBUS and SIGABRT\n *** Segmentation fault Register dump:\n\n EAX: 0000000c EBX: 00000080 ECX:\n00000000 EDX: 0000000c ESI:\nbfdbf080 EDI: 080497e0 EBP:\nbfdbee38 ESP: bfdbee20\n\n EIP: 0805640f EFLAGS: 00010282\n\n CS: 0073 DS: 007b ES: 007b FS:\n0000 GS: 0033 SS: 007b\n\n Trap: 0000000e Error: 00000004 \nOldMask: 00000000 ESP/signal:\nbfdbee20 CR2: 00000024\n\n FPUCW: ffff037f FPUSW: ffff0000 \nTAG: ffffffff IPOFF: 00000000 \nCSSEL: 0000 DATAOFF: 00000000 \nDATASEL: 0000\n\n ST(0) 0000 0000000000000000 ST(1)\n0000 0000000000000000 ST(2) 0000\n0000000000000000 ST(3) 0000\n0000000000000000 ST(4) 0000\n0000000000000000 ST(5) 0000\n0000000000000000 ST(6) 0000\n0000000000000000 ST(7) 0000\n0000000000000000\n\nBacktrace:\n/lib/libSegFault.so[0xb7f9e100]\n??:0(??)[0xb7fa3400]\n/usr/include/c++/4.3/bits/stl_queue.h:226(_ZNSt5queueISsSt5dequeISsSaISsEEE4pushERKSs)[0x805647a]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/player.cpp:73(_ZN6Player5inputESs)[0x805377c]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:159(_ZN6Socket4ReadEv)[0x8050698]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:413(_ZN12ServerSocket4ReadEv)[0x80507ad]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/socket.cpp:300(_ZN12ServerSocket4pollEv)[0x8050b44]\n/home/dbingham/src/middle-earth-mud/alpha6/src/engine/main.cpp:34(main)[0x8049a72]\n/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0xb7d1b775]\n/build/buildd/glibc-2.9/csu/../sysdeps/i386/elf/start.S:122(_start)[0x8049801]\n"
},
{
"answer_id": 15801966,
"author": "arr_sea",
"author_id": 1797414,
"author_profile": "https://Stackoverflow.com/users/1797414",
"pm_score": 4,
"selected": false,
"text": "BACKTRACE: testExe 0x8A5db6b\nFILE: pathToFile/testExe.C:110\nFUNCTION: testFunction(int) \n 107 \n 108 \n 109 int* i = 0x0;\n *110 *i = 5;\n 111 \n 112 }\n 113 return i;\n #!/bin/bash\n\nLOGFILE=$1\n\nNUM_SRC_CONTEXT_LINES=3\n\nold_IFS=$IFS # save the field separator \nIFS=$'\\n' # new field separator, the end of line \n\nfor bt in `cat $LOGFILE | grep '\\[bt\\]'`; do\n IFS=$old_IFS # restore default field separator \n printf '\\n'\n EXEC=`echo $bt | cut -d' ' -f3 | cut -d'(' -f1` \n ADDR=`echo $bt | cut -d'[' -f3 | cut -d']' -f1`\n echo \"BACKTRACE: $EXEC $ADDR\"\n A2L=`addr2line -a $ADDR -e $EXEC -pfC`\n #echo \"A2L: $A2L\"\n\n FUNCTION=`echo $A2L | sed 's/\\<at\\>.*//' | cut -d' ' -f2-99`\n FILE_AND_LINE=`echo $A2L | sed 's/.* at //'`\n echo \"FILE: $FILE_AND_LINE\"\n echo \"FUNCTION: $FUNCTION\"\n\n # print offending source code\n SRCFILE=`echo $FILE_AND_LINE | cut -d':' -f1`\n LINENUM=`echo $FILE_AND_LINE | cut -d':' -f2`\n if ([ -f $SRCFILE ]); then\n cat -n $SRCFILE | grep -C $NUM_SRC_CONTEXT_LINES \"^ *$LINENUM\\>\" | sed \"s/ $LINENUM/*$LINENUM/\"\n else\n echo \"File not found: $SRCFILE\"\n fi\n IFS=$'\\n' # new field separator, the end of line \ndone\n\nIFS=$old_IFS # restore default field separator \n"
},
{
"answer_id": 20556298,
"author": "jard18",
"author_id": 2980910,
"author_profile": "https://Stackoverflow.com/users/2980910",
"pm_score": 2,
"selected": false,
"text": "exit(status) abort()"
},
{
"answer_id": 22532288,
"author": "Daniil Iaitskov",
"author_id": 342882,
"author_profile": "https://Stackoverflow.com/users/342882",
"pm_score": 2,
"selected": false,
"text": "#include <iostream>\n#include <execinfo.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <unistd.h>\n#include <string>\n#include <cassert>\n\nusing namespace std;\n\n//#define STACK_OVERFLOW\n\n#ifdef STACK_OVERFLOW\nstatic char stack_body[64*1024];\nstatic stack_t sigseg_stack;\n#endif\n\nstatic struct sigaction sigseg_handler;\n\nvoid handler(int sig) {\n cerr << \"sig seg fault handler\" << endl;\n const int asize = 10;\n void *array[asize];\n size_t size;\n\n // get void*'s for all entries on the stack\n size = backtrace(array, asize);\n\n // print out all the frames to stderr\n cerr << \"stack trace: \" << endl;\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n cerr << \"resend SIGSEGV to get core dump\" << endl;\n signal(sig, SIG_DFL);\n kill(getpid(), sig);\n}\n\nvoid foo() {\n foo();\n}\n\nint main(int argc, char **argv) {\n#ifdef STACK_OVERFLOW\n sigseg_stack.ss_sp = stack_body;\n sigseg_stack.ss_flags = SS_ONSTACK;\n sigseg_stack.ss_size = sizeof(stack_body);\n assert(!sigaltstack(&sigseg_stack, nullptr));\n sigseg_handler.sa_flags = SA_ONSTACK;\n#else\n sigseg_handler.sa_flags = SA_RESTART; \n#endif\n sigseg_handler.sa_handler = &handler;\n assert(!sigaction(SIGSEGV, &sigseg_handler, nullptr));\n cout << \"sig action set\" << endl;\n foo();\n return 0;\n} \n"
},
{
"answer_id": 41404312,
"author": "Roy",
"author_id": 1040618,
"author_profile": "https://Stackoverflow.com/users/1040618",
"pm_score": 4,
"selected": false,
"text": "#include \"backward.hpp\"\nvoid stacker() {\n\nusing namespace backward;\nStackTrace st;\n\n\nst.load_here(99); //Limit the number of trace depth to 99\nst.skip_n_firsts(3);//This will skip some backward internal function from the trace\n\nPrinter p;\np.snippet = true;\np.object = true;\np.color = true;\np.address = true;\np.print(st, stderr);\n}\n"
},
{
"answer_id": 49050274,
"author": "IInspectable",
"author_id": 1889329,
"author_profile": "https://Stackoverflow.com/users/1889329",
"pm_score": 3,
"selected": false,
"text": "MiniDumpWriteDump"
},
{
"answer_id": 54427899,
"author": "baziorek",
"author_id": 1350091,
"author_profile": "https://Stackoverflow.com/users/1350091",
"pm_score": 4,
"selected": false,
"text": "#include <filesystem>\n#include <sstream>\n#include <fstream>\n#include <signal.h> // ::signal, ::raise\n#include <boost/stacktrace.hpp>\n\nconst char* backtraceFileName = \"./backtraceFile.dump\";\n\nvoid signalHandler(int)\n{\n ::signal(SIGSEGV, SIG_DFL);\n ::signal(SIGABRT, SIG_DFL);\n boost::stacktrace::safe_dump_to(backtraceFileName);\n ::raise(SIGABRT);\n}\n\nvoid sendReport()\n{\n if (std::filesystem::exists(backtraceFileName))\n {\n std::ifstream file(backtraceFileName);\n\n auto st = boost::stacktrace::stacktrace::from_dump(file);\n std::ostringstream backtraceStream;\n backtraceStream << st << std::endl;\n\n // sending the code from st\n\n file.close();\n std::filesystem::remove(backtraceFileName);\n }\n}\n\nint main()\n{\n ::signal(SIGSEGV, signalHandler);\n ::signal(SIGABRT, signalHandler);\n\n sendReport();\n // ... rest of code\n}\n g++ --std=c++17 file.cpp -lstdc++fs -lboost_stacktrace_backtrace -ldl -lbacktrace\n 0# bar(int) at /path/to/source/file.cpp:70\n1# bar(int) at /path/to/source/file.cpp:70\n2# bar(int) at /path/to/source/file.cpp:70\n3# bar(int) at /path/to/source/file.cpp:70\n4# main at /path/to/main.cpp:93\n5# __libc_start_main in /lib/x86_64-linux-gnu/libc.so.6\n6# _start\n"
},
{
"answer_id": 55626241,
"author": "Geoffrey",
"author_id": 637874,
"author_profile": "https://Stackoverflow.com/users/637874",
"pm_score": 2,
"selected": false,
"text": "bfd addr2line [E] crash.linux.c:170 | crit_err_hdlr | ==== FATAL CRASH (a12-151-g28b12c85f4+1) ====\n[E] crash.linux.c:171 | crit_err_hdlr | signal 11 (Segmentation fault), address is (nil)\n[E] crash.linux.c:194 | crit_err_hdlr | [trace]: (0) /home/geoff/Projects/LookingGlass/client/src/main.c:936 (register_key_binds)\n[E] crash.linux.c:194 | crit_err_hdlr | [trace]: (1) /home/geoff/Projects/LookingGlass/client/src/main.c:1069 (run)\n[E] crash.linux.c:194 | crit_err_hdlr | [trace]: (2) /home/geoff/Projects/LookingGlass/client/src/main.c:1314 (main)\n[E] crash.linux.c:199 | crit_err_hdlr | [trace]: (3) /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xeb) [0x7f8aa65f809b]\n[E] crash.linux.c:199 | crit_err_hdlr | [trace]: (4) ./looking-glass-client(_start+0x2a) [0x55c70fc4aeca]\n"
},
{
"answer_id": 71143028,
"author": "Oleksandr Kozlov",
"author_id": 2091463,
"author_profile": "https://Stackoverflow.com/users/2091463",
"pm_score": 1,
"selected": false,
"text": "gdb -ex 'set confirm off' -ex r -ex bt -ex q <my-program>\n"
},
{
"answer_id": 72486459,
"author": "Graham Toal",
"author_id": 210830,
"author_profile": "https://Stackoverflow.com/users/210830",
"pm_score": 0,
"selected": false,
"text": " if ((argc >= 1) && (strcmp(origargv[argc-1], \"--restarting-under-gdb\")) != 0) {\n // initial invocation\n // the \"--restarting-under-gdb\" option is how the copy running under gdb knows\n // not to start another gdb process.\n char *gdb [] = {\n \"/usr/bin/gdb\", \"-q\", \"-batch\", \"-nx\", \"-nh\", \"-return-child-result\",\n \"-ex\", \"run\",\n \"-ex\", \"bt full\",\n \"--args\"\n };\n GCCOPTS=\" -Wall -Wno-return-type -Wno-comment -g -fsanitize=undefined\n -fsanitize-undefined-trap-on-error -fno-sanitize-recover=all -frecord-gcc-switches\n -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -ftrapv\n -grecord-gcc-switches -O0 -ggdb3 \"\n"
},
{
"answer_id": 74549444,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 0,
"selected": false,
"text": "#include <execinfo.h>\n#include <signal.h>\n#include <stdlib.h>\n#include <unistd.h>\n\n#define TRACE_MAX 1024\n\nvoid handler(int sig) {\n (void)sig;\n void *array[TRACE_MAX];\n size_t size;\n const char msg[] = \"failed with a signal\\n\";\n\n size = backtrace(array, TRACE_MAX);\n write(STDERR_FILENO, msg, sizeof(msg));\n backtrace_symbols_fd(array, size, STDERR_FILENO);\n _Exit(1);\n}\n\nvoid my_func_2(void) {\n *((int*)0) = 1;\n}\n\nvoid my_func_1(double f) {\n (void)f;\n my_func_2();\n}\n\nvoid my_func_1(int i) {\n (void)i;\n my_func_2();\n}\n\nint main() {\n /* Make a dummy call to `backtrace` to load libgcc because man backrace says:\n * * backtrace() and backtrace_symbols_fd() don't call malloc() explicitly, but they are part of libgcc, which gets loaded dynamically when first used. Dynamic loading usually triggers a call to mal‐\n * loc(3). If you need certain calls to these two functions to not allocate memory (in signal handlers, for example), you need to make sure libgcc is loaded beforehand.\n */\n void *dummy[1];\n backtrace(dummy, 1);\n signal(SIGSEGV, handler);\n\n my_func_1(1);\n}\n g++ -ggdb3 -O2 -std=c++11 -Wall -Wextra -pedantic -rdynamic -o stacktrace_on_signal_safe.out stacktrace_on_signal_safe.cpp\n./stacktrace_on_signal_safe.out\n -rdynamic failed with a signal\n./stacktrace_on_signal_safe.out(_Z7handleri+0x6e)[0x56239398928e]\n/lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f04b1459520]\n./stacktrace_on_signal_safe.out(main+0x38)[0x562393989118]\n/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f04b1440d90]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f04b1440e40]\n./stacktrace_on_signal_safe.out(_start+0x25)[0x562393989155]\n c++filt ./stacktrace_on_signal_safe.out |& c++filt\n failed with a signal\n/stacktrace_on_signal_safe.out(handler(int)+0x6e)[0x55b6df43f28e]\n/lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f40d4167520]\n./stacktrace_on_signal_safe.out(main+0x38)[0x55b6df43f118]\n/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f40d414ed90]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f40d414ee40]\n./stacktrace_on_signal_safe.out(_start+0x25)[0x55b6df43f155]\n -O0 /stacktrace_on_signal_safe.out(handler(int)+0x76)[0x55d39b68325f]\n/lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f4d8ffdd520]\n./stacktrace_on_signal_safe.out(my_func_2()+0xd)[0x55d39b6832bb]\n./stacktrace_on_signal_safe.out(my_func_1(int)+0x14)[0x55d39b6832f1]\n./stacktrace_on_signal_safe.out(main+0x4a)[0x55d39b68333e]\n/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f4d8ffc4d90]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f4d8ffc4e40]\n./stacktrace_on_signal_safe.out(_start+0x25)[0x55d39b683125]\n addr2line -rdynamic g++ -ggdb3 -O0 -std=c++23 -Wall -Wextra -pedantic -o stacktrace_on_signal_safe.out stacktrace_on_signal_safe.cpp\n./stacktrace_on_signal_safe.out |& sed -r 's/.*\\(//;s/\\).*//' | addr2line -C -e stacktrace_on_signal_safe.out -f\n ??\n??:0\nhandler(int)\n/home/ciro/stacktrace_on_signal_safe.cpp:14\n??\n??:0\nmy_func_2()\n/home/ciro/stacktrace_on_signal_safe.cpp:22\nmy_func_1(i\n/home/ciro/stacktrace_on_signal_safe.cpp:33\nmain\n/home/ciro/stacktrace_on_signal_safe.cpp:45\n??\n??:0\n??\n??:0\n_start\n??:?\n awk +<addr> -rdynamic ./stacktrace_on_signal_safe.out(+0x125f)[0x55984828825f]\n/lib/x86_64-linux-gnu/libc.so.6(+0x42520)[0x7f8644a1e520]\n./stacktrace_on_signal_safe.out(+0x12bb)[0x5598482882bb]\n./stacktrace_on_signal_safe.out(+0x12f1)[0x5598482882f1]\n./stacktrace_on_signal_safe.out(+0x133e)[0x55984828833e]\n/lib/x86_64-linux-gnu/libc.so.6(+0x29d90)[0x7f8644a05d90]\n/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7f8644a05e40]\n./stacktrace_on_signal_safe.out(+0x1125)[0x559848288125]\n printf <stacktrace> boost::stacktrace::safe_dump_to #include <stacktrace>\n#include <iostream>\n\n#include <signal.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nvoid handler(int sig) {\n (void)sig;\n /* De-register this signal in the hope of avoiding infinite loops\n * if asyns signal unsafe things fail later on. But can likely still deadlock. */\n signal(sig, SIG_DFL);\n // std::stacktrace::current\n std::cout << std::stacktrace::current();\n // C99 async signal safe version of exit().\n _Exit(1);\n}\n\nvoid my_func_2(void) {\n *((int*)0) = 1;\n}\n\nvoid my_func_1(double f) {\n (void)f;\n my_func_2();\n}\n\nvoid my_func_1(int i) {\n (void)i;\n my_func_2();\n}\n\nint main() {\n signal(SIGSEGV, handler);\n my_func_1(1);\n}\n g++ -ggdb3 -O2 -std=c++23 -Wall -Wextra -pedantic -o stacktrace_on_signal.out stacktrace_on_signal.cpp -lstdc++_libbacktrace\n./stacktrace_on_signal.out\n 0# handler(int) at /home/ciro/stacktrace_on_signal.cpp:11\n 1# at :0\n 2# my_func_2() at /home/ciro/stacktrace_on_signal.cpp:16\n 3# at :0\n 4# at :0\n 5# at :0\n 6#\n my_func_1 -O0 0# handler(int) at /home/ciro/stacktrace_on_signal.cpp:11\n 1# at :0\n 2# my_func_2() at /home/ciro/stacktrace_on_signal.cpp:16\n 3# my_func_1(int) at /home/ciro/stacktrace_on_signal.cpp:26\n 4# at /home/ciro/stacktrace_on_signal.cpp:31\n 5# at :0\n 6# at :0\n 7# at :0\n 8#\n main backtrace_simple backtrace_simple /* BACKTRACE_USES_MALLOC will be #define'd as 1 if the backtrace\n library will call malloc as it works, 0 if it will call mmap\n instead. This may be used to determine whether it is safe to call\n the backtrace functions from a signal handler. In general this\n only applies to calls like backtrace and backtrace_pcinfo. It does\n not apply to backtrace_simple, which never calls malloc. It does\n not apply to backtrace_print, which always calls fprintf and\n therefore malloc. */\n std::basic_stacktrace std::stacktrace basic_stacktrace std::stacktrace boost::stacktrace::safe_dump_to echo 'core' | sudo tee /proc/sys/kernel/core_pattern\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
77,086 |
<p>Which is faster, python webpages or php webpages?</p>
<p>Does anyone know how the speed of pylons(or any of the other frameworks) compares to a similar website made with php? </p>
<p>I know that serving a python base webpage via cgi is slower than php because of its long start up every time.</p>
<p>I enjoy using pylons and I would still use it if it was slower than php. But if pylons was faster than php, I could maybe, hopefully, eventually convince my employer to allow me to convert the site over to pylons.</p>
|
[
{
"answer_id": 77174,
"author": "indentation",
"author_id": 7706,
"author_profile": "https://Stackoverflow.com/users/7706",
"pm_score": 2,
"selected": false,
"text": "\"hello world\""
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13778/"
] |
77,126 |
<p>What are some suggestions for easy to use C++ compilers for a beginner? Free or open-source ones would be preferred.</p>
|
[
{
"answer_id": 77307,
"author": "magpulse",
"author_id": 13581,
"author_profile": "https://Stackoverflow.com/users/13581",
"pm_score": 2,
"selected": false,
"text": "g++ -o myprogram myprogram.cc\nls -l myprogram\n"
},
{
"answer_id": 77519,
"author": "Cyber Oliveira",
"author_id": 9793,
"author_profile": "https://Stackoverflow.com/users/9793",
"pm_score": 0,
"selected": false,
"text": " c:\\temp> cl /nologo /EHsc /W4 foo.cpp\nc:\\temp> dir /b foo.*\nfoo.cpp <-- your source file\nfoo.obj <-- result of compiling the cpp file\nfoo.pdb <-- debugging symbols (friendly names for debugging)\nfoo.exe <-- result of linking the obj with libraries\n"
},
{
"answer_id": 77862,
"author": "KeyserSoze",
"author_id": 14116,
"author_profile": "https://Stackoverflow.com/users/14116",
"pm_score": 1,
"selected": false,
"text": "I say GCC for simple things because for a more complicated project the build process isn't so easy"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13846/"
] |
77,127 |
<p>I have exceptions created for every condition that my application does not expect. <code>UserNameNotValidException</code>, <code>PasswordNotCorrectException</code> etc.</p>
<p>However I was told I should not create exceptions for those conditions. In my UML those ARE exceptions to the main flow, so why should it not be an exception?</p>
<p>Any guidance or best practices for creating exceptions?</p>
|
[
{
"answer_id": 77164,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 8,
"selected": false,
"text": "UserHasDiedAtKeyboard"
},
{
"answer_id": 77179,
"author": "Jon",
"author_id": 12261,
"author_profile": "https://Stackoverflow.com/users/12261",
"pm_score": 4,
"selected": false,
"text": "throw catch"
},
{
"answer_id": 78087,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "void f1() throws ExceptionType1, ExceptionType2 {}\n\nvoid catchFunction() {\n try{\n while(someCondition){\n try{\n f1(); \n }catch(ExceptionType2 e2){\n //do something, don't break the loop\n }\n }\n }catch(ExceptionType1 e1){\n //break the loop, do something else\n }\n"
},
{
"answer_id": 78935,
"author": "Crusty",
"author_id": 9810,
"author_profile": "https://Stackoverflow.com/users/9810",
"pm_score": -1,
"selected": false,
"text": " If TypeName(ex) = \"UserException\" Then\n Display(ex.message)\n Else\n DisplayError(\"An unexpected error has occured, contact your help desk\") \n LogError(ex)\n End If\n"
},
{
"answer_id": 79931,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 2,
"selected": false,
"text": "{ // class\n ...\n\n public LoginResult Login(string user, string password)\n {\n if (IsInvalidUser(user))\n {\n return new UserInvalidLoginResult(user);\n }\n else if (IsInvalidPassword(user, password))\n {\n return new PasswordInvalidLoginResult(user, password);\n }\n else\n {\n return new SuccessfulLoginResult();\n }\n }\n\n ...\n}\n\npublic abstract class LoginResult\n{\n public readonly string Message;\n\n protected LoginResult(string message)\n {\n this.Message = message;\n }\n}\n\npublic class SuccessfulLoginResult : LoginResult\n{\n public SucccessfulLogin(string user)\n : base(string.Format(\"Login for user '{0}' was successful.\", user))\n { }\n}\n\npublic class UserInvalidLoginResult : LoginResult\n{\n public UserInvalidLoginResult(string user)\n : base(string.Format(\"The username '{0}' is invalid.\", user))\n { }\n}\n\npublic class PasswordInvalidLoginResult : LoginResult\n{\n public PasswordInvalidLoginResult(string password, string user)\n : base(string.Format(\"The password '{0}' for username '{0}' is invalid.\", password, user))\n { }\n}\n public class ValidatedLogin\n{\n public readonly string User;\n public readonly string Password;\n\n public ValidatedLogin(string user, string password)\n {\n if (IsInvalidUser(user))\n {\n throw new UserInvalidException(user);\n }\n else if (IsInvalidPassword(user, password))\n {\n throw new PasswordInvalidException(password);\n }\n\n this.User = user;\n this.Password = password;\n }\n\n public static bool TryCreate(string user, string password, out ValidatedLogin validatedLogin)\n {\n if (IsInvalidUser(user) || \n IsInvalidPassword(user, password))\n {\n return false;\n }\n\n validatedLogin = new ValidatedLogin(user, password);\n\n return true;\n }\n}\n"
},
{
"answer_id": 23236815,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "public class ValueReturnWithInfo<T>\n{\n public T Value{get;private set;}\n public string errorMsg{get;private set;}\n public ValueReturnWithInfo(T value,string errmsg)\n {\n Value = value;\n errMsg = errmsg;\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/279750/"
] |
77,128 |
<p>We have various php projects developed on windows (xampp) that need to be deployed to a mix of linux/windows servers. </p>
<p>We've used <a href="http://www.capify.org/" rel="nofollow noreferrer">capistrano</a> in the past to deploy from windows to the linux servers, but recent changes in architecture and windows servers left the old config not working. The recipe works fine for the linux deployment, but setting up the windows servers has required more time than we have right now. Ideas for the Capistrano recipe are valid answers. obviously the windows/linux servers don't share users, so this complicates it a tad (for the capistrano assumption of same username/password everywhere).</p>
<p>Currently we're using svn-update for the windows servers, which i dislike, since it leaves all the svn files hanging on the production servers. (and we still have to manually svn-update them on windows) And manual updating of files using winscp and syncing the directories with their linux counterparts.</p>
<p>My question is, what tools/setup do you suggest to automatize this deployment scenario:
<strong>"Various php windows/linux developers deploying to 2+ mixed windows/linux machines"</strong></p>
<p>(ps: we have no problems using linux tools or anything working through cygwin, we simply need to make deployment a simple one-step operation)</p>
<p><em>edit: Currently we can't work on a all-linux enviroment, we have to deploy to both linux and windows server. We can start the deploy from anywhere, but we'd prefer to be able to do it from either enviroment.</em></p>
|
[
{
"answer_id": 77440,
"author": "Bruce",
"author_id": 9698,
"author_profile": "https://Stackoverflow.com/users/9698",
"pm_score": 3,
"selected": true,
"text": "rsync svn svn rsync"
},
{
"answer_id": 82311,
"author": "rami",
"author_id": 9629,
"author_profile": "https://Stackoverflow.com/users/9629",
"pm_score": 0,
"selected": false,
"text": "svn:ignore svn update svn export /target/path/ .svn"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9114/"
] |
77,133 |
<p>I want to debug a windows C++ application I've written to see why it isn't responding to WM_QUERYENDSESSION how I expect it to. Clearly it's a little tricky to do this by just shutting the system down. Is there any utility or code which I can use to send a fake WM_QUERYENDSESSION to my application windows myself?</p>
|
[
{
"answer_id": 77496,
"author": "Bob Moore",
"author_id": 9368,
"author_profile": "https://Stackoverflow.com/users/9368",
"pm_score": 1,
"selected": false,
"text": "void CQes_testDlg::OnBtnTest() \n{ \n // enumerate all the top-level windows. \n m_ctrl_ListMsgs.ResetContent(); \n EnumWindows (EnumProc, 0); \n} \n\n\nBOOL CALLBACK EnumProc (HWND hTarget, LPARAM lParam) \n{ \n CString csTitle; \n CString csMsg; \n CWnd * pWnd = CWnd::FromHandle (hTarget); \n BOOL bRetVal = TRUE; \n DWORD dwPID; \n\n if (pWnd) \n { \n pWnd->GetWindowText (csTitle); \n if (csTitle.GetLength() == 0) \n { \n GetWindowThreadProcessId (hTarget, &dwPID); \n csTitle.Format (\"<PID=%d>\", dwPID); \n } \n\n if (pWnd->SendMessage (WM_QUERYENDSESSION, 0, ENDSESSION_LOGOFF)) \n { \n csMsg.Format (\"window 0x%X (%s) returned TRUE\", hTarget, csTitle); \n } \n else \n { \n csMsg.Format (\"window 0x%X (%s) returned FALSE\", hTarget, csTitle); \n bRetVal = FALSE; \n } \n\n mg_pThis->m_ctrl_ListMsgs.AddString (csMsg);\n }\n else \n { \n csMsg.Format (\"Unable to resolve HWND 0x%X to a CWnd\", hTarget); \n mg_pThis->m_ctrl_ListMsgs.AddString (csMsg); \n } \n return bRetVal; \n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1849/"
] |
77,171 |
<p>After reading Evan's and Nilsson's books I am still not sure how to manage Data access in a domain driven project. Should the CRUD methods be part of the repositories, i.e. OrderRepository.GetOrdersByCustomer(customer) or should they be part of the entities: Customer.GetOrders(). The latter approach seems more OO, but it will distribute Data Access for a single entity type among multiple objects, i.e. Customer.GetOrders(), Invoice.GetOrders(), ShipmentBatch.GetOrders() ,etc. What about Inserting and updating?</p>
|
[
{
"answer_id": 77275,
"author": "Chris Bilson",
"author_id": 12934,
"author_profile": "https://Stackoverflow.com/users/12934",
"pm_score": 5,
"selected": true,
"text": "CustomerRepo.GetThoseWhoHaventPaidTheirBill()\n\n// or\n\nGetCustomer(new HaventPaidBillSpecification())\n\n// is better than\n\nforeach (var customer in GetCustomer()) {\n /* logic leaking all over the floor */\n}\n"
},
{
"answer_id": 108610,
"author": "Stefan Moser",
"author_id": 8739,
"author_profile": "https://Stackoverflow.com/users/8739",
"pm_score": 2,
"selected": false,
"text": "customer.Orders;\n CustomerRepository.Add(customer);\nCustomerRepository.Get(customerID);\nCustomerRepository.Save(customer);\nCustomerRepository.Delete(customer);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2133/"
] |
77,172 |
<p>Do you guys keep track of stored procedures and database schema in your source control system of choice?</p>
<p>When you make a change (add a table, update an stored proc, how do you get the changes into source control? </p>
<p>We use SQL Server at work, and I've begun using darcs for versioning, but I'd be curious about general strategies as well as any handy tools.</p>
<p><em>Edit:</em> Wow, thanks for all the great suggestions, guys! I wish I could select more than one "Accepted Answer"!</p>
|
[
{
"answer_id": 77500,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 6,
"selected": true,
"text": "-- change #1234\nALTER TABLE asdf ADD COLUMN MyNewID INT\nGO\n\n-- change #5678\nALTER TABLE asdf DROP COLUMN SomeOtherID\nGO\n if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_MyProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)\ndrop procedure [usp_MyProc]\nGO\n\nCREATE PROCEDURE [usp_MyProc]\n(\n @UserID INT\n)\nAS\n\nSET NOCOUNT ON\n\n-- stored procedure logic.\n\nSET NOCOUNT OFF\n\nGO \n"
},
{
"answer_id": 77782,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Imports Microsoft.VisualStudio.SourceSafe.Interop\nImports System\nImports System.Configuration\n\nModule Module1\n\n Dim sourcesafeDataBase As String, sourcesafeUserName As String, sourcesafePassword As String, sourcesafeProjectName As String, fileFolderName As String\n\n\n Sub Main()\n If My.Application.CommandLineArgs.Count > 0 Then\n GetSetup()\n For Each thisOption As String In My.Application.CommandLineArgs\n Select Case thisOption.ToUpper\n Case \"CHECKIN\"\n DoCheckIn()\n Case \"CHECKOUT\"\n DoCheckOut()\n Case Else\n DisplayUsage()\n End Select\n Next\n Else\n DisplayUsage()\n End If\n End Sub\n\n Sub DisplayUsage()\n Console.Write(System.Environment.NewLine + \"Usage: SourceSafeUpdater option\" + System.Environment.NewLine + _\n \"CheckIn - Check in ( and adds any new ) files in the directory specified in .config\" + System.Environment.NewLine + _\n \"CheckOut - Check out all files in the directory specified in .config\" + System.Environment.NewLine + System.Environment.NewLine)\n End Sub\n\n Sub AddNewItems()\n Dim db As New VSSDatabase\n db.Open(sourcesafeDataBase, sourcesafeUserName, sourcesafePassword)\n Dim Proj As VSSItem\n Dim Flags As Integer = VSSFlags.VSSFLAG_DELTAYES + VSSFlags.VSSFLAG_RECURSYES + VSSFlags.VSSFLAG_DELNO\n Try\n Proj = db.VSSItem(sourcesafeProjectName, False)\n Proj.Add(fileFolderName, \"\", Flags)\n Catch ex As Exception\n If Not ex.Message.ToString.ToLower.IndexOf(\"already exists\") > 0 Then\n Console.Write(ex.Message)\n End If\n End Try\n Proj = Nothing\n db = Nothing\n End Sub\n\n Sub DoCheckIn()\n AddNewItems()\n Dim db As New VSSDatabase\n db.Open(sourcesafeDataBase, sourcesafeUserName, sourcesafePassword)\n Dim Proj As VSSItem\n Dim Flags As Integer = VSSFlags.VSSFLAG_DELTAYES + VSSFlags.VSSFLAG_UPDUPDATE + VSSFlags.VSSFLAG_FORCEDIRYES + VSSFlags.VSSFLAG_RECURSYES\n Proj = db.VSSItem(sourcesafeProjectName, False)\n Proj.Checkin(\"\", fileFolderName, Flags)\n Dim File As String\n For Each File In My.Computer.FileSystem.GetFiles(fileFolderName)\n Try\n Proj.Add(fileFolderName + File)\n Catch ex As Exception\n If Not ex.Message.ToString.ToLower.IndexOf(\"access code\") > 0 Then\n Console.Write(ex.Message)\n End If\n End Try\n Next\n Proj = Nothing\n db = Nothing\n End Sub\n\n Sub DoCheckOut()\n Dim db As New VSSDatabase\n db.Open(sourcesafeDataBase, sourcesafeUserName, sourcesafePassword)\n Dim Proj As VSSItem\n Dim Flags As Integer = VSSFlags.VSSFLAG_REPREPLACE + VSSFlags.VSSFLAG_RECURSYES\n Proj = db.VSSItem(sourcesafeProjectName, False)\n Proj.Checkout(\"\", fileFolderName, Flags)\n Proj = Nothing\n db = Nothing\n End Sub\n\n Sub GetSetup()\n sourcesafeDataBase = ConfigurationManager.AppSettings(\"sourcesafeDataBase\")\n sourcesafeUserName = ConfigurationManager.AppSettings(\"sourcesafeUserName\")\n sourcesafePassword = ConfigurationManager.AppSettings(\"sourcesafePassword\")\n sourcesafeProjectName = ConfigurationManager.AppSettings(\"sourcesafeProjectName\")\n fileFolderName = ConfigurationManager.AppSettings(\"fileFolderName\")\n\n End Sub\n\nEnd Module\n\n\n\n<add key=\"sourcesafeDataBase\" value=\"C:\\wherever\\srcsafe.ini\"/>\n<add key=\"sourcesafeUserName\" value=\"vssautomateuserid\"/>\n<add key=\"sourcesafePassword\" value=\"pw\"/>\n<add key=\"sourcesafeProjectName\" value=\"$/where/you/want/it\"/>\n<add key=\"fileFolderName\" value=\"d:\\yourdirstructure\"/>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7856/"
] |
77,213 |
<p>I have a large number of Enums that implement this interface:</p>
<pre><code>/**
* Interface for an enumeration, each element of which can be uniquely identified by its code
*/
public interface CodableEnum {
/**
* Get the element with a particular code
* @param code
* @return
*/
public CodableEnum getByCode(String code);
/**
* Get the code that identifies an element of the enum
* @return
*/
public String getCode();
}
</code></pre>
<p>A typical example is:</p>
<pre><code>public enum IMType implements CodableEnum {
MSN_MESSENGER("msn_messenger"),
GOOGLE_TALK("google_talk"),
SKYPE("skype"),
YAHOO_MESSENGER("yahoo_messenger");
private final String code;
IMType (String code) {
this.code = code;
}
public String getCode() {
return code;
}
public IMType getByCode(String code) {
for (IMType e : IMType.values()) {
if (e.getCode().equalsIgnoreCase(code)) {
return e;
}
}
}
}
</code></pre>
<p>As you can imagine these methods are virtually identical in all implementations of CodableEnum. I would like to eliminate this duplication, but frankly don't know how. I tried using a class such as the following:</p>
<pre><code>public abstract class DefaultCodableEnum implements CodableEnum {
private final String code;
DefaultCodableEnum(String code) {
this.code = code;
}
public String getCode() {
return this.code;
}
public abstract CodableEnum getByCode(String code);
}
</code></pre>
<p>But this turns out to be fairly useless because:</p>
<ol>
<li>An enum cannot extend a class</li>
<li>Elements of an enum (SKYPE, GOOGLE_TALK, etc.) cannot extend a class</li>
<li>I cannot provide a default implementation of getByCode(), because DefaultCodableEnum is not itself an Enum. I tried changing DefaultCodableEnum to extend java.lang.Enum, but this doesn't appear to be allowed.</li>
</ol>
<p>Any suggestions that do not rely on reflection?
Thanks,
Don</p>
|
[
{
"answer_id": 78306,
"author": "dave",
"author_id": 14355,
"author_profile": "https://Stackoverflow.com/users/14355",
"pm_score": 5,
"selected": true,
"text": "CodeableEnumHelper public class CodeableEnumHelper {\n public static CodeableEnum getByCode(String code, CodeableEnum[] values) {\n for (CodeableEnum e : values) {\n if (e.getCode().equalsIgnoreCase(code)) {\n return e;\n }\n }\n return null;\n }\n}\n CodeableEnum getByCode public enum IMType implements CodeableEnum {\n ...\n public IMType getByCode(String code) {\n return (IMType)CodeableEnumHelper.getByCode(code, this.values());\n } \n}\n"
},
{
"answer_id": 78511,
"author": "triggerNZ",
"author_id": 13822,
"author_profile": "https://Stackoverflow.com/users/13822",
"pm_score": 1,
"selected": false,
"text": "public interface CodeableEnum {\n String getCode();\n}\n import java.lang.reflect.InvocationTargetException;\n\n\npublic class CodeableEnumUtils {\n @SuppressWarnings(\"unchecked\")\n public static <T extends CodeableEnum> T getByCode(String code, Class<T> enumClass) throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {\n T[] allValues = (T[]) enumClass.getMethod(\"values\", new Class[0]).invoke(null, new Object[0]);\n for (T value : allValues) {\n if (value.getCode().equals(code)) {\n return value;\n }\n }\n return null;\n}\n import junit.framework.TestCase;\n\n\npublic class CodeableEnumUtilsTest extends TestCase {\n public void testWorks() throws Exception {\n assertEquals(A.ONE, CodeableEnumUtils.getByCode(\"one\", A.class));\n assertEquals(null, CodeableEnumUtils.getByCode(\"blah\", A.class));\n }\n\nenum A implements CodeableEnum {\n ONE(\"one\"), TWO(\"two\"), THREE(\"three\");\n\n private String code;\n\n private A(String code) {\n this.code = code;\n }\n\n public String getCode() {\n return code;\n } \n}\n}\n"
},
{
"answer_id": 81912,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 3,
"selected": false,
"text": "public class CodeableEnumHelper {\n public static <E extends CodeableEnum> E getByCode(\n String code, E[] values\n ) {\n for (E e : values) {\n if (e.getCode().equalsIgnoreCase(code)) {\n return e;\n }\n }\n return null;\n }\n}\n\npublic enum IMType implements CodableEnum {\n ...\n public IMType getByCode(String code) {\n return CodeableEnumHelper.getByCode(code, values());\n } \n}\n public class CodeableEnumHelper {\n public static <E extends CodeableEnum> Map<String,E> mapByCode(\n E[] values\n ) {\n Map<String,E> map = new HashMap<String,E>();\n for (E e : values) {\n map.put(e.getCode().toLowerCase(Locale.ROOT), value) {\n }\n return map;\n }\n}\n\npublic enum IMType implements CodableEnum {\n ...\n private static final Map<String,IMType> byCode =\n CodeableEnumHelper.mapByCode(values());\n public IMType getByCode(String code) {\n return byCode.get(code.toLowerCase(Locale.ROOT));\n } \n}\n"
},
{
"answer_id": 2471851,
"author": "sleske",
"author_id": 43681,
"author_profile": "https://Stackoverflow.com/users/43681",
"pm_score": 0,
"selected": false,
"text": "public enum MYENUM{\n VAL1,VAL2,VAL3;\n}\n\n/** Map MYENUM to its ID */\npublic static final ImmutableBiMap<MYENUM, Integer> MYENUM_TO_ID = \nnew ImmutableBiMap.Builder<MYENUM, Integer>().\nput(MYENUM.VAL1, 1).\nput(MYENUM.VAL2, 2).\nput(MYENUM.VAL3, 3).\nbuild();\n"
},
{
"answer_id": 2867061,
"author": "Marius Burz",
"author_id": 110750,
"author_profile": "https://Stackoverflow.com/users/110750",
"pm_score": 0,
"selected": false,
"text": "public interface EnumWithId {\n\n public int getId();\n\n}\n public <T extends EnumWithId> T getById(Class<T> enumClass, int id) {\n T[] values = enumClass.getEnumConstants();\n if (values != null) {\n for (T enumConst : values) {\n if (enumConst.getId() == id) {\n return enumConst;\n }\n }\n }\n\n return null;\n}\n MyUtil.getInstance().getById(MyEnum.class, myEnumId);\n"
},
{
"answer_id": 5368044,
"author": "bueyuekt",
"author_id": 668132,
"author_profile": "https://Stackoverflow.com/users/668132",
"pm_score": 1,
"selected": false,
"text": "interface EnumTypeIF {\nString getValue();\n\nEnumTypeIF fromValue(final String theValue);\n\nEnumTypeIF[] getValues();\n\nclass FromValue {\n private FromValue() {\n }\n\n public static EnumTypeIF valueOf(final String theValue, EnumTypeIF theEnumClass) {\n\n for (EnumTypeIF c : theEnumClass.getValues()) {\n if (c.getValue().equals(theValue)) {\n return c;\n }\n }\n throw new IllegalArgumentException(theValue);\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
77,226 |
<p>What is the easiest way to capitalize the first letter in each word of a string?</p>
|
[
{
"answer_id": 77237,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 4,
"selected": false,
"text": "$line = join \" \", map {ucfirst} split \" \", $line;\n"
},
{
"answer_id": 77249,
"author": "piCookie",
"author_id": 8763,
"author_profile": "https://Stackoverflow.com/users/8763",
"pm_score": 5,
"selected": true,
"text": "ucfirst()"
},
{
"answer_id": 77828,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 3,
"selected": false,
"text": "$string =~ s/(\\w+)/\\u$1/g;\n"
},
{
"answer_id": 163826,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 6,
"selected": false,
"text": "$_=\"what's the wrong answer?\";\ns/\\b(\\w)/\\U$1/g\nprint; \n s/([\\w']+)/\\u\\L$1/g\n"
},
{
"answer_id": 182104,
"author": "kixx",
"author_id": 11260,
"author_profile": "https://Stackoverflow.com/users/11260",
"pm_score": 4,
"selected": false,
"text": "$capitalized = join '', map { ucfirst lc $_ } split /(\\s+)/, $line;\n"
},
{
"answer_id": 9508413,
"author": "alemol",
"author_id": 1241476,
"author_profile": "https://Stackoverflow.com/users/1241476",
"pm_score": 2,
"selected": false,
"text": "perl -ne \"print (ucfirst($1)$2) if s/^(\\w)(.*)/\\1\\2/\" file\n"
},
{
"answer_id": 47477440,
"author": "bill god",
"author_id": 8557675,
"author_profile": "https://Stackoverflow.com/users/8557675",
"pm_score": 1,
"selected": false,
"text": "echo \"what's the wrong answer?\" |perl -pe 's/^/ /; s/\\s(\\w+)/ \\u$1/g; s/^ //'\n What's The Wrong Answer?\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77226",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13912/"
] |
77,258 |
<p>I am trying to solve the current problem using GPU capabilities: "given a point cloud P and an oriented plane described by a point and a normal (Pp, Np) return the points in the cloud which lye at a distance equal or less than EPSILON from the plane".</p>
<p>Talking with a colleague of mine I converged toward the following solution:</p>
<p>1) prepare a vertex buffer of the points with an attached texture coordinate such that every point has a different vertex coordinate
2) set projection status to orthogonal
3) rotate the mesh such that the normal of the plane is aligned with the -z axis and offset it such that x,y,z=0 corresponds to Pp
4) set the z-clipping plane such that z:[-EPSILON;+EPSILON]
5) render to a texture
6) retrieve the texture from the graphic card
7) read the texture from the graphic card and see what points were rendered (in terms of their indexes), which are the points within the desired distance range.</p>
<p>Now the problems are the following:
q1) Do I need to open a window-frame to be able to do such operation? I am working within MATLAB and calling MEX-C++. By experience I know that as soon as you open a new frame the whole suit crashes miserably!
q2) what's the primitive to give a GLPoint a texture coordinate?
q3) I am not too clear how the render to a texture would be implemented? any reference, tutorial would be awesome...
q4) How would you retrieve this texture from the card? again, any reference, tutorial would be awesome...</p>
<p>I am on a tight schedule, thus, it would be nice if you could point me out the names of the techniques I should learn about, rather to the GLSL specification document and the OpenGL API as somebody has done. Those are a tiny bit too vague answers to my question.</p>
<p>Thanks a lot for any comment.</p>
<p>p.s.
Also notice that I would rather not use any resource like CUDA if possible, thus, getting something which uses
as much OpenGL elements as possible without requiring me to write a new shader. </p>
<p>Note: cross posted at
<a href="http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=245911#Post245911" rel="nofollow noreferrer">http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=245911#Post245911</a></p>
|
[
{
"answer_id": 81165,
"author": "Sarien",
"author_id": 1994377,
"author_profile": "https://Stackoverflow.com/users/1994377",
"pm_score": 1,
"selected": false,
"text": "n_u = n/norm(n) //this is a normal vector of unit length\nd = scalarprod(n,x) //this is the distance of the plane to the origin\n\nfor each point p_i\n d_i = abs(scalarprod(p_i,n) - d) //this is the distance of the point to the plane\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
77,266 |
<p>Can I persuade <code>operator>></code> in C++ to read both a <code>hex</code> value AND and a <code>decimal</code> value? The following program demonstrates how reading hex goes wrong. I'd like the same <code>istringstream</code> to be able to read both <code>hex</code> and <code>decimal</code>.</p>
<pre><code>#include <iostream>
#include <sstream>
int main(int argc, char** argv)
{
int result = 0;
// std::istringstream is("5"); // this works
std::istringstream is("0x5"); // this fails
while ( is.good() ) {
if ( is.peek() != EOF )
is >> result;
else
break;
}
if ( is.fail() )
std::cout << "failed to read string" << std::endl;
else
std::cout << "successfully read string" << std::endl;
std::cout << "result: " << result << std::endl;
}
</code></pre>
|
[
{
"answer_id": 77359,
"author": "nsanders",
"author_id": 1244,
"author_profile": "https://Stackoverflow.com/users/1244",
"pm_score": 4,
"selected": false,
"text": "is >> std::hex >> result;\n"
},
{
"answer_id": 77360,
"author": "user10392",
"author_id": 10392,
"author_profile": "https://Stackoverflow.com/users/10392",
"pm_score": 5,
"selected": true,
"text": "std::setbase(0) 10 0x10 010 #include <iomanip>\nis >> std::setbase(0) >> result;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1359466/"
] |
77,278 |
<p>People also often ask "How can I compile Perl?" while what they really want is to create an executable that can run on machines even if they don't have Perl installed.</p>
<p>There are several solutions, I know of:</p>
<ol>
<li><a href="http://www.indigostar.com/perl2exe.htm" rel="noreferrer">perl2exe</a> of IndigoStar
It is commercial. I never tried. Its web site says it can cross compile Win32, Linux, and Solaris.</li>
<li><a href="http://www.activestate.com/Products/perl_dev_kit/" rel="noreferrer">Perl Dev Kit</a> from ActiveState.
It is commercial. I used it several years ago on Windows and it worked well for my needs. According to its web site it works on Windows, Mac OS X, Linux, Solaris, AIX and HP-UX.</li>
<li><a href="http://search.cpan.org/dist/PAR/" rel="noreferrer">PAR</a> or rather <a href="http://search.cpan.org/dist/PAR-Packer/" rel="noreferrer">PAR::Packer</a> that is free and open source. Based on the test reports it works on the Windows, Mac OS X, Linux, NetBSD and Solaris but theoretically it should work on other UNIX systems as well.
Recently I have started to use PAR for packaging on Linux and will use it on Windows as well.</li>
</ol>
<p>Other recommended solutions?</p>
|
[
{
"answer_id": 77325,
"author": "Bruce",
"author_id": 9698,
"author_profile": "https://Stackoverflow.com/users/9698",
"pm_score": -1,
"selected": false,
"text": "perlcc perl2exe"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11827/"
] |
77,287 |
<p>I have a <code>modal dialog</code> form which has some "help links" within it which should open other non-modal panels or dialogs on top of it (while keeping the main dialog otherwise modal). </p>
<p>However, these always end up behind the mask. <code>YUI</code> seems to be recognizing the highest <code>z-index</code> out there and setting the mask and modal dialog to be higher than that.</p>
<p>If i wait to panel-ize the help content, then i can set those to have a higher z-index. So far, so good. The problem then is that fields within the secondary, non-modal dialogs are unfocusable. The modal dialog beneath them seems to somehow be preventing the focus from going to anything not in the initial, modal dialog.</p>
<p>It would also be acceptable if i could do this "dialog group modality" with jQuery, if YUI simply won't allow this.</p>
<p>Help!</p>
|
[
{
"answer_id": 162315,
"author": "Bialecki",
"author_id": 2484,
"author_profile": "https://Stackoverflow.com/users/2484",
"pm_score": 3,
"selected": true,
"text": "YAHOO.widget.Overlay.prototype.bringToTop = function() { };\n this.bringToTop = function() { };\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8131/"
] |
77,293 |
<p>I would like to keep the overhead at a minimum. Right now I have:</p>
<pre><code>// Launch a Message Box with advice to the user
DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation);
// The test will only be launched if the user has selected Yes on the Message Box
if(result == DialogResult::Yes)
{
// Execute code
}
</code></pre>
<p>Unfortunately my client would prefer "Continue" and "Cancel" in place of the default "Yes" and "No" button text. It seems like there should be an easy way to do this.</p>
|
[
{
"answer_id": 77457,
"author": "Corin Blaikie",
"author_id": 1736,
"author_profile": "https://Stackoverflow.com/users/1736",
"pm_score": 3,
"selected": true,
"text": "MessageBoxButtons::YesNo MessageBoxButtons::OKCancel"
},
{
"answer_id": 86358,
"author": "Andrew Dunaway",
"author_id": 9058,
"author_profile": "https://Stackoverflow.com/users/9058",
"pm_score": 0,
"selected": false,
"text": "using namespace System::Windows::Forms;\n\n/// <summary>\n/// A message box for the test. Used to ensure user wishes to continue before starting the test.\n/// </summary>\npublic ref class CustomMessageBox : Form\n{\nprivate:\n /// Used to determine which button is pressed, default action is Cancel\n static String^ Button_ID_ = \"Cancel\";\n\n // GUI Elements\n Label^ warningLabel_;\n Button^ continueButton_;\n Button^ cancelButton_;\n\n // Button Events\n void CustomMessageBox::btnContinue_Click(System::Object^ sender, EventArgs^ e);\n void CustomMessageBox::btnCancel_Click(System::Object^ sender, EventArgs^ e);\n\n // Constructor is private. CustomMessageBox should be accessed through the public ShowBox() method\n CustomMessageBox();\n\npublic:\n /// <summary>\n /// Displays the CustomMessageBox and returns a string value of \"Continue\" or \"Cancel\"\n /// </summary>\n static String^ ShowBox();\n};\n #include \"StdAfx.h\"\n#include \"CustomMessageBox.h\"\n\nusing namespace System::Windows::Forms;\nusing namespace System::Drawing;\n\nCustomMessageBox::CustomMessageBox()\n{\n this->Size = System::Drawing::Size(420, 150);\n this->Text=\"Warning\";\n this->AcceptButton=continueButton_;\n this->CancelButton=cancelButton_;\n this->FormBorderStyle= ::FormBorderStyle::FixedDialog;\n this->StartPosition= FormStartPosition::CenterScreen;\n this->MaximizeBox=false;\n this->MinimizeBox=false;\n this->ShowInTaskbar=false;\n\n // Warning Label\n warningLabel_ = gcnew Label();\n warningLabel_->Text=\"This may take awhile, do you wish to continue?\";\n warningLabel_->Location=Point(5,5);\n warningLabel_->Size=System::Drawing::Size(400, 78);\n Controls->Add(warningLabel_);\n\n // Continue Button\n continueButton_ = gcnew Button();\n continueButton_->Text=\"Continue\";\n continueButton_->Location=Point(105,87);\n continueButton_->Size=System::Drawing::Size(70,22);\n continueButton_->Click += gcnew System::EventHandler(this, &CustomMessageBox::btnContinue_Click);\n Controls->Add(continueButton_);\n\n // Cancel Button\n cancelButton_ = gcnew Button();\n cancelButton_->Text=\"Cancel\";\n cancelButton_->Location=Point(237,87);\n cancelButton_->Size=System::Drawing::Size(70,22);\n cancelButton_->Click += gcnew System::EventHandler(this, &CustomMessageBox::btnCancel_Click);\n Controls->Add(cancelButton_);\n}\n\n/// <summary>\n/// Displays the CustomMessageBox and returns a string value of \"Continue\" or \"Cancel\", depending on the button\n/// clicked.\n/// </summary>\nString^ CustomMessageBox::ShowBox()\n{\n CustomMessageBox^ box = gcnew CustomMessageBox();\n box->ShowDialog();\n\n return Button_ID_;\n}\n\n/// <summary>\n/// Event handler: When the Continue button is clicked, set the Button_ID_ value and close the CustomMessageBox.\n/// </summary>\n/// <param name=\"sender\">The source of the event.</param>\n/// <param name=\"e\">The <see cref=\"System.EventArgs\"/> instance containing the event data.</param>\nvoid CustomMessageBox::btnContinue_Click(System::Object^ sender, EventArgs^ e)\n{\n Button_ID_ = \"Continue\";\n this->Close();\n}\n\n/// <summary>\n/// Event handler: When the Cancel button is clicked, set the Button_ID_ value and close the CustomMessageBox.\n/// </summary>\n/// <param name=\"sender\">The source of the event.</param>\n/// <param name=\"e\">The <see cref=\"System.EventArgs\"/> instance containing the event data.</param>\nvoid CustomMessageBox::btnCancel_Click(System::Object^ sender, EventArgs^ e)\n{\n Button_ID_ = \"Cancel\";\n this->Close();\n}\n // Launch a Message Box with advice to the user\nString^ result = CustomMessageBox::ShowBox();\n\n// The test will only be launched if the user has selected Continue on the Message Box\nif(result == \"Continue\")\n{\n // Execute Code\n}\n"
},
{
"answer_id": 13408763,
"author": "Namhwan Sung",
"author_id": 1828322,
"author_profile": "https://Stackoverflow.com/users/1828322",
"pm_score": 0,
"selected": false,
"text": "DialogResult result = MessageBox::Show(\n \"This may take awhile, do you wish to continue?**\\nClick Yes to continue.\\nClick No to cancel.**\",\n \"Warning\",\n MessageBoxButtons::YesNo,\n MessageBoxIcon::Exclamation\n);\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9058/"
] |
77,342 |
<p>The use of XSLT (XML Stylesheet Language Transform) has never seen the same popularity of many of the other languages that came out during the internet boom. While it is in use, and in some cases by large successful companies (i.e. Blizzard Entertainment), it has never seemed to reach mainstream. Why do you think this is?</p>
|
[
{
"answer_id": 77378,
"author": "Mo.",
"author_id": 1870,
"author_profile": "https://Stackoverflow.com/users/1870",
"pm_score": 2,
"selected": false,
"text": "<Really> \n <No>\n <fun/>\n </No>\n</Really> \n"
},
{
"answer_id": 77505,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 2,
"selected": false,
"text": "<xsl:variable name=\"lcletters\">abcdefghijklmnopqrstuvwxyz</xsl:variable>\n<xsl:variable name=\"ucletters\">ABCDEFGHIJKLMNOPQRSTUVWXYZ</xsl:variable> \n\n<xsl:value-of select=\"translate($toconvert,$lcletters,$ucletters)\"/>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13930/"
] |
77,382 |
<p>I have a class with a public array of bytes. Lets say its</p>
<pre><code>Public myBuff as byte()
</code></pre>
<p>Events within the class get chunks of data in byte array. How do i tell the event code to stick the get chunk on the end? Lets say</p>
<pre><code>Private Sub GetChunk
Dim chunk as byte
'... get stuff in chunk
Me.myBuff += chunk '(stick chunk on end of public array)
End sub
</code></pre>
<p>Or am I totally missing the point?</p>
|
[
{
"answer_id": 77449,
"author": "David J. Sokol",
"author_id": 1390,
"author_profile": "https://Stackoverflow.com/users/1390",
"pm_score": 0,
"selected": false,
"text": "ArrayList Add ToArray() ReDim Preserve array(newSize)"
},
{
"answer_id": 78059,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "public BufferSize as long 'or you can just use Ubound(mybuff), I prefer a tracker var tho\npublic MyBuff\n\nprivate sub GetChunk()\ndim chunk as byte\n'get stuff\nBufferSize=BufferSize+1\n\nredim preserve MyBuff(buffersize)\nmybuff(buffersize) = chunk\nend sub\n buffersize=buffersize+ubound(chunk) 'or if it's a fixed-size chunk, just use that number\nredim preserve mybuff(buffersize)\nfor k%=0 to ubound(chunk) 'copy new information to buffersize\n mybuff(k%+buffersize-ubound(chunk))=chunk(k%)\nnext\n public BufSize&,BufAlloc& 'initialize bufalloc to 1 or a number >= bufsize\npublic MyBuff() as byte\n\nsub getdata()\nbufsize=bufsize+ubound(chunk)\nif bufsize>bufalloc then\n bufalloc=bufalloc*2\n redim preserve mybuff(bufalloc)\nend if\nfor k%=0 to ubound(chunk) 'copy new information to buffersize\n mybuff(k%+bufsize-ubound(chunk))=chunk(k%)\nnext\nend sub\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
77,387 |
<p>In the Java collections framework, the Collection interface declares the following method:</p>
<blockquote>
<p><a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T%5B%5D)" rel="noreferrer"><code><T> T[] toArray(T[] a)</code></a></p>
<p>Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.</p>
</blockquote>
<p>If you wanted to implement this method, how would you create an array of the type of <strong>a</strong>, known only at runtime?</p>
|
[
{
"answer_id": 77426,
"author": "Arno",
"author_id": 13685,
"author_profile": "https://Stackoverflow.com/users/13685",
"pm_score": 2,
"selected": false,
"text": "Array.newInstance(Class componentType, int length)\n"
},
{
"answer_id": 77429,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 4,
"selected": false,
"text": "public <T> T[] toArray(T[] a) {\n if (a.length < size)\n a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);\n System.arraycopy(elementData, 0, a, 0, size);\n if (a.length > size)\n a[size] = null;\n return a;\n}\n"
},
{
"answer_id": 77474,
"author": "user9116",
"author_id": 9116,
"author_profile": "https://Stackoverflow.com/users/9116",
"pm_score": 6,
"selected": true,
"text": "java.lang.reflect.Array.newInstance(Class<?> componentType, int length)\n"
},
{
"answer_id": 77481,
"author": "Christian P.",
"author_id": 9479,
"author_profile": "https://Stackoverflow.com/users/9479",
"pm_score": -1,
"selected": false,
"text": "T[] newArray = (T[]) new Object[X]; // where X is the number of elements you want.\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13979/"
] |
77,428 |
<p>So if you have a RIA version (Silverlight or Flash) and a standard HTML version (or AJAX even), should you have the same URL for both, or is it ok to have a different one for the RIA app and just redirect accordingly?</p>
<p>So, for instance, if you have a site (<a href="http://example.com" rel="nofollow noreferrer">http://example.com</a>), is it ok to have the about page URL for the RIA app be <a href="http://example.com/#/about" rel="nofollow noreferrer">http://example.com/#/about</a> and the html be <a href="http://example.com/about" rel="nofollow noreferrer">http://example.com/about</a>? Does it matter? </p>
<p>Of course if you take the route with different URLs you will need to map between them. </p>
|
[
{
"answer_id": 78378,
"author": "Ian Dickinson",
"author_id": 6716,
"author_profile": "https://Stackoverflow.com/users/6716",
"pm_score": 3,
"selected": true,
"text": "http://your.si.te/foobar http://your.si.te/foobar?view=plain"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10893/"
] |
77,434 |
<p>Suppose I have a vector that is nested in a dataframe one or two levels. Is there a quick and dirty way to access the last value, without using the <code>length()</code> function? Something ala PERL's <code>$#</code> special var?</p>
<p>So I would like something like:</p>
<pre><code>dat$vec1$vec2[$#]
</code></pre>
<p>instead of</p>
<pre><code>dat$vec1$vec2[length(dat$vec1$vec2)]
</code></pre>
|
[
{
"answer_id": 83162,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 7,
"selected": false,
"text": "x[length(x)] \n last <- function(x) { return( x[length(x)] ) }\n"
},
{
"answer_id": 83222,
"author": "lindelof",
"author_id": 1428,
"author_profile": "https://Stackoverflow.com/users/1428",
"pm_score": 9,
"selected": false,
"text": "tail tail(vector, n=1)\n tail x[length(x)]"
},
{
"answer_id": 153852,
"author": "Florian Jenn",
"author_id": 23813,
"author_profile": "https://Stackoverflow.com/users/23813",
"pm_score": 6,
"selected": false,
"text": "last <- function(x) { tail(x, n = 1) }\n n= tail(x, 1) last pastecs head tail utils but.last <- function(x) { head(x, n = -1) }\n head tail"
},
{
"answer_id": 21706190,
"author": "James",
"author_id": 269476,
"author_profile": "https://Stackoverflow.com/users/269476",
"pm_score": 4,
"selected": false,
"text": "rev(dat$vect1$vec2)[1]\n"
},
{
"answer_id": 23638765,
"author": "scuerda",
"author_id": 1748028,
"author_profile": "https://Stackoverflow.com/users/1748028",
"pm_score": 4,
"selected": false,
"text": "system.time(\n resultsByLevel$subject <- sapply(resultsByLevel$variable, function(x) {\n s <- strsplit(x, \".\", fixed=TRUE)[[1]]\n s[length(s)]\n })\n )\n\n user system elapsed \n 3.722 0.000 3.594 \n system.time(\n resultsByLevel$subject <- sapply(resultsByLevel$variable, function(x) {\n s <- strsplit(x, \".\", fixed=TRUE)[[1]]\n tail(s, n=1)\n })\n )\n\n user system elapsed \n 28.174 0.000 27.662 \n"
},
{
"answer_id": 27992356,
"author": "Akash ",
"author_id": 2682018,
"author_profile": "https://Stackoverflow.com/users/2682018",
"pm_score": 4,
"selected": false,
"text": "a > a<-c(1:100,555)\n> end(a) #Gives indices of last and first positions\n[1] 101 1\n> a[end(a)[1]] #Gives last element in a vector\n[1] 555\n"
},
{
"answer_id": 32510333,
"author": "Kurt Ludikovsky",
"author_id": 4934536,
"author_profile": "https://Stackoverflow.com/users/4934536",
"pm_score": 3,
"selected": false,
"text": "> a <- c(1:100,555)\n> a[NROW(a)]\n[1] 555\n"
},
{
"answer_id": 37238415,
"author": "anonymous",
"author_id": 179927,
"author_profile": "https://Stackoverflow.com/users/179927",
"pm_score": 8,
"selected": false,
"text": "x[length(x)] mylast(x) mylast tail(x, n=1) dplyr::last(x) x[end(x)[1]]] rev(x)[1] Rcpp::cppFunction('double mylast(NumericVector x) { int n = x.size(); return x[n-1]; }')\noptions(width=100)\nfor (n in c(1e3,1e4,1e5,1e6,1e7)) {\n x <- runif(n);\n print(microbenchmark::microbenchmark(x[length(x)],\n mylast(x),\n tail(x, n=1),\n dplyr::last(x),\n x[end(x)[1]],\n rev(x)[1]))}\n Unit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 171 291.5 388.91 337.5 390.0 3233 100\n mylast(x) 1291 1832.0 2329.11 2063.0 2276.0 19053 100\n tail(x, n = 1) 7718 9589.5 11236.27 10683.0 12149.0 32711 100\n dplyr::last(x) 16341 19049.5 22080.23 21673.0 23485.5 70047 100\n x[end(x)[1]] 7688 10434.0 13288.05 11889.5 13166.5 78536 100\n rev(x)[1] 7829 8951.5 10995.59 9883.0 10890.0 45763 100\nUnit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 204 323.0 475.76 386.5 459.5 6029 100\n mylast(x) 1469 2102.5 2708.50 2462.0 2995.0 9723 100\n tail(x, n = 1) 7671 9504.5 12470.82 10986.5 12748.0 62320 100\n dplyr::last(x) 15703 19933.5 26352.66 22469.5 25356.5 126314 100\n x[end(x)[1]] 13766 18800.5 27137.17 21677.5 26207.5 95982 100\n rev(x)[1] 52785 58624.0 78640.93 60213.0 72778.0 851113 100\nUnit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 214 346.0 583.40 529.5 720.0 1512 100\n mylast(x) 1393 2126.0 4872.60 4905.5 7338.0 9806 100\n tail(x, n = 1) 8343 10384.0 19558.05 18121.0 25417.0 69608 100\n dplyr::last(x) 16065 22960.0 36671.13 37212.0 48071.5 75946 100\n x[end(x)[1]] 360176 404965.5 432528.84 424798.0 450996.0 710501 100\n rev(x)[1] 1060547 1140149.0 1189297.38 1180997.5 1225849.0 1383479 100\nUnit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 327 584.0 1150.75 996.5 1652.5 3974 100\n mylast(x) 2060 3128.5 7541.51 8899.0 9958.0 16175 100\n tail(x, n = 1) 10484 16936.0 30250.11 34030.0 39355.0 52689 100\n dplyr::last(x) 19133 47444.5 55280.09 61205.5 66312.5 105851 100\n x[end(x)[1]] 1110956 2298408.0 3670360.45 2334753.0 4475915.0 19235341 100\n rev(x)[1] 6536063 7969103.0 11004418.46 9973664.5 12340089.5 28447454 100\nUnit: nanoseconds\n expr min lq mean median uq max neval\n x[length(x)] 327 722.0 1644.16 1133.5 2055.5 13724 100\n mylast(x) 1962 3727.5 9578.21 9951.5 12887.5 41773 100\n tail(x, n = 1) 9829 21038.0 36623.67 43710.0 48883.0 66289 100\n dplyr::last(x) 21832 35269.0 60523.40 63726.0 75539.5 200064 100\n x[end(x)[1]] 21008128 23004594.5 37356132.43 30006737.0 47839917.0 105430564 100\n rev(x)[1] 74317382 92985054.0 108618154.55 102328667.5 112443834.0 187925942 100\n rev end O(1) tail dplyr::last O(1) mylast(x) x[length(x)] mylast(x) x[length(x)] x[length(x)]"
},
{
"answer_id": 37686960,
"author": "Enrique Pérez Herrero",
"author_id": 4678112,
"author_profile": "https://Stackoverflow.com/users/4678112",
"pm_score": 4,
"selected": false,
"text": "data.table last library(data.table)\nlast(c(1:10))\n# [1] 10\n"
},
{
"answer_id": 37687126,
"author": "Sam Firke",
"author_id": 4470365,
"author_profile": "https://Stackoverflow.com/users/4470365",
"pm_score": 5,
"selected": false,
"text": "last() last(mtcars$mpg)\n# [1] 21.4\n"
},
{
"answer_id": 43760585,
"author": "smoff",
"author_id": 6029286,
"author_profile": "https://Stackoverflow.com/users/6029286",
"pm_score": 2,
"selected": false,
"text": "last library(xts)\na <- 1:100\nlast(a)\n[1] 100\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14008/"
] |
77,436 |
<p>I have an ant build that makes directories, calls javac and all the regular stuff. The issue I am having is that when I try to do a clean (delete all the stuff that was generated) the delete task reports that is was unable to delete some files. When I try to delete them manually it works just fine. The files are apparently not open by any other process but ant still does not manage to delete them. What can I do?</p>
|
[
{
"answer_id": 53188224,
"author": "momo",
"author_id": 5118529,
"author_profile": "https://Stackoverflow.com/users/5118529",
"pm_score": 0,
"selected": false,
"text": "<rename src=\"file.name\" dest=\"file.name.old\"/>\n<delete file=\"file.name.old\" />\n"
},
{
"answer_id": 69431386,
"author": "Milan Patel",
"author_id": 14627788,
"author_profile": "https://Stackoverflow.com/users/14627788",
"pm_score": 0,
"selected": false,
"text": "sudo ant clean all"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8621/"
] |
77,485 |
<p>What do folks here see as the relative strengths and weaknesses of Git, Mercurial, and Bazaar?</p>
<p>In considering each of them with one another and against version control systems like SVN and Perforce, what issues should be considered?</p>
<p>In planning a migration from SVN to one of these distributed version control systems, what factors would you consider?</p>
|
[
{
"answer_id": 81563,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 1,
"selected": false,
"text": "git svn"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13750/"
] |
77,503 |
<p>I am trying to compare two large datasets from a SQL query. Right now the SQL query is done externally and the results from each dataset is saved into its own csv file. My little C# console application loads up the two text/csv files and compares them for differences and saves the differences to a text file.</p>
<p>Its a very simple application that just loads all the data from the first file into an arraylist and does a .compare() on the arraylist as each line is read from the second csv file. Then saves the records that don't match.</p>
<p>The application works but I would like to improve the performance. I figure I can greatly improve performance if I can take advantage of the fact that both files are sorted, but I don't know a datatype in C# that keeps order and would allow me to select a specific position. Theres a basic array, but I don't know how many items are going to be in each list. I could have over a million records. Is there a data type available that I should be looking at? </p>
|
[
{
"answer_id": 77617,
"author": "David J. Sokol",
"author_id": 1390,
"author_profile": "https://Stackoverflow.com/users/1390",
"pm_score": 2,
"selected": false,
"text": "StreamReader one = new StreamReader(\"C:\\file1.csv\");\nStreamReader two = new StreamReader(\"C:\\file2.csv\");\nString lineOne;\nString lineTwo;\n\nStreamWriter differences = new StreamWriter(\"Output.csv\");\nwhile (!one.EndOfStream)\n{\n lineOne = one.ReadLine();\n lineTwo = two.ReadLine();\n // do your comparison.\n bool areDifferent = true;\n\n if (areDifferent)\n differences.WriteLine(lineOne + lineTwo);\n}\n\none.Close();\ntwo.Close();\ndifferences.Close();\n"
},
{
"answer_id": 77932,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 1,
"selected": false,
"text": "StreamReader one = new StreamReader(\"C:\\file1.csv\");\nStreamReader two = new StreamReader(\"C:\\file2.csv\");\nString lineOne;\nString lineTwo;\nStreamWriter differences = new StreamWriter(\"Output.csv\");\nlineOne = one.ReadLine();\nlineTwo = two.ReadLine();\nwhile (!one.EndOfStream || !two.EndOfStream)\n{\n if(lineOne == lineTwo)\n {\n // lines match, read next line from each and continue\n lineOne = one.ReadLine();\n lineTwo = two.ReadLine();\n continue;\n }\n if(two.EndOfStream || lineOne < lineTwo)\n {\n differences.WriteLine(lineOne);\n lineOne = one.ReadLine();\n }\n if(one.EndOfStream || lineTwo < lineOne)\n {\n differences.WriteLine(lineTwo);\n lineTwo = two.ReadLine();\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8664/"
] |
77,528 |
<p>I'm currently running Vista and I would like to manually complete the same operations as my Windows Service. Since the Windows Service is running under the Local System Account, I would like to emulate this same behavior. Basically, I would like to run CMD.EXE under the Local System Account.</p>
<p>I found information online which suggests lauching the CMD.exe using the DOS Task Scheduler AT command, but I received a Vista warning that "due to security enhancements, this task will run at the time excepted but not interactively." Here's a sample command:</p>
<pre><code>AT 12:00 /interactive cmd.exe
</code></pre>
<p>Another solution suggested creating a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe. </p>
<pre><code>C:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact
C:\sc start RunCMDAsLSA
</code></pre>
<p>In this case the service fails to start and results it the following error message:</p>
<pre><code>FAILED 1053: The service did not respond to the start or control request in a timely fashion.
</code></pre>
<p>The third suggestion was to launch CMD.exe via a Scheduled Task. Though you may run scheduled tasks under various accounts, I don't believe the Local System Account is one of them.</p>
<p>I've tried using the Runas as well, but think I'm running into the same restriction as found when running a scheduled task.</p>
<p>Thus far, each of my attempts have ended in failure. Any suggestions?</p>
|
[
{
"answer_id": 77615,
"author": "Bryant",
"author_id": 10893,
"author_profile": "https://Stackoverflow.com/users/10893",
"pm_score": 3,
"selected": false,
"text": "sc create testsvc binpath= \"cmd /K start\" type= own type= interact"
},
{
"answer_id": 78691,
"author": "Ben Griswold",
"author_id": 4115,
"author_profile": "https://Stackoverflow.com/users/4115",
"pm_score": 9,
"selected": true,
"text": "psexec -i -s cmd.exe\n"
},
{
"answer_id": 16974787,
"author": "raven",
"author_id": 2461825,
"author_profile": "https://Stackoverflow.com/users/2461825",
"pm_score": 6,
"selected": false,
"text": "cd \\ psexec -i -s cmd.exe whoami start explorer.exe"
},
{
"answer_id": 30543362,
"author": "raven",
"author_id": 2461825,
"author_profile": "https://Stackoverflow.com/users/2461825",
"pm_score": 3,
"selected": false,
"text": "cmd.exe system CMD REG ADD \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osk.exe\" /v Debugger /t REG_SZ /d \"C:\\windows\\system32\\cmd.exe\"\n CMD CMD REG ADD \"HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\osk.exe\" /v Debugger /t REG_SZ /d \"C:\\windows\\system32\\cmd.exe\"\n osk NT Authority\\SYSTEM OSK CMD whoami NT Authority\\System Cmd.exe PsExec OSK CMD.exe CMD"
},
{
"answer_id": 50881442,
"author": "anton_rh",
"author_id": 5447906,
"author_profile": "https://Stackoverflow.com/users/5447906",
"pm_score": 1,
"selected": false,
"text": "Shift Restart C:\\Windows C:\\Windows\\System32 X:\\Windows X:\\Windows\\System32 PATH"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4115/"
] |
77,534 |
<p>When running wsdl.exe on a WSDL I created, I get this error:</p>
<blockquote>
<p>Error: Unable to import binding 'SomeBinding' from namespace 'SomeNS'.</p>
<ul>
<li>Unable to import operation 'someOperation'.</li>
<li>These members may not be derived.</li>
</ul>
</blockquote>
<p>I'm using the document-literal style, and to the best of my knowledge I'm following all the rules.</p>
<p>To sum it up, I have a valid WSDL, but the tool doesn't like it.</p>
<p>What I'm looking for is if someone has lots of experience with the wsdl.exe tool and knows about some secret gotcha that I don't.</p>
|
[
{
"answer_id": 4269920,
"author": "mo.",
"author_id": 178454,
"author_profile": "https://Stackoverflow.com/users/178454",
"pm_score": 3,
"selected": false,
"text": "<wsdl:message name=\"AnfrageRisikoAnfrageL\">\n <wsdl:part name=\"parameters\" element=\"his1_0:typeIn\"/>\n</wsdl:message>\n<wsdl:message name=\"AnfrageRisikoAntwortL\">\n <wsdl:part name=\"parameters\" element=\"his1_0:typeOut\"/>\n</wsdl:message>\n <wsdl:message name=\"AnfrageRisikoAnfrageL\">\n <wsdl:part name=\"in\" element=\"his1_0:typeIn\"/>\n</wsdl:message>\n<wsdl:message name=\"AnfrageRisikoAntwortL\">\n <wsdl:part name=\"out\" element=\"his1_0:typeOut\"/>\n</wsdl:message>\n"
},
{
"answer_id": 27252843,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 2,
"selected": false,
"text": "xsd ?wsdl ?singleWsdl .wsdl .svc Visual studio command prompt Visual studio command prompt wsdl.exe C:\\WebPricingService.wsdl\n C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\bin\\amd64\\WebPricingService.cs"
},
{
"answer_id": 44764622,
"author": "Alex Sk",
"author_id": 5284180,
"author_profile": "https://Stackoverflow.com/users/5284180",
"pm_score": 0,
"selected": false,
"text": "<wsdl:operation name=\"FormatReport\">\n <wsdl:documentation>Runs a report, which is returned as the response</wsdl:documentation>\n <wsdl:input message=\"FormatReportRequest\" />\n <wsdl:output message=\"FormatReportResponse\" />\n</wsdl:operation>\n <wsdl:message name=\"FormatReportRequest\">\n <wsdl:part name=\"parameters\" element=\"reporting:FormatReportInput\" />\n</wsdl:message>\n <wsdl:operation name=\"FormatReportAsync\">\n <wsdl:documentation>Creates and submits an Async Report Job to be executed asynchronously by the Async Report Windows Service.</wsdl:documentation>\n <wsdl:input message=\"FormatReportAsyncRequest\" />\n <wsdl:output message=\"FormatReportAsyncResponse\" />\n</wsdl:operation>\n <wsdl:message name=\"FormatReportAsyncRequest\">\n <wsdl:part name=\"parameters\" element=\"reporting:FormatReportInputAsync\" />\n </wsdl:message>\n <xsd:element name=\"FormatReportInput\" type=\"reporting:FormatReportInputType\"/>\n<xsd:element name=\"FormatReportInputAsync\" type=\"reporting:FormatReportAsyncInputType\"/>\n reporting:FormatReportAsyncInputType reporting:FormatReportInputType"
},
{
"answer_id": 52749635,
"author": "user2242618",
"author_id": 2242618,
"author_profile": "https://Stackoverflow.com/users/2242618",
"pm_score": 0,
"selected": false,
"text": "WSDL /Language:VB /out:\"C:\\wsdl\\Ship.vb\" \"C:\\wsdl\\Ship.wsdl\" C:\\wsdl\\UPSSecurity.xsd C:\\wsdl\\ShipWebServiceSchema.xsd C:\\wsdl\\IFWS.xsd C:\\wsdl\\common.xsd\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5726/"
] |
77,535 |
<p>Has anyone found a way to get gcc to build/install on SCO6? With 2.95 and 4.3 I get to the point where it needs to use (2.95) or find (4.3) the assembler and that's where it fails.</p>
<p>If anyone has figured this out I would appreciate the info!</p>
<p>Thanks</p>
|
[
{
"answer_id": 4269920,
"author": "mo.",
"author_id": 178454,
"author_profile": "https://Stackoverflow.com/users/178454",
"pm_score": 3,
"selected": false,
"text": "<wsdl:message name=\"AnfrageRisikoAnfrageL\">\n <wsdl:part name=\"parameters\" element=\"his1_0:typeIn\"/>\n</wsdl:message>\n<wsdl:message name=\"AnfrageRisikoAntwortL\">\n <wsdl:part name=\"parameters\" element=\"his1_0:typeOut\"/>\n</wsdl:message>\n <wsdl:message name=\"AnfrageRisikoAnfrageL\">\n <wsdl:part name=\"in\" element=\"his1_0:typeIn\"/>\n</wsdl:message>\n<wsdl:message name=\"AnfrageRisikoAntwortL\">\n <wsdl:part name=\"out\" element=\"his1_0:typeOut\"/>\n</wsdl:message>\n"
},
{
"answer_id": 27252843,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 2,
"selected": false,
"text": "xsd ?wsdl ?singleWsdl .wsdl .svc Visual studio command prompt Visual studio command prompt wsdl.exe C:\\WebPricingService.wsdl\n C:\\Program Files (x86)\\Microsoft Visual Studio 12.0\\VC\\bin\\amd64\\WebPricingService.cs"
},
{
"answer_id": 44764622,
"author": "Alex Sk",
"author_id": 5284180,
"author_profile": "https://Stackoverflow.com/users/5284180",
"pm_score": 0,
"selected": false,
"text": "<wsdl:operation name=\"FormatReport\">\n <wsdl:documentation>Runs a report, which is returned as the response</wsdl:documentation>\n <wsdl:input message=\"FormatReportRequest\" />\n <wsdl:output message=\"FormatReportResponse\" />\n</wsdl:operation>\n <wsdl:message name=\"FormatReportRequest\">\n <wsdl:part name=\"parameters\" element=\"reporting:FormatReportInput\" />\n</wsdl:message>\n <wsdl:operation name=\"FormatReportAsync\">\n <wsdl:documentation>Creates and submits an Async Report Job to be executed asynchronously by the Async Report Windows Service.</wsdl:documentation>\n <wsdl:input message=\"FormatReportAsyncRequest\" />\n <wsdl:output message=\"FormatReportAsyncResponse\" />\n</wsdl:operation>\n <wsdl:message name=\"FormatReportAsyncRequest\">\n <wsdl:part name=\"parameters\" element=\"reporting:FormatReportInputAsync\" />\n </wsdl:message>\n <xsd:element name=\"FormatReportInput\" type=\"reporting:FormatReportInputType\"/>\n<xsd:element name=\"FormatReportInputAsync\" type=\"reporting:FormatReportAsyncInputType\"/>\n reporting:FormatReportAsyncInputType reporting:FormatReportInputType"
},
{
"answer_id": 52749635,
"author": "user2242618",
"author_id": 2242618,
"author_profile": "https://Stackoverflow.com/users/2242618",
"pm_score": 0,
"selected": false,
"text": "WSDL /Language:VB /out:\"C:\\wsdl\\Ship.vb\" \"C:\\wsdl\\Ship.wsdl\" C:\\wsdl\\UPSSecurity.xsd C:\\wsdl\\ShipWebServiceSchema.xsd C:\\wsdl\\IFWS.xsd C:\\wsdl\\common.xsd\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14046/"
] |
77,552 |
<p>Why is it bad to name a variable <code>id</code> in Python?</p>
|
[
{
"answer_id": 77606,
"author": "brian buck",
"author_id": 5926,
"author_profile": "https://Stackoverflow.com/users/5926",
"pm_score": 2,
"selected": false,
"text": "id id some_id ID >>> id(1)\n9787760\n>>> x = 1\n>>> id(x)\n9787760\n"
},
{
"answer_id": 77612,
"author": "Kevin Little",
"author_id": 14028,
"author_profile": "https://Stackoverflow.com/users/14028",
"pm_score": 9,
"selected": true,
"text": "id() id __builtin__ id(...)\n\n id(object) -> integer\n\n Return the identity of an object. This is guaranteed to be unique among\n simultaneously existing objects. (Hint: it's the object's memory\n address.)\n"
},
{
"answer_id": 77925,
"author": "Sebastian Rittau",
"author_id": 7779,
"author_profile": "https://Stackoverflow.com/users/7779",
"pm_score": 6,
"selected": false,
"text": "id()"
},
{
"answer_id": 79198,
"author": "Nathan Shively-Sanders",
"author_id": 7851,
"author_profile": "https://Stackoverflow.com/users/7851",
"pm_score": 6,
"selected": false,
"text": "id id builtins.id __builtins__.id id def numbered(filename):\n with open(filename) as file:\n for i, input in enumerate(file):\n print(\"%s:\\t%s\" % (i, input), end='')\n id file list dict map all any complex int dir input slice buffer sum min max object"
},
{
"answer_id": 28091085,
"author": "DavidRR",
"author_id": 1497596,
"author_profile": "https://Stackoverflow.com/users/1497596",
"pm_score": 7,
"selected": false,
"text": "single_trailing_underscore_ Tkinter.Toplevel(master, class_='ClassName') id_ = 42\n"
},
{
"answer_id": 62973285,
"author": "wjandrea",
"author_id": 4518341,
"author_profile": "https://Stackoverflow.com/users/4518341",
"pm_score": 3,
"selected": false,
"text": "id id class Employee:\n def __init__(self, name, id):\n \"\"\"Create employee, with their name and badge id.\"\"\"\n self.name = name\n self.id = id\n # ... lots more code, making you forget about the parameter names\n print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))\n\ntay = Employee('Taylor Swift', 1985)\n Created Employee 'Taylor Swift' at 0x7efde30ae910\n Traceback (most recent call last):\n File \"company.py\", line 9, in <module>\n tay = Employee('Taylor Swift', 1985)\n File \"company.py\", line 7, in __init__\n print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))\nTypeError: 'int' object is not callable\n badge_id id_"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5926/"
] |
77,558 |
<p>I want to write a raw byte/byte stream to a position in a file.
This is what I have currently:</p>
<pre><code>$fpr = fopen($out, 'r+');
fseek($fpr, 1); //seek to second byte
fwrite($fpr, 0x63);
fclose($fpr);
</code></pre>
<p>This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99.</p>
<p>Thanks for your time.</p>
|
[
{
"answer_id": 77585,
"author": "nsayer",
"author_id": 13757,
"author_profile": "https://Stackoverflow.com/users/13757",
"pm_score": 4,
"selected": true,
"text": "fwrite() chr(0x63) 0x63"
},
{
"answer_id": 77597,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 1,
"selected": false,
"text": "fwrite($fpr, \"\\x63\");\n"
},
{
"answer_id": 77626,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 2,
"selected": false,
"text": "fwrite($fpr, chr(0x63));\n"
},
{
"answer_id": 8965004,
"author": "Christian",
"author_id": 314056,
"author_profile": "https://Stackoverflow.com/users/314056",
"pm_score": 0,
"selected": false,
"text": "pack()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10333/"
] |
77,582 |
<p>I am looking for a tool for regression testing a suite of equipment we are building.</p>
<p>The current concept is that you create an input file (text/csv) to the tool specifying inputs to the system under test. The tool then captures the outputs from the system and records the inputs and outputs to an output file. </p>
<p>The output is in the same format as the original input file and can be used as an input for following runs of the tool, with the measured outputs matched with the values from the previous run. </p>
<p>The results of two runs will not be exact matches, there are some timing differences that depend on the state of the battery, or which depend on other internal state of the equipment.</p>
<p>We would have to write our own interfaces to pass the commands from the tool to the equipment and to capture the output of the equipment.</p>
<p>This is a relatively simple task, but I am looking for an existing tool / package / library to avoid re-inventing the wheel / steal lessons from.</p>
|
[
{
"answer_id": 77684,
"author": "apenwarr",
"author_id": 42219,
"author_profile": "https://Stackoverflow.com/users/42219",
"pm_score": 0,
"selected": false,
"text": "x = read_input_file(ifilename);\ny1 = read_expected_data(ofilename);\nsend_input_file_to_server();\ny2 = read_output_from_server();\ncheckequal(y1, y2)\n"
},
{
"answer_id": 77729,
"author": "apenwarr",
"author_id": 42219,
"author_profile": "https://Stackoverflow.com/users/42219",
"pm_score": 2,
"selected": false,
"text": "test 0 == $(git diff data/output/ | wc -l)\n"
},
{
"answer_id": 84903,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 1,
"selected": false,
"text": "diff"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13923/"
] |
77,632 |
<p>I thought I'd offer this softball to whomever would like to hit it out of the park. What are generics, what are the advantages of generics, why, where, how should I use them? Please keep it fairly basic. Thanks.</p>
|
[
{
"answer_id": 77691,
"author": "Tom Kidd",
"author_id": 2577,
"author_profile": "https://Stackoverflow.com/users/2577",
"pm_score": 3,
"selected": false,
"text": "Dictionary<int, string> dictionary = new Dictionary<int, string>();\n"
},
{
"answer_id": 77716,
"author": "Kevin Pang",
"author_id": 1574,
"author_profile": "https://Stackoverflow.com/users/1574",
"pm_score": 2,
"selected": false,
"text": "List<SomeCustomClass> blah = new List<SomeCustomClass>();\nblah[0].SomeCustomFunction();\n"
},
{
"answer_id": 77956,
"author": "Vin",
"author_id": 1747,
"author_profile": "https://Stackoverflow.com/users/1747",
"pm_score": 1,
"selected": false,
"text": "List<Customer> custCollection = new List<Customer>;\n object[] custCollection = new object[] { cust1, cust2 };\n"
},
{
"answer_id": 79281,
"author": "etchasketch",
"author_id": 14640,
"author_profile": "https://Stackoverflow.com/users/14640",
"pm_score": 2,
"selected": false,
"text": "class Pair<F, S> {\n public final F first;\n public final S second;\n\n public Pair(F f, S s)\n { \n first = f;\n second = s; \n }\n} \n public class FooManager <F extends Foo>{\n public void setTitle(F foo, String title) {\n foo.setTitle(title);\n }\n}\n"
},
{
"answer_id": 79857,
"author": "Dean Poulin",
"author_id": 5462,
"author_profile": "https://Stackoverflow.com/users/5462",
"pm_score": 3,
"selected": false,
"text": "public interface IEntity\n{\n\n}\n\npublic class Employee : IEntity\n{\n public string FirstName { get; set; }\n public string LastName { get; set; }\n public int EmployeeID { get; set; }\n}\n\npublic class Company : IEntity\n{\n public string Name { get; set; }\n public string TaxID { get; set }\n}\n\npublic class DataService<ENTITY, DATACONTEXT>\n where ENTITY : class, IEntity, new()\n where DATACONTEXT : DataContext, new()\n{\n\n public void Create(List<ENTITY> entities)\n {\n using (DATACONTEXT db = new DATACONTEXT())\n {\n Table<ENTITY> table = db.GetTable<ENTITY>();\n\n foreach (ENTITY entity in entities)\n table.InsertOnSubmit (entity);\n\n db.SubmitChanges();\n }\n }\n}\n\npublic class MyTest\n{\n public void DoSomething()\n {\n var dataService = new DataService<Employee, MyDataContext>();\n dataService.Create(new Employee { FirstName = \"Bob\", LastName = \"Smith\", EmployeeID = 5 });\n var otherDataService = new DataService<Company, MyDataContext>();\n otherDataService.Create(new Company { Name = \"ACME\", TaxID = \"123-111-2233\" });\n\n }\n}\n"
},
{
"answer_id": 953645,
"author": "victor hugo",
"author_id": 70616,
"author_profile": "https://Stackoverflow.com/users/70616",
"pm_score": 1,
"selected": false,
"text": "public abstract class GenericDaoHibernateImpl<T> \n extends HibernateDaoSupport {\n\n private Class<T> type;\n\n public GenericDaoHibernateImpl(Class<T> clazz) {\n type = clazz;\n }\n\n public void update(T object) {\n getHibernateTemplate().update(object);\n }\n\n @SuppressWarnings(\"unchecked\")\n public Integer count() {\n return ((Integer) getHibernateTemplate().execute(\n new HibernateCallback() {\n public Object doInHibernate(Session session) {\n // Code in Hibernate for getting the count\n }\n }));\n }\n .\n .\n .\n}\n public class UserDaoHibernateImpl extends GenericDaoHibernateImpl<User> {\n public UserDaoHibernateImpl() {\n super(User.class); // This is for giving Hibernate a .class\n // work with, as generics disappear at runtime\n }\n\n // Entity specific methods here\n}\n"
},
{
"answer_id": 953646,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 0,
"selected": false,
"text": "List<Stuff> stuffList = getStuff();\nfor(Stuff stuff : stuffList) {\n stuff.do();\n}\n List stuffList = getStuff();\nIterator i = stuffList.iterator();\nwhile(i.hasNext()) {\n Stuff stuff = (Stuff)i.next();\n stuff.do();\n}\n List stuffList = getStuff();\nfor(int i = 0; i < stuffList.size(); i++) {\n Stuff stuff = (Stuff)stuffList.get(i);\n stuff.do();\n}\n"
},
{
"answer_id": 953647,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 4,
"selected": false,
"text": "NullPointerException ClassCastException"
},
{
"answer_id": 953655,
"author": "Peter Lange",
"author_id": 80164,
"author_profile": "https://Stackoverflow.com/users/80164",
"pm_score": 3,
"selected": false,
"text": "public class Foo\n{\n public string Bar() { return \"Bar\"; }\n}\n Arraylist al = new ArrayList();\nList<Foo> fl = new List<Foo>();\n\n//code to add Foos\nal.Add(new Foo());\nf1.Add(new Foo());\n foreach(object o in al)\n{\n Foo f = (Foo)o;\n f.Bar();\n}\n\nforeach(Foo f in fl)\n{\n f.Bar();\n}\n"
},
{
"answer_id": 953683,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 6,
"selected": false,
"text": "class MyObjectList {\n MyObject get(int index) {...}\n}\nclass MyOtherObjectList {\n MyOtherObject get(int index) {...}\n}\nclass AnotherObjectList {\n AnotherObject get(int index) {...}\n}\n class MyList<T> {\n T get(int index) { ... }\n}\n Callable<T> Reference<T> Callable<T> Future<T>"
},
{
"answer_id": 953755,
"author": "jigawot",
"author_id": 117724,
"author_profile": "https://Stackoverflow.com/users/117724",
"pm_score": 2,
"selected": false,
"text": "private <T extends Throwable> T logAndReturn(T t) {\n logThrowable(t); // some logging method that takes a Throwable\n return t;\n}\n ...\n} catch (MyException e) {\n throw logAndReturn(e);\n}\n Throwable ...\nMap<String, Integer> myMap = createHashMap();\n...\npublic <K, V> Map<K, V> createHashMap() {\n return new HashMap<K, V>();\n}\n Map<String, List<String>>"
},
{
"answer_id": 953756,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 5,
"selected": false,
"text": "ClassCastException Map<String, Integer> HashMap Map<String, Integer> m = new HashMap<String, Integer>();\n HashMap Map<String, Integer> m = new Ha HashMap Set Set<Integer> set = new HashSet<Integer>();\nset.add(10);\nset.add(42);\n\nint total = 0;\nfor (int i : set) {\n total += i;\n}\n set.add(10);\nset.add(42);\n 10 Integer 10 42 Integer Set Integer String for (int i : set) {\n total += i;\n}\n Set Integer int Integer int Integer Set Set Set Set set = new HashSet();\nset.add(10);\nset.add(42);\n\nint total = 0;\nfor (Object o : set) {\n total += (Integer)o;\n}\n Object Object add set.add(10);\nset.add(42);\n int 10 42 Integer Set Integer Object Set for (Object o : set) {\n Set Iterable Iterator Iterator<T> Set Iterator Set Object Object Object Set Integer total += (Integer)o;\n Object Integer ClassCastException Integer int int total"
},
{
"answer_id": 953769,
"author": "Bert F",
"author_id": 11296,
"author_profile": "https://Stackoverflow.com/users/11296",
"pm_score": 2,
"selected": false,
"text": "List List"
},
{
"answer_id": 953781,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 4,
"selected": false,
"text": "String foo(String s) s List<T> List<T> T List T List public interface F<A, B> {\n public B f(A a);\n}\n A B f A B A B f F<Integer, String> intToString = new F<Integer, String>() {\n public String f(int i) {\n return String.valueOf(i);\n }\n}\n extends public final class Hash<A> {\n private final F<A, Integer> hashFunction;\n\n public Hash(final F<A, Integer> f) {\n this.hashFunction = f;\n }\n\n public int hash(A a) {\n return hashFunction.f(a);\n }\n}\n Widget FooWidget BarWidget BazWidget Widget<A> Foo Bar Baz Widget<Foo> Widget<Bar> Widget<Baz>"
},
{
"answer_id": 51103844,
"author": "stdout",
"author_id": 1388943,
"author_profile": "https://Stackoverflow.com/users/1388943",
"pm_score": 1,
"selected": false,
"text": "public interface Foo<T extends MyObject> extends Hoo<T>{\n ...\n}\n public <T extends MyObject> foo(T t1, T t2){\n ...\n} \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
] |
77,639 |
<p>When is it right for a constructor to throw an exception? (Or in the case of Objective C: when is it right for an init'er to return nil?)</p>
<p>It seems to me that a constructor should fail -- and thus refuse to create an object -- if the object isn't complete. I.e., the constructor should have a contract with its caller to provide a functional and working object on which methods can be called meaningfully? Is that reasonable?</p>
|
[
{
"answer_id": 77797,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 6,
"selected": false,
"text": "Int32.Parse()"
},
{
"answer_id": 5006212,
"author": "stevex",
"author_id": 8831,
"author_profile": "https://Stackoverflow.com/users/8831",
"pm_score": 2,
"selected": false,
"text": "[[[MyObj alloc] init] autorelease]"
},
{
"answer_id": 42913195,
"author": "cwharris",
"author_id": 696056,
"author_profile": "https://Stackoverflow.com/users/696056",
"pm_score": 4,
"selected": false,
"text": "public class Person\n{\n public string Name { get; }\n public DateTime DateOfBirth { get; }\n\n public Person(string name, DateTime dateOfBirth)\n {\n if (string.IsNullOrWhitespace(name))\n {\n throw new ArgumentException(nameof(name));\n }\n\n if (dateOfBirth > DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n {\n throw new ArgumentOutOfRangeException(nameof(dateOfBirth));\n }\n\n this.Name = name;\n this.DateOfBirth = dateOfBirth;\n }\n}\n public class Person\n{\n public string Name { get; }\n public DateTime DateOfBirth { get; }\n\n public Person(string name, DateTime dateOfBirth)\n {\n this.Name = name;\n this.DateOfBirth = dateOfBirth;\n }\n\n public void Validate()\n {\n if (string.IsNullOrWhitespace(Name))\n {\n throw new ArgumentException(nameof(Name));\n }\n\n if (DateOfBirth > DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n {\n throw new ArgumentOutOfRangeException(nameof(DateOfBirth));\n }\n }\n}\n public class Person\n{\n public string Name { get; }\n public DateTime DateOfBirth { get; }\n\n private Person(string name, DateTime dateOfBirth)\n {\n this.Name = name;\n this.DateOfBirth = dateOfBirth;\n }\n\n public static Person Create(\n string name,\n DateTime dateOfBirth)\n {\n if (string.IsNullOrWhitespace(Name))\n {\n throw new ArgumentException(nameof(name));\n }\n\n if (dateOfBirth > DateTime.UtcNow) // side note: bad use of DateTime.UtcNow\n {\n throw new ArgumentOutOfRangeException(nameof(DateOfBirth));\n }\n\n return new Person(name, dateOfBirth);\n }\n}\n public class RestApiClient\n{\n public RestApiClient(HttpClient httpClient)\n {\n this.httpClient = new httpClient;\n }\n\n public async Task<RestApiClient> Create(string username, string password)\n {\n if (username == null)\n {\n throw new ArgumentNullException(nameof(username));\n }\n\n if (password == null)\n {\n throw new ArgumentNullException(nameof(password));\n }\n\n var basicAuthBytes = Encoding.ASCII.GetBytes($\"{username}:{password}\");\n var basicAuthValue = Convert.ToBase64String(basicAuthBytes);\n\n var authenticationHttpClient = new HttpClient\n {\n BaseUri = new Uri(\"https://auth.example.io\"),\n DefaultRequestHeaders = {\n Authentication = new AuthenticationHeaderValue(\"Basic\", basicAuthValue)\n }\n };\n\n using (authenticationHttpClient)\n {\n var response = await httpClient.GetAsync(\"login\");\n var content = response.Content.ReadAsStringAsync();\n var authToken = content;\n var restApiHttpClient = new HttpClient\n {\n BaseUri = new Uri(\"https://api.example.io\"), // notice this differs from the auth uri\n DefaultRequestHeaders = {\n Authentication = new AuthenticationHeaderValue(\"Bearer\", authToken)\n }\n };\n\n return new RestApiClient(restApiHttpClient);\n }\n }\n}\n Create"
},
{
"answer_id": 49033272,
"author": "Denise Skidmore",
"author_id": 2091951,
"author_profile": "https://Stackoverflow.com/users/2091951",
"pm_score": 1,
"selected": false,
"text": "new delete"
},
{
"answer_id": 51277298,
"author": "Ashley",
"author_id": 5370163,
"author_profile": "https://Stackoverflow.com/users/5370163",
"pm_score": 1,
"selected": false,
"text": "IDisposeable.Dispose using Socket using class A : IDisposable\n{\n public A()\n {\n Console.WriteLine(\"Initialize A's resources.\");\n }\n\n public void Dispose()\n {\n Console.WriteLine(\"Dispose A's resources.\");\n }\n}\n\nclass B : A, IDisposable\n{\n public B()\n {\n Console.WriteLine(\"Initialize B's resources.\");\n throw new Exception(\"B construction failure: B can cleanup anything before throwing so this is not a worry.\");\n }\n\n public new void Dispose()\n {\n Console.WriteLine(\"Dispose B's resources.\");\n base.Dispose();\n }\n}\nclass C : B, IDisposable\n{\n public C()\n {\n Console.WriteLine(\"Initialize C's resources. Not called because B throws during construction. C's resources not a worry.\");\n }\n\n public new void Dispose()\n {\n Console.WriteLine(\"Dispose C's resources.\");\n base.Dispose();\n }\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n try\n {\n using (C c = new C())\n {\n }\n }\n catch\n { \n }\n\n // Resource's allocated by c's \"A\" not explicitly disposed.\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14050/"
] |
77,659 |
<p>I have a .NET <strong>2.0</strong> WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx" rel="noreferrer">MSDN article</a> doesn't mention this, however.
I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of.</p>
<p>Anyone have any experience using one of these and successfully blocking <strong>all</strong> dialogs, script errors, etc?</p>
<p><strong>EDIT</strong></p>
<p>This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, <strong>AxSHDocVW</strong>?</p>
<p><strong>EDIT again</strong></p>
<p>Sorry I forgot to mention this... I'm trying to block a <strong>JavaScript alert()</strong>, with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?</p>
|
[
{
"answer_id": 101632,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 4,
"selected": true,
"text": "window.alert = function () { }\n"
},
{
"answer_id": 110048,
"author": "Jim Crafton",
"author_id": 9864,
"author_profile": "https://Stackoverflow.com/users/9864",
"pm_score": 3,
"selected": false,
"text": "IDocHostUIHandler MSHTML COM IHostDialogHelper\nIDocHostShowUI\n"
},
{
"answer_id": 251524,
"author": "Sire",
"author_id": 2440,
"author_profile": "https://Stackoverflow.com/users/2440",
"pm_score": 4,
"selected": false,
"text": "private void InjectAlertBlocker() {\n HtmlElement head = webBrowser1.Document.GetElementsByTagName(\"head\")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement(\"script\");\n string alertBlocker = \"window.alert = function () { }\";\n scriptEl.SetAttribute(\"text\", alertBlocker);\n head.AppendChild(scriptEl);\n}\n"
},
{
"answer_id": 330495,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "WebBroswer OnNavigated class WebBrowserEx : WebBrowser\n{\n public WebBrowserEx ()\n {\n }\n\n protected override void OnNavigated( WebBrowserNavigatedEventArgs e )\n {\n HtmlElement he = this.Document.GetElementsByTagName( \"head\" )[0];\n HtmlElement se = this.Document.CreateElement( \"script\" );\n mshtml.IHTMLScriptElement element = (mshtml.IHTMLScriptElement)se.DomElement;\n string alertBlocker = \"window.alert = function () { }\";\n element.text = alertBlocker;\n he.AppendChild( se );\n base.OnNavigated( e );\n }\n}\n"
},
{
"answer_id": 5780448,
"author": "abobjects.com",
"author_id": 618173,
"author_profile": "https://Stackoverflow.com/users/618173",
"pm_score": 2,
"selected": false,
"text": "InjectAlertBlocker private void InjectAlertBlocker() {\n HtmlElement head = webBrowser1.Document.GetElementsByTagName(\"head\")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement(\"script\");\n IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n string alertBlocker = \"window.alert = function () { }\";\n element.text = alertBlocker;\n head.AppendChild(scriptEl);\n}\n MSHTML COM using mshtml; IHTMLElement Navigated private void InjectAlertBlocker()\n{\n HtmlElement head = webBrowser1.Document.GetElementsByTagName(\"head\")[0];\n HtmlElement scriptEl = webBrowser1.Document.CreateElement(\"script\");\n IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;\n string alertBlocker = \"window.alert = function () { }\";\n element.text = alertBlocker;\n head.AppendChild(scriptEl);\n}\n\nprivate void webDest_Navigated(object sender, WebBrowserNavigatedEventArgs e)\n{\n InjectAlertBlocker();\n}\n"
},
{
"answer_id": 7903067,
"author": "Prashant Bassi",
"author_id": 1014615,
"author_profile": "https://Stackoverflow.com/users/1014615",
"pm_score": 2,
"selected": false,
"text": "webBrowser1.ScriptErrorsSuppressed = true;\n"
},
{
"answer_id": 9412021,
"author": "Legoless",
"author_id": 573186,
"author_profile": "https://Stackoverflow.com/users/573186",
"pm_score": 0,
"selected": false,
"text": "string alertBlocker = \"window.print = function emptyMethod() { }; window.alert = function emptyMethod() { }; window.open = function emptyMethod() { };\"; \nthis.Document.InvokeScript(\"execScript\", new Object[] { alertBlocker, \"JavaScript\" });\n"
},
{
"answer_id": 9812051,
"author": "Harry",
"author_id": 126537,
"author_profile": "https://Stackoverflow.com/users/126537",
"pm_score": 3,
"selected": false,
"text": "Browser.Navigated +=\n new WebBrowserNavigatedEventHandler(\n (object sender, WebBrowserNavigatedEventArgs args) => {\n Action<HtmlDocument> blockAlerts = (HtmlDocument d) => {\n HtmlElement h = d.GetElementsByTagName(\"head\")[0];\n HtmlElement s = d.CreateElement(\"script\");\n IHTMLScriptElement e = (IHTMLScriptElement)s.DomElement;\n e.text = \"window.alert=function(){};\";\n h.AppendChild(s);\n };\n WebBrowser b = sender as WebBrowser;\n blockAlerts(b.Document);\n for (int i = 0; i < b.Document.Window.Frames.Count; i++)\n try { blockAlerts(b.Document.Window.Frames[i].Document); }\n catch (Exception) { };\n }\n );\n"
},
{
"answer_id": 14669921,
"author": "volody",
"author_id": 241811,
"author_profile": "https://Stackoverflow.com/users/241811",
"pm_score": 2,
"selected": false,
"text": "public class MyBrowser : WebBrowser\n{\n\n [PermissionSetAttribute(SecurityAction.LinkDemand, Name = \"FullTrust\")]\n public MyBrowser()\n {\n }\n\n protected override WebBrowserSiteBase CreateWebBrowserSiteBase()\n {\n var manager = new NewWindowManagerWebBrowserSite(this);\n return manager;\n }\n\n protected class NewWindowManagerWebBrowserSite : WebBrowserSite, IServiceProvider, IDocHostShowUI\n {\n private readonly NewWindowManager _manager;\n\n public NewWindowManagerWebBrowserSite(WebBrowser host)\n : base(host)\n {\n _manager = new NewWindowManager();\n }\n\n public int ShowMessage(IntPtr hwnd, string lpstrText, string lpstrCaption, int dwType, string lpstrHelpFile, int dwHelpContext, out int lpResult)\n {\n lpResult = 0;\n return Constants.S_OK; // S_OK Host displayed its UI. MSHTML does not display its message box.\n }\n\n // Only files of types .chm and .htm are supported as help files.\n public int ShowHelp(IntPtr hwnd, string pszHelpFile, uint uCommand, uint dwData, POINT ptMouse, object pDispatchObjectHit)\n {\n return Constants.S_OK; // S_OK Host displayed its UI. MSHTML does not display its message box.\n }\n\n #region Implementation of IServiceProvider\n\n public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject)\n {\n if ((guidService == Constants.IID_INewWindowManager && riid == Constants.IID_INewWindowManager))\n {\n ppvObject = Marshal.GetComInterfaceForObject(_manager, typeof(INewWindowManager));\n if (ppvObject != IntPtr.Zero)\n {\n return Constants.S_OK;\n }\n }\n ppvObject = IntPtr.Zero;\n return Constants.E_NOINTERFACE;\n }\n\n #endregion\n }\n }\n\n[ComVisible(true)]\n[Guid(\"01AFBFE2-CA97-4F72-A0BF-E157038E4118\")]\npublic class NewWindowManager : INewWindowManager\n{\n public int EvaluateNewWindow(string pszUrl, string pszName,\n string pszUrlContext, string pszFeatures, bool fReplace, uint dwFlags, uint dwUserActionTime)\n {\n\n // use E_FAIL to be the same as CoInternetSetFeatureEnabled with FEATURE_WEBOC_POPUPMANAGEMENT\n //int hr = MyBrowser.Constants.E_FAIL; \n int hr = MyBrowser.Constants.S_FALSE; //Block\n //int hr = MyBrowser.Constants.S_OK; //Allow all\n return hr;\n }\n}\n"
},
{
"answer_id": 36258414,
"author": "IsLeadByte",
"author_id": 6123304,
"author_profile": "https://Stackoverflow.com/users/6123304",
"pm_score": 0,
"selected": false,
"text": "BeforeScriptExecute BeforeScriptExecute pdispwindow pdispwindow.execscript(\"window.alert = function () { }\")\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13791/"
] |
77,664 |
<p>We're currently running a server on Compatibility mode 8 and I want to update it. </p>
<ul>
<li>What are the implications of just going in and changing it? </li>
<li>What is likely to break? </li>
<li>Is there anything that checks the data will survive before I perform it? </li>
<li>Can I rollback to mode 8 without performing a restore and without loss of data?</li>
</ul>
|
[
{
"answer_id": 83146,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "char()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
] |
77,694 |
<p>I've defined a view with the CCK and View 2 modules. I would like to quickly define a template specific to this view. Is there any tutorial or information on this? What are the files I need to modify?</p>
<hr>
<p><strong>Here are my findings: (Edited)</strong></p>
<p>In fact, there are two ways to theme a view: the "<strong>field</strong>" way and the "<strong>node</strong>" way. In "edit View", you can choose "<code>Row style: Node</code>", or "<code>Row style: Fields</code>".</p>
<ul>
<li>with the "<strong>Node</strong>" way, you can create a <strong>node-contentname.tpl.php</strong> which will be called for each node in the view. You'll have access to your cck field values with $field_name[0]['value']. (edit2) You can use <strong>node-view-viewname.tpl.php</strong> which will be only called for each node displayed from this view.</li>
<li>with the "<strong>Field</strong>" way, you add a views-view-field--viewname--field-name-value.tpl.php for each field you want to theme individually.</li>
</ul>
<p>Thanks to previous responses, I've used the following tools :</p>
<ul>
<li>In the 'Basic Settings' block, the 'Theme: Information' to see all the different templates you can modify.</li>
<li>The <a href="http://drupal.org/project/devel" rel="nofollow noreferrer">Devel module</a>'s "Theme developer" to quickly find the field variable names.</li>
<li><a href="http://views-help.doc.logrus.com/" rel="nofollow noreferrer">View 2 documentation</a>, especially the <a href="http://views-help.doc.logrus.com/help/views/using-theme" rel="nofollow noreferrer">"Using Theme"</a> page.</li>
</ul>
|
[
{
"answer_id": 78158,
"author": "Pierre-Jean Coudert",
"author_id": 8450,
"author_profile": "https://Stackoverflow.com/users/8450",
"pm_score": 7,
"selected": true,
"text": "Row style: Node Row style: Fields"
},
{
"answer_id": 1248513,
"author": "userp2m3h",
"author_id": 152933,
"author_profile": "https://Stackoverflow.com/users/152933",
"pm_score": 2,
"selected": false,
"text": "YOUR_MODULE_DIR _views_theme_functions views_view views_view__test_view__block test_view"
},
{
"answer_id": 5420512,
"author": "James",
"author_id": 673434,
"author_profile": "https://Stackoverflow.com/users/673434",
"pm_score": 3,
"selected": false,
"text": "views-view-fields.tpl.php if($view->name == 'articleList' || $view->name == 'frontList' \n|| $view->name == 'archiveList') {\n/* field formatting code */\n} else {\n/* the default code running here */\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8450/"
] |
77,695 |
<p>What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of?</p>
|
[
{
"answer_id": 77840,
"author": "xdg",
"author_id": 11800,
"author_profile": "https://Stackoverflow.com/users/11800",
"pm_score": 5,
"selected": false,
"text": "file:///path/to/my/cpan/mirror\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9532/"
] |
77,718 |
<p>Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?</p>
<p>Isn't <code>Complex a, b, c; a = b + c;</code> much simpler than <code>Complex a, b, c; a = b.add(c);</code>?</p>
<p>Is there a known reason for this, valid arguments for <em>not</em> allowing operator overloading? Is the reason arbitrary, or lost to time?</p>
|
[
{
"answer_id": 77798,
"author": "Sebastian Redl",
"author_id": 8922,
"author_profile": "https://Stackoverflow.com/users/8922",
"pm_score": 4,
"selected": false,
"text": "Object.Equals Object.ReferenceEquals"
},
{
"answer_id": 77811,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 2,
"selected": false,
"text": "Complex a, b, c; a = b + c;\n Complex a, b, c; a = b.add(c);\n"
},
{
"answer_id": 77963,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 5,
"selected": true,
"text": "a Complex a, b, c;\n// ...\na = b.add(c);\n a operator= Complex b.set(1, 0); // initialize to real number '1'\na = b; \nb.set(2, 0);\nassert( !a.equals(b) ); // this assertion will fail\n operator= a b operator+ operator= Complex operator= operator=="
},
{
"answer_id": 78167,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "// a = b + c\nComplex a, b, c; a = b.add(c);\n"
},
{
"answer_id": 82890,
"author": "user15793",
"author_id": 15793,
"author_profile": "https://Stackoverflow.com/users/15793",
"pm_score": 5,
"selected": false,
"text": "quantity<force> F = 2.0*newton;\nquantity<length> dx = 2.0*meter;\nquantity<energy> E = F * dx;\nstd::cout << \"Energy = \" << E << endl;\n"
},
{
"answer_id": 194889,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 10,
"selected": false,
"text": "// C++\nT operator + (const T & a, const T & b) // add ?\n{\n T c ;\n c.value = a.value - b.value ; // subtract !!!\n return c ;\n}\n\n// Java\nstatic T add (T a, T b) // add ?\n{\n T c = new T() ;\n c.value = a.value - b.value ; // subtract !!!\n return c ;\n}\n\n/* C */\nT add (T a, T b) /* add ? */\n{\n T c ;\n c.value = a.value - b.value ; /* subtract !!! */\n return c ;\n}\n Cloneable class MySincereHandShake implements Cloneable\n{\n public Object clone()\n {\n return new MyVengefulKickInYourHead() ;\n }\n}\n Cloneable toString() MyComplexNumber toString() MyComplexNumber.equals add Cloneable ++ // C++ comparison for built-ins and user-defined types\nbool isEqual = A == B ;\nbool isNotEqual = A != B ;\nbool isLesser = A < B ;\nbool isLesserOrEqual = A <= B ;\n\n// Java comparison for user-defined types\nboolean isEqual = A.equals(B) ;\nboolean isNotEqual = ! A.equals(B) ;\nboolean isLesser = A.comparesTo(B) < 0 ;\nboolean isLesserOrEqual = A.comparesTo(B) <= 0 ;\n // C++ container accessors, more natural\nvalue = myArray[25] ; // subscript operator\nvalue = myVector[25] ; // subscript operator\nvalue = myString[25] ; // subscript operator\nvalue = myMap[\"25\"] ; // subscript operator\nmyArray[25] = value ; // subscript operator\nmyVector[25] = value ; // subscript operator\nmyString[25] = value ; // subscript operator\nmyMap[\"25\"] = value ; // subscript operator\n\n// Java container accessors, each one has its special notation\nvalue = myArray[25] ; // subscript operator\nvalue = myVector.get(25) ; // method get\nvalue = myString.charAt(25) ; // method charAt\nvalue = myMap.get(\"25\") ; // method get\nmyArray[25] = value ; // subscript operator\nmyVector.set(25, value) ; // method set\nmyMap.put(\"25\", value) ; // method put\n Matrix // C++ YMatrix matrix implementation on CodeProject\n// http://www.codeproject.com/KB/architecture/ymatrix.aspx\n// A, B, C, D, E, F are Matrix objects;\nE = A * (B / 2) ;\nE += (A - B) * (C + D) ;\nF = E ; // deep copy of the matrix\n\n// Java JAMA matrix implementation (seriously...)\n// http://math.nist.gov/javanumerics/jama/doc/\n// A, B, C, D, E, F are Matrix objects;\nE = A.times(B.times(0.5)) ;\nE.plusEquals(A.minus(B).times(C.plus(D))) ;\nF = E.copy() ; // deep copy of the matrix\n BigInteger BigDecimal // C++ Random Access iterators\n++it ; // move to the next item\n--it ; // move to the previous item\nit += 5 ; // move to the next 5th item (random access)\nvalue = *it ; // gets the value of the current item\n*it = 3.1415 ; // sets the value 3.1415 to the current item\n(*it).foo() ; // call method foo() of the current item\n\n// Java ListIterator<E> \"bi-directional\" iterators\nvalue = it.next() ; // move to the next item & return the value\nvalue = it.previous() ; // move to the previous item & return the value\nit.set(3.1415) ; // sets the value 3.1415 to the current item\n // C++ Functors\nmyFunctorObject(\"Hello World\", 42) ;\n\n// Java Functors ???\nmyFunctorObject.execute(\"Hello World\", 42) ;\n // C++ stream handling (with the << operator)\n stringStream << \"Hello \" << 25 << \" World\" ;\n fileStream << \"Hello \" << 25 << \" World\" ;\n outputStream << \"Hello \" << 25 << \" World\" ;\n networkStream << \"Hello \" << 25 << \" World\" ;\nanythingThatOverloadsShiftOperator << \"Hello \" << 25 << \" World\" ;\n\n// Java concatenation\nmyStringBuffer.append(\"Hello \").append(25).append(\" World\") ;\n MyString = \"Hello \" + 25 + \" World\" ; // C++ primitive/advanced types\ntemplate<typename T>\nT getAverage(const T & p_lhs, const T & p_rhs)\n{\n return (p_lhs + p_rhs) / 2 ;\n}\n\nint intValue = getAverage(25, 42) ;\ndouble doubleValue = getAverage(25.25, 42.42) ;\ncomplex complexValue = getAverage(cA, cB) ; // cA, cB are complex\nMatrix matrixValue = getAverage(mA, mB) ; // mA, mB are Matrix\n\n// Java primitive/advanced types\n// It won't really work in Java, even with generics. Sorry.\n + - * + - * + toString() clone() equals() + add clone && || && || struct struct"
},
{
"answer_id": 48502000,
"author": "Sarien",
"author_id": 1994377,
"author_profile": "https://Stackoverflow.com/users/1994377",
"pm_score": 1,
"selected": false,
"text": ">>> IP()\n<IP |>\n>>> IP()/TCP()\n<IP frag=0 proto=TCP |<TCP |>>\n>>> Ether()/IP()/TCP()\n<Ether type=0x800 |<IP frag=0 proto=TCP |<TCP |>>>\n>>> IP()/TCP()/\"GET / HTTP/1.0\\r\\n\\r\\n\"\n<IP frag=0 proto=TCP |<TCP |<Raw load='GET / HTTP/1.0\\r\\n\\r\\n' |>>>\n>>> Ether()/IP()/IP()/UDP()\n<Ether type=0x800 |<IP frag=0 proto=IP |<IP frag=0 proto=UDP |<UDP |>>>>\n>>> IP(proto=55)/TCP()\n<IP frag=0 proto=55 |<TCP |>>\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
77,744 |
<p>I have a command line program, which outputs logging to the screen.</p>
<p>I want error lines to show up in red. Is there some special character codes I can output to switch the text color to red, then switch it back to white?</p>
<p>I'm using ruby but I imagine this would be the same in any other language.</p>
<p>Something like:</p>
<pre><code>red = "\0123" # character code
white = "\0223"
print "#{red} ERROR: IT BROKE #{white}"
print "other stuff"
</code></pre>
|
[
{
"answer_id": 77803,
"author": "betelgeuce",
"author_id": 366182,
"author_profile": "https://Stackoverflow.com/users/366182",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Console_Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n Console.ForegroundColor = ConsoleColor.DarkRed;\n Console.WriteLine(\"Hello World\");\n Console.ReadKey();\n }\n }\n}\n"
},
{
"answer_id": 77861,
"author": "artur02",
"author_id": 13937,
"author_profile": "https://Stackoverflow.com/users/13937",
"pm_score": 2,
"selected": false,
"text": "for (int x = 0; x < colorNames.Length; x++)\n{\n Console.Write(\"{0,2}: \", x);\n Console.BackgroundColor = ConsoleColor.Black;\n Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), colorNames[x]);\n Console.Write(\"This is foreground color {0}.\", colorNames[x]);\n Console.ResetColor();\n Console.WriteLine();\n}\n"
},
{
"answer_id": 77867,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "system(\"Color F1\"); 0 = Black 8 = Gray\n1 = Blue 9 = Light Blue\n2 = Green A = Light Green\n3 = Aqua B = Light Aqua\n4 = Red C = Light Red\n5 = Purple D = Light Purple\n6 = Yellow E = Light Yellow\n7 = White F = Bright White\n SetConsoleAttribute"
},
{
"answer_id": 78002,
"author": "Michael",
"author_id": 13379,
"author_profile": "https://Stackoverflow.com/users/13379",
"pm_score": 2,
"selected": false,
"text": "color [background][foreground] 0 = Black 8 = Gray\n1 = Blue 9 = Light Blue\n2 = Green A = Light Green\n3 = Aqua B = Light Aqua\n4 = Red C = Light Red\n5 = Purple D = Light Purple\n6 = Yellow E = Light Yellow\n7 = White F = Bright White\n color 18"
},
{
"answer_id": 78741,
"author": "manveru",
"author_id": 8367,
"author_profile": "https://Stackoverflow.com/users/8367",
"pm_score": 5,
"selected": false,
"text": "require 'win32console'\nputs \"\\e[31mHello, World!\\e[0m\"\n red require 'win32console'\n class String\n def red\n \"\\e[31m#{self}\\e[0m\"\n end\n end\n\n puts \"Hello, World!\".red\n require 'win32console'\n\nclass String\n { :reset => 0,\n :bold => 1,\n :dark => 2,\n :underline => 4,\n :blink => 5,\n :negative => 7,\n :black => 30,\n :red => 31,\n :green => 32,\n :yellow => 33,\n :blue => 34,\n :magenta => 35,\n :cyan => 36,\n :white => 37,\n }.each do |key, value|\n define_method key do\n \"\\e[#{value}m\" + self + \"\\e[0m\"\n end\n end\nend\n\nputs \"Hello, World!\".red\n gem install term-ansicolor\n require 'win32console'\nrequire 'term/ansicolor'\n\nclass String\n include Term::ANSIColor\nend\n\nputs \"Hello, World!\".red\nputs \"Hello, World!\".blue\nputs \"Annoy me!\".blink.yellow.bold\n"
},
{
"answer_id": 31743032,
"author": "Adam",
"author_id": 3254245,
"author_profile": "https://Stackoverflow.com/users/3254245",
"pm_score": 2,
"selected": false,
"text": "gem install color-console\n require 'color-console'\n\nConsole.puts \"Some text\" # Outputs text using the current console colours\nConsole.puts \"Some other text\", :red # Outputs red text with the current background\nConsole.puts \"Yet more text\", nil, :blue # Outputs text using the current foreground and a blue background\n\n# The following lines output BlueRedGreen on a single line, each word in the appropriate color\nConsole.write \"Blue \", :blue\nConsole.write \"Red \", :red\nConsole.write \"Green\", :green\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] |
77,813 |
<p>Does anyone have any pointers on how to read the Windows EventLog without using JNI? Or if you <em>have to</em> use JNI, are there any good open-source libraries for doing so?</p>
|
[
{
"answer_id": 3832161,
"author": "dB.",
"author_id": 123094,
"author_profile": "https://Stackoverflow.com/users/123094",
"pm_score": 2,
"selected": false,
"text": "EventLogIterator iter = new EventLogIterator(\"Application\"); \nwhile(iter.hasNext()) { \n EventLogRecord record = iter.next(); \n System.out.println(record.getRecordId() \n + \": Event ID: \" + record.getEventId() \n + \", Event Type: \" + record.getType() \n + \", Event Source: \" + record.getSource()); \n} \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1693/"
] |
77,826 |
<p>One thing I've started doing more often recently is <strong>retrieving some data</strong> at the beginning of a task <strong>and storing it in a $_SESSION['myDataForTheTask']</strong>. </p>
<p>Now it seems very convenient to do so but I don't know anything about performance, security risks or similar, using this approach. Is it something which is regularly done by programmers with more expertise or is it more of an amateur thing to do?</p>
<p><strong>For example:</strong></p>
<pre><code>if (!isset($_SESSION['dataentry']))
{
$query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=" . mysql_real_escape_string($_GET['wave_id']);
$result_taskinfo = $db->query($query_taskinfo);
$row_taskinfo = $result_taskinfo->fetch_row();
$dataentry = array("pcode" => $row_taskinfo[0], "modules" => $row_taskinfo[1], "data_id" => 0, "wavenum" => $row_taskinfo[2], "prequest" => FALSE, "highlight" => array());
$_SESSION['dataentry'] = $dataentry;
}
</code></pre>
|
[
{
"answer_id": 77906,
"author": "Ryan Smith",
"author_id": 10420,
"author_profile": "https://Stackoverflow.com/users/10420",
"pm_score": 3,
"selected": false,
"text": "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=\".$_GET['wave_id'];\n mysql_real_escape_string() $query_taskinfo = \"SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id='\".mysql_real_escape_string($_GET['wave_id']).\"'\";\n"
},
{
"answer_id": 78089,
"author": "William Macdonald",
"author_id": 2725,
"author_profile": "https://Stackoverflow.com/users/2725",
"pm_score": 2,
"selected": false,
"text": "$query_taskinfo = \"SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=\".(int)$_GET['wave_id'].\" LIMIT 1\";\n"
},
{
"answer_id": 767861,
"author": "Tom",
"author_id": 42754,
"author_profile": "https://Stackoverflow.com/users/42754",
"pm_score": 2,
"selected": false,
"text": "$_SESSION session_start()"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
77,835 |
<p>I am trying to run a SeleniumTestCase with phpunit but I cannot get it to run with the phpunit.bat script. </p>
<p>My goal is to use phpunit with Selenium RC in CruiseControl & phpUnderControl. This is what the test looks like:</p>
<pre><code>require_once 'PHPUnit/Extensions/SeleniumTestCase.php';
class WebTest extends PHPUnit_Extensions_SeleniumTestCase
{
protected function setUp()
{
$this->setBrowser('*firefox');
$this->setBrowserUrl('http://www.example.com/');
}
public function testTitle()
{
$this->open('http://www.example.com/');
$this->assertTitleEquals('Example Web Page');
}
}
</code></pre>
<p>I also got PEAR in the include_path and PHPUnit installed with the Selenium extension. I installed these with the pear installer so I guess that's not the problem. </p>
<p>Any help would be very much appreciated. </p>
<p>Thanks, Remy</p>
|
[
{
"answer_id": 2146178,
"author": "CruiZen",
"author_id": 232647,
"author_profile": "https://Stackoverflow.com/users/232647",
"pm_score": 1,
"selected": false,
"text": "<?php .. ?> <? .. ?> <?php\nrequire_once 'PHPUnit/Framework.php';\n\nclass StackTest extends PHPUnit_Framework_TestCase\n{\n public function testPushAndPop()\n {\n $stack = array();\n $this->assertEquals(0, count($stack));\n\n array_push($stack, 'foo');\n $this->assertEquals('foo', $stack[count($stack)-1]);\n $this->assertEquals(1, count($stack));\n\n $this->assertEquals('foo', array_pop($stack));\n $this->assertEquals(0, count($stack));\n }\n}\n?>\n"
},
{
"answer_id": 4456097,
"author": "farinspace",
"author_id": 97433,
"author_profile": "https://Stackoverflow.com/users/97433",
"pm_score": 4,
"selected": false,
"text": "/PEAR/PHPUnit/Extensions/SeleniumTestCase.php\n pear uninstall phpunit/PHPUnit\n\npear uninstall phpunit/PHPUnit_Selenium\n\npear install phpunit/PHPUnit\n pear install phpunit/PHPUnit_Selenium\n"
},
{
"answer_id": 9059767,
"author": "mosid",
"author_id": 1023151,
"author_profile": "https://Stackoverflow.com/users/1023151",
"pm_score": 1,
"selected": false,
"text": "sudo apt-get install php5-curl sudo pear install phpunit/PHPUnit_Selenium"
},
{
"answer_id": 26145421,
"author": "Slava Nikoolin",
"author_id": 4099507,
"author_profile": "https://Stackoverflow.com/users/4099507",
"pm_score": 1,
"selected": false,
"text": "class WebTest extends \\PHPUnit_Extensions_Selenium2TestCase\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12645/"
] |
77,836 |
<p>Given two vectors <strong>A</strong> and <strong>B</strong> which form the line segment <strong>L</strong> = A-B.
Furthermore given a view frustum <strong>F</strong> which is defined by its left, right, bottom, top, near and far planes.</p>
<p>How do I clip <strong>L</strong> against <strong>F</strong>? </p>
<p>That is, test for an intersection <em>and</em> where on L that intersection occurs?
(Keep in mind that a line segment can have <strong>more</strong> than one intersection with the frustum if it intersects two sides at a corner.)</p>
<p>If possible, provide a code example please (C++ or Python preferred).</p>
|
[
{
"answer_id": 34960552,
"author": "ideasman42",
"author_id": 432509,
"author_profile": "https://Stackoverflow.com/users/432509",
"pm_score": 1,
"selected": false,
"text": "min > max def clip_segment_v3_plane_n(p1, p2, planes):\n \"\"\"\n - p1, p2: pair of 3d vectors defining a line segment.\n - planes: a sequence of (4 floats): `(x, y, z, d)`.\n\n Returns 2 vector triplets (the clipped segment)\n or (None, None) then segment is entirely outside.\n \"\"\"\n dp = sub_v3v3(p2, p1)\n\n p1_fac = 0.0\n p2_fac = 1.0\n\n for p in planes:\n div = dot_v3v3(p, dp)\n if div != 0.0:\n t = -plane_point_side_v3(p, p1)\n if div > 0.0: # clip p1 lower bounds\n if t >= div:\n return None, None\n if t > 0.0:\n fac = (t / div)\n if fac > p1_fac:\n p1_fac = fac\n if p1_fac > p2_fac:\n return None, None\n elif div < 0.0: # clip p2 upper bounds\n if t > 0.0:\n return None, None\n if t > div:\n fac = (t / div)\n if fac < p2_fac:\n p2_fac = fac\n if p1_fac > p2_fac:\n return None, None\n\n p1_clip = add_v3v3(p1, mul_v3_fl(dp, p1_fac))\n p2_clip = add_v3v3(p1, mul_v3_fl(dp, p2_fac))\n\n return p1_clip, p2_clip\n\n\n# inline math library\ndef add_v3v3(v0, v1):\n return (\n v0[0] + v1[0],\n v0[1] + v1[1],\n v0[2] + v1[2],\n )\n\ndef sub_v3v3(v0, v1):\n return (\n v0[0] - v1[0],\n v0[1] - v1[1],\n v0[2] - v1[2],\n )\n\ndef dot_v3v3(v0, v1):\n return (\n (v0[0] * v1[0]) +\n (v0[1] * v1[1]) +\n (v0[2] * v1[2])\n )\n\ndef mul_v3_fl(v0, f):\n return (\n v0[0] * f,\n v0[1] * f,\n v0[2] * f,\n )\n\ndef plane_point_side_v3(p, v):\n return dot_v3v3(p, v) + p[3]\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14157/"
] |
77,873 |
<p>Are there PHP libraries which can be used to fill PDF forms and then save (flatten) them to PDF files?</p>
|
[
{
"answer_id": 78300,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 7,
"selected": true,
"text": "pdftk fill_form output flatten ...\n<< /T(f1-1) /V(text of field) >>\n<< /T(f1-2) /V(text of another field) >>\n...\n"
},
{
"answer_id": 89023,
"author": "josh.chavanne",
"author_id": 14708,
"author_profile": "https://Stackoverflow.com/users/14708",
"pm_score": 2,
"selected": false,
"text": " <?php\nrequire('fpdf.php');\n$pdf=new PDF();\n$pdf->AddPage();\n$pdf->SetY(30);\n$pdf->SetX(100);\n$pdf->MultiCell(10,4,$_POST['content'],0,'J');\n$pdf->Output();\n?>\n <form action=\"fooPDF.php\" method=\"post\">\n <p>PDF CONTENT: <textarea name=\"content\" ></textarea></p>\n <p><input type=\"submit\" /></p>\n </form>\n"
},
{
"answer_id": 12772058,
"author": "Val Redchenko",
"author_id": 572660,
"author_profile": "https://Stackoverflow.com/users/572660",
"pm_score": 3,
"selected": false,
"text": "file -bi fields.fdf\n application/octet-stream; charset=binary\n cat fields.fdf | sed -e's/\\x00//g' | sed -e's/\\xFE\\xFF//g' > better.fdf\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14166/"
] |
77,887 |
<p>As someone who is just starting to learn the intricacies of computer debugging, for the life of me, I can't understand how to read the Stack Text of a dump in Windbg. I've no idea of where to start on how to interpret them or how to go about it. Can anyone offer direction to this poor soul?</p>
<p>ie (the only dump I have on hand with me actually)</p>
<pre>>b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94
b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255
b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0
b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000</pre>
<p>I know the problem is to do with the Nvidia display driver, but what I want to know is how to actually read the stack (eg, what is b69dd8f4?) :-[</p>
|
[
{
"answer_id": 78111,
"author": "sachaa",
"author_id": 1152057,
"author_profile": "https://Stackoverflow.com/users/1152057",
"pm_score": 5,
"selected": true,
"text": "SRV*c:\\symbols*http://msdl.microsoft.com/download/symbols\n kpn 200\n 01 MODULE!CLASS.FUNCTIONNAME1(...)\n02 MODULE!CLASS.FUNCTIONNAME2(...)\n03 MODULE!CLASS.FUNCTIONNAME3(...)\n04 MODULE!CLASS.FUNCTIONNAME4(...)\n 01 MODULE!+989823\n void main()\n{\n method1();\n}\n\nvoid method1()\n{\n method2();\n}\n\nint method2()\n{\n return 20/0;\n}\n 01 MYDLL!method2()\n02 MYDLL!method1()\n03 MYDLL!main()\n b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94\nb69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255\nb69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0\nb69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14173/"
] |
77,890 |
<p>I am writing some code to see if there is a hole in the firewall exception list for <strong>WinXP</strong> and <strong>Vista</strong> for a specific port used by our client software. </p>
<p>I can see that I can use the <code>NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts</code> to get a list of the current Open port exceptions. But i can not figure out how to get that enumerated list in to something that I can use in my Delphi program. </p>
<p>My latest try is listed below. It's giving me an access violation when I use <code>port_list.Item</code>. I know that's wrong, it was mostly wishful thinking on my part. Any help would be appreciated.</p>
<pre><code>function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean;
var
i, h: integer;
port_list, port: OleVariant;
begin
Result := False;
port_list := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts;
for i := 0 to port_list.Count - 1 do
begin
port := port_list.Item[i];
if (port.PortNumber = iPortNumber) then
begin
Result := True;
break;
end;
end;
end;
</code></pre>
|
[
{
"answer_id": 78144,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 0,
"selected": false,
"text": "Result := False;\nport_enum := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts._NewEnum;\nwhile port_enum.MoveNext <> Null do // try assigned if that doesn't work\nbegin\n port = e.Current as INetFwOpenPort;\n if (port.PortNumber = iPortNumber) then\n begin\n Result := True;\n break;\n end;\nend;\n"
},
{
"answer_id": 105813,
"author": "Ray Jenkins",
"author_id": 12425,
"author_profile": "https://Stackoverflow.com/users/12425",
"pm_score": 1,
"selected": false,
"text": "constructor TFirewallUtility.Create;\nbegin\n inherited Create;\n CoInitialize(nil);\n mxCurrentFirewallProfile := INetFwMgr(CreateOLEObject('HNetCfg.FwMgr')).LocalPolicy.CurrentProfile;\nend;\n\nfunction TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean;\nbegin\n try\n Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Port = iPortNumber;\n except\n Result := False;\n end;\nend;\n\nfunction TFirewallUtility.IsPortEnabled(iPortNumber: integer): boolean;\nbegin\n try\n Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Enabled;\n except\n Result := False;\n end;\nend;\n\nprocedure TFirewallUtility.SetPortEnabled(iPortNumber: integer; sPortName: string; xProtocol: TFirewallPortProtocol);\nbegin\n try\n mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, CFirewallPortProtocalConsts[xProtocol]).Enabled := True;\n except\n HaltIf(True, 'xFirewallManager.TFirewallUtility.IsPortEnabled: Port not in exception list.');\n end;\nend;\n\nprocedure TFirewallUtility.AddPortToFirewall(sPortName: string; iPortNumber: Cardinal; xProtocol: TFirewallPortProtocol);\nvar\n port: INetFwOpenPort;\nbegin\n port := INetFwOpenPort(CreateOLEObject('HNetCfg.FWOpenPort'));\n port.Name := sPortName;\n port.Protocol := CFirewallPortProtocalConsts[xProtocol];\n port.Port := iPortNumber;\n port.Scope := NET_FW_SCOPE_ALL;\n port.Enabled := true;\n mxCurrentFirewallProfile.GloballyOpenPorts.Add(port);\nend;\n"
},
{
"answer_id": 1613254,
"author": "jpfollenius",
"author_id": 62391,
"author_profile": "https://Stackoverflow.com/users/62391",
"pm_score": 1,
"selected": false,
"text": "type\n IEnumVariant = interface(IUnknown)\n ['{00020404-0000-0000-C000-000000000046}']\n function Next(celt: LongWord; var rgvar : OleVariant;\n pceltFetched: PLongWord): HResult; stdcall;\n function Skip(celt: LongWord): HResult; stdcall;\n function Reset: HResult; stdcall;\n function Clone(out Enum : IEnumVariant) : HResult; stdcall;\n end;\n\nvar\n Enum : IEnumVariant;\n Port : OleVariant;\n Count : Integer;\n...\nCount := 1;\nIUnknown (Profile.GloballyOpenPorts._NewEnum).QueryInterface (IEnumVariant, Enum);\nEnum.Reset;\nwhile (Enum.Next (1, FirewallPort, @Count) = S_OK) do\n begin\n if (FirewallPort.Port = Port) then\n Exit (True)\n end;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12425/"
] |
77,900 |
<p>Has anyone ever written a function that can convert all of the controls on an aspx page into a read only version? For example, if UserDetails.aspx is used to edit and save a users information, if someone with inappropriate permissions enter the page, I would like to render it as read-only. So, most controls would be converted to labels, loaded with the corresponding data from the editable original control.</p>
<p>I think it would likely be a fairly simple routine, ie: </p>
<pre><code>Dim ctlParent As Control = Me.txtTest.Parent
Dim ctlOLD As TextBox = Me.txtTest
Dim ctlNEW As Label = New Label
ctlNEW.Width = ctlOLD.Width
ctlNEW.Text = ctlOLD.Text
ctlParent.Controls.Remove(ctlOLD)
ctlParent.Controls.Add(ctlNEW)
</code></pre>
<p>...is really all you need for a textbox --> label conversion, but I was hoping someone might know of an existing function out there as there are likely a few pitfalls here and there with certain controls and situations.</p>
<p>Update:<br>
- Just setting the ReadOnly property to true is not a viable solution, as it looks dumb having things greyed out like that.
- Avoiding manually creating a secondary view is the entire point of this, so using an ingenious way to display a read only version of the user interface that was built by hand using labels is wat I am trying to avoid.</p>
<p>Thanks!!</p>
|
[
{
"answer_id": 77938,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 2,
"selected": false,
"text": "lblWhatever.Text = txtWhatever.Text = whateverOriginatingSource;\nlblSomethingElse.Text = txtSomethingElse.Text = somethingElseOriginatingSource;\n\nmyViews.SelectedIndex = myConditionOrVariableThatDeterminesEditable ? 0 : 1;\n <asp:Multiview ID=\"myViews\" SelectedIndex=\"1\">\n <asp:View ID=\"EditView\">\n <asp:TextBox ID=\"txtWhatever\" /><br />\n <asp:TextBox ID=\"txtSomethingElse\" />\n </asp:View>\n <asp:View ID=\"DisplayView\">\n <asp:Label ID=\"lblWhatever\" /><br />\n <asp:Label ID=\"lblSomethingElse\" />\n </asp:View>\n</asp:Multiview>\n"
},
{
"answer_id": 78143,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "MyTextBox : TextBox {\n public override void RenderControl(HtmlTextWriter writer) {\n if (this.ReadOnly) {\n writer.WriteBeginTag(\"label\");\n writer.Write(this.Value);\n writer.WriteEndTag();\n }\n }\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8678/"
] |
77,914 |
<p>I have an Apache 2 installation on Debian with mod_ssl installed. The server private key is protected by a passphase that needs to be entered on start-up. The error and access logs are subject to logrotate on a weekly basis. I find that Apache crashes with a passphrase-related error shortly after logrotate runs.</p>
<p>I understand that logrotate fires a SIGHUP to Apache after archiving logs and I suspect this is causing a reload and subsequent failure getting the passphrase for the server key.</p>
<p>Well, enough with my theories, here is the question:</p>
<p>Is there a "best practice" way in which to configure Apache to allow its SSL server keys to be protected by a passphrase (without storing that passphrase in a file somewhere) so that it won't crash when logrotate runs?</p>
<p>It is fine to require user input on server startup, but not restart or reload.</p>
|
[
{
"answer_id": 77987,
"author": "Andrew Cholakian",
"author_id": 11105,
"author_profile": "https://Stackoverflow.com/users/11105",
"pm_score": 2,
"selected": false,
"text": "CustomLog \"| /usr/sbin/cronolog /pathtologs/%Y_%m/sitename.com-%Y%m%d.log\" combined\n"
},
{
"answer_id": 421136,
"author": "Derek P.",
"author_id": 45615,
"author_profile": "https://Stackoverflow.com/users/45615",
"pm_score": 2,
"selected": false,
"text": "openssl rsa -in example.tld.key -out example.tld.key\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13956/"
] |
77,934 |
<p>I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?</p>
|
[
{
"answer_id": 78937,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 2,
"selected": false,
"text": "package require Img\nset image [image create photo -file /path/to/image.bmp]\nlabel .l -image $image\npack .l\n"
},
{
"answer_id": 104227,
"author": "Alasdair",
"author_id": 2654,
"author_profile": "https://Stackoverflow.com/users/2654",
"pm_score": 3,
"selected": true,
"text": "(defpackage #:ltk-image-example\n (:use #:cl #:ltk))\n\n(in-package #:ltk-image-example)\n\n(defun image-example ()\n (with-ltk ()\n (let ((image (make-image)))\n (image-load image \"testimage.gif\")\n (let ((canvas (make-instance 'canvas)))\n (create-image canvas 0 0 :image image)\n (configure canvas :width 800)\n (configure canvas :height 640)\n (pack canvas)))))\n (defclass photo-image(tkobject)\n ((data :accessor data :initform nil :initarg :data)\n )\n )\n\n(defmethod widget-path ((photo photo-image))\n (name photo))\n\n(defmethod initialize-instance :after ((p photo-image)\n &key width height format grayscale data)\n (check-type data (or null string))\n (setf (name p) (create-name))\n (format-wish \"image create photo ~A~@[ -width ~a~]~@[ -height ~a~]~@[ -format \\\"~a\\\"~]~@[ -grayscale~*~]~@[ -data ~s~]\"\n (name p) width height format grayscale data))\n\n(defun make-image ()\n (let* ((name (create-name))\n (i (make-instance 'photo-image :name name)))\n ;(create i)\n i))\n\n(defgeneric image-load (p filename))\n(defmethod image-load((p photo-image) filename)\n ;(format t \"loading file ~a~&\" filename)\n (send-wish (format nil \"~A read {~A} -shrink\" (name p) filename))\n p)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1994377/"
] |
77,936 |
<p>As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:</p>
<pre><code>centroid = average(x), average(y), average(z)
</code></pre>
<p>where <code>x</code>, <code>y</code> and <code>z</code> are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.</p>
|
[
{
"answer_id": 85787,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 2,
"selected": false,
"text": "N # number of points\nsums = dict(x=0,y=0,z=0) # sums of the locations for each point\n"
},
{
"answer_id": 37780869,
"author": "Chris",
"author_id": 454063,
"author_profile": "https://Stackoverflow.com/users/454063",
"pm_score": 5,
"selected": true,
"text": "centroid = average(x), average(y), average(z) middle = middle(x), middle(y), middle(z) median median = median(x), median(y), median(z) middle average median"
},
{
"answer_id": 66577393,
"author": "Mello",
"author_id": 12392216,
"author_profile": "https://Stackoverflow.com/users/12392216",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\nvectors = np.array(Listv)\ncentroid = np.mean(vectors, axis=0)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/676/"
] |
77,954 |
<p>How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that <code>use strict;</code> isn't sufficient for this purpose.</p>
|
[
{
"answer_id": 77969,
"author": "Neil",
"author_id": 14193,
"author_profile": "https://Stackoverflow.com/users/14193",
"pm_score": 2,
"selected": false,
"text": "use Carp ();\n local $SIG{__WARN__} = \\&Carp::confess;\nlocal $SIG{__WARN__} = \\&Carp::cluck;\n confess cluck"
},
{
"answer_id": 77971,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 5,
"selected": true,
"text": "use warnings FATAL => 'uninitialized';\n\nuse Carp ();\n$SIG{__DIE__} = \\&Carp::confess;\n man 3pm warnings"
},
{
"answer_id": 77972,
"author": "mopoke",
"author_id": 14054,
"author_profile": "https://Stackoverflow.com/users/14054",
"pm_score": 1,
"selected": false,
"text": "use Carp qw();\n\n[....]\n\nCarp::confess '$variableName is undef' unless defined $variableName;\n\n[....]\n"
},
{
"answer_id": 77980,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 2,
"selected": false,
"text": "$SIG{__WARN__} = sub { die \"Undef value: @_\" if $_[0] =~ /undefined/ };\n"
},
{
"answer_id": 78239,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 4,
"selected": false,
"text": "%SIG use Carp::Always perl -MCarp::Always PERL5OPT -MCarp::Always perldoc perlrun"
},
{
"answer_id": 5873113,
"author": "user736584",
"author_id": 736584,
"author_profile": "https://Stackoverflow.com/users/736584",
"pm_score": 0,
"selected": false,
"text": "use strict;\nuse warnings FATAL => 'uninitialized';\nuse Carp ();\n$SIG{__DIE__} = \\&Carp::confess;\n\nmy $x = undef; # it would be enough to say my $x;\nif (!$x->{test}) {\nprint \"no warnings, no errors\\n\";\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14193/"
] |
77,982 |
<p>How can I dismiss dialog in Cocoa application when user presses Esc or Enter key? I have OK button, is it possible to make it default button?</p>
|
[
{
"answer_id": 78110,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 4,
"selected": true,
"text": "NSAlert NSRunAlertPanel NSBeginAlertSheet"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77982",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14131/"
] |
77,990 |
<p>How do some programs edit whats being displayed on the terminal (to pick a random example, the program 'sl')? I'm thinking of the Linux terminal here, it may happen in other OS's too, I don't know. I've always thought once some text was displayed, it stayed there. How do you change it without redrawing the entire screen? </p>
|
[
{
"answer_id": 78039,
"author": "mana",
"author_id": 12016,
"author_profile": "https://Stackoverflow.com/users/12016",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\ni=1\nwhile [ true ]\n do\n echo -e -n \"\\r $i\"\n i=$((i+1))\n done\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14210/"
] |
77,996 |
<p>Is it possible to create custom events in C++? For example, say I have the variable X, and the variable Y. Whenever X changes, I would like to execute a function that sets Y equal to 3X. Is there a way to create such a trigger/event? (triggers are common in some databases)</p>
|
[
{
"answer_id": 78135,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 3,
"selected": false,
"text": "template <typename T>\nclass Observable\n{\n T underlying;\n\npublic:\n Observable<T>& operator=(const T &rhs) {\n underlying = rhs;\n fireObservers();\n\n return *this;\n }\n operator T() { return underlying; }\n\n void addObserver(ObsType obs) { ... }\n void fireObservers() { /* Pass every event handler a const & to this instance /* }\n};\n Observable<int> x;\nx.registerObserver(...);\n\nx = 5;\nint y = x;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/77996",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13790/"
] |
78,018 |
<p>In our development environment each developer has their own dev server. Often times they do not actually develop on that server but develop from their local machine, deploy to their dev server, and then attach with the remote debugger to do debugging.</p>
<p>My question is; how can I use MSBuild to execute a different set of tasks for each user?</p>
<p>I want to enable each user to define their own build process with MSBuild tasks but I don't want that to necessarily affect the other developers. I also want a default set of tasks to execute if a given user explicitly defined their own process.</p>
<p>Example:</p>
<ul>
<li>SomeProj.csproj
<ul>
<li>Default MS Build process is to copy to test server or staging server</li>
<li>Custom process for Steve is to copy to Steve's dev server</li>
<li>Custom process for Eric is to copy to Eric's dev server</li>
</ul></li>
</ul>
|
[
{
"answer_id": 102482,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "$(USERNAME)"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
78,048 |
<p>What's the best way to detect an application crash in XP (produces the same pair of 'error' windows each time - each with same window title) and then restart it?</p>
<p>I'm especially interested to hear of solutions that use minimal system resources as the system in question is quite old. </p>
<p>I had thought of using a scripting language like AutoIt (<a href="http://www.autoitscript.com/autoit3/" rel="noreferrer">http://www.autoitscript.com/autoit3/</a>), and perhaps triggering a 'detector' script every few minutes? </p>
<p>Would this be better done in Python, Perl, PowerShell or something else entirely?</p>
<p>Any ideas, tips, or thoughts much appreciated.</p>
<p>EDIT: It doesn't actually crash (i.e. exit/terminate - thanks @tialaramex). It displays a dialog waiting for user input, followed by another dialog waiting for further user input, then it actually exits. It's these dialogs that I'd like to detect and deal with.</p>
|
[
{
"answer_id": 783527,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "from ctypes import windll, c_int, Structure\nimport subprocess\n\nWaitForDebugEvent = windll.kernel32.WaitForDebugEvent \nContinueDebugEvent = windll.kernel32.ContinueDebugEvent\nDBG_CONTINUE = 0x00010002L \nDBG_EXCEPTION_NOT_HANDLED = 0x80010001L\n\nevent_names = { \n 3: 'CREATE_PROCESS_DEBUG_EVENT',\n 2: 'CREATE_THREAD_DEBUG_EVENT',\n 1: 'EXCEPTION_DEBUG_EVENT',\n 5: 'EXIT_PROCESS_DEBUG_EVENT',\n 4: 'EXIT_THREAD_DEBUG_EVENT',\n 6: 'LOAD_DLL_DEBUG_EVENT',\n 8: 'OUTPUT_DEBUG_STRING_EVENT', \n 9: 'RIP_EVENT',\n 7: 'UNLOAD_DLL_DEBUG_EVENT',\n}\nclass DEBUG_EVENT(Structure):\n _fields_ = [\n ('dwDebugEventCode', c_int),\n ('dwProcessId', c_int),\n ('dwThreadId', c_int),\n ('u', c_int*20)]\n\ndef run_with_debugger(args):\n proc = subprocess.Popen(args, creationflags=1)\n event = DEBUG_EVENT()\n\n while True:\n if WaitForDebugEvent(pointer(event), 10):\n print event_names.get(event.dwDebugEventCode, \n 'Unknown Event %s' % event.dwDebugEventCode)\n ContinueDebugEvent(event.dwProcessId, event.dwThreadId, DBG_CONTINUE)\n retcode = proc.poll()\n if retcode is not None:\n return retcode\n\nrun_with_debugger(['python', 'crash.py'])\n"
},
{
"answer_id": 949667,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "from ctypes import windll, c_uint, c_void_p, Structure, Union, pointer\nimport subprocess\n\nWaitForDebugEvent = windll.kernel32.WaitForDebugEvent\nContinueDebugEvent = windll.kernel32.ContinueDebugEvent\nDBG_CONTINUE = 0x00010002L\nDBG_EXCEPTION_NOT_HANDLED = 0x80010001L\n\nevent_names = {\n 1: 'EXCEPTION_DEBUG_EVENT',\n 2: 'CREATE_THREAD_DEBUG_EVENT',\n 3: 'CREATE_PROCESS_DEBUG_EVENT',\n 4: 'EXIT_THREAD_DEBUG_EVENT',\n 5: 'EXIT_PROCESS_DEBUG_EVENT',\n 6: 'LOAD_DLL_DEBUG_EVENT',\n 7: 'UNLOAD_DLL_DEBUG_EVENT',\n 8: 'OUTPUT_DEBUG_STRING_EVENT',\n 9: 'RIP_EVENT',\n}\n\nEXCEPTION_MAXIMUM_PARAMETERS = 15\n\nEXCEPTION_DATATYPE_MISALIGNMENT = 0x80000002\nEXCEPTION_ACCESS_VIOLATION = 0xC0000005\nEXCEPTION_ILLEGAL_INSTRUCTION = 0xC000001D\nEXCEPTION_ARRAY_BOUNDS_EXCEEDED = 0xC000008C\nEXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094\nEXCEPTION_INT_OVERFLOW = 0xC0000095\nEXCEPTION_STACK_OVERFLOW = 0xC00000FD\n\n\nclass EXCEPTION_DEBUG_INFO(Structure):\n _fields_ = [\n (\"ExceptionCode\", c_uint),\n (\"ExceptionFlags\", c_uint),\n (\"ExceptionRecord\", c_void_p),\n (\"ExceptionAddress\", c_void_p),\n (\"NumberParameters\", c_uint),\n (\"ExceptionInformation\", c_void_p * EXCEPTION_MAXIMUM_PARAMETERS),\n ]\n\nclass EXCEPTION_DEBUG_INFO(Structure):\n _fields_ = [\n ('ExceptionRecord', EXCEPTION_DEBUG_INFO),\n ('dwFirstChance', c_uint),\n ]\n\nclass DEBUG_EVENT_INFO(Union):\n _fields_ = [\n (\"Exception\", EXCEPTION_DEBUG_INFO),\n ]\n\nclass DEBUG_EVENT(Structure):\n _fields_ = [\n ('dwDebugEventCode', c_uint),\n ('dwProcessId', c_uint),\n ('dwThreadId', c_uint),\n ('u', DEBUG_EVENT_INFO)\n ]\n\ndef run_with_debugger(args):\n proc = subprocess.Popen(args, creationflags=1)\n event = DEBUG_EVENT()\n\n num_exception = 0\n\n while True:\n if WaitForDebugEvent(pointer(event), 10):\n print event_names.get(event.dwDebugEventCode, 'Unknown Event %s' % event.dwDebugEventCode)\n\n if event.dwDebugEventCode == 1:\n num_exception += 1\n\n exception_code = event.u.Exception.ExceptionRecord.ExceptionCode\n\n if exception_code == 0x80000003L:\n print \"Unknow exception:\", hex(exception_code)\n\n else:\n if exception_code == EXCEPTION_ACCESS_VIOLATION:\n print \"EXCEPTION_ACCESS_VIOLATION\"\n\n elif exception_code == EXCEPTION_INT_DIVIDE_BY_ZERO:\n print \"EXCEPTION_INT_DIVIDE_BY_ZERO\"\n\n elif exception_code == EXCEPTION_STACK_OVERFLOW:\n print \"EXCEPTION_STACK_OVERFLOW\"\n\n else:\n print \"Other exception:\", hex(exception_code)\n\n break\n\n ContinueDebugEvent(event.dwProcessId, event.dwThreadId, DBG_CONTINUE)\n\n retcode = proc.poll()\n if retcode is not None:\n return retcode\n\nrun_with_debugger(['crash.exe'])\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13967/"
] |
78,053 |
<p>I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do:</p>
<pre><code>Excel::HPageBreaksPtr pHPageBreaks = pSheet->GetHPageBreaks();
long count = pHPageBreaks->Count;
for (long i=0; i < count; ++i)
{
Excel::HPageBreakPtr pHPageBreak = pHPageBreaks->GetItem(i+1);
Excel::RangePtr pLocation = pHPageBreak->GetLocation();
printf("Page break at row %d\n", pLocation->Row);
pLocation.Release();
pHPageBreak.Release();
}
pHPageBreaks.Release();
</code></pre>
<p>I expect this to print out the row numbers of each of the horizontal page breaks in <code>pSheet</code>. The problem I'm having is that although <code>count</code> correctly indicates the number of page breaks in the worksheet, I can only ever seem to retrieve the first one. On the second run through the loop, calling <code>pHPageBreaks->GetItem(i)</code> throws an exception, with error number 0x8002000b, "invalid index".</p>
<p>Attempting to use <code>pHPageBreaks->Get_NewEnum()</code> to get an enumerator to iterate over the collection also fails with the same error, immediately on the call to <code>Get_NewEnum()</code>.</p>
<p>I've looked around for a solution, and the closest thing I've found so far is <a href="http://support.microsoft.com/kb/210663/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/210663/en-us</a>. I have tried activating various cells beyond the page breaks, including the cells just beyond the range to be printed, as well as the lower-right cell (IV65536), but it didn't help.</p>
<p>If somebody can tell me how to get Excel to return the locations of all of the page breaks in a sheet, that would be awesome!</p>
<p>Thank you.</p>
<p>@Joel: Yes, I have tried displaying the user interface, and then setting <code>ScreenUpdating</code> to true - it produced the same results. Also, I have since tried combinations of setting <code>pSheet->PrintArea</code> to the entire worksheet and/or calling <code>pSheet->ResetAllPageBreaks()</code> before my call to get the <code>HPageBreaks</code> collection, which didn't help either.</p>
<p>@Joel: I've used <code>pSheet->UsedRange</code> to determine the row to scroll past, and Excel does scroll past all the horizontal breaks, but I'm still having the same issue when I try to access the second one. Unfortunately, switching to Excel 2007 did not help either.</p>
|
[
{
"answer_id": 78866,
"author": "Joel Spolsky",
"author_id": 4,
"author_profile": "https://Stackoverflow.com/users/4",
"pm_score": 3,
"selected": true,
"text": "Range(\"A1\").Select\nnumRows = Range(\"A1\").End(xlDown).Row\n\nWhile ActiveWindow.ScrollRow < numRows\n ActiveWindow.LargeScroll Down:=1\nWend\n\nFor Each x In ActiveSheet.HPageBreaks\n Debug.Print x.Location.Row\nNext\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14238/"
] |
78,064 |
<p>I've read this <a href="https://stackoverflow.com/questions/40122/exceptions-in-web-services">thread</a> for WCF has inbuilt Custom Fault codes and stuff.</p>
<p>But what is the best practice for <em>ASP.Net</em> web services? Do I throw exceptions and let the client handle the exception or send an Error code (success, failure etc) that the client would rely upon to do its processing.</p>
<p>Update: Just to discuss further in case of <em>SOAP</em>, let's say the client makes a <em>web svc</em> call which is supposed to be a notification message (no return value expected), so everything goes smooth and no exceptions are thrown by the svc. </p>
<p>Now how will the client know if the notification call has gotten lost due to a communication/network problem or something in between the server and the client? compare this with not having any exception thrown. Client might assume it's a success. But it's not. The call got lost somewhere.</p>
<p>Does send a 'success' error code ensures to the client that the call went smooth? is there any other way to achieve this or is the scenario above even possible?</p>
|
[
{
"answer_id": 91536,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 3,
"selected": true,
"text": "Private Sub WebServiceExceptionHandler(ByVal ex As Exception)\n Dim ueh As New AspUnhandledExceptionHandler\n ueh.HandleException(ex)\n\n '-- Build the detail element of the SOAP fault.\n Dim doc As New System.Xml.XmlDocument\n Dim node As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _\n SoapException.DetailElementName.Name, _\n SoapException.DetailElementName.Namespace)\n\n '-- append our error detail string to the SOAP detail element\n Dim details As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _\n \"ExceptionInfo\", _\n SoapException.DetailElementName.Namespace)\n details.InnerText = ueh.ExceptionToString(ex)\n node.AppendChild(details)\n\n '-- re-throw the exception so we can package additional info\n Throw New SoapException(\"Unhandled Exception: \" & ex.Message, _\n SoapException.ClientFaultCode, _\n Context.Request.Url.ToString, node)\nEnd Sub\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1747/"
] |
78,069 |
<p>Anyone know of any good MSBuild tasks that will execute a PowerShell script and pass it different parameters?</p>
<p>I was able to find <a href="http://bartdesmet.net/blogs/bart/archive/2008/02/16/invoking-powershell-scripts-from-msbuild.aspx" rel="nofollow noreferrer">B# .NET Blog: Invoking PowerShell scripts from MSBuild</a>, but I'm hoping for something that is a little more polished.</p>
<p>If I can't find anything I will of course just go ahead and polish my own using that blog post as a starter.</p>
|
[
{
"answer_id": 3465029,
"author": "Ruben Bartelink",
"author_id": 11635,
"author_profile": "https://Stackoverflow.com/users/11635",
"pm_score": 3,
"selected": false,
"text": "PowerShellTaskFactory"
},
{
"answer_id": 12817556,
"author": "Ruben Bartelink",
"author_id": 11635,
"author_profile": "https://Stackoverflow.com/users/11635",
"pm_score": 3,
"selected": false,
"text": "cmd.exe .ps1 <Exec \n IgnoreStandardErrorWarningFormat=\"true\"\n Command=\"PowerShell "$(ThingToDo)"\" />\n ThingToDo ThingToDo ERRORLEVEL .cmd \" ThingToDo <PropertyGroup>\n <__PsInvokeCommand>powershell \"Invoke-Command</__PsInvokeCommand>\n <__BlockBegin>-ScriptBlock { $errorActionPreference='Stop';</__BlockBegin>\n <__BlockEnd>; exit $LASTEXITCODE }</__BlockEnd>\n <_PsCmdStart>$(__PsInvokeCommand) $(__BlockBegin)</_PsCmdStart>\n <_PsCmdEnd>$(__BlockEnd)\"</_PsCmdEnd>\n</PropertyGroup>\n <Exec \n IgnoreStandardErrorWarningFormat=\"true\"\n Command=\"$(_PsCmdStart)$(ThingToDo)$(_PsCmdEnd)\" />\n"
},
{
"answer_id": 41051774,
"author": "Garrett Serack",
"author_id": 181469,
"author_profile": "https://Stackoverflow.com/users/181469",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\n <!-- #1 Place this line at the top of any msbuild script (ie, csproj, etc) -->\n <PropertyGroup><PowerShell># 2>nul || type %~df0|find /v \"setlocal\"|find /v \"errorlevel\"|powershell.exe -noninteractive -& exit %errorlevel% || #</PowerShell></PropertyGroup>\n\n <!-- #2 in any target you want to run a script -->\n <Target Name=\"default\" >\n\n <PropertyGroup> <!-- #3 prefix your powershell script with the $(PowerShell) variable, then code as normal! -->\n <myscript>$(PowerShell)\n #\n # powershell script can do whatever you need.\n #\n dir \".\\*.cs\" -recurse |% {\n write-host Examining file named: $_.FullName\n # do other stuff here...\n } \n $answer = 2+5\n write-host Answer is $answer !\n </myscript>\n </PropertyGroup>\n\n <!-- #4 and execute the script like this -->\n <Exec Command=\"$(myscript)\" EchoOff=\"true\" /> \n </Target>\n</Project>\n <script2><![CDATA[ $(PowerShell)\n # your powershell code goes here!\n write-host \"<<Hi mom!>>\"\n]]></script2>\n <script3>$(PowerShell)\n # your powershell code goes here!\n (dir \"*.cs\" -recurse).FullName\n</script3>\n\n<Exec Command=\"$(script3)\" EchoOff=\"true\" ConsoleToMSBuild=\"true\"> \n <Output TaskParameter=\"ConsoleOutput\" PropertyName=\"items\" />\n</Exec>\n<Touch Files=\"$(items)\" /> \n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
78,077 |
<p>What is the best/fastest way to sort Alphanumeric fields? </p>
|
[
{
"answer_id": 78118,
"author": "Ciaran",
"author_id": 5048,
"author_profile": "https://Stackoverflow.com/users/5048",
"pm_score": 1,
"selected": false,
"text": "$fruits = array(\"lemon\", \"orange\", \"banana\", \"apple\");\nsort($fruits);\n\nforeach ($fruits as $key => $val)\n{\n echo \"fruits[\" . $key . \"] = \" . $val . \"\\n\";\n}\n fruits[0] = apple\nfruits[1] = banana\nfruits[2] = lemon\nfruits[3] = orange\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14239/"
] |
78,091 |
<p>In the middle of a Perl script, there is a system command I want to execute. I have a string that contains the data that needs to be fed into stdin (the command only accepts input from stdin), and I need to capture the output written to stdout. I've looked at the various methods of executing system commands in Perl, and the <code>open</code> function seems to be what I need, except that it looks like I can only capture stdin or stdout, not both.</p>
<p>At the moment, it seems like my best solution is to use <code>open</code>, redirect stdout into a temporary file, and read from the file after the command finishes. Is there a better solution?</p>
|
[
{
"answer_id": 78154,
"author": "X-Istence",
"author_id": 13986,
"author_profile": "https://Stackoverflow.com/users/13986",
"pm_score": 1,
"selected": false,
"text": "open2()\n"
},
{
"answer_id": 78201,
"author": "benzado",
"author_id": 10947,
"author_profile": "https://Stackoverflow.com/users/10947",
"pm_score": 2,
"selected": false,
"text": "use IPC::Open2;\n $pid = open2($cmd_out, $cmd_in, 'some cmd and args');\n"
},
{
"answer_id": 78323,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "my $result = qx( command args 2>&1 ); \nmy $rc=$?; \n# $rc >> 8 is the exit code of the called program.\n\nif ($rc != 0 ) { \n error(); \n} \n my @lines = qx( command args 2>&1 ); \n\nforeach ( my $line ) (@lines) { \n if ( $line =~ /some pattern/ ) { \n do_something(); \n } \n} \n"
},
{
"answer_id": 79723,
"author": "xdg",
"author_id": 11800,
"author_profile": "https://Stackoverflow.com/users/11800",
"pm_score": 3,
"selected": false,
"text": "use IPC::Run3; # Exports run3() by default\n\nrun3( \\@cmd, \\$in, \\$out, \\$err );\n"
},
{
"answer_id": 81251,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 0,
"selected": false,
"text": "open(TMP,\">tmpfile\");\nprint TMP $tmpdata ;\nopen(RES,\"$yourcommand|\");\n$res = \"\" ;\nwhile(<RES>){\n$res .= $_ ;\n}\n"
},
{
"answer_id": 82219,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "$output = filter $input, 'somecmd', '--with', 'various=args', '--etc';\n die"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
78,125 |
<p>The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc & g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care):</p>
<pre><code>char **a;
const char** b = a;
</code></pre>
<p>I can understand and accept this.<br>
The C++ solution to this problem is to change b to be a const char * const *, which disallows reassignment of the pointers and prevents you from circumventing const-correctness (<a href="http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17" rel="nofollow noreferrer">C++ FAQ</a>).<br></p>
<pre><code>char **a;
const char* const* b = a;
</code></pre>
<p>However, in pure C, the corrected version (using const char * const *) still gives a warning, and I don't understand why.
Is there a way to get around this without using a cast?</p>
<p>To clarify:<br>
1) Why does this generate a warning in C? It should be entirely const-safe, and the C++ compiler seems to recognize it as such.<br>
2) What is the correct way to go about accepting this char** as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to?
For example, if I wanted to write a function:</p>
<pre><code>void f(const char* const* in) {
// Only reads the data from in, does not write to it
}
</code></pre>
<p>And I wanted to invoke it on a char**, what would be the correct type for the parameter?</p>
|
[
{
"answer_id": 78202,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 7,
"selected": true,
"text": "char** const char*const*"
},
{
"answer_id": 78218,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 3,
"selected": false,
"text": "const_cast const const const const const const void foo(const int*);\n foo const char *y;\n\nchar **a = &y; // a points to y\nconst char **b = a; // now b also points to y\n\n// const protection has been violated, because:\n\nconst char x = 42; // x must never be modified\n*b = &x; // the type of *b is const char *, so set it \n // with &x which is const char* ..\n // .. so y is set to &x... oops;\n*y = 43; // y == &x... so attempting to modify const \n // variable. oops! undefined behavior!\ncout << x << endl;\n const const const b a const 42 43 const char * const *"
},
{
"answer_id": 78410,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 0,
"selected": false,
"text": "#include <stdlib.h> \n#include <stdio.h>\nvoid foo(const char * const * bar)\n{\n printf(\"bar %s null\\n\", bar ? \"is not\" : \"is\");\n}\n\nint main(int argc, char **argv) \n{\n char **x = NULL; \n const char* const*y = x;\n foo(x);\n foo(y);\n return 0; \n}\n test.c(8) : warning C4100: 'argv' : unreferenced formal parameter\ntest.c(8) : warning C4100: 'argc' : unreferenced formal parameter\n test.c(8) : warning C4100: 'argv' : unreferenced formal parameter\ntest.c(8) : warning C4100: 'argc' : unreferenced formal parameter\n test2.c: In function `main':\ntest2.c:11: warning: initialization from incompatible pointer type\ntest2.c:12: warning: passing arg 1 of `foo' from incompatible pointer type\n"
},
{
"answer_id": 78427,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 0,
"selected": false,
"text": "const volatile int *const serial_port = SERIAL_PORT;\n char *const p = (char *) 0xb000;\n//error: p = (char *) 0xc000;\nchar **q = (char **)&p;\n*q = (char *)0xc000; // p is now 0xc000\n"
},
{
"answer_id": 78534,
"author": "Fabio Ceconello",
"author_id": 8999,
"author_profile": "https://Stackoverflow.com/users/8999",
"pm_score": 4,
"selected": false,
"text": "char **a;\nconst char* const* b = a;\n const char **a;\nconst char* const* b = a;\n char **a;\nconst char* const* b = (const char **)a;\n"
},
{
"answer_id": 98399,
"author": "wnoise",
"author_id": 15464,
"author_profile": "https://Stackoverflow.com/users/15464",
"pm_score": 1,
"selected": false,
"text": "char c = 'c';\nchar *p = &c;\nchar **a = &p;\n\nconst char *bi = *a;\nconst char * const * b = &bi;\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14266/"
] |
78,127 |
<p>Apple's CoreGraphics library defines two functions for describing an arc.</p>
<ul>
<li>CGPathAddArc adds an arc based on a center point, radius, and pair of angles.</li>
<li>CGPathAddArcToPoint adds an arc based on a radius and a pair of tangent lines.</li>
</ul>
<p>The details are explained in <a href="http://developer.apple.com/documentation/GraphicsImaging/Reference/CGPath/Reference/reference.html" rel="noreferrer">the CGPath API reference</a>. Why two functions? Simple convenience? Is one more efficient than the other? Is one defined in terms of the other?</p>
|
[
{
"answer_id": 19065433,
"author": "James Snook",
"author_id": 2599552,
"author_profile": "https://Stackoverflow.com/users/2599552",
"pm_score": 6,
"selected": false,
"text": "CGContextAddArc startAngle endAngle radius x y CGContextAddArcToPoint x1 x2 y1 y2 radius (x1, y1) (x1, y1) (x2, y2) (x2, y2)"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10947/"
] |
78,141 |
<h2>Edit - New Question</h2>
<p>Ok lets rephrase the question more generically. </p>
<p>Using reflection, is there a way to dynamically call at runtime a base class method that you may be overriding. You cannot use the 'base' keyword at compile time because you cannot be sure it exists. At runtime I want to list my ancestors methods and call the ancestor methods.</p>
<p>I tried using GetMethods() and such but all they return are "pointers" to the most derived implementation of the method. Not an implementation on a base class.</p>
<h2>Background</h2>
<p>We are developing a system in C# 3.0 with a relatively big class hierarchy. Some of these classes, anywhere in the hierarchy, have resources that need to be
disposed of, those implement the <strong>IDisposable</strong> interface.</p>
<h2>The Problem</h2>
<p>Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable,
to "automatically" call <strong>base.Dispose(bDisposing)</strong> if any ancestors also implements IDisposable. This way, if some class higher up in the hierarchy starts implementing
or stops implementing IDisposable that will be taken care of automatically.</p>
<p>The issue is two folds. </p>
<ul>
<li>First, finding if any ancestors implements IDisposable. </li>
<li>Second, calling base.Dispose(bDisposing) conditionally.</li>
</ul>
<p>The first part, finding about ancestors implementing IDisposable, I have been able to deal with. </p>
<p>The second part is the tricky one. Despite all my
efforts, I haven't been able to call base.Dispose(bDisposing) from a derived class. All my attempts failed. They either caused
compilation errors or called the wrong Dispose() method, that is the most derived one, thus looping forever.</p>
<p>The main issue is that you <strong>cannot actually refer to base.Dispose()</strong> directly in your code if there is no such thing as an
ancestor implementing it (<em>be reminded that there might have no ancestors yet implementing IDisposable, but I want the derived code to be ready when and if such
a thing happens in the future</em>). That leave us with the <strong>Reflection</strong> mechanisms, but I did not find a proper way of doing it. Our code is quite filled with
advanced reflection techniques and I think I did not miss anything obvious there.</p>
<h2>My Solution</h2>
<p>My best shot yet was to have some conditional code using in commented code. Changing the IDisposable hierarchy would either break the build
(if no IDisposable ancestor exists) or throw an exception (if there are IDisposable ancestors but base.Dispose is not called).</p>
<p>Here is some code I am posting to show you what my Dispose(bDisposing) method looks like. I am putting this code at the end of all the Dispose()
methods throughout the hierarchy. Any new classes are created from templates that also includes this code. </p>
<pre><code>public class MyOtherClassBase
{
// ...
}
public class MyDerivedClass : MyOtherClassBase, ICalibrable
{
private bool m_bDisposed = false;
~MyDerivedClass()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool bDisposing)
{
if (!m_bDisposed) {
if (bDisposing) {
// Dispose managed resources
}
// Dispose unmanaged resources
}
m_bDisposed = true;
Type baseType = typeof(MyDerivedClass).BaseType;
if (baseType != null) {
if (baseType.GetInterface("IDisposable") != null) {
// If you have no ancestors implementing base.Dispose(...), comment
// the following line AND uncomment the throw.
//
// This way, if any of your ancestors decide one day to implement
// IDisposable you will know about it right away and proceed to
// uncomment the base.Dispose(...) in addition to commenting the throw.
//base.Dispose(bDisposing);
throw new ApplicationException("Ancestor base.Dispose(...) not called - "
+ baseType.ToString());
}
}
}
}
</code></pre>
<p><strong>So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?</strong></p>
<h2>More Background</h2>
<p>There is another mechanism in the application where all objects are registered with a main class. The class checks if they implement IDisposable.
If so, they are disposed of properly by the application. This avoids having the code using the classes to deal with
calling Dispose() all around by themselves. Thus, adding IDisposable to a class that has no ancestor history of IDisposable still works perfectly.</p>
|
[
{
"answer_id": 78315,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 3,
"selected": false,
"text": "components components components"
},
{
"answer_id": 78322,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 0,
"selected": false,
"text": "public class MyVeryBaseClass {\n protected void RealDispose(bool isDisposing) {\n IDisposable tryme = this as IDisposable;\n if (tryme != null) { // we implement IDisposable\n this.Dispose();\n base.RealDispose(isDisposing);\n }\n }\n}\npublic class FirstChild : MyVeryBaseClasee {\n //non-disposable\n}\npublic class SecondChild : FirstChild, IDisposable {\n ~SecondChild() {\n Dispose(false);\n }\n public void Dispose() {\n Dispose(true);\n GC.SuppressFinalize(this);\n base.RealDispose(true);\n }\n protected virtual void Dispose(bool bDisposing) {\n if (!m_bDisposed) {\n if (bDisposing) {\n }// Dispose managed resources\n } // Dispose unmanaged resources\n }\n}\n"
},
{
"answer_id": 78458,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 0,
"selected": false,
"text": "Dispose(bool) IDisposable // Disposal Helper Functions\npublic static class Disposing\n{\n // Executes IDisposable.Dispose() if it exists.\n public static void DisposeSuperclass(object o)\n {\n Type baseType = o.GetType().BaseType;\n bool superclassIsDisposable = typeof(IDisposable).IsAssignableFrom(baseType);\n if (superclassIsDisposable)\n {\n System.Reflection.MethodInfo baseDispose = baseType.GetMethod(\"Dispose\", new Type[] { });\n baseDispose.Invoke(o, null);\n }\n }\n}\n\nclass classA: IDisposable\n{\n public void Dispose()\n {\n Console.WriteLine(\"Disposing A\");\n }\n}\n\nclass classB : classA, IDisposable\n{\n}\n\nclass classC : classB, IDisposable\n{\n public void Dispose()\n {\n Console.WriteLine(\"Disposing C\");\n Disposing.DisposeSuperclass(this);\n }\n}\n"
},
{
"answer_id": 3681224,
"author": "SUmeet Khandelwal",
"author_id": 443903,
"author_profile": "https://Stackoverflow.com/users/443903",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace TestDisposeInheritance\n{\n class Program\n {\n static void Main(string[] args)\n {\n classC c = new classC();\n c.Dispose();\n }\n }\n\n class classA: IDisposable \n { \n private bool m_bDisposed;\n protected virtual void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine(\"Dispose A\"); \n }\n // Dispose unmanaged resources \n }\n }\n public void Dispose() \n {\n Dispose(true);\n GC.SuppressFinalize(this);\n Console.WriteLine(\"Disposing A\"); \n } \n } \n\n class classB : classA, IDisposable \n {\n private bool m_bDisposed;\n public void Dispose()\n {\n Dispose(true);\n base.Dispose();\n GC.SuppressFinalize(this);\n Console.WriteLine(\"Disposing B\");\n }\n\n protected override void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine(\"Dispose B\");\n }\n // Dispose unmanaged resources \n }\n }\n } \n\n class classC : classB, IDisposable \n {\n private bool m_bDisposed;\n public void Dispose() \n {\n Dispose(true);\n base.Dispose();\n GC.SuppressFinalize(this);\n Console.WriteLine(\"Disposing C\"); \n }\n protected override void Dispose(bool bDisposing)\n {\n if (!m_bDisposed)\n {\n if (bDisposing)\n {\n // Dispose managed resources\n Console.WriteLine(\"Dispose C\"); \n }\n // Dispose unmanaged resources \n }\n }\n } \n\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7984/"
] |
78,157 |
<p>I'm working on an embedded Linux project that interfaces an ARM9 to a hardware video encoder chip, and writes the video out to SD card or USB stick. The software architecture involves a kernel driver that reads data into a pool of buffers, and a userland app that writes the data to a file on the mounted removable device.</p>
<p>I am finding that above a certain data rate (around 750kbyte/sec) I start to see the userland video-writing app stalling for maybe half a second, about every 5 seconds. This is enough to cause the kernel driver to run out of buffers - and even if I could increase the number of buffers, the video data has to be synchronised (ideally within 40ms) with other things that are going on in real time. Between these 5 second "lag spikes", the writes complete well within 40ms (as far as the app is concerned - I appreciate they're buffered by the OS)</p>
<p>I think this lag spike is to do with the way Linux is flushing data out to disk - I note that pdflush is designed to wake up every 5s, my understanding is that this would be what does the writing. As soon as the stall is over the userland app is able to quickly service and write the backlog of buffers (that didn't overflow).</p>
<p>I think the device I'm writing to has reasonable ultimate throughput: copying a 15MB file from a memory fs and waiting for sync to complete (and the usb stick's light to stop flashing) gave me a write speed of around 2.7MBytes/sec.</p>
<p>I'm looking for two kinds of clues:</p>
<ol>
<li><p>How can I stop the bursty writing from stalling my app - perhaps process priorities, realtime patches, or tuning the filesystem code to write continuously rather than burstily?</p></li>
<li><p>How can I make my app(s) aware of what is going on with the filesystem in terms of write backlog and throughput to the card/stick? I have the ability to change the video bitrate in the hardware codec on the fly which would be much better than dropping frames, or imposing an artificial cap on maximum allowed bitrate.</p></li>
</ol>
<p>Some more info: this is a 200MHz ARM9 currently running a Montavista 2.6.10-based kernel.</p>
<p>Updates:<ul>
<li>Mounting the filesystem SYNC causes throughput to be much too poor.
<li>The removable media is FAT/FAT32 formatted and must be as the purpose of the design is that the media can be plugged into any Windows PC and read.
<li>Regularly calling sync() or fsync() say, every second causes regular stalls and unacceptably poor throughput
<li>I am using write() and open(O_WRONLY | O_CREAT | O_TRUNC) rather than fopen() etc.
<li>I can't immediately find anything online about the mentioned "Linux realtime filesystems". Links?
</ul></p>
<p>I hope this makes sense. First embedded Linux question on stackoverflow? :)</p>
|
[
{
"answer_id": 78284,
"author": "Drew Frezell",
"author_id": 10954,
"author_profile": "https://Stackoverflow.com/users/10954",
"pm_score": 3,
"selected": false,
"text": "fopen, fread, fwrite open, read, write O_SYNC copy_to_user"
},
{
"answer_id": 84160,
"author": "shodanex",
"author_id": 11589,
"author_profile": "https://Stackoverflow.com/users/11589",
"pm_score": 1,
"selected": false,
"text": "empty_buffer_queue\nready_buffer_queue\nvideo_data_ready_semaphore\n buf=get_buffer()\nbufer_to_write = buf_dequeue(empty_buffer_queue)\nmemcpy(bufer_to_write, buf)\nbuf_enqueue(bufer_to_write, ready_buffer_queue)\nsem_post(video_data_ready_semaphore)\n sem_wait(vido_data_ready_semaphore)\nbufer_to_write = buf_dequeue(ready_buffer_queue)\nwrite_buffer\nbuf_enqueue(bufer_to_write, empty_buffer_queue)\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200/"
] |
78,161 |
<p>In a C++ app, I have an hWnd pointing to a window running in a third party process. This window contains controls which extend the COM TreeView control. I am interested in obtaining the CheckState of this control.<br>
I use the hWnd to get an HTREEITEM using TreeView_GetRoot(hwnd) from commctrl.h</p>
<p>hwnd points to the window and hItem is return value from TreeView_GetRoot(hwnd). They are used as follows:</p>
<pre><code>int iCheckState = TreeView_GetCheckState(hwnd, hItem);
switch (iCheckState)
{
case 0:
// (unchecked)
case 1:
// checked
...
}
</code></pre>
<p>I'm looking to port this code into a C# app which does the same thing (switches off the CheckState of the TreeView control). I have never used COM and am quite unfamiliar.</p>
<p>I have tried using the .NET mscomctl but can't find equivalent methods to TreeView_GetRoot or TreeView_GetCheckState. I'm totally stuck and don't know how to recreate this code in C# :(</p>
<p>Suggestions?</p>
|
[
{
"answer_id": 79794,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": true,
"text": "#define TreeView_SetItemState(hwndTV, hti, data, _mask) \\\n{ TVITEM _ms_TVi;\\\n _ms_TVi.mask = TVIF_STATE; \\\n _ms_TVi.hItem = (hti); \\\n _ms_TVi.stateMask = (_mask);\\\n _ms_TVi.state = (data);\\\n SNDMSG((hwndTV), TVM_SETITEM, 0, (LPARAM)(TV_ITEM *)&_ms_TVi);\\\n}\n\n#define TreeView_SetCheckState(hwndTV, hti, fCheck) \\\n TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck)?2:1), TVIS_STATEIMAGEMASK)\n static class Interop {\n\npublic static IntPtr TreeView_SetCheckState(HandleRef hwndTV, IntPtr hti, bool fCheck) {\n return TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck) ? 2 : 1), (uint)TVIS.TVIS_STATEIMAGEMASK);\n}\n\npublic static IntPtr TreeView_SetItemState(HandleRef hwndTV, IntPtr hti, uint data, uint _mask) {\n TVITEM _ms_TVi = new TVITEM();\n _ms_TVi.mask = (uint)TVIF.TVIF_STATE;\n _ms_TVi.hItem = (hti);\n _ms_TVi.stateMask = (_mask);\n _ms_TVi.state = (data);\n IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(_ms_TVi));\n Marshal.StructureToPtr(_ms_TVi, p, false);\n IntPtr r = SendMessage(hwndTV, (int)TVM.TVM_SETITEMW, IntPtr.Zero, p);\n Marshal.FreeCoTaskMem(p);\n return r;\n}\n\nprivate static uint INDEXTOSTATEIMAGEMASK(int i) { return ((uint)(i) << 12); }\n\n[DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\nprivate static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam);\n\nprivate enum TVIF : uint {\n TVIF_STATE = 0x0008\n}\n\nprivate enum TVIS : uint {\n TVIS_STATEIMAGEMASK = 0xF000\n}\n\nprivate enum TVM : int {\n TV_FIRST = 0x1100,\n TVM_SETITEMA = (TV_FIRST + 13),\n TVM_SETITEMW = (TV_FIRST + 63)\n}\n\nprivate struct TVITEM {\n public uint mask;\n public IntPtr hItem;\n public uint state;\n public uint stateMask;\n public IntPtr pszText;\n public int cchTextMax;\n public int iImage;\n public int iSelectedImage;\n public int cChildren;\n public IntPtr lParam;\n}\n}\n"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165305/"
] |
78,172 |
<p>In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that they might be protected by a lock or not (barriers perhaps).</p>
<p>Does the pthread POSIX standard have any say about this, is this compiler-dependent or neither?</p>
<p>Edit to add: Thanks for the great answers. But what if you're <em>not</em> using locks; what if you're using <a href="http://en.wikipedia.org/wiki/Barrier_(computer_science)" rel="noreferrer">barriers</a> for example? Or code that uses primitives such as <a href="http://en.wikipedia.org/wiki/Compare_and_swap" rel="noreferrer">compare-and-swap</a> to directly and atomically modify a shared variable...</p>
|
[
{
"answer_id": 559133,
"author": "cmcginty",
"author_id": 64313,
"author_profile": "https://Stackoverflow.com/users/64313",
"pm_score": 2,
"selected": false,
"text": "Volatile volatile volatile"
},
{
"answer_id": 8120128,
"author": "IOException",
"author_id": 230803,
"author_profile": "https://Stackoverflow.com/users/230803",
"pm_score": 2,
"selected": false,
"text": " volatile int Ready; \n\n int Message[100]; \n\n void foo( int i ) { \n\n Message[i/10] = 42; \n\n Ready = 1; \n\n }\n"
},
{
"answer_id": 36608264,
"author": "David Schwartz",
"author_id": 721269,
"author_profile": "https://Stackoverflow.com/users/721269",
"pm_score": -1,
"selected": false,
"text": "volatile volatile volatile volatile"
},
{
"answer_id": 46987303,
"author": "Patrick Pan",
"author_id": 2376062,
"author_profile": "https://Stackoverflow.com/users/2376062",
"pm_score": 0,
"selected": false,
"text": "int y;\nint x = READ_ONCE(y);\n int y;\nint x = *(volatile int *)&y;\n"
},
{
"answer_id": 58935671,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 1,
"selected": false,
"text": "pthread_lock pthread_barrier_wait()\npthread_cond_broadcast()\npthread_cond_signal()\npthread_cond_timedwait()\npthread_cond_wait()\npthread_create()\npthread_join()\npthread_mutex_lock()\npthread_mutex_timedlock()\npthread_mutex_trylock()\npthread_mutex_unlock()\npthread_spin_lock()\npthread_spin_trylock()\npthread_spin_unlock()\npthread_rwlock_rdlock()\npthread_rwlock_timedrdlock()\npthread_rwlock_timedwrlock()\npthread_rwlock_tryrdlock()\npthread_rwlock_trywrlock()\npthread_rwlock_unlock()\npthread_rwlock_wrlock()\nsem_post()\nsem_timedwait()\nsem_trywait()\nsem_wait()\nsemctl()\nsemop()\nwait()\nwaitpid()\n pthread_mutex_lock pthread_mutex_unlock volatile"
}
] |
2008/09/16
|
[
"https://Stackoverflow.com/questions/78172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11688/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.