qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
78,847 | <p>ASP.NET 1.1 - I have a DataGrid on an ASPX page that is databound and displays a value within a textbox. The user is able to change this value, then click on a button where the code behind basically iterates through each DataGridItem in the grid, does a FindControl for the ID of the textbox then assigns the .Text value to a variable which is then used to update the database. The DataGrid is rebound with the new values.</p>
<p>The issue I'm having is that when assigning the .Text value to the variable, the value being retrieved is the original databound value and not the newly entered user value. Any ideas as to what may be causing this behaviour?</p>
<p>Code sample:</p>
<pre><code>foreach(DataGridItem dgi in exGrid.Items)
{
TextBox Text1 = (TextBox)dgi.FindControl("TextID");
string exValue = Text1.Text; //This is retrieving the original bound value not the newly entered value
// do stuff with the new value
}
</code></pre>
| [
{
"answer_id": 79791,
"author": "Nathan Feger",
"author_id": 8563,
"author_profile": "https://Stackoverflow.com/users/8563",
"pm_score": 1,
"selected": false,
"text": "<p>Are you able to manage permissions on this database? Would adding a separate user who only has read access to a database be sufficient for this type of scenario? This could be a read-only user on the main database, but is only effectively used on the snapshot db.</p>\n\n<p>i.e. Add a new user, readerMan5000 who is only given select access, to the database in question. Then require users to authenticate through that new credential.</p>\n\n<p>Note to future commenters, you may want to read: \n<a href=\"http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/\" rel=\"nofollow noreferrer\">http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/</a>\nor \n<a href=\"http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx</a>\nbefore you open your big mouth like me. :)</p>\n"
},
{
"answer_id": 215786,
"author": "Brent Ozar",
"author_id": 26837,
"author_profile": "https://Stackoverflow.com/users/26837",
"pm_score": 0,
"selected": false,
"text": "<p>You can't change permissions after you take the snapshot, but here's one workaround: instead of having them access the tables directly, require them to use views instead. If the views are used only for reporting, then you can set tight security on them in the original database, and then have the users hit those views in the snapshot. You'll need to restrict access on the underlying tables though if you want it to be effective.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/710/"
]
| ASP.NET 1.1 - I have a DataGrid on an ASPX page that is databound and displays a value within a textbox. The user is able to change this value, then click on a button where the code behind basically iterates through each DataGridItem in the grid, does a FindControl for the ID of the textbox then assigns the .Text value to a variable which is then used to update the database. The DataGrid is rebound with the new values.
The issue I'm having is that when assigning the .Text value to the variable, the value being retrieved is the original databound value and not the newly entered user value. Any ideas as to what may be causing this behaviour?
Code sample:
```
foreach(DataGridItem dgi in exGrid.Items)
{
TextBox Text1 = (TextBox)dgi.FindControl("TextID");
string exValue = Text1.Text; //This is retrieving the original bound value not the newly entered value
// do stuff with the new value
}
``` | Are you able to manage permissions on this database? Would adding a separate user who only has read access to a database be sufficient for this type of scenario? This could be a read-only user on the main database, but is only effectively used on the snapshot db.
i.e. Add a new user, readerMan5000 who is only given select access, to the database in question. Then require users to authenticate through that new credential.
Note to future commenters, you may want to read:
<http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/>
or
<http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx>
before you open your big mouth like me. :) |
78,849 | <p>I have an image (mx) and i want to get the uint of the pixel that was clicked.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 79221,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 3,
"selected": false,
"text": "<p>A few minutes on the <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html\" rel=\"nofollow noreferrer\">BitmapData LiveDoc Page</a> will take you where you need to go. Once you have your image loaded into a Bitmap variable, you can access its BitmapData property. Add a <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/events/MouseEvent.html#CLICK\" rel=\"nofollow noreferrer\">Mouse Click Event</a> Listener to the image and then use <a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/display/BitmapData.html\" rel=\"nofollow noreferrer\">BitmapData::getPixel</a>. The example for getPixel shows how to convert the uint response to an rgb hex code.</p>\n\n<p>Here's a modification of the Example given on the BitmapData page that worked for me (using mxmlc - YMMV):</p>\n\n<pre><code>package {\n import flash.display.Bitmap;\n import flash.display.BitmapData;\n import flash.display.Loader;\n import flash.display.Sprite;\n import flash.events.Event;\n import flash.events.MouseEvent;\n import flash.net.URLRequest;\n\n public class BitmapDataExample extends Sprite {\n private var url:String = \"santa-drunk1.jpg\";\n private var size:uint = 200;\n private var image:Bitmap;\n\n public function BitmapDataExample() {\n configureAssets();\n }\n\n private function configureAssets():void {\n var loader:Loader = new Loader();\n loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);\n\n var request:URLRequest = new URLRequest(url);\n loader.load(request);\n addChild(loader);\n }\n\n private function completeHandler(event:Event):void {\n var loader:Loader = Loader(event.target.loader);\n this.image = Bitmap(loader.content);\n\n this.addEventListener(MouseEvent.CLICK, this.clickListener);\n }\n\n private function clickListener(event:MouseEvent):void {\n var pixelValue:uint = this.image.bitmapData.getPixel(event.localX, event.localY)\n trace(pixelValue.toString(16));\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 85391,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 4,
"selected": true,
"text": "<p>Here's an even simpler implementation. All you do is take a snapshot of the stage using the <strong>draw()</strong> method of bitmapData, then use <strong>getPixel()</strong> on the pixel under the mouse. The advantage of this is that you can sample anything that's been drawn to the stage, not just a given bitmap.</p>\n\n<pre><code>import flash.display.Bitmap;\nimport flash.display.BitmapData;\nimport flash.events.*;\n\nstage.addEventListener(MouseEvent.CLICK, getColorSample);\n\nfunction getColorSample(e:MouseEvent):void {\n var bd:BitmapData = new BitmapData(stage.width, stage.height);\n bd.draw(stage);\n var b:Bitmap = new Bitmap(bd);\n trace(b.bitmapData.getPixel(stage.mouseX,stage.mouseX));\n}\n</code></pre>\n\n<p>Hope this is helpful!</p>\n\n<hr>\n\n<p><strong>Edit</strong>:</p>\n\n<p>This edited version uses a single <code>BitmapData</code>, and removes the unnecessary step of creating a <code>Bitmap</code>. If you're sampling the color on <code>MOUSE_MOVE</code> then this is essential to avoid memory issues. </p>\n\n<p>Note: if you're using a custom cursor sprite you'll have to use an object other than 'state' or else you'll be sampling the color of the custom sprite instead of what's under it.</p>\n\n<pre><code>import flash.display.Bitmap;\nimport flash.display.BitmapData;\nimport flash.events.*;\n\nprivate var _stageBitmap:BitmapData;\n\nstage.addEventListener(MouseEvent.CLICK, getColorSample);\n\nfunction getColorSample(e:MouseEvent):void \n{\n if (_stageBitmap == null) {\n _stageBitmap = new BitmapData(stage.width, stage.height);\n }\n _stageBitmap.draw(stage);\n\n var rgb:uint = _stageBitmap.getPixel(stage.mouseX,stage.mouseY);\n\n var red:int = (rgb >> 16 & 0xff);\n var green:int = (rgb >> 8 & 0xff);\n var blue:int = (rgb & 0xff);\n\n trace(red + \",\" + green + \",\" + blue);\n}\n</code></pre>\n"
},
{
"answer_id": 8619705,
"author": "darscan",
"author_id": 53303,
"author_profile": "https://Stackoverflow.com/users/53303",
"pm_score": 3,
"selected": false,
"text": "<p>This is not specific to Flex or mx:Image, and allows you to grab a pixel color value from any bitmap drawable object (provided you have permission):</p>\n\n<pre><code>private const bitmapData:BitmapData = new BitmapData(1, 1);\nprivate const matrix:Matrix = new Matrix();\nprivate const clipRect:Rectangle = new Rectangle(0, 0, 1, 1);\n\npublic function getColor(drawable:IBitmapDrawable, x:Number, y:Number):uint\n{\n matrix.setTo(1, 0, 0, 1, -x, -y)\n bitmapData.draw(drawable, matrix, null, null, clipRect);\n return bitmapData.getPixel(0, 0);\n}\n</code></pre>\n\n<p>You could easily grab a pixel from the stage or your mx:Image instance. It's a lot more efficient than drawing the entire stage (or drawable object), and should be fast enough to hook up to MouseEvent.MOUSE_MOVE for instant visual feedback.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1748529/"
]
| I have an image (mx) and i want to get the uint of the pixel that was clicked.
Any ideas? | Here's an even simpler implementation. All you do is take a snapshot of the stage using the **draw()** method of bitmapData, then use **getPixel()** on the pixel under the mouse. The advantage of this is that you can sample anything that's been drawn to the stage, not just a given bitmap.
```
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.*;
stage.addEventListener(MouseEvent.CLICK, getColorSample);
function getColorSample(e:MouseEvent):void {
var bd:BitmapData = new BitmapData(stage.width, stage.height);
bd.draw(stage);
var b:Bitmap = new Bitmap(bd);
trace(b.bitmapData.getPixel(stage.mouseX,stage.mouseX));
}
```
Hope this is helpful!
---
**Edit**:
This edited version uses a single `BitmapData`, and removes the unnecessary step of creating a `Bitmap`. If you're sampling the color on `MOUSE_MOVE` then this is essential to avoid memory issues.
Note: if you're using a custom cursor sprite you'll have to use an object other than 'state' or else you'll be sampling the color of the custom sprite instead of what's under it.
```
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.events.*;
private var _stageBitmap:BitmapData;
stage.addEventListener(MouseEvent.CLICK, getColorSample);
function getColorSample(e:MouseEvent):void
{
if (_stageBitmap == null) {
_stageBitmap = new BitmapData(stage.width, stage.height);
}
_stageBitmap.draw(stage);
var rgb:uint = _stageBitmap.getPixel(stage.mouseX,stage.mouseY);
var red:int = (rgb >> 16 & 0xff);
var green:int = (rgb >> 8 & 0xff);
var blue:int = (rgb & 0xff);
trace(red + "," + green + "," + blue);
}
``` |
78,852 | <p>Mapping a collection of enums with NHibernate</p>
<p>Specifically, using Attributes for the mappings.</p>
<p>Currently I have this working mapping the collection as type Int32 and NH seems to take care of it, but it's not exactly ideal.</p>
<p>The error I receive is "Unable to determine type" when trying to map the collection as of the type of the enum I am trying to map.</p>
<p>I found a post that said to define a class as</p>
<pre><code>public class CEnumType : EnumStringType {
public CEnumType() : base(MyEnum) { }
}
</code></pre>
<p>and then map the enum as CEnumType, but this gives "CEnumType is not mapped" or something similar.</p>
<p>So has anyone got experience doing this?</p>
<p>So anyway, just a simple reference code snippet to give an example with</p>
<pre><code> [NHibernate.Mapping.Attributes.Class(Table = "OurClass")]
public class CClass : CBaseObject
{
public enum EAction
{
do_action,
do_other_action
};
private IList<EAction> m_class_actions = new List<EAction>();
[NHibernate.Mapping.Attributes.Bag(0, Table = "ClassActions", Cascade="all", Fetch = CollectionFetchMode.Select, Lazy = false)]
[NHibernate.Mapping.Attributes.Key(1, Column = "Class_ID")]
[NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "Int32")]
public virtual IList<EAction> Actions
{
get { return m_class_actions; }
set { m_class_actions = value;}
}
}
</code></pre>
<p>So, anyone got the correct attributes for me to map this collection of enums as actual enums? It would be really nice if they were stored in the db as strings instead of ints too but it's not completely necessary.</p>
| [
{
"answer_id": 80485,
"author": "alvin",
"author_id": 15121,
"author_profile": "https://Stackoverflow.com/users/15121",
"pm_score": 1,
"selected": false,
"text": "<p>This is the way i do it. There's probably an easier way but this works for me.</p>\n\n<p>Edit: sorry, i overlooked that you want it as a list. I don't know how to do that...</p>\n\n<p>Edit2: maybe you can map it as a protected IList[string], and convert to public IList[EAction] just as i do with a simple property.</p>\n\n<pre><code> public virtual ContractGroups Group\n {\n get\n {\n if (GroupString.IsNullOrEmpty())\n return ContractGroups.Default;\n\n return GroupString.ToEnum<ContractGroups>(); // extension method\n }\n set { GroupString = value.ToString(); }\n }\n\n // this is castle activerecord, you can map this property in NH mapping file as an ordinary string\n [Property(\"`Group`\", NotNull = true)] \n protected virtual string GroupString\n {\n get;\n set;\n }\n\n\n\n /// <summary>\n /// Converts to an enum of type <typeparamref name=\"TEnum\"/>.\n /// </summary>\n /// <typeparam name=\"TEnum\">The type of the enum.</typeparam>\n /// <param name=\"self\">The self.</param>\n /// <returns></returns>\n /// <remarks>From <see href=\"http://www.mono-project.com/Rocks\">Mono Rocks</see>.</remarks>\n public static TEnum ToEnum<TEnum>(this string self)\n where TEnum : struct, IComparable, IFormattable, IConvertible\n {\n Argument.SelfNotNull(self);\n\n return (TEnum)Enum.Parse(typeof(TEnum), self);\n }\n</code></pre>\n"
},
{
"answer_id": 214268,
"author": "kͩeͣmͮpͥ ͩ",
"author_id": 26479,
"author_profile": "https://Stackoverflow.com/users/26479",
"pm_score": 1,
"selected": false,
"text": "<p>instead of</p>\n\n<pre><code>[NHibernate.Mapping.Attributes.Element(2, Column = \"EAction\", Type = \"Int32\")]\n</code></pre>\n\n<p>try</p>\n\n<pre><code>[NHibernate.Mapping.Attributes.Element(2, Column = \"EAction\", Type = \"String\")]\n</code></pre>\n\n<p>ie: change the <code>Int32</code> to <code>String</code></p>\n"
},
{
"answer_id": 271296,
"author": "Geoff Bennett",
"author_id": 35377,
"author_profile": "https://Stackoverflow.com/users/35377",
"pm_score": 1,
"selected": false,
"text": "<p>While I haven't tried using it myself, I stumbled across this code a little while ago and it looks pretty interesting:</p>\n\n<p><a href=\"http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx\" rel=\"nofollow noreferrer\" title=\"Jimmy Bogard - Enumeration Classes\">http://www.lostechies.com/blogs/jimmy_bogard/archive/2008/08/12/enumeration-classes.aspx</a></p>\n\n<p>Like I said, I haven't used it myself, but I'm going to give it a go in a project RSN.</p>\n"
},
{
"answer_id": 2807763,
"author": "Lisa",
"author_id": 314283,
"author_profile": "https://Stackoverflow.com/users/314283",
"pm_score": 2,
"selected": false,
"text": "<p>You will need to map your CEnum type directly. In XML mappings this would mean creating a new class mapping element in your NHibernate XML mappings file.</p>\n\n<p><code><pre></p>\n\n<pre><code><hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.2\" assembly=\"YourAssembly\"\n auto-import=\"true\" default-lazy=\"false\">\n\n ...\n\n <class name=\"YourAssemblyNamespace.CEnum\" table=\"CEnumTable\" mutable=\"false\" >\n <id name=\"Id\" unsaved-value=\"0\" column=\"id\">\n <generator class=\"native\"/>\n </id>\n\n ...\n\n </class>\n\n</hibernate-mapping>\n</code></pre>\n\n<p></pre></code></p>\n\n<p>To do it with attribute mappings, something like this on top of your CEnum class:</p>\n\n<p><code>[NHibernate.Mapping.Attributes.Class(Table = \"CEnumTable\")] //etc as you require</code></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/924607/"
]
| Mapping a collection of enums with NHibernate
Specifically, using Attributes for the mappings.
Currently I have this working mapping the collection as type Int32 and NH seems to take care of it, but it's not exactly ideal.
The error I receive is "Unable to determine type" when trying to map the collection as of the type of the enum I am trying to map.
I found a post that said to define a class as
```
public class CEnumType : EnumStringType {
public CEnumType() : base(MyEnum) { }
}
```
and then map the enum as CEnumType, but this gives "CEnumType is not mapped" or something similar.
So has anyone got experience doing this?
So anyway, just a simple reference code snippet to give an example with
```
[NHibernate.Mapping.Attributes.Class(Table = "OurClass")]
public class CClass : CBaseObject
{
public enum EAction
{
do_action,
do_other_action
};
private IList<EAction> m_class_actions = new List<EAction>();
[NHibernate.Mapping.Attributes.Bag(0, Table = "ClassActions", Cascade="all", Fetch = CollectionFetchMode.Select, Lazy = false)]
[NHibernate.Mapping.Attributes.Key(1, Column = "Class_ID")]
[NHibernate.Mapping.Attributes.Element(2, Column = "EAction", Type = "Int32")]
public virtual IList<EAction> Actions
{
get { return m_class_actions; }
set { m_class_actions = value;}
}
}
```
So, anyone got the correct attributes for me to map this collection of enums as actual enums? It would be really nice if they were stored in the db as strings instead of ints too but it's not completely necessary. | You will need to map your CEnum type directly. In XML mappings this would mean creating a new class mapping element in your NHibernate XML mappings file.
```
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="YourAssembly"
auto-import="true" default-lazy="false">
...
<class name="YourAssemblyNamespace.CEnum" table="CEnumTable" mutable="false" >
<id name="Id" unsaved-value="0" column="id">
<generator class="native"/>
</id>
...
</class>
</hibernate-mapping>
```
To do it with attribute mappings, something like this on top of your CEnum class:
`[NHibernate.Mapping.Attributes.Class(Table = "CEnumTable")] //etc as you require` |
78,884 | <p>I have an xslt sheet with some text similar to below:</p>
<pre><code><xsl:text>I am some text, and I want to be bold</xsl:text>
</code></pre>
<p>I would like some text to be bold, but this doesn't work.</p>
<pre><code><xsl:text>I am some text, and I want to be <strong>bold<strong></xsl:text>
</code></pre>
<p>The deprecated b tag doesn't work either. How do I format text within an xsl:text tag?</p>
| [
{
"answer_id": 78904,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 3,
"selected": false,
"text": "<p>Try this: </p>\n\n<pre><code><fo:inline font-weight=\"bold\"><xsl:text>Bold text</xsl:text></fo:inline>\n</code></pre>\n\n<ul>\n<li><a href=\"http://www.ecrion.com/Support/Resources/XSL-FOTutorial/Inline.xml.html\" rel=\"noreferrer\">XSL-FO Tutoria: Inline Text\nFormatting</a></li>\n<li><a href=\"http://www.w3schools.com/xslfo/obj_inline.asp\" rel=\"noreferrer\">XSL-FO inline Object</a></li>\n</ul>\n"
},
{
"answer_id": 78917,
"author": "David Medinets",
"author_id": 219658,
"author_profile": "https://Stackoverflow.com/users/219658",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p><xsl:text <strong>disable-output-escaping=\"yes\"</strong>>I want to be <strong>bold<strong> </xsl:text></p>\n</blockquote>\n"
},
{
"answer_id": 78927,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": -1,
"selected": false,
"text": "<p>XSL-FO formatting should be able to do that, see the W3Schools <a href=\"http://w3schools.com/xslfo/default.asp\" rel=\"nofollow noreferrer\">tutorial</a>.</p>\n"
},
{
"answer_id": 80522,
"author": "jelovirt",
"author_id": 2679,
"author_profile": "https://Stackoverflow.com/users/2679",
"pm_score": 4,
"selected": true,
"text": "<p>You don't. <code>xsl:text</code> can only contain text nodes and <code><strong></code> is an element node, not a string that starts with less-than character; XSLT is about creating node trees, not markup. So, you have to do </p>\n\n<pre><code><xsl:text>I am some text, and I want to be </xsl:text>\n<strong>bold<strong>\n<xsl:text> </xsl:text>\n</code></pre>\n"
},
{
"answer_id": 6410661,
"author": "Pavan",
"author_id": 732642,
"author_profile": "https://Stackoverflow.com/users/732642",
"pm_score": 0,
"selected": false,
"text": "<p>The answer for this depends on how much formatting is needed in the content and also where you get content from.\nIf you have less content and less formatting then you can use what jelovirt suggested</p>\n\n<pre><code><xsl:text>I am some text, and I want to be </xsl:text>\n<strong>bold<strong>\n<xsl:text> </xsl:text>\n</code></pre>\n\n<p>However if your content has large formatting then what David Medinets suggests is better way to do it</p>\n\n<pre><code><xsl:text disable-output-escaping=\"yes\">\n</code></pre>\n\n<p>We have some instructions to print on UI. The set of instructions is huge and of course we read those from XML file.</p>\n\n<p>In such cases the above method is easy to use and maintain too. That is because the content is provided by technical writers. They have no knowledge of XSL. They know using HTML tags and they can easily edit the XML file.</p>\n"
},
{
"answer_id": 59292527,
"author": "Ricardo PSilva",
"author_id": 3179207,
"author_profile": "https://Stackoverflow.com/users/3179207",
"pm_score": 0,
"selected": false,
"text": "<p>the correct way to use the strong tag is </p>\n\n<pre><code><strong>This text is strong</strong>\n</code></pre>\n\n<p>not <code><strong></code> at the end</p>\n\n<p>Here is the information reference: <a href=\"https://www.w3schools.com/html/html_formatting.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/html/html_formatting.asp</a></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5989/"
]
| I have an xslt sheet with some text similar to below:
```
<xsl:text>I am some text, and I want to be bold</xsl:text>
```
I would like some text to be bold, but this doesn't work.
```
<xsl:text>I am some text, and I want to be <strong>bold<strong></xsl:text>
```
The deprecated b tag doesn't work either. How do I format text within an xsl:text tag? | You don't. `xsl:text` can only contain text nodes and `<strong>` is an element node, not a string that starts with less-than character; XSLT is about creating node trees, not markup. So, you have to do
```
<xsl:text>I am some text, and I want to be </xsl:text>
<strong>bold<strong>
<xsl:text> </xsl:text>
``` |
78,913 | <p>What is the single most effective practice to prevent <a href="http://en.wikipedia.org/wiki/Arithmetic_overflow" rel="nofollow noreferrer">arithmetic overflow</a> and <a href="http://en.wikipedia.org/wiki/Arithmetic_underflow" rel="nofollow noreferrer">underflow</a>?</p>
<p>Some examples that come to mind are:</p>
<ul>
<li>testing based on valid input ranges</li>
<li>validation using formal methods</li>
<li>use of invariants</li>
<li>detection at runtime using language features or libraries (this does not prevent it)</li>
</ul>
| [
{
"answer_id": 78936,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": true,
"text": "<p>One possibility is to use a language that has arbitrarily sized integers that never overflow / underflow.</p>\n\n<p>Otherwise, if this is something you're really concerned about, and if your language allows it, write a wrapper class that acts like an integer, but checks every operation for overflow. You could even have it do the check on debug builds, and leave things optimized for release builds. In a language like C++, you could do this, and it would behave almost exactly like an integer for release builds, but for debug builds you'd get full run-time checking.</p>\n\n<pre><code>class CheckedInt\n{\nprivate: \n int Value;\n\npublic:\n // Constructor\n CheckedInt(int src) : Value(src) {}\n\n // Conversions back to int\n operator int&() { return Value; }\n operator const int &() const { return Value; }\n\n // Operators\n CheckedInt operator+(CheckedInt rhs) const\n {\n if (rhs.Value < 0 && rhs.Value + Value > Value)\n throw OverflowException();\n if (rhs.Value > 0 && rhs.Value + Value < Value)\n throw OverflowException();\n return CheckedInt(rhs.Value + Value);\n }\n\n // Lots more operators...\n};\n</code></pre>\n\n<p>Edit:</p>\n\n<p>Turns out someone is <a href=\"http://www.codeplex.com/SafeInt\" rel=\"nofollow noreferrer\">doing this already for C++</a> - the current implementation is focused for Visual Studio, but it looks like they're getting support for gcc as well.</p>\n"
},
{
"answer_id": 78941,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 1,
"selected": false,
"text": "<p>I write a lot of test code to do range/validity checking on my code. This tends to catch most of these types of situations - and definitely helps me write more bulletproof code.</p>\n"
},
{
"answer_id": 78949,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 1,
"selected": false,
"text": "<p>Use high precision floating point numbers like a <a href=\"http://en.wikipedia.org/wiki/Long_double\" rel=\"nofollow noreferrer\">long double</a>.</p>\n"
},
{
"answer_id": 79074,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are missing one very important option in your list: choose the right programming language for the job. There are many programming languages which do not have these problems, because they don't have fixed size integers.</p>\n"
},
{
"answer_id": 79470,
"author": "pro3carp3",
"author_id": 7899,
"author_profile": "https://Stackoverflow.com/users/7899",
"pm_score": 0,
"selected": false,
"text": "<p>There are more important considerations when choosing which language you use than the size of the integer. Simply check your input if you don't know if the value is in bounds, or use exception handling if the case is extremely rare.</p>\n"
},
{
"answer_id": 1028197,
"author": "mturquette",
"author_id": 123330,
"author_profile": "https://Stackoverflow.com/users/123330",
"pm_score": 0,
"selected": false,
"text": "<p>A wrapper that checks for inconsistencies will make sense in many cases. If an additive operation (ie, addition or multiplication) on two or more integers results in a smaller value than the operands then you know something went wrong. Every additive operation should be followed by,</p>\n\n<pre><code>if (sum < operand1 || sum < operand2)\n omg_error();\n</code></pre>\n\n<p>Likewise any operation that should logically result in a smaller value should be check to see if it was accidentally embiggin'd.</p>\n"
},
{
"answer_id": 9234479,
"author": "Jay Abraham",
"author_id": 893216,
"author_profile": "https://Stackoverflow.com/users/893216",
"pm_score": 0,
"selected": false,
"text": "<p>Have you investigated the use of formal methods to check your code to prove that it is free of overflows? A formal methods technique known as abstract interpretation can check the robustness of your software to prove that your software will not suffer from an overflow, underflow, divide by zero, overflow, or other similar run-time error. It is a mathematical technique that exhaustively analyzes your software. The technique was pioneered by Patrick Cousot in the 1970s. It was successfully used to diagnose an overflow condition in the Arian 5 rocket where an overflow caused the destruction of the launch vehicle. The overflow was caused while converting a floating point number to an integer. You can find more information about this technique <a href=\"http://www.mathworks.com/discovery/formal-methods.html\" rel=\"nofollow\">here</a> and also on <a href=\"http://en.wikipedia.org/wiki/Abstract_interpretation\" rel=\"nofollow\">Wikipedia</a>.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3836/"
]
| What is the single most effective practice to prevent [arithmetic overflow](http://en.wikipedia.org/wiki/Arithmetic_overflow) and [underflow](http://en.wikipedia.org/wiki/Arithmetic_underflow)?
Some examples that come to mind are:
* testing based on valid input ranges
* validation using formal methods
* use of invariants
* detection at runtime using language features or libraries (this does not prevent it) | One possibility is to use a language that has arbitrarily sized integers that never overflow / underflow.
Otherwise, if this is something you're really concerned about, and if your language allows it, write a wrapper class that acts like an integer, but checks every operation for overflow. You could even have it do the check on debug builds, and leave things optimized for release builds. In a language like C++, you could do this, and it would behave almost exactly like an integer for release builds, but for debug builds you'd get full run-time checking.
```
class CheckedInt
{
private:
int Value;
public:
// Constructor
CheckedInt(int src) : Value(src) {}
// Conversions back to int
operator int&() { return Value; }
operator const int &() const { return Value; }
// Operators
CheckedInt operator+(CheckedInt rhs) const
{
if (rhs.Value < 0 && rhs.Value + Value > Value)
throw OverflowException();
if (rhs.Value > 0 && rhs.Value + Value < Value)
throw OverflowException();
return CheckedInt(rhs.Value + Value);
}
// Lots more operators...
};
```
Edit:
Turns out someone is [doing this already for C++](http://www.codeplex.com/SafeInt) - the current implementation is focused for Visual Studio, but it looks like they're getting support for gcc as well. |
78,924 | <p>I have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email. </p>
<p>It is working for me, except sometimes the rule fails and Outlook deactivates it. </p>
<p>Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day. </p>
<p>I would love to fix this once and for all.</p>
| [
{
"answer_id": 79000,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email. It is working for me, except sometimes the rule fails and Outlook deactivates it. Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day. I would love to fix this once and for all.</p>\n\n<p>Here is the code stripped of the functionality, but giving you an idea of how it looks:</p>\n\n<pre><code> Public WithEvents myOlItems As Outlook.Items\n\n Public Sub Application_Startup()\n ' Reference the items in the Inbox. Because myOlItems is declared\n ' \"WithEvents\" the ItemAdd event will fire below.\n ' Set myOlItems = Outlook.Session.GetDefaultFolder(olFolderInbox).Items\n Set myOlItems = Application.GetNamespace(\"MAPI\").GetDefaultFolder(olFolderInbox).Items\n End Sub\n\n Private Sub myOlItems_ItemAdd(ByVal Item As Object)\n On Error Resume Next\n If TypeName(Item) = \"MailItem\" Then\n MyMessageHandler Item\n End If\n End Sub\n\n Public Sub MyMessageHandler(ByRef Item As MailItem)\n Dim strSender As String\n Dim strSubject As String\n\n If TypeName(Item) <> \"MailItem\" Then\n Exit Sub\n End If\n\n strSender = LCase(Item.SenderEmailAddress)\n strSubject = Item.Subject\n\n rem do stuff\n rem do stuff\n rem do stuff\n End Sub\n</code></pre>\n\n<p>One error I get is \"Type Mismatch\" calling MyMessageHandler where VB complains that Item is not a MailItem. Okay, but TypeName(Item) returns \"MailItem\", so how come Item is not a MailItem?</p>\n\n<p>Another one I get is where an email with an empty subject comes along. The line</p>\n\n<pre><code>strSubject = Item.Subject\n</code></pre>\n\n<p>gives me an error. I know Item.Subject should be blank, but why is that an error?</p>\n\n<p>Thanks.</p>\n"
},
{
"answer_id": 150607,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 2,
"selected": false,
"text": "<p>My memory is somewhat cloudy on this, but I believe that a MailItem is not a MailItem when it is something like a read receipt. (Unfortunately, the VBA code that demonstrated this was written at another job and isn't around now.)</p>\n\n<p>I also had code written to process incoming messages, probably for the same reason you did (too many rules for Exchange, or rules too complex for the Rules Wizard), and seem to recall running into the same problem you have, that some items seemed to be from a different type even though I was catching them with something like what you wrote.</p>\n\n<p>I'll see if I can produce a specific example if it will help.</p>\n"
},
{
"answer_id": 8672202,
"author": "Killian Tyler",
"author_id": 1121762,
"author_profile": "https://Stackoverflow.com/users/1121762",
"pm_score": 4,
"selected": false,
"text": "<p>This code showed me the different TypeNames that were in my Inbox:</p>\n\n<pre><code>Public Sub GetTypeNamesInbox()\nDim myOlItems As Outlook.Items\nSet myOlItems = application.GetNamespace(\"MAPI\").GetDefaultFolder(olFolderInbox).Items\nDim msg As Object\n\nFor Each msg In myOlItems\n Debug.Print TypeName(msg)\n 'emails are typename MailItem\n 'Meeting responses are typename MeetingItem\n 'Delivery receipts are typename ReportItem\nNext msg\n\nEnd Sub\n</code></pre>\n\n<p>HTH</p>\n"
},
{
"answer_id": 11145745,
"author": "JimmyPena",
"author_id": 190829,
"author_profile": "https://Stackoverflow.com/users/190829",
"pm_score": 1,
"selected": false,
"text": "<p>There are many types of items that can be seen in the default Inbox.</p>\n\n<p>In the called procedure, assign the incoming item to an <code>Object</code> type variable. Then use <code>TypeOf</code> or <code>TypeName</code> to determine if it is a <code>MailItem</code>. Only then should your code perform actions that apply to emails.</p>\n\n<p>i.e.</p>\n\n<pre><code>Dim obj As Object\n\nIf TypeName(obj) = \"MailItem\" Then\n ' your code for mail items here\nEnd If\n</code></pre>\n"
},
{
"answer_id": 11634371,
"author": "Radek",
"author_id": 1549220,
"author_profile": "https://Stackoverflow.com/users/1549220",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Dim objInboxFolder As MAPIFolder\nDim oItem As MailItem\nSet objInboxFolder = GetNamespace(\"MAPI\").GetDefaultFolder(olFolderInbox)\n\nFor Each Item In objInboxFolder.Items\n If TypeName(Item) = \"MailItem\" Then\n Set oItem = Item\n\nnext\n</code></pre>\n"
},
{
"answer_id": 12183994,
"author": "Bruce E. Leandro",
"author_id": 1634032,
"author_profile": "https://Stackoverflow.com/users/1634032",
"pm_score": 2,
"selected": false,
"text": "<p>I use the following VBA code snippet in other Office Applications, where the Outlook Library is directly referenced.</p>\n\n<pre><code>' Outlook Variables\n\n Dim objOutlook As Outlook.Application: Set objOutlook = New Outlook.Application\n Dim objNameSpace As Outlook.NameSpace: Set objNameSpace = objOutlook.GetNamespace(\"MAPI\")\n Dim objFolder As MAPIFolder: Set objFolder = objNameSpace.PickFolder()\n Dim objMailItem As Outlook.MailItem\n\n Dim iCounter As Integer: iCounter = objFolder.Items.Count\n Dim i As Integer\n\n For i = iCounter To 1 Step -1\n If TypeOf objFolder.Items(i) Is MailItem Then\n Set objMailItem = objFolder.Items(i)\n With objMailItem\n</code></pre>\n\n<p>etc.</p>\n"
},
{
"answer_id": 16250499,
"author": "htd",
"author_id": 2234464,
"author_profile": "https://Stackoverflow.com/users/2234464",
"pm_score": 0,
"selected": false,
"text": "<p>why not use a simple error handler for the code? Seriously. You could write an error for each read of a property or object that seems to fail. Then have it Resume no matter what. No need for complex error handling. Think of a test that shows an empty subject. Since you don't know what value it will return, if any, and it seems to error on an empty or blank subject, you need to picture it as a simple test with a possible error. Run the test as an if statement (one in which you will get an error anyway), and have the program resume on error.<br/></p>\n\n<pre><code>On Error Resume Next\nIf object.subject = Null 'produces an error when subject is null, otherwise allows a good read\n strSubject = \"\" 'sets the subject grab string to a null or empty string as a string\nElse\n strSubject = object.subject 'Sets the subject grab string to the subject of the message\\item\nEnd If\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78924",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email.
It is working for me, except sometimes the rule fails and Outlook deactivates it.
Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day.
I would love to fix this once and for all. | This code showed me the different TypeNames that were in my Inbox:
```
Public Sub GetTypeNamesInbox()
Dim myOlItems As Outlook.Items
Set myOlItems = application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
Dim msg As Object
For Each msg In myOlItems
Debug.Print TypeName(msg)
'emails are typename MailItem
'Meeting responses are typename MeetingItem
'Delivery receipts are typename ReportItem
Next msg
End Sub
```
HTH |
78,932 | <p>I have the following HTML <code><select></code> element:</p>
<pre><code><select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
</code></pre>
<p>Using a JavaScript function with the <code>leaveCode</code> number as a parameter, how do I select the appropriate option in the list?</p>
| [
{
"answer_id": 78945,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 11,
"selected": true,
"text": "<p>You can use this function:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function selectElement(id, valueToSelect) { \n let element = document.getElementById(id);\n element.value = valueToSelect;\n}\n\nselectElement('leaveCode', '11');</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><select id=\"leaveCode\" name=\"leaveCode\">\n <option value=\"10\">Annual Leave</option>\n <option value=\"11\">Medical Leave</option>\n <option value=\"14\">Long Service</option>\n <option value=\"17\">Leave Without Pay</option>\n</select></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Optionally if you want to trigger onchange event also, you can use :</p>\n<pre><code>element.dispatchEvent(new Event('change'))\n</code></pre>\n"
},
{
"answer_id": 78947,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 5,
"selected": false,
"text": "<p>Not answering the question, but you can also select by index, where i is the index of the item you wish to select:</p>\n\n<pre><code>var formObj = document.getElementById('myForm');\nformObj.leaveCode[i].selected = true;\n</code></pre>\n\n<p>You can also loop through the items to select by display value with a loop:</p>\n\n<pre><code>for (var i = 0, len < formObj.leaveCode.length; i < len; i++) \n if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;\n</code></pre>\n"
},
{
"answer_id": 78950,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": -1,
"selected": false,
"text": "<p>I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:</p>\n\n<pre><code>document.getElementById(\"optionID\").select();\n</code></pre>\n\n<p>If that doesn't work, maybe it'll get you closer to a solution :P</p>\n"
},
{
"answer_id": 78954,
"author": "mmattax",
"author_id": 1638,
"author_profile": "https://Stackoverflow.com/users/1638",
"pm_score": 2,
"selected": false,
"text": "<pre>\n<code>\nfunction foo(value)\n{\n var e = document.getElementById('leaveCode');\n if(e) e.value = value;\n}\n</code>\n</pre>\n"
},
{
"answer_id": 78960,
"author": "William",
"author_id": 9193,
"author_profile": "https://Stackoverflow.com/users/9193",
"pm_score": 4,
"selected": false,
"text": "<pre><code>document.getElementById('leaveCode').value = '10';\n</code></pre>\n\n<p>That should set the selection to \"Annual Leave\"</p>\n"
},
{
"answer_id": 78976,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 2,
"selected": false,
"text": "<p>Should be something along these lines:</p>\n\n<pre><code>function setValue(inVal){\nvar dl = document.getElementById('leaveCode');\nvar el =0;\nfor (var i=0; i<dl.options.length; i++){\n if (dl.options[i].value == inVal){\n el=i;\n break;\n }\n}\ndl.selectedIndex = el;\n}\n</code></pre>\n"
},
{
"answer_id": 79040,
"author": "Robert Swisher",
"author_id": 1852,
"author_profile": "https://Stackoverflow.com/users/1852",
"pm_score": 1,
"selected": false,
"text": "<p>Why not add a variable for the element's Id and make it a reusable function?</p>\n\n<pre><code>function SelectElement(selectElementId, valueToSelect)\n{ \n var element = document.getElementById(selectElementId);\n element.value = valueToSelect;\n}\n</code></pre>\n"
},
{
"answer_id": 79528,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 2,
"selected": false,
"text": "<p>Suppose your form is named <strong>form1</strong>:</p>\n\n<pre><code>function selectValue(val)\n{\n var lc = document.form1.leaveCode;\n for (i=0; i&lt;lc.length; i++)\n {\n if (lc.options[i].value == val)\n {\n lc.selectedIndex = i;\n return;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 79534,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 5,
"selected": false,
"text": "<pre><code>function setSelectValue (id, val) {\n document.getElementById(id).value = val;\n}\nsetSelectValue('leaveCode', 14);\n</code></pre>\n"
},
{
"answer_id": 4519880,
"author": "Einar Ólafsson",
"author_id": 373032,
"author_profile": "https://Stackoverflow.com/users/373032",
"pm_score": 7,
"selected": false,
"text": "<p>If you are using jQuery you can also do this:</p>\n\n<pre><code>$('#leaveCode').val('14');\n</code></pre>\n\n<p>This will select the <code><option></code> with the value of 14.</p>\n\n<hr>\n\n<p>With plain Javascript, this can also be achieved with two <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document#Methods\" rel=\"noreferrer\"><code>Document</code> methods</a>:</p>\n\n<ul>\n<li><p>With <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector\" rel=\"noreferrer\"><code>document.querySelector</code></a>, you can select an element based on a CSS selector:</p>\n\n<pre><code>document.querySelector('#leaveCode').value = '14'\n</code></pre></li>\n<li><p>Using the more established approach with <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById\" rel=\"noreferrer\"><code>document.getElementById()</code></a>, that will, as the name of the function implies, let you select an element based on its <code>id</code>:</p>\n\n<pre><code>document.getElementById('leaveCode').value = '14'\n</code></pre></li>\n</ul>\n\n<p>You can run the below code snipped to see these methods and the jQuery function in action:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const jQueryFunction = () => {\r\n \r\n $('#leaveCode').val('14'); \r\n \r\n}\r\n\r\nconst querySelectorFunction = () => {\r\n \r\n document.querySelector('#leaveCode').value = '14' \r\n \r\n}\r\n\r\nconst getElementByIdFunction = () => {\r\n \r\n document.getElementById('leaveCode').value='14' \r\n \r\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>input {\r\n display:block;\r\n margin: 10px;\r\n padding: 10px\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><select id=\"leaveCode\" name=\"leaveCode\">\r\n <option value=\"10\">Annual Leave</option>\r\n <option value=\"11\">Medical Leave</option>\r\n <option value=\"14\">Long Service</option>\r\n <option value=\"17\">Leave Without Pay</option>\r\n</select>\r\n\r\n<input type=\"button\" value=\"$('#leaveCode').val('14');\" onclick=\"jQueryFunction()\" />\r\n<input type=\"button\" value=\"document.querySelector('#leaveCode').value = '14'\" onclick=\"querySelectorFunction()\" />\r\n<input type=\"button\" value=\"document.getElementById('leaveCode').value = '14'\" onclick=\"getElementByIdFunction()\" />\r\n\r\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 5346940,
"author": "Lana",
"author_id": 665322,
"author_profile": "https://Stackoverflow.com/users/665322",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way if you need to:<br>\n1) Click a button which defines select option<br>\n2) Go to another page, where select option is<br>\n3) Have that option value selected on another page</p>\n\n<p><strong>1)</strong> your button links (say, on home page)</p>\n\n<pre><code><a onclick=\"location.href='contact.php?option=1';\" style=\"cursor:pointer;\">Sales</a>\n<a onclick=\"location.href='contact.php?option=2';\" style=\"cursor:pointer;\">IT</a>\n</code></pre>\n\n<p>(where <strong>contact.php</strong> is your page with select options. Note the page url has ?option=1 or 2)</p>\n\n<p><strong>2)</strong> put this code on your second page (my case <strong>contact.php</strong>) </p>\n\n<pre><code><?\nif (isset($_GET['option']) && $_GET['option'] != \"\") {\n$pg = $_GET['option']; \n} ?>\n</code></pre>\n\n<p><strong>3)</strong> make the option value selected, depending on the button clicked</p>\n\n<pre><code><select>\n<option value=\"Sales\" <? if ($pg == '1') { echo \"selected\"; } ?> >Sales</option>\n<option value=\"IT\" <? if ($pg == '2') { echo \"selected\"; } ?> >IT</option>\n</select>\n</code></pre>\n\n<p>.. and so on.<br>\nSo this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.</p>\n"
},
{
"answer_id": 11905147,
"author": "Toskan",
"author_id": 533426,
"author_profile": "https://Stackoverflow.com/users/533426",
"pm_score": 4,
"selected": false,
"text": "<p>I compared the different methods:</p>\n\n<p><a href=\"https://jsfiddle.net/8sM7s/1/\" rel=\"nofollow noreferrer\">Comparison of the different ways on how to set a value of a select with JS or jQuery</a></p>\n\n<p>code:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>$(function() {\n var oldT = new Date().getTime();\n var element = document.getElementById('myId');\n element.value = 4;\n console.error(new Date().getTime() - oldT);\n\n oldT = new Date().getTime();\n $(\"#myId option\").filter(function() {\n return $(this).attr('value') == 4;\n }).attr('selected', true);\n console.error(new Date().getTime() - oldT);\n\n oldT = new Date().getTime();\n $(\"#myId\").val(\"4\");\n console.error(new Date().getTime() - oldT);\n});\n</code></pre>\n\n<p>Output on a select with ~4000 elements:</p>\n\n<ul>\n<li>1 ms </li>\n<li>58 ms</li>\n<li>612 ms</li>\n</ul>\n\n<p>With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).\nWe had roughly 2 s delay after a val()</p>\n\n<p>Note as well: I am setting value depending on the real value, not the text value.</p>\n"
},
{
"answer_id": 21422704,
"author": "almyz125",
"author_id": 1253882,
"author_profile": "https://Stackoverflow.com/users/1253882",
"pm_score": -1,
"selected": false,
"text": "<p>If using PHP you could try something like this:</p>\n\n<pre><code>$value = '11';\n$first = '';\n$second = '';\n$third = '';\n$fourth = '';\n\nswitch($value) {\n case '10' :\n $first = 'selected';\n break;\n case '11' :\n $second = 'selected';\n break;\n case '14' :\n $third = 'selected';\n break;\n case '17' :\n $fourth = 'selected';\n break;\n }\n\necho'\n<select id=\"leaveCode\" name=\"leaveCode\">\n <option value=\"10\" '. $first .'>Annual Leave</option>\n <option value=\"11\" '. $second .'>Medical Leave</option>\n <option value=\"14\" '. $third .'>Long Service</option>\n <option value=\"17\" '. $fourth .'>Leave Without Pay</option>\n</select>';\n</code></pre>\n"
},
{
"answer_id": 30573683,
"author": "lumi77",
"author_id": 236928,
"author_profile": "https://Stackoverflow.com/users/236928",
"pm_score": 4,
"selected": false,
"text": "<p>I tried the above JavaScript/jQuery-based solutions, such as: </p>\n\n<pre><code>$(\"#leaveCode\").val(\"14\");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>var leaveCode = document.querySelector('#leaveCode');\nleaveCode[i].selected = true;\n</code></pre>\n\n<p>in an AngularJS app, where there was a <strong>required</strong> <select> element.</p>\n\n<p>None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (<strong>ng-pristine</strong> and <strong>ng-invalid</strong> classes still present).</p>\n\n<p>To force the AngularJS validation, call jQuery <a href=\"https://api.jquery.com/change/\" rel=\"noreferrer\">change()</a> after selecting an option:</p>\n\n<pre><code>$(\"#leaveCode\").val(\"14\").change();\n</code></pre>\n\n<p>and</p>\n\n<pre><code>var leaveCode = document.querySelector('#leaveCode');\nleaveCode[i].selected = true;\n$(leaveCode).change();\n</code></pre>\n"
},
{
"answer_id": 37445649,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You most likely want this:</p>\n\n<pre><code>$(\"._statusDDL\").val('2');\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>$('select').prop('selectedIndex', 3); \n</code></pre>\n"
},
{
"answer_id": 63377136,
"author": "Ashutosh Tiwari",
"author_id": 12125692,
"author_profile": "https://Stackoverflow.com/users/12125692",
"pm_score": 0,
"selected": false,
"text": "<p>Most of the code mentioned here didn't worked for me!</p>\n<p><strong>At last, this worked</strong></p>\n<p><em><strong>window.addEventListener</strong> is important, otherwise, your JS code will run before values are fetched in the Options</em></p>\n<pre><code> window.addEventListener("load", function () {\n // Selecting Element with ID - leaveCode //\n var formObj = document.getElementById('leaveCode');\n\n // Setting option as selected\n let len;\n for (let i = 0, len = formObj.length; i < len; i++){\n if (formObj[i].value == '<value to show in Select>') \n formObj.options[i].selected = true;\n }\n });\n</code></pre>\n<p>Hope, this helps!</p>\n"
},
{
"answer_id": 63882977,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 4,
"selected": false,
"text": "<h1>Short</h1>\n<p>This is size improvement of <a href=\"https://stackoverflow.com/a/78960/860099\">William answer</a></p>\n<pre><code>leaveCode.value = '14';\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>leaveCode.value = '14';</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><select id=\"leaveCode\" name=\"leaveCode\">\n <option value=\"10\">Annual Leave</option>\n <option value=\"11\">Medical Leave</option>\n <option value=\"14\">Long Service</option>\n <option value=\"17\">Leave Without Pay</option>\n</select></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6340/"
]
| I have the following HTML `<select>` element:
```
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
```
Using a JavaScript function with the `leaveCode` number as a parameter, how do I select the appropriate option in the list? | You can use this function:
```js
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
```
```html
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
```
Optionally if you want to trigger onchange event also, you can use :
```
element.dispatchEvent(new Event('change'))
``` |
78,974 | <p>I've written a control that inherits from the <code>System.Web.UI.WebControls.DropDownList</code> and so I don't have any code in front for this control, but I still want to set the OutputCache directive. I there any way to set this in the C# code, say with an attribute or something like that? </p>
<p>I'm particularly hoping to be able to replicate the <code>VaryByParam</code> property</p>
| [
{
"answer_id": 79012,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));\nResponse.Cache.SetCacheability(HttpCacheability.Server);\nResponse.Cache.SetValidUntilExpires(true);\n</code></pre>\n"
},
{
"answer_id": 3258564,
"author": "matt-dot-net",
"author_id": 380518,
"author_profile": "https://Stackoverflow.com/users/380518",
"pm_score": 3,
"selected": true,
"text": "<p>I realize this is an incredibly old question but it is still worthy of an answer.</p>\n\n<p>What you are talking about isn't a User Control it is a Custom Control. What you want to do with the OutputCache can be done simply with the Context Cache.</p>\n\n<p>In your code where you are getting the data and binding to your DropDownList do something like this:</p>\n\n<pre><code> List<Object> listOfObjects = null;\n//assuming a List of Objects... it doesn't matter whatever type of data you use\n if (Context.Cache[\"MyDataCacheKey\"] == null)\n {\n // data not cached, load it from database\n listOfObjects = GetDataFromDB();\n//add your data to the context cache with a sliding expiration of 10 minutes.\n Context.Cache.Add(\"MyDataCacheKey\", listOfObjects, null,\n System.Web.Caching.Cache.NoAbsoluteExpiration,\n TimeSpan.FromMinutes(10.0),\n System.Web.Caching.CacheItemPriority.Normal, null);\n }\n else\n listOfObjects = (List<Object>)Context.Cache[\"MyDataCacheKey\"];\n\n DropDownList1.DataSource = listOfObjects;\n DropDownList1.DataBind();\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
]
| I've written a control that inherits from the `System.Web.UI.WebControls.DropDownList` and so I don't have any code in front for this control, but I still want to set the OutputCache directive. I there any way to set this in the C# code, say with an attribute or something like that?
I'm particularly hoping to be able to replicate the `VaryByParam` property | I realize this is an incredibly old question but it is still worthy of an answer.
What you are talking about isn't a User Control it is a Custom Control. What you want to do with the OutputCache can be done simply with the Context Cache.
In your code where you are getting the data and binding to your DropDownList do something like this:
```
List<Object> listOfObjects = null;
//assuming a List of Objects... it doesn't matter whatever type of data you use
if (Context.Cache["MyDataCacheKey"] == null)
{
// data not cached, load it from database
listOfObjects = GetDataFromDB();
//add your data to the context cache with a sliding expiration of 10 minutes.
Context.Cache.Add("MyDataCacheKey", listOfObjects, null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(10.0),
System.Web.Caching.CacheItemPriority.Normal, null);
}
else
listOfObjects = (List<Object>)Context.Cache["MyDataCacheKey"];
DropDownList1.DataSource = listOfObjects;
DropDownList1.DataBind();
``` |
78,978 | <p>I'm working on a regular expression in a <code>.NET</code> project to get a specific tag. I would like to match the entire DIV tag and its contents:</p>
<pre><code><html>
<head><title>Test</title></head>
<body>
<p>The first paragraph.</p>
<div id='super_special'>
<p>The Store paragraph</p>
</div>
</body>
</head>
</code></pre>
<p>Code:</p>
<pre><code> Regex re = new Regex("(<div id='super_special'>.*?</div>)", RegexOptions.Multiline);
if (re.IsMatch(test))
Console.WriteLine("it matches");
else
Console.WriteLine("no match");
</code></pre>
<p>I want to match this:</p>
<pre><code><div id="super_special">
<p>Anything could go in here...doesn't matter. Let's get it all</p>
</div>
</code></pre>
<p>I thought <code>.</code> was supposed to get all characters, but it seems to having trouble with the carriage returns. What is my regex missing?</p>
<p>Thanks.</p>
| [
{
"answer_id": 78985,
"author": "mopoke",
"author_id": 14054,
"author_profile": "https://Stackoverflow.com/users/14054",
"pm_score": 1,
"selected": false,
"text": "<p>Depends what language you're working in. \nFor example, in perl you'd use the regex modifier s:</p>\n\n<pre><code>m{<div id=\"super_special\">.*?</span>}s\n</code></pre>\n"
},
{
"answer_id": 78989,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>What language are you using? In .NET you must set an option to ensure that it isn't single line. </p>\n"
},
{
"answer_id": 78992,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 0,
"selected": false,
"text": "<p>. (dot) Matches any single character except line break characters \\r and \\n. Most regex flavors have an option to make the dot match line break characters too. . matches x or (almost) any other character </p>\n"
},
{
"answer_id": 78993,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 0,
"selected": false,
"text": "<p>maybe: .<em>[\\r\\n]</em>.<em>[\\r\\n]</em></p>\n"
},
{
"answer_id": 78995,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>Depends on the language. If on python, you are missing the re.S flag, like this (to remove the match):</p>\n\n<pre><code>re.compile('<div id=\"super_special\">.*?</div>',re.S).sub(your_html,'')\n</code></pre>\n\n<p>Similar flags exist for other regexps implementations, they are called \"Single Line\" or \"Multi Line\" or something like that.</p>\n\n<p>But <strong>DO NOT USE REGEXPS TO PARSE HTML</strong>. It's a direct path to maintenance hell. Use a HTML parser like Beautiful Soup. Check <a href=\"https://stackoverflow.com/questions/55391/python-regular-expression-for-html-parsing-beautifulsoup#55424\">these</a> <a href=\"https://stackoverflow.com/questions/2861/options-for-html-scraping#5093\">links</a> for useful resources in that direction.</p>\n"
},
{
"answer_id": 79024,
"author": "Jörg W Mittag",
"author_id": 2988,
"author_profile": "https://Stackoverflow.com/users/2988",
"pm_score": 3,
"selected": false,
"text": "<p>Please, pretty please, do yourself a <em>huge</em> favor: use an HTML parser for parsing HTML. Seriously. That's what they are there for.</p>\n\n<p>HTML is a <em>very</em> complex language. No matter <em>how long</em> you will be tweaking, fiddling, fixing, honing your Regexp, there will <em>always</em> be a case you're missing.</p>\n\n<p>Anyway, you have to tell your Regexp engine to match multiple lines instead of just one. In some of the most popular ones you do that by applying the <code>/m</code> modifier.</p>\n\n<p>But let me repeat: <em>please</em> use an HTML parser. Everytime someone uses a Regexp to parse HTML, a kitten dies ...</p>\n"
},
{
"answer_id": 79032,
"author": "Bennor McCarthy",
"author_id": 14451,
"author_profile": "https://Stackoverflow.com/users/14451",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is that the . metacharacter doesn't match newlines by default. You have to use the single-line modifier to achieve this. In .NET, you can either use RegexOptions.SingleLine as the last parameter to the method you're using, or use the modifier directly in the pattern, e.g:</p>\n\n<pre><code>(?s)(<div id=\"super_special\">.*?</div>)\n</code></pre>\n"
},
{
"answer_id": 79066,
"author": "Mike Tunnicliffe",
"author_id": 13956,
"author_profile": "https://Stackoverflow.com/users/13956",
"pm_score": 1,
"selected": false,
"text": "<p>Most languages have some way to make . match newlines:</p>\n\n<ul>\n<li>In Java: Pattern.compile(\"pattern\", Pattern.MULTILINE);</li>\n<li>In Perl and Ruby: /pattern/m</li>\n<li>In VB: Regex.IsMatch(s, \"pattern\", RegexOptions.Multiline)</li>\n</ul>\n\n<p>In general it's not a good idea to use regexp to match XML/HTML, because XML/HTML tags can be nested, for example:</p>\n\n<pre><code> <div id=\"super_special\">\n <div>Nothing</div>\n <p>Anything could go in here...doesn't matter. Let's get it all</p>\n </div>\n</code></pre>\n\n<p>... here you could easily end up matching:</p>\n\n<pre><code> <div id=\"super_special\">\n <div>Nothing</div>\n</code></pre>\n\n<p>On the other hand, if you know <strong>for sure</strong> that the HTML you are matching will always be safe for your regexp, then don't let me stop you (although, even then you should think twice about saving your future self from a potential debugging headache).</p>\n"
},
{
"answer_id": 79079,
"author": "André Chalella",
"author_id": 4850,
"author_profile": "https://Stackoverflow.com/users/4850",
"pm_score": 2,
"selected": true,
"text": "<p>Out-of-the-box, without special modifiers, most regex implementations don't go beyond the end-of-line to match text. You probably should look in the documentation of the regex engine you're using for such modifier.</p>\n\n<p>I have one other advice: beware of greed! Traditionally, regex <strong>are</strong> greedy which means that your regex would probably match this:</p>\n\n<pre><code><div id=\"super_special\">\n I'm the wanted div!\n</div>\n<div id=\"not_special\">\n I'm not wanted, but I've been caught too :(\n</div>\n</code></pre>\n\n<p>You should check for a \"not-greedy\" modifier, so that your regex would stop matching text at the <strong>first</strong> occurence of <code></div></code>, not at the <strong>last</strong> one.</p>\n\n<p>Also, as others have said, consider using an HTML parser instead of regexes. It will save you a lot of headache.</p>\n\n<p><em>Edit: even a non-greedy regex wouldn't work as expected either, if <code><div></code>s are nested! Another reason to consider using an HTML parser.</em></p>\n"
},
{
"answer_id": 79377,
"author": "Mike Kantor",
"author_id": 14607,
"author_profile": "https://Stackoverflow.com/users/14607",
"pm_score": 0,
"selected": false,
"text": "<p>None of these regex suggestions will work. Depending on whether they're greedy or not, they will match either the very last </div> in the document, or the very first </div> after your starting string, which may be a div nested inside the one you're interested in.</p>\n\n<p>Regular expressions are not really the ideal tool for this purpose, but if your situation is simple enough that you don't really want to parse the HTML, you can do this using a Microsoft-proprietary extension to regex available in .NET. For a nice explanation, see <a href=\"http://www.codeproject.com/KB/recipes/Nested_RegEx_explained.aspx\" rel=\"nofollow noreferrer\">this nice article by Morten Maate</a>.</p>\n"
},
{
"answer_id": 110757,
"author": "Martijn",
"author_id": 17439,
"author_profile": "https://Stackoverflow.com/users/17439",
"pm_score": 0,
"selected": false,
"text": "<p>Regular expressions alone are simply not powerful enough to solve your problem. You need something more powerful, such as context-free grammars. See <a href=\"http://en.wikipedia.org/wiki/Chomsky_hierarchy\" rel=\"nofollow noreferrer\">Chomsky hierarchy</a> at Wikipedia.</p>\n\n<p>In other words (as has been said before), don't use regex to parse HTML.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/78978",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27870/"
]
| I'm working on a regular expression in a `.NET` project to get a specific tag. I would like to match the entire DIV tag and its contents:
```
<html>
<head><title>Test</title></head>
<body>
<p>The first paragraph.</p>
<div id='super_special'>
<p>The Store paragraph</p>
</div>
</body>
</head>
```
Code:
```
Regex re = new Regex("(<div id='super_special'>.*?</div>)", RegexOptions.Multiline);
if (re.IsMatch(test))
Console.WriteLine("it matches");
else
Console.WriteLine("no match");
```
I want to match this:
```
<div id="super_special">
<p>Anything could go in here...doesn't matter. Let's get it all</p>
</div>
```
I thought `.` was supposed to get all characters, but it seems to having trouble with the carriage returns. What is my regex missing?
Thanks. | Out-of-the-box, without special modifiers, most regex implementations don't go beyond the end-of-line to match text. You probably should look in the documentation of the regex engine you're using for such modifier.
I have one other advice: beware of greed! Traditionally, regex **are** greedy which means that your regex would probably match this:
```
<div id="super_special">
I'm the wanted div!
</div>
<div id="not_special">
I'm not wanted, but I've been caught too :(
</div>
```
You should check for a "not-greedy" modifier, so that your regex would stop matching text at the **first** occurence of `</div>`, not at the **last** one.
Also, as others have said, consider using an HTML parser instead of regexes. It will save you a lot of headache.
*Edit: even a non-greedy regex wouldn't work as expected either, if `<div>`s are nested! Another reason to consider using an HTML parser.* |
79,041 | <p>I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic). </p>
<p>So for these records (id-parent_id pairs):</p>
<pre><code>0-7 0-4 4-9 4-14 4-16 9-6
</code></pre>
<p>I have this tree:</p>
<pre><code>0
├ 7
└ 4
├ 9
| └ 6
├ 14
└ 16
</code></pre>
<p>I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.</p>
<p>I'm confused... does this fits into the classical tree problems? or is it a graph one?</p>
<p>How can I compose this structure and solve this problem using php?</p>
| [
{
"answer_id": 79067,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 2,
"selected": true,
"text": "<p>This is the perfect chance to use recursion!</p>\n\n<p>Pseudo-code:</p>\n\n<pre><code>nodeList = {}\nenumerateNodes(rootNode, nodeList);\n\nfunction enumerateNodes(node, nodeList) {\n nodeList += node;\n foreach ( childnode in node.children ) {\n enumerateNodes(childnode, nodeList);\n }\n}\n</code></pre>\n\n<p>Edit: Didn't notice that your tree is in the adjacent list format. I would probably just build that into an actual tree datastructure before I started working with it. Just loop through all pairs (creating nodes the first time you see them) and linking them. I <em>think</em> it should be easy...</p>\n"
},
{
"answer_id": 79100,
"author": "Brettski",
"author_id": 5836,
"author_profile": "https://Stackoverflow.com/users/5836",
"pm_score": 2,
"selected": false,
"text": "<p>Adjacent list models are very difficult to deal with. The company I am with now uses them for hierarchies and it causes great headaches. I have successfully used Celko's nested set models for prior employers and they work great for creating, maintaining and using hierarchies (trees). </p>\n\n<p>I found this link which describes them: <a href=\"http://www.intelligententerprise.com/001020/celko.jhtml\" rel=\"nofollow noreferrer\">http://www.intelligententerprise.com/001020/celko.jhtml</a></p>\n\n<p>But I would also recommend the book \"SQL for Smarties: Advanced SQL Programming\" written by Joe Celko and covers nested sets. </p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/0123693799\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Joe Celko's SQL for Smarties: Advanced SQL Programming</a></p>\n\n<p><a href=\"https://rads.stackoverflow.com/amzn/click/com/1558609202\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Joe Celko's Trees and Hierarchies in SQL for Smarties</a></p>\n"
},
{
"answer_id": 79112,
"author": "Sridhar Iyer",
"author_id": 13820,
"author_profile": "https://Stackoverflow.com/users/13820",
"pm_score": 0,
"selected": false,
"text": "<p>This is a graph problem. Check out <a href=\"http://en.wikipedia.org/wiki/Breadth-first_search\" rel=\"nofollow noreferrer\">BFS(breadth first search)</a> and <a href=\"http://en.wikipedia.org/wiki/Depth-first_search\" rel=\"nofollow noreferrer\">DFS(depth first search).</a>. You can google out those terms and find hundreds of implementations on the web.</p>\n"
},
{
"answer_id": 79232,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 0,
"selected": false,
"text": "<p>This is trivial with a nested set implementation. See here for more details:</p>\n\n<p><a href=\"http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/\" rel=\"nofollow noreferrer\">http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/</a></p>\n\n<p>Otherwise, write something like this:</p>\n\n<pre><code>def get_subtree(node)\n if children.size > 0\n return children.collect { |n| get_subtree(n) }\n else\n return node\n end\nend\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861/"
]
| I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent\_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic).
So for these records (id-parent\_id pairs):
```
0-7 0-4 4-9 4-14 4-16 9-6
```
I have this tree:
```
0
├ 7
└ 4
├ 9
| └ 6
├ 14
└ 16
```
I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.
I'm confused... does this fits into the classical tree problems? or is it a graph one?
How can I compose this structure and solve this problem using php? | This is the perfect chance to use recursion!
Pseudo-code:
```
nodeList = {}
enumerateNodes(rootNode, nodeList);
function enumerateNodes(node, nodeList) {
nodeList += node;
foreach ( childnode in node.children ) {
enumerateNodes(childnode, nodeList);
}
}
```
Edit: Didn't notice that your tree is in the adjacent list format. I would probably just build that into an actual tree datastructure before I started working with it. Just loop through all pairs (creating nodes the first time you see them) and linking them. I *think* it should be easy... |
79,121 | <p>So, im trying to write some code that utilizes Nvidia's CUDA architecture. I noticed that copying to and from the device was really hurting my overall performance, so now I am trying to move a large amount of data onto the device.</p>
<p>As this data is used in numerous functions, I would like it to be global. Yes, I can pass pointers around, but I would really like to know how to work with globals in this instance. </p>
<p>So, I have device functions that want to access a device allocated array.</p>
<p>Ideally, I could do something like:</p>
<pre><code>__device__ float* global_data;
main()
{
cudaMalloc(global_data);
kernel1<<<blah>>>(blah); //access global data
kernel2<<<blah>>>(blah); //access global data again
}
</code></pre>
<p>However, I havent figured out how to create a dynamic array. I figured out a work around by declaring the array as follows:</p>
<pre><code>__device__ float global_data[REALLY_LARGE_NUMBER];
</code></pre>
<p>And while that doesn't require a cudaMalloc call, I would prefer the dynamic allocation approach.</p>
| [
{
"answer_id": 79256,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Spend some time focusing on the copious documentation offered by NVIDIA.</p>\n\n<p>From the Programming Guide:</p>\n\n<pre><code>float* devPtr;\ncudaMalloc((void**)&devPtr, 256 * sizeof(*devPtr));\ncudaMemset(devPtr, 0, 256 * sizeof(*devPtr));\n</code></pre>\n\n<p>That's a simple example of how to allocate memory. Now, in your kernels, you should accept a pointer to a float like so:</p>\n\n<pre><code>__global__\nvoid kernel1(float *some_neat_data)\n{\n some_neat_data[threadIdx.x]++;\n}\n\n__global__\nvoid kernel2(float *potentially_that_same_neat_data)\n{\n potentially_that_same_neat_data[threadIdx.x] *= 0.3f;\n}\n</code></pre>\n\n<p>So now you can invoke them like so:</p>\n\n<pre><code>float* devPtr;\ncudaMalloc((void**)&devPtr, 256 * sizeof(*devPtr));\ncudaMemset(devPtr, 0, 256 * sizeof(*devPtr));\n\nkernel1<<<1,128>>>(devPtr);\nkernel2<<<1,128>>>(devPtr);\n</code></pre>\n\n<blockquote>\n <p>As this data is used in numerous\n functions, I would like it to be\n global.</p>\n</blockquote>\n\n<p>There are few good reasons to use globals. This definitely is not one. I'll leave it as an exercise to expand this example to include moving \"devPtr\" to a global scope.</p>\n\n<p>EDIT:</p>\n\n<p>Ok, the fundamental problem is this: your kernels can only access device memory and the only global-scope pointers that they can use are GPU ones. When calling a kernel from your CPU, behind the scenes what happens is that the pointers and primitives get copied into GPU registers and/or shared memory before the kernel gets executed.</p>\n\n<p>So the closest I can suggest is this: use cudaMemcpyToSymbol() to achieve your goals. But, in the background, consider that a different approach might be the Right Thing.</p>\n\n<pre><code>#include <algorithm>\n\n__constant__ float devPtr[1024];\n\n__global__\nvoid kernel1(float *some_neat_data)\n{\n some_neat_data[threadIdx.x] = devPtr[0] * devPtr[1];\n}\n\n__global__\nvoid kernel2(float *potentially_that_same_neat_data)\n{\n potentially_that_same_neat_data[threadIdx.x] *= devPtr[2];\n}\n\n\nint main(int argc, char *argv[])\n{\n float some_data[256];\n for (int i = 0; i < sizeof(some_data) / sizeof(some_data[0]); i++)\n {\n some_data[i] = i * 2;\n }\n cudaMemcpyToSymbol(devPtr, some_data, std::min(sizeof(some_data), sizeof(devPtr) ));\n float* otherDevPtr;\n cudaMalloc((void**)&otherDevPtr, 256 * sizeof(*otherDevPtr));\n cudaMemset(otherDevPtr, 0, 256 * sizeof(*otherDevPtr));\n\n kernel1<<<1,128>>>(otherDevPtr);\n kernel2<<<1,128>>>(otherDevPtr);\n\n return 0;\n}\n</code></pre>\n\n<p>Don't forget '--host-compilation=c++' for this example.</p>\n"
},
{
"answer_id": 79336,
"author": "Voltaire",
"author_id": 14621,
"author_profile": "https://Stackoverflow.com/users/14621",
"pm_score": 0,
"selected": false,
"text": "<p>Erm, it was exactly that problem of moving devPtr to global scope that was my problem.</p>\n\n<p>I have an implementation that does exactly that, with the two kernels having a pointer to data passed in. I explicitly don't want to pass in those pointers.</p>\n\n<p>I have read the documentation fairly closely, and hit up the nvidia forums (and google searched for an hour or so), but I haven't found an implementation of a global dynamic device array that actually runs (i have tried several that compile and then fail in new and interesting ways).</p>\n"
},
{
"answer_id": 79796,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Something like this should probably work.</p>\n\n<pre><code>#include <algorithm>\n\n#define NDEBUG\n#define CUT_CHECK_ERROR(errorMessage) do { \\\n cudaThreadSynchronize(); \\\n cudaError_t err = cudaGetLastError(); \\\n if( cudaSuccess != err) { \\\n fprintf(stderr, \"Cuda error: %s in file '%s' in line %i : %s.\\n\", \\\n errorMessage, __FILE__, __LINE__, cudaGetErrorString( err) );\\\n exit(EXIT_FAILURE); \\\n } } while (0)\n\n\n__device__ float *devPtr;\n\n__global__\nvoid kernel1(float *some_neat_data)\n{\n devPtr = some_neat_data;\n}\n\n__global__\nvoid kernel2(void)\n{\n devPtr[threadIdx.x] *= .3f;\n}\n\n\nint main(int argc, char *argv[])\n{\n float* otherDevPtr;\n cudaMalloc((void**)&otherDevPtr, 256 * sizeof(*otherDevPtr));\n cudaMemset(otherDevPtr, 0, 256 * sizeof(*otherDevPtr));\n\n kernel1<<<1,128>>>(otherDevPtr);\n CUT_CHECK_ERROR(\"kernel1\");\n\n kernel2<<<1,128>>>();\n\n CUT_CHECK_ERROR(\"kernel2\");\n\n return 0;\n}\n</code></pre>\n\n<p>Give it a whirl.</p>\n"
},
{
"answer_id": 89477,
"author": "Mark Borgerding",
"author_id": 3343,
"author_profile": "https://Stackoverflow.com/users/3343",
"pm_score": 0,
"selected": false,
"text": "<p>check out the samples included with the SDK. Many of those sample projects are a decent way to learn by example.</p>\n"
},
{
"answer_id": 94437,
"author": "Voltaire",
"author_id": 14621,
"author_profile": "https://Stackoverflow.com/users/14621",
"pm_score": 1,
"selected": false,
"text": "<p>I went ahead and tried the solution of allocating a temporary pointer and passing it to a simple global function similar to kernel1.</p>\n\n<p>The good news is that it does work :)</p>\n\n<p>However, I think it confuses the compiler as I now get \"Advisory: Cannot tell what pointer points to, assuming global memory space\" whenever I try to access the global data. Luckily, the assumption happens to be correct, but the warnings are annoying.</p>\n\n<p>Anyway, for the record - I have looked at many of the examples and did run through the nvidia exercises where the point is to get the output to say \"Correct!\". However, I haven't looked at <em>all</em> of them. If anyone knows of an sdk example where they do dynamic global device memory allocation, I would still like to know.</p>\n"
},
{
"answer_id": 3511490,
"author": "Nils",
"author_id": 44232,
"author_profile": "https://Stackoverflow.com/users/44232",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>As this data is used in numerous functions, I would like it to be global.</p>\n</blockquote>\n\n<p>-</p>\n\n<blockquote>\n <p>There are few good reasons to use globals. This definitely is not one. I'll leave it as an \n exercise to expand this example to include moving \"devPtr\" to a global scope.</p>\n</blockquote>\n\n<p>What if the kernel operates on a large const structure consisting of arrays? Using the so called constant memory is not an option, because it's very limited in size.. so then you have to put it in global memory..?</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14621/"
]
| So, im trying to write some code that utilizes Nvidia's CUDA architecture. I noticed that copying to and from the device was really hurting my overall performance, so now I am trying to move a large amount of data onto the device.
As this data is used in numerous functions, I would like it to be global. Yes, I can pass pointers around, but I would really like to know how to work with globals in this instance.
So, I have device functions that want to access a device allocated array.
Ideally, I could do something like:
```
__device__ float* global_data;
main()
{
cudaMalloc(global_data);
kernel1<<<blah>>>(blah); //access global data
kernel2<<<blah>>>(blah); //access global data again
}
```
However, I havent figured out how to create a dynamic array. I figured out a work around by declaring the array as follows:
```
__device__ float global_data[REALLY_LARGE_NUMBER];
```
And while that doesn't require a cudaMalloc call, I would prefer the dynamic allocation approach. | Something like this should probably work.
```
#include <algorithm>
#define NDEBUG
#define CUT_CHECK_ERROR(errorMessage) do { \
cudaThreadSynchronize(); \
cudaError_t err = cudaGetLastError(); \
if( cudaSuccess != err) { \
fprintf(stderr, "Cuda error: %s in file '%s' in line %i : %s.\n", \
errorMessage, __FILE__, __LINE__, cudaGetErrorString( err) );\
exit(EXIT_FAILURE); \
} } while (0)
__device__ float *devPtr;
__global__
void kernel1(float *some_neat_data)
{
devPtr = some_neat_data;
}
__global__
void kernel2(void)
{
devPtr[threadIdx.x] *= .3f;
}
int main(int argc, char *argv[])
{
float* otherDevPtr;
cudaMalloc((void**)&otherDevPtr, 256 * sizeof(*otherDevPtr));
cudaMemset(otherDevPtr, 0, 256 * sizeof(*otherDevPtr));
kernel1<<<1,128>>>(otherDevPtr);
CUT_CHECK_ERROR("kernel1");
kernel2<<<1,128>>>();
CUT_CHECK_ERROR("kernel2");
return 0;
}
```
Give it a whirl. |
79,126 | <p>I'm building a function to extend the <code>Enum.Parse</code> concept that</p>
<ul>
<li>Allows a default value to be parsed in case that an Enum value is not found</li>
<li>Is case insensitive</li>
</ul>
<p>So I wrote the following:</p>
<pre><code>public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
</code></pre>
<p>I am getting a Error Constraint cannot be special class <code>System.Enum</code>.</p>
<p>Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the <code>Parse</code> function and pass a type as an attribute, which forces the ugly boxing requirement to your code.</p>
<p><strong>EDIT</strong> All suggestions below have been greatly appreciated, thanks.</p>
<p>Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)</p>
<pre><code>public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
</code></pre>
<p><strong>EDIT:</strong> (16th Feb 2015) Christopher Currens has posted <a href="https://stackoverflow.com/a/8086788">a compiler enforced type-safe generic solution in MSIL or F#</a> below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.</p>
<p><strong>EDIT 2:</strong> (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)</p>
| [
{
"answer_id": 79148,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 3,
"selected": false,
"text": "<p>Hope this is helpful:</p>\n\n<pre><code>public static TValue ParseEnum<TValue>(string value, TValue defaultValue)\n where TValue : struct // enum \n{\n try\n {\n if (String.IsNullOrEmpty(value))\n return defaultValue;\n return (TValue)Enum.Parse(typeof (TValue), value);\n }\n catch(Exception ex)\n {\n return defaultValue;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 79251,
"author": "Bivoauc",
"author_id": 14715,
"author_profile": "https://Stackoverflow.com/users/14715",
"pm_score": 4,
"selected": false,
"text": "<p>I modified the sample by dimarzionist. This version will only work with Enums and not let structs get through. </p>\n\n<pre><code>public static T ParseEnum<T>(string enumString)\n where T : struct // enum \n {\n if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)\n throw new Exception(\"Type given must be an Enum\");\n try\n {\n\n return (T)Enum.Parse(typeof(T), enumString, true);\n }\n catch (Exception ex)\n {\n return default(T);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 79319,
"author": "Karg",
"author_id": 12685,
"author_profile": "https://Stackoverflow.com/users/12685",
"pm_score": 4,
"selected": false,
"text": "<p>You can define a static constructor for the class that will check that the type T is an enum and throw an exception if it is not. This is the method mentioned by Jeffery Richter in his book CLR via C#.</p>\n\n<pre><code>internal sealed class GenericTypeThatRequiresAnEnum<T> {\n static GenericTypeThatRequiresAnEnum() {\n if (!typeof(T).IsEnum) {\n throw new ArgumentException(\"T must be an enumerated type\");\n }\n }\n}\n</code></pre>\n\n<p>Then in the parse method, you can just use Enum.Parse(typeof(T), input, true) to convert from string to the enum. The last true parameter is for ignoring case of the input. </p>\n"
},
{
"answer_id": 79903,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 10,
"selected": false,
"text": "<p>Since <code>Enum</code> Type implements <code>IConvertible</code> interface, a better implementation should be something like this:</p>\n\n<pre><code>public T GetEnumFromString<T>(string value) where T : struct, IConvertible\n{\n if (!typeof(T).IsEnum) \n {\n throw new ArgumentException(\"T must be an enumerated type\");\n }\n\n //...\n}\n</code></pre>\n\n<p>This will still permit passing of value types implementing <code>IConvertible</code>. The chances are rare though.</p>\n"
},
{
"answer_id": 1093531,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 2,
"selected": false,
"text": "<p>Interestingly enough, apparently this is <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vs2010ctpvbcs/thread/5844d719-3ef6-4000-913c-27c108269e71\" rel=\"nofollow noreferrer\">possible in other langauges</a> (Managed C++, IL directly). </p>\n\n<p>To Quote:</p>\n\n<blockquote>\n <p>... Both constraints actually produce valid IL and can also be consumed by C# if written in another language (you can declare those constraints in managed C++ or in IL).</p>\n</blockquote>\n\n<p>Who knows </p>\n"
},
{
"answer_id": 2661254,
"author": "Sunny Rajwadi",
"author_id": 319544,
"author_profile": "https://Stackoverflow.com/users/319544",
"pm_score": 3,
"selected": false,
"text": "<p>I do have specific requirement where I required to use enum with text associated with enum value. For example when I use enum to specify error type it required to describe error details.</p>\n\n<pre><code>public static class XmlEnumExtension\n{\n public static string ReadXmlEnumAttribute(this Enum value)\n {\n if (value == null) throw new ArgumentNullException(\"value\");\n var attribs = (XmlEnumAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (XmlEnumAttribute), true);\n return attribs.Length > 0 ? attribs[0].Name : value.ToString();\n }\n\n public static T ParseXmlEnumAttribute<T>(this string str)\n {\n foreach (T item in Enum.GetValues(typeof(T)))\n {\n var attribs = (XmlEnumAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(XmlEnumAttribute), true);\n if(attribs.Length > 0 && attribs[0].Name.Equals(str)) return item;\n }\n return (T)Enum.Parse(typeof(T), str, true);\n }\n}\n\npublic enum MyEnum\n{\n [XmlEnum(\"First Value\")]\n One,\n [XmlEnum(\"Second Value\")]\n Two,\n Three\n}\n\n static void Main()\n {\n // Parsing from XmlEnum attribute\n var str = \"Second Value\";\n var me = str.ParseXmlEnumAttribute<MyEnum>();\n System.Console.WriteLine(me.ReadXmlEnumAttribute());\n // Parsing without XmlEnum\n str = \"Three\";\n me = str.ParseXmlEnumAttribute<MyEnum>();\n System.Console.WriteLine(me.ReadXmlEnumAttribute());\n me = MyEnum.One;\n System.Console.WriteLine(me.ReadXmlEnumAttribute());\n}\n</code></pre>\n"
},
{
"answer_id": 3859812,
"author": "Jeff",
"author_id": 164438,
"author_profile": "https://Stackoverflow.com/users/164438",
"pm_score": 2,
"selected": false,
"text": "<p>I always liked this (you could modify as appropriate):</p>\n\n<pre><code>public static IEnumerable<TEnum> GetEnumValues()\n{\n Type enumType = typeof(TEnum);\n\n if(!enumType.IsEnum)\n throw new ArgumentException(\"Type argument must be Enum type\");\n\n Array enumValues = Enum.GetValues(enumType);\n return enumValues.Cast<TEnum>();\n}\n</code></pre>\n"
},
{
"answer_id": 4460247,
"author": "Martin",
"author_id": 394076,
"author_profile": "https://Stackoverflow.com/users/394076",
"pm_score": 4,
"selected": false,
"text": "<p>I tried to improve the code a bit:</p>\n\n<pre><code>public T LoadEnum<T>(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible\n{\n if (Enum.IsDefined(typeof(T), value))\n {\n return (T)Enum.Parse(typeof(T), value, true);\n }\n return defaultValue;\n}\n</code></pre>\n"
},
{
"answer_id": 8086788,
"author": "Christopher Currens",
"author_id": 721276,
"author_profile": "https://Stackoverflow.com/users/721276",
"pm_score": 11,
"selected": true,
"text": "<h2>This feature is finally supported in C# 7.3!</h2>\n<p>The following snippet (from <a href=\"https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190\" rel=\"noreferrer\">the dotnet samples</a>) demonstrates how:</p>\n<pre><code>public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum\n{\n var result = new Dictionary<int, string>();\n var values = Enum.GetValues(typeof(T));\n\n foreach (int item in values)\n result.Add(item, Enum.GetName(typeof(T), item));\n return result;\n}\n</code></pre>\n<p>Be sure to set your language version in your C# project to version 7.3.</p>\n<hr />\n<p>Original Answer below:</p>\n<p>I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but <em>is possible</em> in MSIL. I wrote this little....thing</p>\n<pre><code>// license: http://www.apache.org/licenses/LICENSE-2.0.html\n.assembly MyThing{}\n.class public abstract sealed MyThing.Thing\n extends [mscorlib]System.Object\n{\n .method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,\n !!T defaultValue) cil managed\n {\n .maxstack 2\n .locals init ([0] !!T temp,\n [1] !!T return_value,\n [2] class [mscorlib]System.Collections.IEnumerator enumerator,\n [3] class [mscorlib]System.IDisposable disposer)\n // if(string.IsNullOrEmpty(strValue)) return defaultValue;\n ldarg strValue\n call bool [mscorlib]System.String::IsNullOrEmpty(string)\n brfalse.s HASVALUE\n br RETURNDEF // return default it empty\n \n // foreach (T item in Enum.GetValues(typeof(T)))\n HASVALUE:\n // Enum.GetValues.GetEnumerator()\n ldtoken !!T\n call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)\n call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)\n callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator() \n stloc enumerator\n .try\n {\n CONDITION:\n ldloc enumerator\n callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()\n brfalse.s LEAVE\n \n STATEMENTS:\n // T item = (T)Enumerator.Current\n ldloc enumerator\n callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()\n unbox.any !!T\n stloc temp\n ldloca.s temp\n constrained. !!T\n \n // if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;\n callvirt instance string [mscorlib]System.Object::ToString()\n callvirt instance string [mscorlib]System.String::ToLower()\n ldarg strValue\n callvirt instance string [mscorlib]System.String::Trim()\n callvirt instance string [mscorlib]System.String::ToLower()\n callvirt instance bool [mscorlib]System.String::Equals(string)\n brfalse.s CONDITION\n ldloc temp\n stloc return_value\n leave.s RETURNVAL\n \n LEAVE:\n leave.s RETURNDEF\n }\n finally\n {\n // ArrayList's Enumerator may or may not inherit from IDisposable\n ldloc enumerator\n isinst [mscorlib]System.IDisposable\n stloc.s disposer\n ldloc.s disposer\n ldnull\n ceq\n brtrue.s LEAVEFINALLY\n ldloc.s disposer\n callvirt instance void [mscorlib]System.IDisposable::Dispose()\n LEAVEFINALLY:\n endfinally\n }\n \n RETURNDEF:\n ldarg defaultValue\n stloc return_value\n \n RETURNVAL:\n ldloc return_value\n ret\n }\n} \n</code></pre>\n<p>Which generates a function that <strong>would</strong> look like this, if it were valid C#:</p>\n<pre><code>T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum\n</code></pre>\n<p>Then with the following C# code:</p>\n<pre><code>using MyThing;\n// stuff...\nprivate enum MyEnum { Yes, No, Okay }\nstatic void Main(string[] args)\n{\n Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No\n Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay\n Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum\n}\n</code></pre>\n<p>Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you're able to constrain this method by <code>System.Enum</code>. It's also kind of a bummer, because it gets compiled into a separate assembly. However, it doesn't mean you have to deploy it that way.</p>\n<p>By removing the line <code>.assembly MyThing{}</code> and invoking ilasm as follows:</p>\n<pre><code>ilasm.exe /DLL /OUTPUT=MyThing.netmodule\n</code></pre>\n<p>you get a netmodule instead of an assembly.</p>\n<p>Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you'd have to leave it in 2 separate assemblies when you're debugging. The only way you can add them as part of your assembly would be to run csc.exe yourself using the <code>/addmodule:{files}</code> command line argument. It wouldn't be <em>too</em> painful in an MSBuild script. Of course, if you're brave or stupid, you can run csc yourself manually each time. And it certainly gets more complicated as multiple assemblies need access to it.</p>\n<p>So, it CAN be done in .Net. Is it worth the extra effort? Um, well, I guess I'll let you decide on that one.</p>\n<hr />\n<h3>F# Solution as alternative</h3>\n<p>Extra Credit: It turns out that a generic restriction on <code>enum</code> is possible in at least one other .NET language besides MSIL: F#.</p>\n<pre class=\"lang-ml prettyprint-override\"><code>type MyThing =\n static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =\n /// protect for null (only required in interop with C#)\n let str = if isNull str then String.Empty else str\n\n Enum.GetValues(typedefof<'T>)\n |> Seq.cast<_>\n |> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)\n |> function Some x -> x | None -> defaultValue\n</code></pre>\n<p>This one is easier to maintain since it's a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code <em>is</em> very different) and it relies on the <code>FSharp.Core</code> library, which, just like any other external library, needs to become part of your distribution.</p>\n<p>Here's how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs:</p>\n<pre><code>// works, result is inferred to have type StringComparison\nvar result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);\n// type restriction is recognized by C#, this fails at compile time\nvar result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);\n</code></pre>\n"
},
{
"answer_id": 10273741,
"author": "expert",
"author_id": 226895,
"author_profile": "https://Stackoverflow.com/users/226895",
"pm_score": 1,
"selected": false,
"text": "<p>I loved Christopher Currens's solution using IL but for those who don't want to deal with tricky business of including MSIL into their build process I wrote similar function in C#.</p>\n\n<p>Please note though that you can't use generic restriction like <code>where T : Enum</code> because Enum is special type. Therefore I have to check if given generic type is really enum.</p>\n\n<p>My function is:</p>\n\n<pre><code>public static T GetEnumFromString<T>(string strValue, T defaultValue)\n{\n // Check if it realy enum at runtime \n if (!typeof(T).IsEnum)\n throw new ArgumentException(\"Method GetEnumFromString can be used with enums only\");\n\n if (!string.IsNullOrEmpty(strValue))\n {\n IEnumerator enumerator = Enum.GetValues(typeof(T)).GetEnumerator();\n while (enumerator.MoveNext())\n {\n T temp = (T)enumerator.Current;\n if (temp.ToString().ToLower().Equals(strValue.Trim().ToLower()))\n return temp;\n }\n }\n\n return defaultValue;\n}\n</code></pre>\n"
},
{
"answer_id": 16736914,
"author": "Yahoo Serious",
"author_id": 422877,
"author_profile": "https://Stackoverflow.com/users/422877",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Edit</strong></p>\n\n<p>The question has now superbly been answered by <a href=\"https://stackoverflow.com/a/28527552/422877\">Julien Lebosquain</a>.\nI would also like to extend his answer with <code>ignoreCase</code>, <code>defaultValue</code> and optional arguments, while adding <code>TryParse</code> and <code>ParseOrDefault</code>.</p>\n\n<pre><code>public abstract class ConstrainedEnumParser<TClass> where TClass : class\n// value type constraint S (\"TEnum\") depends on reference type T (\"TClass\") [and on struct]\n{\n // internal constructor, to prevent this class from being inherited outside this code\n internal ConstrainedEnumParser() {}\n // Parse using pragmatic/adhoc hard cast:\n // - struct + class = enum\n // - 'guaranteed' call from derived <System.Enum>-constrained type EnumUtils\n public static TEnum Parse<TEnum>(string value, bool ignoreCase = false) where TEnum : struct, TClass\n {\n return (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase);\n }\n public static bool TryParse<TEnum>(string value, out TEnum result, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T\n {\n var didParse = Enum.TryParse(value, ignoreCase, out result);\n if (didParse == false)\n {\n result = defaultValue;\n }\n return didParse;\n }\n public static TEnum ParseOrDefault<TEnum>(string value, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T\n {\n if (string.IsNullOrEmpty(value)) { return defaultValue; }\n TEnum result;\n if (Enum.TryParse(value, ignoreCase, out result)) { return result; }\n return defaultValue;\n }\n}\n\npublic class EnumUtils: ConstrainedEnumParser<System.Enum>\n// reference type constraint to any <System.Enum>\n{\n // call to parse will then contain constraint to specific <System.Enum>-class\n}\n</code></pre>\n\n<p>Examples of usage:</p>\n\n<pre><code>WeekDay parsedDayOrArgumentException = EnumUtils.Parse<WeekDay>(\"monday\", ignoreCase:true);\nWeekDay parsedDayOrDefault;\nbool didParse = EnumUtils.TryParse<WeekDay>(\"clubs\", out parsedDayOrDefault, ignoreCase:true);\nparsedDayOrDefault = EnumUtils.ParseOrDefault<WeekDay>(\"friday\", ignoreCase:true, defaultValue:WeekDay.Sunday);\n</code></pre>\n\n<hr>\n\n<p><strong>Old</strong></p>\n\n<p>My old improvements on <a href=\"https://stackoverflow.com/a/79903\">Vivek's answer</a> by using the comments and 'new' developments:</p>\n\n<ul>\n<li>use <code>TEnum</code> for clarity for users</li>\n<li>add more interface-constraints for additional constraint-checking</li>\n<li>let <a href=\"http://msdn.microsoft.com/en-us/library/dd991317.aspx\" rel=\"noreferrer\"><code>TryParse</code></a> handle <code>ignoreCase</code> with the existing parameter\n(introduced in VS2010/.Net 4) </li>\n<li>optionally use the generic <a href=\"http://msdn.microsoft.com/en-us/library/xwth0h0d.aspx\" rel=\"noreferrer\"><code>default</code> value</a> (introduced in VS2005/.Net 2)</li>\n<li>use <a href=\"http://msdn.microsoft.com/en-us/library/dd264739.aspx\" rel=\"noreferrer\">optional arguments</a>(introduced in VS2010/.Net 4) with default values, for <code>defaultValue</code> and <code>ignoreCase</code></li>\n</ul>\n\n<p>resulting in:</p>\n\n<pre><code>public static class EnumUtils\n{\n public static TEnum ParseEnum<TEnum>(this string value,\n bool ignoreCase = true,\n TEnum defaultValue = default(TEnum))\n where TEnum : struct, IComparable, IFormattable, IConvertible\n {\n if ( ! typeof(TEnum).IsEnum) { throw new ArgumentException(\"TEnum must be an enumerated type\"); }\n if (string.IsNullOrEmpty(value)) { return defaultValue; }\n TEnum lResult;\n if (Enum.TryParse(value, ignoreCase, out lResult)) { return lResult; }\n return defaultValue;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17852186,
"author": "niaher",
"author_id": 111438,
"author_profile": "https://Stackoverflow.com/users/111438",
"pm_score": 1,
"selected": false,
"text": "<p>I've encapsulated Vivek's solution into a utility class that you can reuse. Please note that you still should define type constraints \"where T : struct, IConvertible\" on your type.</p>\n\n<pre><code>using System;\n\ninternal static class EnumEnforcer\n{\n /// <summary>\n /// Makes sure that generic input parameter is of an enumerated type.\n /// </summary>\n /// <typeparam name=\"T\">Type that should be checked.</typeparam>\n /// <param name=\"typeParameterName\">Name of the type parameter.</param>\n /// <param name=\"methodName\">Name of the method which accepted the parameter.</param>\n public static void EnforceIsEnum<T>(string typeParameterName, string methodName)\n where T : struct, IConvertible\n {\n if (!typeof(T).IsEnum)\n {\n string message = string.Format(\n \"Generic parameter {0} in {1} method forces an enumerated type. Make sure your type parameter {0} is an enum.\",\n typeParameterName,\n methodName);\n\n throw new ArgumentException(message);\n }\n }\n\n /// <summary>\n /// Makes sure that generic input parameter is of an enumerated type.\n /// </summary>\n /// <typeparam name=\"T\">Type that should be checked.</typeparam>\n /// <param name=\"typeParameterName\">Name of the type parameter.</param>\n /// <param name=\"methodName\">Name of the method which accepted the parameter.</param>\n /// <param name=\"inputParameterName\">Name of the input parameter of this page.</param>\n public static void EnforceIsEnum<T>(string typeParameterName, string methodName, string inputParameterName)\n where T : struct, IConvertible\n {\n if (!typeof(T).IsEnum)\n {\n string message = string.Format(\n \"Generic parameter {0} in {1} method forces an enumerated type. Make sure your input parameter {2} is of correct type.\",\n typeParameterName,\n methodName,\n inputParameterName);\n\n throw new ArgumentException(message);\n }\n }\n\n /// <summary>\n /// Makes sure that generic input parameter is of an enumerated type.\n /// </summary>\n /// <typeparam name=\"T\">Type that should be checked.</typeparam>\n /// <param name=\"exceptionMessage\">Message to show in case T is not an enum.</param>\n public static void EnforceIsEnum<T>(string exceptionMessage)\n where T : struct, IConvertible\n {\n if (!typeof(T).IsEnum)\n {\n throw new ArgumentException(exceptionMessage);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 22636379,
"author": "KarmaEDV",
"author_id": 2620046,
"author_profile": "https://Stackoverflow.com/users/2620046",
"pm_score": 2,
"selected": false,
"text": "<p>This is my take at it. Combined from the answers and MSDN</p>\n\n<pre><code>public static TEnum ParseToEnum<TEnum>(this string text) where TEnum : struct, IConvertible, IComparable, IFormattable\n{\n if (string.IsNullOrEmpty(text) || !typeof(TEnum).IsEnum)\n throw new ArgumentException(\"TEnum must be an Enum type\");\n\n try\n {\n var enumValue = (TEnum)Enum.Parse(typeof(TEnum), text.Trim(), true);\n return enumValue;\n }\n catch (Exception)\n {\n throw new ArgumentException(string.Format(\"{0} is not a member of the {1} enumeration.\", text, typeof(TEnum).Name));\n }\n}\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/kxydatf9%28v=vs.110%29.aspx\" rel=\"nofollow\">MSDN Source</a></p>\n"
},
{
"answer_id": 28527552,
"author": "Julien Lebosquain",
"author_id": 183367,
"author_profile": "https://Stackoverflow.com/users/183367",
"pm_score": 8,
"selected": false,
"text": "<h1>C# ≥ 7.3</h1>\n\n<p>Starting with C# 7.3 (available with Visual Studio 2017 ≥ v15.7), this code is now completely valid:</p>\n\n<pre><code>public static TEnum Parse<TEnum>(string value)\n where TEnum : struct, Enum\n{\n ...\n}\n</code></pre>\n\n<hr>\n\n<h1>C# ≤ 7.2</h1>\n\n<p>You can have a real compiler enforced enum constraint by abusing constraint inheritance. The following code specifies both a <code>class</code> and a <code>struct</code> constraints at the same time:</p>\n\n<pre><code>public abstract class EnumClassUtils<TClass>\nwhere TClass : class\n{\n\n public static TEnum Parse<TEnum>(string value)\n where TEnum : struct, TClass\n {\n return (TEnum) Enum.Parse(typeof(TEnum), value);\n }\n\n}\n\npublic class EnumUtils : EnumClassUtils<Enum>\n{\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>EnumUtils.Parse<SomeEnum>(\"value\");\n</code></pre>\n\n<p>Note: this is specifically stated in the C# 5.0 language specification:</p>\n\n<blockquote>\n <p>If type parameter S depends on type parameter T then:\n [...] It is valid for\n S to have the value type constraint and T to have the reference type\n constraint. Effectively this limits T to the types System.Object,\n System.ValueType, System.Enum, and any interface type.</p>\n</blockquote>\n"
},
{
"answer_id": 40357283,
"author": "Basheer AL-MOMANI",
"author_id": 4251431,
"author_profile": "https://Stackoverflow.com/users/4251431",
"pm_score": 1,
"selected": false,
"text": "<p>I created an extension Method <code>to get integer value from enum</code> \ntake look at method implementation </p>\n\n<pre><code>public static int ToInt<T>(this T soure) where T : IConvertible//enum\n{\n if (typeof(T).IsEnum)\n {\n return (int) (IConvertible)soure;// the tricky part\n }\n //else\n // throw new ArgumentException(\"T must be an enumerated type\");\n return soure.ToInt32(CultureInfo.CurrentCulture);\n}\n</code></pre>\n\n<p>this is usage </p>\n\n<pre><code>MemberStatusEnum.Activated.ToInt()// using extension Method\n(int) MemberStatusEnum.Activated //the ordinary way\n</code></pre>\n"
},
{
"answer_id": 45274236,
"author": "BatteryBackupUnit",
"author_id": 684096,
"author_profile": "https://Stackoverflow.com/users/684096",
"pm_score": 1,
"selected": false,
"text": "<p>As stated in other answers before; while this cannot be expressed in source-code it can actually be done on IL Level.\n@Christopher Currens <a href=\"https://stackoverflow.com/a/8086788/684096\">answer</a> shows how the IL do to that.</p>\n\n<p>With <a href=\"https://github.com/Fody/Fody\" rel=\"nofollow noreferrer\">Fody</a>s Add-In <a href=\"https://github.com/Fody/ExtraConstraints\" rel=\"nofollow noreferrer\">ExtraConstraints.Fody</a> there's a very simple way, complete with build-tooling, to achieve this. Just add their nuget packages (<code>Fody</code>, <code>ExtraConstraints.Fody</code>) to your project and add the constraints as follows (Excerpt from the Readme of ExtraConstraints):</p>\n\n<pre><code>public void MethodWithEnumConstraint<[EnumConstraint] T>() {...}\n\npublic void MethodWithTypeEnumConstraint<[EnumConstraint(typeof(ConsoleColor))] T>() {...}\n</code></pre>\n\n<p>and Fody will add the necessary IL for the constraint to be present.\nAlso note the additional feature of constraining delegates:</p>\n\n<pre><code>public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()\n{...}\n\npublic void MethodWithTypeDelegateConstraint<[DelegateConstraint(typeof(Func<int>))] T> ()\n{...}\n</code></pre>\n\n<p>Regarding Enums, you might also want to take note of the highly interesting <a href=\"https://github.com/TylerBrinkley/Enums.NET\" rel=\"nofollow noreferrer\">Enums.NET</a>.</p>\n"
},
{
"answer_id": 47457596,
"author": "uluorta",
"author_id": 785915,
"author_profile": "https://Stackoverflow.com/users/785915",
"pm_score": 0,
"selected": false,
"text": "<p>If it's ok to use direct casting afterwards, I guess you can use the <code>System.Enum</code> base class in your method, wherever necessary. You just need to replace the type parameters carefully. So the method implementation would be like:</p>\n\n<pre><code>public static class EnumUtils\n{\n public static Enum GetEnumFromString(string value, Enum defaultValue)\n {\n if (string.IsNullOrEmpty(value)) return defaultValue;\n foreach (Enum item in Enum.GetValues(defaultValue.GetType()))\n {\n if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;\n }\n return defaultValue;\n }\n}\n</code></pre>\n\n<p>Then you can use it like:</p>\n\n<pre><code>var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue);\n</code></pre>\n"
},
{
"answer_id": 49432554,
"author": "DiskJunky",
"author_id": 1838819,
"author_profile": "https://Stackoverflow.com/users/1838819",
"pm_score": 5,
"selected": false,
"text": "<p>The existing answers are true as of C# <=7.2. However, there is a C# language <a href=\"https://github.com/dotnet/csharplang/issues/104\" rel=\"noreferrer\">feature request</a> (tied to a <a href=\"https://github.com/dotnet/corefx/issues/15453\" rel=\"noreferrer\">corefx</a> feature request) to allow the following;</p>\n\n<pre><code>public class MyGeneric<TEnum> where TEnum : System.Enum\n{ }\n</code></pre>\n\n<p>At time of writing, the feature is \"In discussion\" at the Language Development Meetings.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>As per <a href=\"https://stackoverflow.com/users/661933/nawfal\">nawfal</a>'s info, this is being introduced in C# <a href=\"https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-Preview-relnotes#csharp\" rel=\"noreferrer\">7.3</a>.</p>\n\n<p><strong>EDIT 2</strong></p>\n\n<p>This is now in C# 7.3 forward (<a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7-3\" rel=\"noreferrer\">release notes</a>)</p>\n\n<p>Sample;</p>\n\n<pre><code>public static Dictionary<int, string> EnumNamedValues<T>()\n where T : System.Enum\n{\n var result = new Dictionary<int, string>();\n var values = Enum.GetValues(typeof(T));\n\n foreach (int item in values)\n result.Add(item, Enum.GetName(typeof(T), item));\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 50270186,
"author": "baumgarb",
"author_id": 4587483,
"author_profile": "https://Stackoverflow.com/users/4587483",
"pm_score": 4,
"selected": false,
"text": "<p>It should also be considered that since the release of C# 7.3 using Enum constraints is supported out-of-the-box without having to do additional checking and stuff.</p>\n\n<p>So going forward and given you've changed the language version of your project to C# 7.3 the following code is going to work perfectly fine:</p>\n\n<pre><code> private static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum\n {\n // Your code goes here...\n }\n</code></pre>\n\n<p>In case you're don't know how to change the language version to C# 7.3 see the following screenshot:\n<a href=\"https://i.stack.imgur.com/GMWgy.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/GMWgy.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>EDIT 1 - Required Visual Studio Version and considering ReSharper</strong></p>\n\n<p>For Visual Studio to recognize the new syntax you need at least version 15.7. You can find that also mentioned in Microsoft's release notes, see <a href=\"https://learn.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes#whats-new-in-157\" rel=\"noreferrer\">Visual Studio 2017 15.7 Release Notes</a>. Thanks @MohamedElshawaf for pointing out this valid question.</p>\n\n<p>Pls also note that in my case ReSharper 2018.1 as of writing this EDIT does not yet support C# 7.3. Having ReSharper activated it highlights the Enum constraint as an error telling me <em>Cannot use 'System.Array', 'System.Delegate', 'System.Enum', 'System.ValueType', 'object' as type parameter constraint</em>. \nReSharper suggests as a quick fix to <em>Remove 'Enum' constraint of type paramter T of method</em> </p>\n\n<p>However, if you turn off ReSharper temporarily under <em>Tools -> Options -> ReSharper Ultimate -> General</em> you'll see that the syntax is perfectly fine given that you use VS 15.7 or higher and C# 7.3 or higher. </p>\n"
},
{
"answer_id": 50596283,
"author": "Rodney P. Barbati",
"author_id": 1588303,
"author_profile": "https://Stackoverflow.com/users/1588303",
"pm_score": -1,
"selected": false,
"text": "<p>Just for completeness, the following is a Java solution. I am certain the same could be done in C# as well. It avoids having to specify the type anywhere in code - instead, you specify it in the strings you are trying to parse.</p>\n\n<p>The problem is that there isn't any way to know which enumeration the String might match - so the answer is to solve that problem.</p>\n\n<p>Instead of accepting just the string value, accept a String that has both the enumeration and the value in the form \"enumeration.value\". Working code is below - requires Java 1.8 or later. This would also make the XML more precise as in you would see something like color=\"Color.red\" instead of just color=\"red\".</p>\n\n<p>You would call the acceptEnumeratedValue() method with a string containing the enum name dot value name. </p>\n\n<p>The method returns the formal enumerated value.</p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\nimport java.util.function.Function;\n\n\npublic class EnumFromString {\n\n enum NumberEnum {One, Two, Three};\n enum LetterEnum {A, B, C};\n\n\n Map<String, Function<String, ? extends Enum>> enumsByName = new HashMap<>();\n\n public static void main(String[] args) {\n EnumFromString efs = new EnumFromString();\n\n System.out.print(\"\\nFirst string is NumberEnum.Two - enum is \" + efs.acceptEnumeratedValue(\"NumberEnum.Two\").name());\n System.out.print(\"\\nSecond string is LetterEnum.B - enum is \" + efs.acceptEnumeratedValue(\"LetterEnum.B\").name());\n\n }\n\n public EnumFromString() {\n enumsByName.put(\"NumberEnum\", s -> {return NumberEnum.valueOf(s);});\n enumsByName.put(\"LetterEnum\", s -> {return LetterEnum.valueOf(s);});\n }\n\n public Enum acceptEnumeratedValue(String enumDotValue) {\n\n int pos = enumDotValue.indexOf(\".\");\n\n String enumName = enumDotValue.substring(0, pos);\n String value = enumDotValue.substring(pos + 1);\n\n Enum enumeratedValue = enumsByName.get(enumName).apply(value);\n\n return enumeratedValue;\n }\n\n\n}\n</code></pre>\n"
},
{
"answer_id": 58731308,
"author": "Cubelaster",
"author_id": 1562834,
"author_profile": "https://Stackoverflow.com/users/1562834",
"pm_score": 1,
"selected": false,
"text": "<p>This is my implementation. Basically, you can setup any attribute and it works. </p>\n\n<pre><code>public static class EnumExtensions\n {\n public static string GetDescription(this Enum @enum)\n {\n Type type = @enum.GetType();\n FieldInfo fi = type.GetField(@enum.ToString());\n DescriptionAttribute[] attrs =\n fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];\n if (attrs.Length > 0)\n {\n return attrs[0].Description;\n }\n return null;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 69573641,
"author": "Chris F Carroll",
"author_id": 550314,
"author_profile": "https://Stackoverflow.com/users/550314",
"pm_score": 3,
"selected": false,
"text": "<p>note that <code>System.Enum</code> <code>Parse()</code> & <code>TryParse()</code> methods still have <code>where struct</code> constraints rather than <code>where Enum</code>, so that this won't compile:</p>\n<pre><code> bool IsValid<TE>(string attempted) where TE : Enum\n {\n return Enum.TryParse(attempted, out TE _);\n }\n</code></pre>\n<p>but this will:</p>\n<pre><code>bool Ok<TE>(string attempted) where TE : struct,Enum\n{\n return Enum.TryParse(attempted, out var _)\n}\n</code></pre>\n<p>as a result, <code>where struct,Enum</code> may be preferable to just <code>where Enum</code></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
]
| I'm building a function to extend the `Enum.Parse` concept that
* Allows a default value to be parsed in case that an Enum value is not found
* Is case insensitive
So I wrote the following:
```
public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
```
I am getting a Error Constraint cannot be special class `System.Enum`.
Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the `Parse` function and pass a type as an attribute, which forces the ugly boxing requirement to your code.
**EDIT** All suggestions below have been greatly appreciated, thanks.
Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)
```
public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
```
**EDIT:** (16th Feb 2015) Christopher Currens has posted [a compiler enforced type-safe generic solution in MSIL or F#](https://stackoverflow.com/a/8086788) below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.
**EDIT 2:** (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :) | This feature is finally supported in C# 7.3!
--------------------------------------------
The following snippet (from [the dotnet samples](https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190)) demonstrates how:
```
public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
{
var result = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (int item in values)
result.Add(item, Enum.GetName(typeof(T), item));
return result;
}
```
Be sure to set your language version in your C# project to version 7.3.
---
Original Answer below:
I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but *is possible* in MSIL. I wrote this little....thing
```
// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
extends [mscorlib]System.Object
{
.method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
!!T defaultValue) cil managed
{
.maxstack 2
.locals init ([0] !!T temp,
[1] !!T return_value,
[2] class [mscorlib]System.Collections.IEnumerator enumerator,
[3] class [mscorlib]System.IDisposable disposer)
// if(string.IsNullOrEmpty(strValue)) return defaultValue;
ldarg strValue
call bool [mscorlib]System.String::IsNullOrEmpty(string)
brfalse.s HASVALUE
br RETURNDEF // return default it empty
// foreach (T item in Enum.GetValues(typeof(T)))
HASVALUE:
// Enum.GetValues.GetEnumerator()
ldtoken !!T
call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator()
stloc enumerator
.try
{
CONDITION:
ldloc enumerator
callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
brfalse.s LEAVE
STATEMENTS:
// T item = (T)Enumerator.Current
ldloc enumerator
callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
unbox.any !!T
stloc temp
ldloca.s temp
constrained. !!T
// if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
callvirt instance string [mscorlib]System.Object::ToString()
callvirt instance string [mscorlib]System.String::ToLower()
ldarg strValue
callvirt instance string [mscorlib]System.String::Trim()
callvirt instance string [mscorlib]System.String::ToLower()
callvirt instance bool [mscorlib]System.String::Equals(string)
brfalse.s CONDITION
ldloc temp
stloc return_value
leave.s RETURNVAL
LEAVE:
leave.s RETURNDEF
}
finally
{
// ArrayList's Enumerator may or may not inherit from IDisposable
ldloc enumerator
isinst [mscorlib]System.IDisposable
stloc.s disposer
ldloc.s disposer
ldnull
ceq
brtrue.s LEAVEFINALLY
ldloc.s disposer
callvirt instance void [mscorlib]System.IDisposable::Dispose()
LEAVEFINALLY:
endfinally
}
RETURNDEF:
ldarg defaultValue
stloc return_value
RETURNVAL:
ldloc return_value
ret
}
}
```
Which generates a function that **would** look like this, if it were valid C#:
```
T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
```
Then with the following C# code:
```
using MyThing;
// stuff...
private enum MyEnum { Yes, No, Okay }
static void Main(string[] args)
{
Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay
Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
}
```
Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you're able to constrain this method by `System.Enum`. It's also kind of a bummer, because it gets compiled into a separate assembly. However, it doesn't mean you have to deploy it that way.
By removing the line `.assembly MyThing{}` and invoking ilasm as follows:
```
ilasm.exe /DLL /OUTPUT=MyThing.netmodule
```
you get a netmodule instead of an assembly.
Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you'd have to leave it in 2 separate assemblies when you're debugging. The only way you can add them as part of your assembly would be to run csc.exe yourself using the `/addmodule:{files}` command line argument. It wouldn't be *too* painful in an MSBuild script. Of course, if you're brave or stupid, you can run csc yourself manually each time. And it certainly gets more complicated as multiple assemblies need access to it.
So, it CAN be done in .Net. Is it worth the extra effort? Um, well, I guess I'll let you decide on that one.
---
### F# Solution as alternative
Extra Credit: It turns out that a generic restriction on `enum` is possible in at least one other .NET language besides MSIL: F#.
```ml
type MyThing =
static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
/// protect for null (only required in interop with C#)
let str = if isNull str then String.Empty else str
Enum.GetValues(typedefof<'T>)
|> Seq.cast<_>
|> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
|> function Some x -> x | None -> defaultValue
```
This one is easier to maintain since it's a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code *is* very different) and it relies on the `FSharp.Core` library, which, just like any other external library, needs to become part of your distribution.
Here's how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs:
```
// works, result is inferred to have type StringComparison
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
// type restriction is recognized by C#, this fails at compile time
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
``` |
79,129 | <p>For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on.</p>
<p>The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile.</p>
<pre><code>[AcceptVerbs("POST")]
public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip)
{
MembershipUser user = Membership.GetUser();
ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;
profile.Company = company;
profile.Phone = phone;
profile.Fax = fax;
profile.City = city;
profile.State = state;
profile.Zip = zip;
profile.Save();
return RedirectToAction("Index", "Account");
}</code></pre>
<p>The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null.</p>
<p>Following is a snippet of my web.config:</p>
<p><pre><code><profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="FirstName" type="string" />
<add name="LastName" type="string" />
<add name="Company" type="string" />
<add name="Phone" type="string" />
<add name="Fax" type="string" />
<add name="City" type="string" />
<add name="State" type="string" />
<add name="Zip" type="string" />
<add name="Email" type="string" >
</properties>
</profile></pre></code></p>
<p>The MembershipProvider is working without a hitch, so I know that the connection string is good.</p>
<p>Just in case it's helpful, here is my ProfileCommon class:</p>
<pre><code>public class ProfileCommon : ProfileBase
{
public virtual string Company
{
get
{
return ((string)(this.GetPropertyValue("Company")));
}
set
{
this.SetPropertyValue("Company", value);
}
}
public virtual string Phone
{
get
{
return ((string)(this.GetPropertyValue("Phone")));
}
set
{
this.SetPropertyValue("Phone", value);
}
}
public virtual string Fax
{
get
{
return ((string)(this.GetPropertyValue("Fax")));
}
set
{
this.SetPropertyValue("Fax", value);
}
}
public virtual string City
{
get
{
return ((string)(this.GetPropertyValue("City")));
}
set
{
this.SetPropertyValue("City", value);
}
}
public virtual string State
{
get
{
return ((string)(this.GetPropertyValue("State")));
}
set
{
this.SetPropertyValue("State", value);
}
}
public virtual string Zip
{
get
{
return ((string)(this.GetPropertyValue("Zip")));
}
set
{
this.SetPropertyValue("Zip", value);
}
}
public virtual ProfileCommon GetProfile(string username)
{
return ((ProfileCommon)(ProfileBase.Create(username)));
}
}</code></pre>
<p>Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects?</p>
<p>Thank you in advance...</p>
| [
{
"answer_id": 80594,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure about the whole question, but one thing I noticed in your code:</p>\n\n<pre><code>ProfileCommon profile = (ProfileCommon)ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;\n</code></pre>\n\n<p>You do not need both the (ProfileCommon) and the as ProfileCommon. They both do casts, but the () throws and exception while the as returns a null if the cast can't be made.</p>\n"
},
{
"answer_id": 93963,
"author": "Dave Dunkin",
"author_id": 453303,
"author_profile": "https://Stackoverflow.com/users/453303",
"pm_score": 3,
"selected": false,
"text": "<p>Try <a href=\"http://code.msdn.microsoft.com/WebProfileBuilder\" rel=\"nofollow noreferrer\">Web Profile Builder</a>. It's a build script that automagically generates a WebProfile class (equivalent to ProfileCommon) from web.config.</p>\n"
},
{
"answer_id": 260926,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The web.config file in the MVC Beta is wrong. The SqlProfileProvider is in System.Web.Profile, not System.Web.Security. Change this, and it should start working for you.</p>\n"
},
{
"answer_id": 434793,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "<p>Here's what you need to do:</p>\n\n<p>1) In Web.config's section, add \"inherits\" attribute in addition to your other attribute settings:</p>\n\n<pre><code><profile inherits=\"MySite.Models.ProfileCommon\" defaultProvider=\"....\n</code></pre>\n\n<p>2) Remove entire <code><properties></code> section from Web.config, since you have already defined them in your custom ProfileCommon class and also instructed to inherit from your custom class in previous step</p>\n\n<p>3) Change the code of your ProfileCommon.GetProfile() method to </p>\n\n<pre><code>public virtual ProfileCommon GetProfile(string username) \n{ \n return Create(username) as ProfileCommon; \n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10792/"
]
| For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on.
The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile.
```
[AcceptVerbs("POST")]
public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip)
{
MembershipUser user = Membership.GetUser();
ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;
profile.Company = company;
profile.Phone = phone;
profile.Fax = fax;
profile.City = city;
profile.State = state;
profile.Zip = zip;
profile.Save();
return RedirectToAction("Index", "Account");
}
```
The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null.
Following is a snippet of my web.config:
```
<profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="FirstName" type="string" />
<add name="LastName" type="string" />
<add name="Company" type="string" />
<add name="Phone" type="string" />
<add name="Fax" type="string" />
<add name="City" type="string" />
<add name="State" type="string" />
<add name="Zip" type="string" />
<add name="Email" type="string" >
</properties>
</profile>
```
The MembershipProvider is working without a hitch, so I know that the connection string is good.
Just in case it's helpful, here is my ProfileCommon class:
```
public class ProfileCommon : ProfileBase
{
public virtual string Company
{
get
{
return ((string)(this.GetPropertyValue("Company")));
}
set
{
this.SetPropertyValue("Company", value);
}
}
public virtual string Phone
{
get
{
return ((string)(this.GetPropertyValue("Phone")));
}
set
{
this.SetPropertyValue("Phone", value);
}
}
public virtual string Fax
{
get
{
return ((string)(this.GetPropertyValue("Fax")));
}
set
{
this.SetPropertyValue("Fax", value);
}
}
public virtual string City
{
get
{
return ((string)(this.GetPropertyValue("City")));
}
set
{
this.SetPropertyValue("City", value);
}
}
public virtual string State
{
get
{
return ((string)(this.GetPropertyValue("State")));
}
set
{
this.SetPropertyValue("State", value);
}
}
public virtual string Zip
{
get
{
return ((string)(this.GetPropertyValue("Zip")));
}
set
{
this.SetPropertyValue("Zip", value);
}
}
public virtual ProfileCommon GetProfile(string username)
{
return ((ProfileCommon)(ProfileBase.Create(username)));
}
}
```
Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects?
Thank you in advance... | Here's what you need to do:
1) In Web.config's section, add "inherits" attribute in addition to your other attribute settings:
```
<profile inherits="MySite.Models.ProfileCommon" defaultProvider="....
```
2) Remove entire `<properties>` section from Web.config, since you have already defined them in your custom ProfileCommon class and also instructed to inherit from your custom class in previous step
3) Change the code of your ProfileCommon.GetProfile() method to
```
public virtual ProfileCommon GetProfile(string username)
{
return Create(username) as ProfileCommon;
}
```
Hope this helps. |
79,165 | <p>I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like:</p>
<p>SVN repository in: <code>svn://myserver/path/to/svn/repos</code></p>
<p>Git repository in: <code>git://myserver/path/to/git/repos</code></p>
<pre><code>git-do-the-magic-svn-import-with-history \
svn://myserver/path/to/svn/repos \
git://myserver/path/to/git/repos
</code></pre>
<p>I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example.</p>
| [
{
"answer_id": 79178,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 10,
"selected": true,
"text": "<p>Magic:</p>\n\n<pre><code>$ git svn clone http://svn/repo/here/trunk\n</code></pre>\n\n<p>Git and SVN operate very differently. You need to learn Git, and if you want to track changes from SVN upstream, you need to learn <code>git-svn</code>. The <code>git-svn</code> <a href=\"https://git-scm.com/docs/git-svn\" rel=\"noreferrer\">main page has a good examples section</a>:</p>\n\n<pre><code>$ git svn --help\n</code></pre>\n"
},
{
"answer_id": 79188,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"https://web.archive.org/web/20160314221641/https://jonmaddox.com/2008/03/05/cleanly-migrate-your-subversion-repository-to-a-git-repository/\" rel=\"noreferrer\">Cleanly Migrate Your Subversion Repository To a Git Repository</a>. First you have to create a file that maps your Subversion commit author names to Git commiters, say <code>~/authors.txt</code>:</p>\n\n<pre><code>jmaddox = Jon Maddox <[email protected]>\nbigpappa = Brian Biggs <[email protected]>\n</code></pre>\n\n<p>Then you can download the Subversion data into a Git repository:</p>\n\n<pre><code>mkdir repo && cd repo\ngit svn init http://subversion/repo --no-metadata\ngit config svn.authorsfile ~/authors.txt\ngit svn fetch\n</code></pre>\n\n<p>If you’re on a Mac, you can get <code>git-svn</code> from MacPorts by installing <code>git-core +svn</code>.</p>\n\n<p>If your subversion repository is on the same machine as your desired git repository,\nthen you can use this syntax for the init step, otherwise all the same:</p>\n\n<pre><code>git svn init file:///home/user/repoName --no-metadata\n</code></pre>\n"
},
{
"answer_id": 85456,
"author": "EfForEffort",
"author_id": 14113,
"author_profile": "https://Stackoverflow.com/users/14113",
"pm_score": 4,
"selected": false,
"text": "<p>See the official <a href=\"http://git-scm.com/docs/git-svn\" rel=\"noreferrer\">git-svn manpage</a>. In particular, look under \"Basic Examples\":</p>\n\n<blockquote>\n <p>Tracking and contributing to an entire Subversion-managed project (complete\n with a trunk, tags and branches):</p>\n</blockquote>\n\n<pre><code># Clone a repo (like git clone):\n git svn clone http://svn.foo.org/project -T trunk -b branches -t tags\n</code></pre>\n"
},
{
"answer_id": 86094,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 6,
"selected": false,
"text": "<p>I suggest getting comfortable with Git before trying to use git-svn constantly, i.e. keeping SVN as the centralized repo and using Git locally.</p>\n<p>However, for a simple migration with all the history, here are the few simple steps:</p>\n<p>Initialize the local repo:</p>\n<pre><code>mkdir project\ncd project\ngit svn init http://svn.url\n</code></pre>\n<p>Mark how far back you want to start importing revisions:</p>\n<pre><code>git svn fetch -r42\n</code></pre>\n<p>(or just "git svn fetch" for all revs)</p>\n<p>Actually, fetch everything since then:</p>\n<pre><code>git svn rebase\n</code></pre>\n<p>You can check the result of the import with Gitk. I'm not sure if this works on Windows, it works on OSX and Linux:</p>\n<pre><code>gitk\n</code></pre>\n<p>When you've got your SVN repo cloned locally, you may want to push it to a centralized Git repo for easier collaboration.</p>\n<p>First create your empty remote repo (maybe on <a href=\"http://github.com\" rel=\"nofollow noreferrer\">GitHub</a>?):</p>\n<pre><code>git remote add origin [email protected]:user/project-name.git\n</code></pre>\n<p>Then, optionally sync your main branch so the pull operation will automatically merge the remote master with your local master when both contain new stuff:</p>\n<pre><code>git config branch.master.remote origin\ngit config branch.master.merge refs/heads/master\n</code></pre>\n<p>After that, you may be interested in trying out my very own <code>git_remote_branch</code> tool, which helps to deal with remote branches:</p>\n<p>First explanatory post: "<a href=\"http://programblings.com/2008/06/23/git-remote-branches/\" rel=\"nofollow noreferrer\">Git remote branches</a>"</p>\n<p>Follow-up for the most recent version: "<a href=\"http://programblings.com/2008/08/06/time-to-git-collaborating-with-git_remote_branch/\" rel=\"nofollow noreferrer\">Time to git collaborating with git_remote_branch</a>"</p>\n"
},
{
"answer_id": 110020,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 3,
"selected": false,
"text": "<p>GitHub now has a feature to <a href=\"http://github.com/blog/156-subversion-importing\" rel=\"noreferrer\">import from an SVN repository</a>. I never tried it, though.</p>\n"
},
{
"answer_id": 139428,
"author": "Gregg Lind",
"author_id": 15842,
"author_profile": "https://Stackoverflow.com/users/15842",
"pm_score": 2,
"selected": false,
"text": "<p>As another aside, the git-stash command is a godsend when trying to git with git-svn dcommits.</p>\n\n<p>A typical process:</p>\n\n<ol>\n<li>set up git repo</li>\n<li>do some work on different files</li>\n<li>decide to check some of the work in, using git</li>\n<li>decide to <code>svn-dcommit</code></li>\n<li>get the dreaded \"cannot commit with a dirty index\" error. </li>\n</ol>\n\n<p>The solution (requires git 1.5.3+): </p>\n\n<pre><code>git stash; git svn dcommit ; git stash apply\n</code></pre>\n"
},
{
"answer_id": 3787897,
"author": "burkestar",
"author_id": 391678,
"author_profile": "https://Stackoverflow.com/users/391678",
"pm_score": 0,
"selected": false,
"text": "<p><em><a href=\"http://www.viget.com/extend/effectively-using-git-with-subversion/\" rel=\"nofollow\">Effectively using Git with Subversion</a></em> is a gentle introduction to git-svn. For existing SVN repositories, git-svn makes this super easy. If you're starting a new repository, it's vastly easier to first create an empty SVN repository and then import using git-svn than it is going in the opposite direction. Creating a new Git repository then importing into SVN can be done, but it is a bit painful, especially if you're new to Git and hope to preserve the commit history.</p>\n"
},
{
"answer_id": 3972103,
"author": "cmcginty",
"author_id": 64313,
"author_profile": "https://Stackoverflow.com/users/64313",
"pm_score": 11,
"selected": false,
"text": "<p>Create a users file (i.e. <code>users.txt</code>) for mapping SVN users to Git:</p>\n<pre><code>user1 = First Last Name <[email protected]>\nuser2 = First Last Name <[email protected]>\n...\n</code></pre>\n<p>You can use this one-liner to build a template from your existing SVN repository:</p>\n<pre><code>svn log -q | awk -F '|' '/^r/ {gsub(/ /, "", $2); sub(" $", "", $2); print $2" = "$2" <"$2">"}' | sort -u > users.txt\n</code></pre>\n<p>SVN will stop if it finds a missing SVN user, not in the file. But after that, you can update the file and pick up where you left off.</p>\n<p>Now pull the SVN data from the repository:</p>\n<pre><code>git svn clone --stdlayout --no-metadata --authors-file=users.txt svn://hostname/path dest_dir-tmp\n</code></pre>\n<p>This command will create a new Git repository in <code>dest_dir-tmp</code> and start pulling the SVN repository. Note that the "--stdlayout" flag implies you have the common "trunk/, branches/, tags/" SVN layout. If your layout differs, become familiar with <code>--tags</code>, <code>--branches</code>, <code>--trunk</code> options (in general <code>git svn help</code>).</p>\n<p>All common protocols are allowed: <code>svn://</code>, <code>http://</code>, <code>https://</code>. The URL should target the base repository, something like <a href=\"http://svn.mycompany.com/myrepo/repository\" rel=\"noreferrer\">http://svn.mycompany.com/myrepo/repository</a>. The URL string must <strong>not</strong> include <code>/trunk</code>, <code>/tag</code> or <code>/branches</code>.</p>\n<p>Note that after executing this command it very often looks like the operation is "hanging/frozen", and it's quite normal that it can be stuck for a long time after initializing the new repository. Eventually, you will then see log messages which indicate that it's migrating.</p>\n<p>Also note that if you omit the <code>--no-metadata</code> flag, Git will append information about the corresponding SVN revision to the commit message (i.e. <code>git-svn-id: svn://svn.mycompany.com/myrepo/<branchname/trunk>@<RevisionNumber> <Repository UUID></code>)</p>\n<p>If a user name is not found, update your <code>users.txt</code> file then:</p>\n<pre><code>cd dest_dir-tmp\ngit svn fetch\n</code></pre>\n<p>You might have to repeat that last command several times, if you have a large project until all of the Subversion commits have been fetched:</p>\n<pre><code>git svn fetch\n</code></pre>\n<p>When completed, Git will checkout the SVN <code>trunk</code> into a new branch. Any other branches are set up as remotes. You can view the other SVN branches with:</p>\n<pre><code>git branch -r\n</code></pre>\n<p>If you want to keep other remote branches in your repository, you want to create a local branch for each one manually. (Skip trunk/master.) If you don't do this, the branches won't get cloned in the final step.</p>\n<pre><code>git checkout -b local_branch remote_branch\n# It's OK if local_branch and remote_branch are the same names\n</code></pre>\n<p>Tags are imported as branches. You have to create a local branch, make a tag and delete the branch to have them as tags in Git. To do it with tag "v1":</p>\n<pre><code>git checkout -b tag_v1 remotes/tags/v1\ngit checkout master\ngit tag v1 tag_v1\ngit branch -D tag_v1\n</code></pre>\n<p>Clone your GIT-SVN repository into a clean Git repository:</p>\n<pre><code>git clone dest_dir-tmp dest_dir\nrm -rf dest_dir-tmp\ncd dest_dir\n</code></pre>\n<p>The local branches that you created earlier from remote branches will only have been copied as remote branches into the newly cloned repository. (Skip trunk/master.) For each branch you want to keep:</p>\n<pre><code>git checkout -b local_branch origin/remote_branch\n</code></pre>\n<p>Finally, remove the remote from your clean Git repository that points to the now-deleted temporary repository:</p>\n<pre><code>git remote rm origin\n</code></pre>\n"
},
{
"answer_id": 4860157,
"author": "Thiago Leão Moreira",
"author_id": 141639,
"author_profile": "https://Stackoverflow.com/users/141639",
"pm_score": 6,
"selected": false,
"text": "<p>I used the <a href=\"https://github.com/nirvdrum/svn2git\" rel=\"noreferrer\">svn2git script</a> and works like a charm.</p>\n"
},
{
"answer_id": 4974152,
"author": "kdahlhaus",
"author_id": 164133,
"author_profile": "https://Stackoverflow.com/users/164133",
"pm_score": 4,
"selected": false,
"text": "<p>Pro Git 8.2 explains it:\n<a href=\"http://git-scm.com/book/en/Git-and-Other-Systems-Migrating-to-Git\" rel=\"noreferrer\">http://git-scm.com/book/en/Git-and-Other-Systems-Migrating-to-Git</a></p>\n"
},
{
"answer_id": 5385391,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 2,
"selected": false,
"text": "<p>I highly recommend this <a href=\"http://www.tfnico.com/presentations/git-and-subversion\" rel=\"nofollow\">short series of screencasts</a> I just discovered. The author walks you through the basic operations, and showcases some more advanced usages.</p>\n"
},
{
"answer_id": 8262076,
"author": "Alexander Kitaev",
"author_id": 351457,
"author_profile": "https://Stackoverflow.com/users/351457",
"pm_score": 5,
"selected": false,
"text": "<p>There is a new solution for smooth migration from Subversion to Git (or for using both simultaneously): <a href=\"http://subgit.com/\" rel=\"nofollow noreferrer\">SubGit</a>. </p>\n\n<p>I'm working on this project myself. We use SubGit in our repositories - some of my teammates use Git and some Subversion and so far it works very well.</p>\n\n<p>To migrate from Subversion to Git with SubGit you need to run:</p>\n\n<pre><code>$ subgit install svn_repos\n...\nTRANSLATION SUCCESSFUL \n</code></pre>\n\n<p>After that you'll get Git repository in svn_repos/.git and may clone it, or just continue to use Subversion and this new Git repository together: SubGit will make sure that both are always kept in sync. </p>\n\n<p>In case your Subversion repository contains multiple projects, then multiple Git repositories will be created in svn_repos/git directory. To customize translation before running it do the following:</p>\n\n<pre><code>$ subgit configure svn_repos\n$ edit svn_repos/conf/subgit.conf (change mapping, add authors mapping, etc)\n$ subgit install svn_repos\n</code></pre>\n\n<p>With <a href=\"http://subgit.com/\" rel=\"nofollow noreferrer\">SubGit</a> you may migrate to pure Git (not git-svn) and start using it while still keeping Subversion as long as you need it (for your already configured build tools, for instance).</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 9316931,
"author": "Jason Huntley",
"author_id": 1214542,
"author_profile": "https://Stackoverflow.com/users/1214542",
"pm_score": 2,
"selected": false,
"text": "<p>I just wanted to add my contribution to the Git community. I wrote a simple bash script which automates the full import. Unlike other migration tools, this tool relies on native git instead of jGit. This tool also supports repositories with a large revision history and or large blobs. It's available via github:</p>\n\n<p><a href=\"https://github.com/onepremise/SGMS\" rel=\"nofollow\">https://github.com/onepremise/SGMS</a></p>\n\n<p>This script will convert projects stored in SVN with the following format:</p>\n\n<pre><code>/trunk\n /Project1\n /Project2\n/branches\n /Project1\n /Project2\n/tags\n /Project1\n /Project2\n</code></pre>\n\n<p>This scheme is also popular and supported as well:</p>\n\n<pre><code>/Project1\n /trunk\n /branches\n /tags\n/Project2\n /trunk\n /branches\n /tags\n</code></pre>\n\n<p>Each project will get synchronized over by project name:</p>\n\n<pre><code>Ex: ./migration https://svnurl.com/basepath project1\n</code></pre>\n\n<p>If you wish to convert the full repo over, use the following syntax:</p>\n\n<pre><code>Ex: ./migration https://svnurl.com/basepath .\n</code></pre>\n"
},
{
"answer_id": 16074080,
"author": "CAD bloke",
"author_id": 492,
"author_profile": "https://Stackoverflow.com/users/492",
"pm_score": 3,
"selected": false,
"text": "<p>TortoiseGit does this. see this blog post: <a href=\"http://jimmykeen.net/articles/03-nov-2012/how-migrate-from-svn-to-git-windows-using-tortoise-clients\" rel=\"noreferrer\">http://jimmykeen.net/articles/03-nov-2012/how-migrate-from-svn-to-git-windows-using-tortoise-clients</a></p>\n\n<p>Yeah, I know answering with links isn't splendid but it's a solution, eh?</p>\n"
},
{
"answer_id": 19001024,
"author": "thoutbeckers",
"author_id": 2338613,
"author_profile": "https://Stackoverflow.com/users/2338613",
"pm_score": 3,
"selected": false,
"text": "<p>A somewhat extended answer using just git, SVN, and bash. It includes steps for SVN repositories that do not use the conventional layout with a trunk/branches/tags directory layout (SVN does absolutely nothing to enforce this kind of layout).</p>\n\n<p>First use this bash script to scan your SVN repo for the different people who contributed and to generate a template for a mapping file:</p>\n\n<pre><code>#!/usr/bin/env bash\nauthors=$(svn log -q | grep -e '^r' | awk 'BEGIN { FS = \"|\" } ; { print $2 }' | sort | uniq)\nfor author in ${authors}; do\n echo \"${author} = NAME <USER@DOMAIN>\";\ndone\n</code></pre>\n\n<p>Use this to create an <code>authors</code> file where you map svn usernames to usernames and email as set by your developers using <a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-config.html\" rel=\"nofollow\"><code>git config</code></a> properties <code>user.name</code> and <code>user.email</code> (note that for a service like GitHub only having a matching email is enough).</p>\n\n<p>Then have <a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-svn.html\" rel=\"nofollow\"><code>git svn</code></a> clone the svn repository to a git repository, telling it about the mapping:</p>\n\n<p><code>git svn clone --authors-file=authors --stdlayout svn://example.org/Folder/projectroot</code></p>\n\n<p>This can take incredibly long, since git svn will individually check out every revision for every tag or branch that exists. (note that tags in SVN are just really branches, so they end up as such in Git). You can speed this up by removing old tags and branches in SVN you don't need. </p>\n\n<p>Running this on a server in the same network or on the same server can also really speed this up. Also, if for some reason this process gets interrupted you <em>can</em> resume it using</p>\n\n<p><code>git svn rebase --continue</code></p>\n\n<p>In a lot of cases you're done here. But if your SVN repo has an unconventional layout where you simply have a directory in SVN you want to put in a git branch you can do some extra steps.</p>\n\n<p>The simplest is to just make a new SVN repo on your server that does follow convention and use <code>svn copy</code> to put your directory in trunk or a branch. This might be the only way if your directory is all the way at the root of the repo, when I last tried this <code>git svn</code> simply refused to do a checkout.</p>\n\n<p>You can also do this using git. For <code>git svn clone</code> simply use the directory you want to to put in a git branch.</p>\n\n<p>After run</p>\n\n<pre><code>git branch --set-upstream master git-svn\ngit svn rebase\n</code></pre>\n\n<p>Note that this required Git 1.7 or higher.</p>\n"
},
{
"answer_id": 19814186,
"author": "NateS",
"author_id": 187883,
"author_profile": "https://Stackoverflow.com/users/187883",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a simple shell script with no dependencies that will convert one or more SVN repositories to git and push them to GitHub.</p>\n\n<p><a href=\"https://gist.github.com/NathanSweet/7327535\" rel=\"nofollow\">https://gist.github.com/NathanSweet/7327535</a></p>\n\n<p>In about 30 lines of script it: clones using git SVN, creates a .gitignore file from SVN::ignore properties, pushes into a bare git repository, renames SVN trunk to master, converts SVN tags to git tags, and pushes it to GitHub while preserving the tags.</p>\n\n<p>I went thru a lot of pain to move a dozen SVN repositories from Google Code to GitHub. It didn't help that I used Windows. Ruby was all kinds of broken on my old Debian box and getting it working on Windows was a joke. Other solutions failed to work with Cygwin paths. Even once I got something working, I couldn't figure out how to get the tags to show up on GitHub (the secret is --follow-tags).</p>\n\n<p>In the end I cobbled together two short and simple scripts, linked above, and it works great. The solution does not need to be any more complicated than that!</p>\n"
},
{
"answer_id": 22380906,
"author": "Andrew B",
"author_id": 329028,
"author_profile": "https://Stackoverflow.com/users/329028",
"pm_score": 3,
"selected": false,
"text": "<p>This guide on atlassian's website is one of the best I have found:</p>\n\n<p><a href=\"https://www.atlassian.com/git/migration\" rel=\"noreferrer\">https://www.atlassian.com/git/migration</a></p>\n\n<p>This tool - <a href=\"https://bitbucket.org/atlassian/svn-migration-scripts\" rel=\"noreferrer\">https://bitbucket.org/atlassian/svn-migration-scripts</a> - is also really useful for generating your authors.txt among other things.</p>\n"
},
{
"answer_id": 24255861,
"author": "Craig Myles",
"author_id": 373406,
"author_profile": "https://Stackoverflow.com/users/373406",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using SourceTree you can do this directly from the app. Goto File -> New/Clone then do the following: </p>\n\n<ol>\n<li>Enter the remote SVN URL as the \"Source Path / URL\".</li>\n<li>Enter your credentials when prompted.</li>\n<li>Enter the local folder location as the \"Destination path\". </li>\n<li>Give it a name. </li>\n<li>In the advanced options select \"Git\" from the dropdown in \"Create local\nrepository of type\".</li>\n<li>You can optionally specify a revision to clone from.</li>\n<li>Hit Clone.</li>\n</ol>\n\n<p>Open the repo in SourceTree and you'll see your commit messages have been migrated too.</p>\n\n<p>Now go to Repository -> Repository Settings and add the new remote repo details. Delete the SVN remote if you wish (I did this through the \"Edit Config File\" option.</p>\n\n<p>Push the code to the new remote repo when you are ready and code freely.</p>\n"
},
{
"answer_id": 24879012,
"author": "Valarpirai",
"author_id": 3863121,
"author_profile": "https://Stackoverflow.com/users/3863121",
"pm_score": 3,
"selected": false,
"text": "<p>You have to Install</p>\n\n<pre><code>git\ngit-svn\n</code></pre>\n\n<p>Copied from this link <a href=\"http://john.albin.net/git/convert-subversion-to-git\" rel=\"noreferrer\">http://john.albin.net/git/convert-subversion-to-git</a>.</p>\n\n<p><strong>1. Retrieve a list of all Subversion committers</strong></p>\n\n<p>Subversion simply lists the username for each commit. Git’s commits have much richer data, but at its simplest, the commit author needs to have a name and email listed. By default the git-svn tool will just list the SVN username in both the author and email fields. But with a little bit of work, you can create a list of all SVN users and what their corresponding Git name and emails are. This list can be used by git-svn to transform plain svn usernames into proper Git committers.</p>\n\n<p>From the root of your local Subversion checkout, run this command:</p>\n\n<pre><code>svn log -q | awk -F '|' '/^r/ {sub(\"^ \", \"\", $2); sub(\" $\", \"\", $2); print $2\" = \"$2\" <\"$2\">\"}' | sort -u > authors-transform.txt\n</code></pre>\n\n<p>That will grab all the log messages, pluck out the usernames, eliminate any duplicate usernames, sort the usernames and place them into a “authors-transform.txt” file. Now edit each line in the file. For example, convert:</p>\n\n<pre><code>jwilkins = jwilkins <jwilkins>\n</code></pre>\n\n<p>into this:</p>\n\n<pre><code>jwilkins = John Albin Wilkins <[email protected]>\n</code></pre>\n\n<p><strong>2. Clone the Subversion repository using git-svn</strong></p>\n\n<pre><code>git svn clone [SVN repo URL] --no-metadata -A authors-transform.txt --stdlayout ~/temp\n</code></pre>\n\n<p>This will do the standard git-svn transformation (using the authors-transform.txt file you created in step 1) and place the git repository in the “~/temp” folder inside your home directory.</p>\n\n<p><strong>3. Convert svn:ignore properties to .gitignore</strong></p>\n\n<p>If your svn repo was using svn:ignore properties, you can easily convert this to a .gitignore file using:</p>\n\n<pre><code>cd ~/temp\ngit svn show-ignore > .gitignore\ngit add .gitignore\ngit commit -m 'Convert svn:ignore properties to .gitignore.'\n</code></pre>\n\n<p><strong>4. Push repository to a bare git repository</strong></p>\n\n<p>First, create a bare repository and make its default branch match svn’s “trunk” branch name.</p>\n\n<pre><code>git init --bare ~/new-bare.git\ncd ~/new-bare.git\ngit symbolic-ref HEAD refs/heads/trunk\n</code></pre>\n\n<p>Then push the temp repository to the new bare repository.</p>\n\n<pre><code>cd ~/temp\ngit remote add bare ~/new-bare.git\ngit config remote.bare.push 'refs/remotes/*:refs/heads/*'\ngit push bare\n</code></pre>\n\n<p>You can now safely delete the ~/temp repository.</p>\n\n<p><strong>5. Rename “trunk” branch to “master”</strong></p>\n\n<p>Your main development branch will be named “trunk” which matches the name it was in Subversion. You’ll want to rename it to Git’s standard “master” branch using:</p>\n\n<pre><code>cd ~/new-bare.git\ngit branch -m trunk master\n</code></pre>\n\n<p><strong>6. Clean up branches and tags</strong></p>\n\n<p>git-svn makes all of Subversions tags into very-short branches in Git of the form “tags/name”. You’ll want to convert all those branches into actual Git tags using:</p>\n\n<pre><code>cd ~/new-bare.git\ngit for-each-ref --format='%(refname)' refs/heads/tags |\ncut -d / -f 4 |\nwhile read ref\ndo\n git tag \"$ref\" \"refs/heads/tags/$ref\";\n git branch -D \"tags/$ref\";\ndone\n</code></pre>\n\n<p>This step will take a bit of typing. :-) But, don’t worry; your unix shell will provide a > secondary prompt for the extra-long command that starts with git for-each-ref.</p>\n"
},
{
"answer_id": 25823518,
"author": "leftclickben",
"author_id": 1007512,
"author_profile": "https://Stackoverflow.com/users/1007512",
"pm_score": 2,
"selected": false,
"text": "<p>For <strong>GitLab</strong> users I've put up a gist on how I migrated from SVN here:</p>\n<p><a href=\"https://gist.github.com/leftclickben/322b7a3042cbe97ed2af\" rel=\"nofollow noreferrer\">https://gist.github.com/leftclickben/322b7a3042cbe97ed2af</a></p>\n<h1>Steps to migrate from SVN to GitLab</h1>\n<h2>Setup</h2>\n<ul>\n<li>SVN is hosted at <code>svn.domain.com.au</code>.</li>\n<li>SVN is accessible via <code>http</code> (other protocols should work).</li>\n<li>GitLab is hosted at <code>git.domain.com.au</code> and:\n<ul>\n<li>A group is created with the namespace <code>dev-team</code>.</li>\n<li>At least one user account is created, added to the group, and has an SSH key for the account being used for the migration (test using <code>ssh [email protected]</code>).</li>\n<li>The project <code>favourite-project</code> is created in the <code>dev-team</code> namespace.</li>\n</ul>\n</li>\n<li>The file <code>users.txt</code> contains the relevant user details, one user per line, of the form <code>username = First Last <[email protected]></code>, where <code>username</code> is the username given in SVN logs. (See first link in References section for details, in particular answer by user Casey).</li>\n</ul>\n<h2>Versions</h2>\n<ul>\n<li>subversion version 1.6.17 (r1128011)</li>\n<li>git version 1.9.1</li>\n<li>GitLab version 7.2.1 ff1633f</li>\n<li>Ubuntu server 14.04</li>\n</ul>\n<h2>Commands</h2>\n<pre><code>bash\ngit svn clone --stdlayout --no-metadata -A users.txt \nhttp://svn.domain.com.au/svn/repository/favourite-project\ncd favourite-project\ngit remote add gitlab [email protected]:dev-team/favourite-project.git\ngit push --set-upstream gitlab master\n</code></pre>\n<p>That's it! Reload the project page in GitLab web UI and you will see all commits and files now listed.</p>\n<h2>Notes</h2>\n<ul>\n<li>If there are unknown users, the <code>git svn clone</code> command will stop, in which case, update <code>users.txt</code>, <code>cd favourite-project</code> and <code>git svn fetch</code> will continue from where it stopped.</li>\n<li>The standard <code>trunk</code>-<code>tags</code>-<code>branches</code> layout for SVN repository is required.</li>\n<li>The SVN URL given to the <code>git svn clone</code> command stops at the level immediately above <code>trunk/</code>, <code>tags/</code> and <code>branches/</code>.</li>\n<li>The <code>git svn clone</code> command produces a lot of output, including some warnings at the top; I ignored the warnings.</li>\n</ul>\n"
},
{
"answer_id": 28364465,
"author": "it3xl",
"author_id": 390940,
"author_profile": "https://Stackoverflow.com/users/390940",
"pm_score": 4,
"selected": false,
"text": "<h1><a href=\"http://www.subgit.com/\" rel=\"nofollow noreferrer\">SubGit</a> (vs Blue Screen of Death)</h1>\n<pre><code>subgit import --svn-url url://svn.serv/Bla/Bla directory/path/Local.git.Repo\n</code></pre>\n<p>It's all.</p>\n<p>+ To update from SVN, a Git repository is created by the first command.</p>\n<pre><code>subgit import directory/path/Local.git.Repo\n</code></pre>\n<hr />\n<p>I used a way to migrate to Git instantly for a huge repository. <br/>\nOf course, you need some preparation. <br/>\nBut you may don't stop the development process, at all.</p>\n<p>Here is my way.</p>\n<p>My solution looks like:</p>\n<ul>\n<li><strong>Migrate SVN to a Git repository</strong></li>\n<li><strong>Update the Git repository just before team's switching to</strong>.</li>\n</ul>\n<p>Migration takes a lot of time for a big SVN repository. <br/>\nBut updating of the completed migration just seconds.</p>\n<p>Of course, I'm using <a href=\"http://www.subgit.com/remote-book.html#7\" rel=\"nofollow noreferrer\">SubGit</a>, mama.\ngit-svn makes me <a href=\"http://en.wikipedia.org/wiki/Blue_Screen_of_Death\" rel=\"nofollow noreferrer\">Blue Screen of Death</a>. Just constantly.\nAnd git-svn is boring me with Git's "<a href=\"https://stackoverflow.com/questions/21123415/git-pull-aborted-with-error-filename-too-long\">filename too long</a>" fatal error.</p>\n<p><strong>STEPS</strong></p>\n<p><strong>1.</strong> <a href=\"http://www.subgit.com/download.html\" rel=\"nofollow noreferrer\">Download SubGit</a></p>\n<p><strong>2.</strong> Prepare migrate and update commands.</p>\n<p>Let's say we do it for Windows (it's trivial to port to Linux). <br/>\nIn a SubGit's installation <strong>bin</strong> directory (subgit-2.X.X\\bin), create two .bat files.</p>\n<p>Content of a file/command for the migration:</p>\n<pre><code>start subgit import --svn-url url://svn.serv/Bla/Bla directory/path/Local.git.Repo\n</code></pre>\n<p>The "start" command is optional here (Windows). It'll allow to see errors on start and left a shell opened after completion of the SubGit.</p>\n<p>You may add here <a href=\"http://www.subgit.com/remote-book.html#7\" rel=\"nofollow noreferrer\">additional parameters similar to git-svn</a>.\nI'm using only <strong>--default-domain myCompanyDomain.com</strong> to fix the domain of the email address of SVN authors. <br/>\nI have the standard SVN repository's structure (trunk/branches/tags) and we didn't have troubles with "authors mapping". So I'm doing nothing anymore.</p>\n<p><em>(If you want to migrate tags like branches or your SVN have multiple branches/tags folders you may consider using the more verbose SubGit <a href=\"https://stackoverflow.com/questions/23251394/subgit-import-and-multiple-branches-directories\">approach</a>)</em></p>\n<p><strong>Tip 1</strong>: Use --minimal-revision YourSvnRevNumber to see fast how things boil out (some kind of a debugging).\nEspecially useful is to see resolved author names or emails. <br/>\nOr to limit the migration history depth.</p>\n<p><strong>Tip 2</strong>: Migration may be interrupted (<kbd>Ctrl</kbd> + <kbd>C</kbd>) and restored by running of the next updating command/file. <br/>\nI don't advise doing this for big repositories. I have received "Out of memory Java+Windows exception".</p>\n<p><strong>Tip 3</strong>: Better to create a copy of your result bare repository.</p>\n<p>Content of a file/command for updating:</p>\n<pre><code>start subgit import directory/path/Local.git.Repo\n</code></pre>\n<p>You may run it any amount of time when you want to obtain the last team's commits to your Git repository.</p>\n<p><strong>Warning!</strong> Don't touch your bare repository (creation of branches for example). <br/>\nYou'll take the next fatal error:</p>\n<blockquote>\n<p>Unrecoverable error: are out of sync and cannot be synced ... Translating Subversion revisions to Git commits...</p>\n</blockquote>\n<p><strong>3.</strong> Run the first command/file. It'll take a loooong time for a big repository. 30 hours for my humble repository.</p>\n<p>It's all. <br/>\nYou may update your Git repository from SVN at any time any amount of times by running the second file/command. And before switching your development team to Git. <br/>\nIt'll take just seconds.</p>\n<hr />\n<hr />\n<p>There's one more useful task.</p>\n<p><strong>Push your local Git repository to a remote Git repository</strong></p>\n<p>Is it your case? Let's proceed.</p>\n<ol>\n<li>Configure your remotes</li>\n</ol>\n<p>Run:</p>\n<pre><code>$ git remote add origin url://your/repo.git\n</code></pre>\n<ol start=\"2\">\n<li>Prepare to initial send of your huge local Git repository to a remote repository</li>\n</ol>\n<p>By default your Git can't send big chunks.\n<a href=\"https://stackoverflow.com/a/18696820/390940\">fatal: The remote end hung up unexpectedly</a></p>\n<p>Let's run for it:</p>\n<pre><code>git config --global http.postBuffer 1073741824\n</code></pre>\n<p>524288000 - 500 MB\n1073741824 - 1 GB, etc.</p>\n<p>Fix your local <a href=\"https://www.google.com/search?newwindow=1&espv=2&q=windows+git+unable+to+get+local+issuer+certificate&oq=windows+git+unable+to+get+local+issuer+certificate&gs_l=serp.3...53528.55201.0.55497.12.9.0.0.0.1.398.398.3-1.1.0.msedr...0...1c.1.61.serp..12.0.0.rqc3smB1Tyo\" rel=\"nofollow noreferrer\">certificate troubles</a>. If your git-server uses a broken certificate.</p>\n<p><strong>I have disabled <a href=\"https://stackoverflow.com/a/8755199/390940\">certificates</a>.</strong></p>\n<p>Also your Git server may have a <a href=\"https://stackoverflow.com/questions/13456025/rpc-failed-result-22-http-code-404\">request amount limitations needing to be corrected</a>.</p>\n<ol start=\"3\">\n<li><a href=\"https://stackoverflow.com/questions/6865302/push-local-git-repo-to-new-remote-including-all-branches-and-tags\">Push all migration</a> to the team's remote Git repository.</li>\n</ol>\n<p>Run with a local Git:</p>\n<pre><code>git push origin --mirror\n</code></pre>\n<p>(<em>git push origin '*:*'</em> for old Git versions)</p>\n<p>If you get the following: <strong>error: cannot spawn git: No such file or directory</strong>... For me the full recreation of my repository solves this error (30 hours). You can try the next commands</p>\n<pre><code>git push origin --all\ngit push origin --tags\n</code></pre>\n<p>Or try to <a href=\"https://groups.google.com/d/msg/msysgit/6bFAPUQDQLI/d_ko7gWViC8J\" rel=\"nofollow noreferrer\">reinstall Git</a> (<strong>useless for me</strong>).\nOr you may create branches from all you tags and push them. Or, or, or...</p>\n"
},
{
"answer_id": 29173307,
"author": "krlmlr",
"author_id": 946850,
"author_profile": "https://Stackoverflow.com/users/946850",
"pm_score": 4,
"selected": false,
"text": "<h1><a href=\"http://www.catb.org/esr/reposurgeon/\" rel=\"noreferrer\">reposurgeon</a></h1>\n\n<p>For complicated cases, reposurgeon by <a href=\"https://en.wikipedia.org/wiki/Eric_S._Raymond\" rel=\"noreferrer\">Eric S. Raymond</a> is the tool of choice. In addition to SVN, it supports many other version control systems via the <code>fast-export</code> format, and also <a href=\"http://en.wikipedia.org/wiki/Concurrent_Versions_System\" rel=\"noreferrer\">CVS</a>. The author reports successful conversions of ancient repositories such as <a href=\"http://en.wikipedia.org/wiki/Emacs\" rel=\"noreferrer\">Emacs</a> and <a href=\"https://en.wikipedia.org/wiki/FreeBSD\" rel=\"noreferrer\">FreeBSD</a>.</p>\n\n<p>The tool apparently <a href=\"http://www.catb.org/~esr/reposurgeon/features.html\" rel=\"noreferrer\">aims at near perfect conversion</a> (such as converting SVN's <code>svn:ignore</code> properties to <code>.gitignore</code> files) even for difficult repository layouts with a long history. For many cases, other tools might be easier to use.</p>\n\n<p>Before delving into the documentation of the <code>reposurgeon</code> command line, be sure to read the excellent <a href=\"http://www.catb.org/esr/dvcs-migration-guide.html\" rel=\"noreferrer\">DVCS migration guide</a> which goes over the conversion process step by step.</p>\n"
},
{
"answer_id": 31318711,
"author": "Nanda",
"author_id": 4990518,
"author_profile": "https://Stackoverflow.com/users/4990518",
"pm_score": 0,
"selected": false,
"text": "<p>Download the Ruby installer for Windows and install the latest version with it. Add Ruby executables to your path.</p>\n\n<ul>\n<li>Install svn2git</li>\n<li>Start menu -> All programs -> Ruby -> Start a command prompt with Ruby</li>\n<li><p>Then type “gem install svn2git” and enter</p>\n\n<p><strong>Migrate Subversion repository</strong></p></li>\n<li><p>Open a Ruby command prompt and go to the directory where the files are to be migrated</p>\n\n<p>Then svn2git <a href=\"http://[domain\" rel=\"nofollow\">http://[domain</a> name]/svn/ [repository root]</p></li>\n<li><p>It may take few hours to migrate the project to Git depends on the project code size.</p></li>\n<li><p>This major step helps in creating the Git repository structure as mentioned below.</p>\n\n<p>SVN (/Project_components) trunk --> Git master\nSVN (/Project_components) branches --> Git branches\nSVN (/Project_components) tags --> Git tags</p></li>\n</ul>\n\n<p>Create the remote repository and push the changes.</p>\n"
},
{
"answer_id": 31727222,
"author": "Josh Benson",
"author_id": 5174258,
"author_profile": "https://Stackoverflow.com/users/5174258",
"pm_score": 0,
"selected": false,
"text": "<p>GitHub has an importer. Once you've created the repository, you can import from an existing repository, via its URL. It will ask for your credentials if applicable and go from there.</p>\n\n<p>As it's running it will find authors, and you can simply map them to users on GitHub.</p>\n\n<p>I have used it for a few repositories now, and it's pretty accurate and much faster too! It took 10 minutes for a repository with ~4000 commits, and after it took my friend four days!</p>\n"
},
{
"answer_id": 34879129,
"author": "Zitrax",
"author_id": 11722,
"author_profile": "https://Stackoverflow.com/users/11722",
"pm_score": 0,
"selected": false,
"text": "<p>Several answers here refer to <a href=\"https://github.com/nirvdrum/svn2git\" rel=\"nofollow\">https://github.com/nirvdrum/svn2git</a>, but for large repositories this can be slow. I had a try using <a href=\"https://github.com/svn-all-fast-export/svn2git\" rel=\"nofollow\">https://github.com/svn-all-fast-export/svn2git</a> instead which is a tool with exactly the same name but was used to migrate KDE from SVN to Git.</p>\n\n<p>Slightly more work to set it up but when done the conversion itself for me took minutes where the other script spent hours.</p>\n"
},
{
"answer_id": 35410032,
"author": "Ruslan Makrenko",
"author_id": 4953065,
"author_profile": "https://Stackoverflow.com/users/4953065",
"pm_score": 0,
"selected": false,
"text": "<p>There are different methods to achieve this goal. I've tried some of them and found really working one with just git and svn installed on Windows OS.</p>\n\n<p>Prerequisites: </p>\n\n<ol>\n<li>git on windows (I've used this one) <a href=\"https://git-scm.com/\" rel=\"nofollow noreferrer\">https://git-scm.com/</a> </li>\n<li>svn with console tools installed (I've used tortoise svn) </li>\n<li>Dump file of your SVN repository. \n<code>svnadmin dump /path/to/repository > repo_name.svn_dump</code></li>\n</ol>\n\n<p>Steps to achieve final goal (move all repository with history to a git, firstly local git, then remote)</p>\n\n<ol>\n<li><p>Create empty repository (using console tools or tortoiseSVN) in directory REPO_NAME_FOLDER\n<code>cd REPO_NAME_PARENT_FOLDER</code>, put dumpfile.dump into REPO_NAME_PARENT_FOLDER</p></li>\n<li><p><code>svnadmin load REPO_NAME_FOLDER < dumpfile.dump</code> Wait for this operation, it may be long</p></li>\n<li><p>This command is silent, so open second cmd window : <code>svnserve -d -R --root REPO_NAME_FOLDER</code> \nWhy not just use file:///...... ? Cause next command will fail with <code>Unable to open ... to URL:</code>, thanks to the answer <a href=\"https://stackoverflow.com/a/6300968/4953065\">https://stackoverflow.com/a/6300968/4953065</a></p></li>\n<li><p>Create new folder SOURCE_GIT_FOLDER</p></li>\n<li><code>cd SOURCE_GIT_FOLDER</code></li>\n<li>git svn clone svn://localhost/ Wait for this operation.</li>\n</ol>\n\n<p>Finally, what do we got?</p>\n\n<p>Lets check our Local repository : </p>\n\n<pre><code>git log\n</code></pre>\n\n<p>See your previous commits? If yes - okay</p>\n\n<p>So now you have fully functional local git repository with your sources and old svn history.\nNow, if you want to move it to some server, use the following commands : </p>\n\n<pre><code>git remote add origin https://fullurlpathtoyourrepo/reponame.git\ngit push -u origin --all # pushes up the repo and its refs for the first time\ngit push -u origin --tags # pushes up any tags\n</code></pre>\n\n<p>In my case, I've dont need tags command cause my repo dont have tags.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 35605248,
"author": "Pablo Belaustegui",
"author_id": 5975111,
"author_profile": "https://Stackoverflow.com/users/5975111",
"pm_score": 3,
"selected": false,
"text": "<p>I've posted an step by step guide (<a href=\"http://blog.10pines.com/2016/02/24/svn-to-git/\" rel=\"noreferrer\">here</a>) to convert svn in to git including converting svn tags in to git tags and svn branches in to git branches.</p>\n\n<p>Short version:</p>\n\n<p>1) clone svn from an specific revision number. (the revision number must be the oldest you want to migrate)</p>\n\n<pre><code>git svn clone --username=yourSvnUsername -T trunk_subdir -t tags_subdir -b branches_subdir -r aRevisionNumber svn_url gitreponame\n</code></pre>\n\n<p>2) fetch svn data. This step it's the one it takes most time.</p>\n\n<pre><code>cd gitreponame\ngit svn fetch\n</code></pre>\n\n<p>repeat git svn fetch until finishes without error</p>\n\n<p>3) get master branch updated</p>\n\n<pre><code>git svn rebase\n</code></pre>\n\n<p>4) Create local branches from svn branches by copying references</p>\n\n<pre><code>cp .git/refs/remotes/origin/* .git/refs/heads/\n</code></pre>\n\n<p>5) convert svn tags into git tags</p>\n\n<pre><code>git for-each-ref refs/remotes/origin/tags | sed 's#^.*\\([[:xdigit:]]\\{40\\}\\).*refs/remotes/origin/tags/\\(.*\\)$#\\2 \\1#g' | while read p; do git tag -m \"tag from svn\" $p; done\n</code></pre>\n\n<p>6) Put a repository at a better place like github</p>\n\n<pre><code>git remotes add newrepo [email protected]:aUser/aProjectName.git\ngit push newrepo refs/heads/*\ngit push --tags newrepo\n</code></pre>\n\n<p>If you want more details, read my <a href=\"http://blog.10pines.com/2016/02/24/svn-to-git/\" rel=\"noreferrer\">post</a> or ask me.</p>\n"
},
{
"answer_id": 36986911,
"author": "Pankaj",
"author_id": 926520,
"author_profile": "https://Stackoverflow.com/users/926520",
"pm_score": 3,
"selected": false,
"text": "<p>We can use <code>git svn clone</code> commands as below.</p>\n\n<ul>\n<li><code>svn log -q <SVN_URL> | awk -F '|' '/^r/ {sub(\"^ \", \"\", $2); sub(\" $\", \"\", $2); print $2\" = \"$2\" <\"$2\">\"}' | sort -u > authors.txt</code></li>\n</ul>\n\n<p>Above command will create authors file from SVN commits.</p>\n\n<ul>\n<li><code>svn log --stop-on-copy <SVN_URL></code></li>\n</ul>\n\n<p>Above command will give you first revision number when your SVN project got created.</p>\n\n<ul>\n<li><code>git svn clone -r<SVN_REV_NO>:HEAD --no-minimize-url --stdlayout --no-metadata --authors-file authors.txt <SVN_URL></code></li>\n</ul>\n\n<p>Above command will create the Git repository in local.</p>\n\n<p>Problem is that it won't convert branches and tags to push. You will have to do them manually. For example below for branches:</p>\n\n<pre><code>$ git remote add origin https://github.com/pankaj0323/JDProjects.git\n$ git branch -a\n* master\n remotes/origin/MyDevBranch\n remotes/origin/tags/MyDevBranch-1.0\n remotes/origin/trunk\n$$ git checkout -b MyDevBranch origin/MyDevBranch\nBranch MyDevBranch set up to track remote branch MyDevBranch from origin.\nSwitched to a new branch 'MyDevBranch'\n$ git branch -a\n* MyDevBranch\n master\n remotes/origin/MyDevBranch\n remotes/origin/tags/MyDevBranch-1.0\n remotes/origin/trunk\n$\n</code></pre>\n\n<p>For tags:</p>\n\n<pre><code>$git checkout origin/tags/MyDevBranch-1.0\nNote: checking out 'origin/tags/MyDevBranch-1.0'.\nYou are in 'detached HEAD' state. You can look around, make experimental\nchanges and commit them, and you can discard any commits you make in this\nstate without impacting any branches by performing another checkout.\n\nIf you want to create a new branch to retain commits you create, you may\ndo so (now or later) by using -b with the checkout command again. Example:\n\n git checkout -b new_branch_name\n\nHEAD is now at 3041d81... Creating a tag\n$ git branch -a\n* (detached from origin/tags/MyDevBranch-1.0)\n MyDevBranch\n master\n remotes/origin/MyDevBranch\n remotes/origin/tags/MyDevBranch-1.0\n remotes/origin/trunk\n$ git tag -a MyDevBranch-1.0 -m \"creating tag\"\n$git tag\nMyDevBranch-1.0\n$\n</code></pre>\n\n<p>Now push master, branches and tags to remote git repository.</p>\n\n<pre><code>$ git push origin master MyDevBranch MyDevBranch-1.0\nCounting objects: 14, done.\nDelta compression using up to 8 threads.\nCompressing objects: 100% (11/11), done.\nWriting objects: 100% (14/14), 2.28 KiB | 0 bytes/s, done.\nTotal 14 (delta 3), reused 0 (delta 0)\nTo https://github.com/pankaj0323/JDProjects.git\n * [new branch] master -> master\n * [new branch] MyDevBranch -> MyDevBranch\n * [new tag] MyDevBranch-1.0 -> MyDevBranch-1.0\n$\n</code></pre>\n\n<h1><strong>svn2git utility</strong></h1>\n\n<p><a href=\"https://github.com/nirvdrum/svn2git\" rel=\"noreferrer\">svn2git</a> utility removes manual efforts with branches and tags.</p>\n\n<p>Install it using command <code>sudo gem install svn2git</code>. After that run below command.</p>\n\n<ul>\n<li><code>$ svn2git <SVN_URL> --authors authors.txt --revision <SVN_REV_NO></code></li>\n</ul>\n\n<p>Now you can list the branches, tags and push them easily.</p>\n\n<pre><code>$ git remote add origin https://github.com/pankaj0323/JDProjects.git\n$ git branch -a\n MyDevBranch\n* master\n remotes/svn/MyDevBranch\n remotes/svn/trunk\n$ git tag\n MyDevBranch-1.0\n$ git push origin master MyDevBranch MyDevBranch-1.0\n</code></pre>\n\n<p>Imagine you have 20 branches and tags, obviously svn2git will save you a lot of time and that's why I like it better than native commands. It's a nice wrapper around native <code>git svn clone</code> command. </p>\n\n<p>For a complete example, refer my <a href=\"http://www.journaldev.com/10618/svn-to-git-migration-complete-tutorial\" rel=\"noreferrer\">blog entry</a>.</p>\n"
},
{
"answer_id": 37684168,
"author": "PShetty",
"author_id": 2160694,
"author_profile": "https://Stackoverflow.com/users/2160694",
"pm_score": 0,
"selected": false,
"text": "<p>Converting svn submodule/folder 'MyModule' into git with history without tags nor branches.</p>\n\n<ul>\n<li>git svn clone --no-metadata\n--trunk=SomeFolder1/SomeFolder2/SomeFolder3/MyModule <a href=\"http://svnhost:port/repo_root_folder/MyModule_temp\" rel=\"nofollow\">http://svnhost:port/repo_root_folder/MyModule_temp</a> -A\nC:\\cheetah\\svn\\authors-transform.txt</li>\n<li>git clone MyModule_temp MyModule</li>\n<li>cd MyModule</li>\n<li>git flow init</li>\n<li>git remote set-url origin\n<a href=\"https://userid@stashhost/stash/scm/xyzxyz/MyModule.git\" rel=\"nofollow\">https://userid@stashhost/stash/scm/xyzxyz/MyModule.git</a></li>\n<li>git push -u origin master</li>\n<li>git push -u origin develop</li>\n</ul>\n\n<p>To retain svn ignore list use the above comments after step 1</p>\n"
},
{
"answer_id": 41449157,
"author": "Pedro Vicente",
"author_id": 4739800,
"author_profile": "https://Stackoverflow.com/users/4739800",
"pm_score": 0,
"selected": false,
"text": "<p>I used the following script to read a text file that has a list of all my SVN repositories and convert them to Git, and later use <code>git clone --bare</code> to convert to a bare Git repository:</p>\n\n<pre><code>#!/bin/bash\nfile=\"list.txt\"\nwhile IFS= read -r repo_name\ndo\n printf '%s\\n' \"$repo_name\"\n sudo git svn clone --shared --preserve-empty-dirs --authors-file=users.txt file:///programs/svn/$repo_name\n sudo git clone --bare /programs/git/$repo_name $repo_name.git\n sudo chown -R www-data:www-data $repo_name.git\n sudo rm -rf $repo_name\ndone <\"$file\"\n</code></pre>\n\n<p>list.txt has the format:</p>\n\n<pre><code>repo1_name\nrepo2_name\n</code></pre>\n\n<p>And users.txt has the format:</p>\n\n<blockquote>\n <p><code>(no author) = Prince Rogers <[email protected]></code></p>\n</blockquote>\n\n<p>www-data is the Apache web server user, and permission is needed to push changes over HTTP.</p>\n"
},
{
"answer_id": 48636876,
"author": "cljk",
"author_id": 1574012,
"author_profile": "https://Stackoverflow.com/users/1574012",
"pm_score": 2,
"selected": false,
"text": "<p>I´m on a windows machine and made a small Batch to transfer a SVN repo with history (but without branches) to a GIT repo by just calling</p>\n\n<p><code>transfer.bat http://svn.my.address/svn/myrepo/trunk https://git.my.address/orga/myrepo</code></p>\n\n<p>Perhaps anybody can use it. It creates a TMP-folder checks out the SVN repo there with git and adds the new origin and pushes it... and deletes the folder again.</p>\n\n<pre><code>@echo off \nSET FROM=%1 \nSET TO=%2 \nSET TMP=tmp_%random%\n\necho from: %FROM% \necho to: %TO% \necho tmp: %TMP%\n\npause\n\ngit svn clone --no-metadata --authors-file=users.txt %FROM% %TMP% \ncd %TMP% \ngit remote add origin %TO% \ngit push --set-upstream origin master\n\n\ncd .. \necho delete %TMP% ... \npause\n\nrmdir /s /q %TMP%\n</code></pre>\n\n<p>You still need the users.txt with your user-mappings like</p>\n\n<pre><code>User1 = User One <[email protected]>\n</code></pre>\n"
},
{
"answer_id": 48732137,
"author": "Anand Tripathi",
"author_id": 5230702,
"author_profile": "https://Stackoverflow.com/users/5230702",
"pm_score": -1,
"selected": false,
"text": "<h1>For this, I have used <strong>svn2git</strong> library with the following procedure:</h1>\n\n<blockquote>\n <p>sudo apt-get install git-core git-svn ruby<br>\n sudo gem install svn2git<br>\n svn log --quiet | grep -E \"r[0-9]+ \\| .+ \\|\" | cut -d'|' -f2 | sed 's/ //g' | sort | uniq > authors.txt (this command is for mapping the authors)</p>\n</blockquote>\n\n<p>Above step should be performed in the folder that you are going to convert from svn to git.</p>\n\n<blockquote>\n <p>Add one mapping per line in authors.txt like this</p>\n</blockquote>\n\n<pre><code>anand = Anand Tripathi <email_id>\ntrip = Tripathi Anand <email_id>\n</code></pre>\n\n<p>Create a folder for a new git repository and execute the command below having the path of authors.txt</p>\n\n<pre><code>svn2git <svn_repo_path> --nobranches --notags --notrunk --no-minimize-url --username <user_name> --verbose --authors <author.txt_path>\n\nIf no trunk and no tag and branch is present then have to execute the above command else if root is trunk then mention rootistrunk or trunk is present then --trunk <trunk_name>\n</code></pre>\n\n<blockquote>\n <p>git remote add origin <br>\n git push --all origin <br>\n git push --tags origin</p>\n</blockquote>\n"
},
{
"answer_id": 63570098,
"author": "dgates82",
"author_id": 2209181,
"author_profile": "https://Stackoverflow.com/users/2209181",
"pm_score": 1,
"selected": false,
"text": "<p>First, credit to the answer from @cmcginty. It was a great starting point for me, and much of what I'll post here borrowed heavily from it. However, the repos that I was moving have years of history which led to a few issues following that answer to the letter (hundreds of branches and tags that would need to be manually moved for one; read more later).</p>\n<p>So after hours of searching and trial and error I was able to put together a script which allowed me to easily move several projects from SVN to GIT, and I've decided to share my findings here in case anyone else is in my shoes.</p>\n<p><tl;dr> Let's get started</p>\n<hr />\n<p>First, create an 'Authors' file which will translate basic svn users to more complex git users. The easiest way to do this is using a command to extract all users from the svn repo you are going to move.</p>\n<pre><code>svn log -q | awk -F '|' '/^r/ {sub("^ ", "", $2); sub(" $", "", $2); print $2" = "$2" <"$2">"}' | sort -u > authors-transform.txt\n</code></pre>\n<p>This will produce a file called authors-transform.txt with a line for each user that has made a change in the svn repo it was ran from.</p>\n<pre><code>someuser = someuser <someuser>\n</code></pre>\n<p>Update to include full name and email for git</p>\n<pre><code>someuser = Some User <[email protected]>\n</code></pre>\n<p>Now start the clone using your authors file</p>\n<pre><code>git svn clone --stdlayout --no-metadata -r854:HEAD --authors-file=authors-transform.txt https://somesvnserver/somerepo/ temp\n</code></pre>\n<ul>\n<li>--stdlayout indicates that the svn repo follows the standard /trunk /branches /tags layout</li>\n<li>--no-metadata tells git not to stamp metadata relating to the svn commits on each git commit. If this is not a one-way conversion remove this tag</li>\n<li>-r854:HEAD only fetches history from revision 854 up. This is where I hit my first snag; the repo I was converting had a 'corrupted' commit at revision 853 so it would not clone. Using this parameter allows you to only clone part of the history.</li>\n<li>temp is the name of the directory that will be created to initialize\nthe new git repo</li>\n</ul>\n<p>This step can take awhile, particularly on a large or old repo (roughly 18 hours for one of ours). You can also use that -r switch to only take a small history to see the clone, and fetch the rest later.</p>\n<p>Move to the new directory</p>\n<pre><code>cd temp\n</code></pre>\n<p>Fetch any missing history if you only pulled partial in clone</p>\n<pre><code>git svn fetch\n</code></pre>\n<p>Tags are created as branches during cloning. If you only have a few you can convert them one at a time.</p>\n<pre><code>git 1.0.0 origin/tags/1.0.0\n</code></pre>\n<p>However, this is tedious if you have hundreds of tags, so the following script worked for me.</p>\n<pre><code>for brname in `git branch -r | grep tags | awk '{gsub(/^[^\\/]+\\//,"",$1); print $1}'`; do echo $brname; tname=${brname:5}; echo $tname; git tag $tname origin/tags/$tname; done\n</code></pre>\n<p>You also need to checkout all branches you want to keep</p>\n<pre><code>git checkout -b branchname origin/branches/branchname\n</code></pre>\n<p>And if you have a lot of branches as well, this script may help</p>\n<pre><code>for brname in `git branch -r | grep -v master | grep -v HEAD | grep -v trunk | grep -v tags | awk '{gsub(/^[^\\/]+\\//,"",$1); print $1}'`; do echo $brname; git checkout -b $brname origin/$brname; done\n</code></pre>\n<p>This will ignore the trunk branch, as it will already be checked out as master and save a step later deleting the duplicate branch, as well as ignoring the /tags that we already converted.</p>\n<p>Now is a good time to take a look at the new repo and make sure you have a <strong>local</strong> branch or tag for anything you want to keep as remote branches will be dropped in a moment.</p>\n<p>Ok, now lets clone everything we've checked out to a clean repo (named temp2 here)</p>\n<pre><code>cd ..\ngit clone temp temp2\ncd temp2\n</code></pre>\n<p>Now we'll need to checkout all of the branches one more time before pushing them to their final remote, so follow your favorite method from above.</p>\n<p>If you're following gitflow you can rename your working branch to develop.</p>\n<pre><code>git checkout -b WORKING\ngit branch -m develop\ngit push origin --delete WORKING\ngit push origin -u develop\n</code></pre>\n<p>Now, if everything looks good, you're ready to push to your git repository</p>\n<pre><code>git remote set-url origin https://somebitbucketserver/somerepo.git\ngit push -u origin --all\ngit push origin --tags\n</code></pre>\n<p>I did run into one final issue which was that Control Freak initially blocked me from pushing tags that I didn't create, so if your team uses Control Freak you may need to disable or adjust that setting for your initial push.</p>\n"
},
{
"answer_id": 68242281,
"author": "Bharathiraja",
"author_id": 2648257,
"author_profile": "https://Stackoverflow.com/users/2648257",
"pm_score": 0,
"selected": false,
"text": "<p>All in One - shell script for <code>SVN</code> to <code>GIT</code> Migration. Mention the <code>GIT</code> and <code>SVN</code> details with placeholder <code><></code></p>\n<pre><code>#!/bin/bash\n\n######## Project name \nPROJECT_NAME="Helloworld"\nEMAIL="example mail"\n\n#Credientials Repo\nGIT_USER='<git username>'\nGIT_PWD='<git password>'\nSVN_USER='<svn username>'\nSVN_PWD='<svn password>'\n\n######## SVN repository to be migrated # Dont use https - error will be thrown\nBASE_SVN="<SVN URL>/Helloworld"\n\n#Organization inside BASE_SVN\nBRANCHES="branches"\nTAGS="tags"\nTRUNK="trunk"\n\n#Credientials\ngit config --global user.name '<git username>'\ngit config --global user.password '<git password>'\ngit config --global credential.helper 'cache --timeout=3600'\n\n######## GIT repository to migrate - Ensure already project created in Git\nGIT_URL=https://$GIT_USER:$GIT_PWD@<GIT URL>/Helloworld.git\n\n###########################\n#### Don't need to change from here\n###########################\n\n#Geral Configuration\nABSOLUTE_PATH=$(pwd)\nTMP=$ABSOLUTE_PATH/$PROJECT_NAME\n\n#Branchs Configuration\nSVN_BRANCHES=$BASE_SVN/$BRANCHES\nSVN_TAGS=$BASE_SVN/$TAGS\nSVN_TRUNK=$BASE_SVN/$TRUNK\n\nAUTHORS=$PROJECT_NAME"-authors.txt"\n\necho '[LOG] Starting migration of '$SVN_TRUNK\necho '[LOG] Using: '$(git --version)\necho '[LOG] Using: '$(svn --version | grep svn,)\n\nmkdir $TMP\necho\necho '[DIR] cd' $TMP\ncd $TMP\n\necho\necho '[LOG] Getting authors'\nsvn --username $SVN_USER --password $SVN_PWD log -q $BASE_SVN | awk -F '|' '/^r/ {sub("^ ", "", $2); sub(" $", "", $2); print $2" = "$2" <"$2"@"$EMAIL">"}' | sort -u >> $AUTHORS\n\necho\necho '[RUN] git svn clone --authors-file='$AUTHORS' --trunk='$TRUNK' --branches='$BRANCHES' --tags='$TAGS $BASE_SVN $TMP\ngit svn clone --authors-file=$AUTHORS --trunk=$TRUNK --branches=$BRANCHES --tags=$TAGS $BASE_SVN $TMP\n\n#Not working so no need to mention it\n#--stdlayout $PROJECT_NAME\necho\necho '[RUN] svn ls '$SVN_BRANCHES\nsvn ls $SVN_BRANCHES\n\necho \necho 'git branch -a'\ngit branch -a\n\necho\necho '[LOG] Getting first revision'\nFIRST_REVISION=$( svn log -r 1:HEAD --limit 1 $BASE_SVN | awk -F '|' '/^r/ {sub("^ ", "", $1); sub(" $", "", $1); print $1}' )\n\necho\necho '[RUN] git svn fetch -'$FIRST_REVISION':HEAD'\ngit svn fetch -$FIRST_REVISION:HEAD\n\n#Branches and Tags \necho\necho '[RUN] svn ls '$SVN_BRANCHES\nfor BRANCH in $(svn ls $SVN_BRANCHES); do\n echo git branch ${BRANCH%/} remotes/svn/${BRANCH%/}\n git branch ${BRANCH%/} remotes/svn/${BRANCH%/}\ndone\n\ngit for-each-ref --format="%(refname:short) %(objectname)" refs/remotes/origin/tags | grep -v "@" | cut -d / -f 3- |\nwhile read ref\ndo\n echo git tag -a $ref -m 'import tag from svn'\n git tag -a $ref -m 'import tag from svn'\ndone\n\ngit for-each-ref --format="%(refname:short)" refs/remotes/origin/tags | cut -d / -f 1- |\nwhile read ref\ndo\n git branch -rd $ref\ndone\n \necho\necho 'git tag'\ngit tag\n\necho\necho 'git show-ref --tags'\ngit show-ref --tags\n\necho\necho '[RUN] git remote add origin '$GIT_URL\ngit remote add origin $GIT_URL\n\necho\necho '[RUN] git push'\ngit push origin --all --force\ngit push origin --tags\n\n#echo git branch -d -r trunk\n#git branch -d -r trunk\n\ngit config --global credential.helper cache\necho 'Successful.'\n</code></pre>\n<ul>\n<li>When you run above script, it will fetch branches and tags details from SVN and put it under <code>.git</code> folder.</li>\n<li>Crosscheck whether all branches are there in the <code>SVN</code> that should be available under this <code>.git/refs/heads</code> folder.</li>\n<li>If some branches are missing which was there in <code>SVN</code> then do manually copy branches files from <code>.git/refs/remotes/origin/<branches></code> to <code>.git/refs/heads</code></li>\n<li>Only copy branches (including <code>master</code>) and ignore if any <code>tags</code> or <code>trunk</code>.</li>\n<li>Now run the script again. You could see all <code>branches</code> and <code>tags</code> in git repositories.</li>\n</ul>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
]
| I read the Git manual, FAQ, Git - SVN crash course, etc. and they all explain this and that, but nowhere can you find a simple instruction like:
SVN repository in: `svn://myserver/path/to/svn/repos`
Git repository in: `git://myserver/path/to/git/repos`
```
git-do-the-magic-svn-import-with-history \
svn://myserver/path/to/svn/repos \
git://myserver/path/to/git/repos
```
I don't expect it to be that simple, and I don't expect it to be a single command. But I do expect it not to try to explain anything - just to say what steps to take given this example. | Magic:
```
$ git svn clone http://svn/repo/here/trunk
```
Git and SVN operate very differently. You need to learn Git, and if you want to track changes from SVN upstream, you need to learn `git-svn`. The `git-svn` [main page has a good examples section](https://git-scm.com/docs/git-svn):
```
$ git svn --help
``` |
79,197 | <p>What's a simple way to combine <strong>feed</strong> and <strong>feed2</strong>? I want the items from <strong>feed2</strong> to be added to <strong>feed</strong>. Also I want to avoid duplicates as <strong>feed</strong> might already have items when a question is tagged with both WPF and Silverlight.</p>
<pre><code>Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri);
SyndicationFeed feed = SyndicationFeed.Load(reader);
Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri);
SyndicationFeed feed2 = SyndicationFeed.Load(reader2);
</code></pre>
| [
{
"answer_id": 79372,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 0,
"selected": false,
"text": "<p>If it's solely for stackoverflow, you can use this :<br>\n<a href=\"https://stackoverflow.com/feeds/tag/silverlight%20wpf\">https://stackoverflow.com/feeds/tag/silverlight%20wpf</a><br>\nThis <strong>will</strong> do an union of the two tags.</p>\n\n<p>For a more general solution, I don't know. You'd probably have to manually iterate the elements of the two feeds and join them together. You can compare the <id> elements of <entry>s to see if they are duplicates.</p>\n"
},
{
"answer_id": 79376,
"author": "Frater",
"author_id": 14746,
"author_profile": "https://Stackoverflow.com/users/14746",
"pm_score": 1,
"selected": false,
"text": "<p>Well, one possibility is to create a new syndication feed that is a clone of the first feed, and then simply iterate through each post on the second one, check the first for its existence, and add it if it doesn't exist.</p>\n\n<p>Something along the lines of:</p>\n\n<pre><code>SyndicationFeed newFeed = feed.clone;\nforeach(SyndicationItem item in feed2.items)\n{\n if (!newFeed.contains(item))\n newFeed.items.Add(item);\n}\n</code></pre>\n\n<p>might be able to do it. It looks like 'items' is a simple enumberable list of syndication items, so theres not reason you can't simply add them.</p>\n"
},
{
"answer_id": 86322,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 5,
"selected": true,
"text": "<p>You can use LINQ to simplify the code to join two lists (don't forget to put System.Linq in your usings and if necessary reference System.Core in your project) Here's a Main that does the union and prints them to console (with proper cleanup of the Reader).</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\nusing System.ServiceModel.Syndication;\n\nnamespace FeedUnion\n{\n class Program\n {\n static void Main(string[] args)\n {\n Uri feedUri = new Uri(\"http://stackoverflow.com/feeds/tag/silverlight\"); \n SyndicationFeed feed;\n SyndicationFeed feed2;\n using(XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri))\n {\n feed= SyndicationFeed.Load(reader); \n }\n Uri feed2Uri = new Uri(\"http://stackoverflow.com/feeds/tag/wpf\"); \n using (XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri))\n {\n feed2 = SyndicationFeed.Load(reader2);\n }\n SyndicationFeed feed3 = new SyndicationFeed(feed.Items.Union(feed2.Items));\n StringBuilder builder = new StringBuilder();\n using (XmlWriter writer = XmlWriter.Create(builder))\n {\n feed3.SaveAsRss20(writer);\n System.Console.Write(builder.ToString());\n System.Console.Read();\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8916265,
"author": "rasx",
"author_id": 22944,
"author_profile": "https://Stackoverflow.com/users/22944",
"pm_score": 0,
"selected": false,
"text": "<p>I've turned today's accepted answer into a unit test just to explore this slightly:</p>\n\n<pre><code> [TestMethod]\n public void ShouldCombineRssFeeds()\n {\n //reference: http://stackoverflow.com/questions/79197/combining-two-syndicationfeeds\n\n SyndicationFeed feed;\n SyndicationFeed feed2;\n\n var feedUri = new Uri(\"http://stackoverflow.com/feeds/tag/silverlight\");\n using(var reader = XmlReader.Create(feedUri.AbsoluteUri))\n {\n feed = SyndicationFeed.Load(reader);\n }\n\n Assert.IsTrue(feed.Items.Count() > 0, \"The expected feed items are not here.\");\n\n var feed2Uri = new Uri(\"http://stackoverflow.com/feeds/tag/wpf\");\n using(var reader2 = XmlReader.Create(feed2Uri.AbsoluteUri))\n {\n feed2 = SyndicationFeed.Load(reader2);\n }\n\n Assert.IsTrue(feed2.Items.Count() > 0, \"The expected feed items are not here.\");\n\n var feedsCombined = new SyndicationFeed(feed.Items.Union(feed2.Items));\n\n Assert.IsTrue(\n feedsCombined.Items.Count() == feed.Items.Count() + feed2.Items.Count(),\n \"The expected number of combined feed items are not here.\");\n\n var builder = new StringBuilder();\n using(var writer = XmlWriter.Create(builder))\n {\n feedsCombined.SaveAsRss20(writer);\n writer.Flush();\n writer.Close();\n }\n\n var xmlString = builder.ToString();\n\n Assert.IsTrue(new Func<bool>(\n () =>\n {\n var test = false;\n\n var xDoc = XDocument.Parse(xmlString);\n var count = xDoc.Root.Element(\"channel\").Elements(\"item\").Count();\n test = (count == feedsCombined.Items.Count());\n\n return test;\n }\n ).Invoke(), \"The expected number of RSS items are not here.\");\n }\n</code></pre>\n"
},
{
"answer_id": 17917480,
"author": "Manjit",
"author_id": 2629183,
"author_profile": "https://Stackoverflow.com/users/2629183",
"pm_score": 0,
"selected": false,
"text": "<pre><code> //Executed and Tested :) \n using (XmlReader reader = XmlReader.Create(strFeed))\n {\n rssData = SyndicationFeed.Load(reader);\n model.BlogFeed = rssData; ;\n }\n using (XmlReader reader = XmlReader.Create(strFeed1))\n {\n rssData1 = SyndicationFeed.Load(reader);\n model.BlogFeed = rssData1;\n }\n\n SyndicationFeed feed3 = new SyndicationFeed(rssData.Items.Union(rssData1.Items));\n model.BlogFeed = feed3; \n return View(model);\n</code></pre>\n"
},
{
"answer_id": 35239636,
"author": "Pherekles",
"author_id": 4565121,
"author_profile": "https://Stackoverflow.com/users/4565121",
"pm_score": 0,
"selected": false,
"text": "<p>This worked fine for me:</p>\n\n<pre><code>// create temporary List of SyndicationItem's\nList<SyndicationItem> tempItems = new List<SyndicationItem>();\n\n// add all feed items to the list\ntempItems.AddRange(feed.Items);\ntempItems.AddRange(feed2.Items);\n\n// remove duplicates with Linq 'Distinct()'-method depending on yourattributes\n\n// add list without duplicates to 'feed2'\nfeed2.Items = tempItems\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1133/"
]
| What's a simple way to combine **feed** and **feed2**? I want the items from **feed2** to be added to **feed**. Also I want to avoid duplicates as **feed** might already have items when a question is tagged with both WPF and Silverlight.
```
Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri);
SyndicationFeed feed = SyndicationFeed.Load(reader);
Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri);
SyndicationFeed feed2 = SyndicationFeed.Load(reader2);
``` | You can use LINQ to simplify the code to join two lists (don't forget to put System.Linq in your usings and if necessary reference System.Core in your project) Here's a Main that does the union and prints them to console (with proper cleanup of the Reader).
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ServiceModel.Syndication;
namespace FeedUnion
{
class Program
{
static void Main(string[] args)
{
Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
SyndicationFeed feed;
SyndicationFeed feed2;
using(XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri))
{
feed= SyndicationFeed.Load(reader);
}
Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
using (XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri))
{
feed2 = SyndicationFeed.Load(reader2);
}
SyndicationFeed feed3 = new SyndicationFeed(feed.Items.Union(feed2.Items));
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder))
{
feed3.SaveAsRss20(writer);
System.Console.Write(builder.ToString());
System.Console.Read();
}
}
}
}
``` |
79,215 | <p>For example, if I have a page located in Views/Home/Index.aspx and a JavaScript file located in Views/Home/Index.js, how do you reference this on the aspx page?</p>
<p>The example below doesn't work even though the compiler says the path is correct</p>
<pre><code><script src="Index.js" type="text/javascript"></script>
</code></pre>
<p>The exact same issue has been posted here in more detail:
<a href="http://forums.asp.net/p/1319380/2619991.aspx" rel="nofollow noreferrer">http://forums.asp.net/p/1319380/2619991.aspx</a></p>
<p>If this is not currently possible, will it be in the future? If not, how is everyone managing their javascript resources for large Asp.net MVC projects? Do you just create a folder structure in the Content folder that mirrors your View folder structure? YUCK!</p>
| [
{
"answer_id": 79246,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the VirtualPathUtility.ToAbsolute method like below to convert the app relative url of the .js file to an absolute one that can be written to the page:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"<%=VirtualPathUtility.ToAbsolute(\"~/Views/Home/Index.js\") %>\"></script>\n</code></pre>\n"
},
{
"answer_id": 79267,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 1,
"selected": false,
"text": "<p>You should have separated folder structure for scripts. For example JavaScript folder under application root. Storing js files with views is not only affects you with path resolving issues but also affects security and permissions thins. Also it's much more easier later to embed JS files as assembly resources if you will decide to deploy some of your application parts separately in future when they are stored in dedicated subfolder. </p>\n"
},
{
"answer_id": 79772,
"author": "Vyrotek",
"author_id": 10941,
"author_profile": "https://Stackoverflow.com/users/10941",
"pm_score": 2,
"selected": true,
"text": "<p>For shared javascript resources using the Content folder makes sense. The issue was I was specifically trying to solve was aspx page specific javascript that would never be reused. </p>\n\n<p>I think what I will just have to do is put the aspx page specific javascript right onto the page itself and keep the shared js resources in the Content folder.</p>\n"
},
{
"answer_id": 80638,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a nice extension method for HtmlHelper:</p>\n\n<pre><code>public static class JavaScriptExtensions\n{\n public static string JavaScript(this HtmlHelper html, string source)\n {\n TagBuilder tagBuilder = new TagBuilder(\"script\");\n tagBuilder.Attributes.Add(\"type\", \"text/javascript\");\n tagBuilder.Attributes.Add(\"src\", VirtualPathUtility.ToAbsolute(source));\n return tagBuilder.ToString(TagRenderMode.Normal);\n }\n}\n</code></pre>\n\n<p>Use it like this:</p>\n\n<pre><code><%=Html.JavaScript(\"~/Content/MicrosoftAjax.js\")%>\n</code></pre>\n"
},
{
"answer_id": 8094695,
"author": "Pablo Montilla",
"author_id": 83169,
"author_profile": "https://Stackoverflow.com/users/83169",
"pm_score": 0,
"selected": false,
"text": "<p>If you re-route your pages to a custom RouteHandler, you can check for existence of files before handling the RequestContext to the MvcHandler class.</p>\n\n<p>Example (not complete):</p>\n\n<pre><code>public class RouteHandler : IRouteHandler\n{\n public IHttpHandler \n GetHttpHandler(RequestContext requestContext)\n {\n var request = requestContext.HttpContext.Request;\n\n // Here you should probably make the 'Views' directory appear in the correct place.\n var path = request.MapPath(request.Path); \n if(File.Exists(path)) {\n // This is internal, you probably should make your own version.\n return new StaticFileHandler(requestContext);\n }\n else {\n return new MvcHandler(requestContext);\n }\n }\n}\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10941/"
]
| For example, if I have a page located in Views/Home/Index.aspx and a JavaScript file located in Views/Home/Index.js, how do you reference this on the aspx page?
The example below doesn't work even though the compiler says the path is correct
```
<script src="Index.js" type="text/javascript"></script>
```
The exact same issue has been posted here in more detail:
<http://forums.asp.net/p/1319380/2619991.aspx>
If this is not currently possible, will it be in the future? If not, how is everyone managing their javascript resources for large Asp.net MVC projects? Do you just create a folder structure in the Content folder that mirrors your View folder structure? YUCK! | For shared javascript resources using the Content folder makes sense. The issue was I was specifically trying to solve was aspx page specific javascript that would never be reused.
I think what I will just have to do is put the aspx page specific javascript right onto the page itself and keep the shared js resources in the Content folder. |
79,258 | <p>Is there a tool that will find for me all the css classes that I am referencing in my HTML that don't actually exist?</p>
<p>ie. if I have <ul class="topnav" /> in my HTML and the topnav class doesn't exist in any of the referenced CSS files.</p>
<p>This is similar to <a href="https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website">SO#33242</a>, which asks how to find unused CSS styles. This isn't a duplicate, as that question asks which CSS classes are not used. This is the opposite problem.</p>
| [
{
"answer_id": 79306,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 1,
"selected": false,
"text": "<p>Error Console in Firefox. Although, it gives <strong>all</strong> CSS errors, so you have to read through it.</p>\n"
},
{
"answer_id": 79321,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.jetbrains.com/idea/features/html_css_editor.html\" rel=\"nofollow noreferrer\" title=\"IntelliJ Idea\">IntelliJ Idea</a> tool does that as well. </p>\n"
},
{
"answer_id": 79433,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 3,
"selected": true,
"text": "<p>You can put this JavaScript in the page that can perform this task for you:</p>\n\n<pre><code>function forItems(a, f) {\n for (var i = 0; i < a.length; i++) f(a.item(i))\n}\n\nfunction classExists(className) {\n var pattern = new RegExp('\\\\.' + className + '\\\\b'), found = false\n\n try {\n forItems(document.styleSheets, function(ss) {\n // decompose only screen stylesheets\n if (!ss.media.length || /\\b(all|screen)\\b/.test(ss.media.mediaText))\n forItems(ss.cssRules, function(r) {\n // ignore rules other than style rules\n if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {\n found = true\n throw \"found\"\n }\n })\n })\n } catch(e) {}\n\n\n return found\n}\n</code></pre>\n"
},
{
"answer_id": 97654,
"author": "Buzz",
"author_id": 13113,
"author_profile": "https://Stackoverflow.com/users/13113",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.sitepoint.com/dustmeselectors/\" rel=\"nofollow noreferrer\">This Firefox extension</a> is does exactly what you want.</p>\n\n<p>It locates all unused selectors. </p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4640/"
]
| Is there a tool that will find for me all the css classes that I am referencing in my HTML that don't actually exist?
ie. if I have <ul class="topnav" /> in my HTML and the topnav class doesn't exist in any of the referenced CSS files.
This is similar to [SO#33242](https://stackoverflow.com/questions/33242/how-can-i-find-unused-images-and-css-styles-in-a-website), which asks how to find unused CSS styles. This isn't a duplicate, as that question asks which CSS classes are not used. This is the opposite problem. | You can put this JavaScript in the page that can perform this task for you:
```
function forItems(a, f) {
for (var i = 0; i < a.length; i++) f(a.item(i))
}
function classExists(className) {
var pattern = new RegExp('\\.' + className + '\\b'), found = false
try {
forItems(document.styleSheets, function(ss) {
// decompose only screen stylesheets
if (!ss.media.length || /\b(all|screen)\b/.test(ss.media.mediaText))
forItems(ss.cssRules, function(r) {
// ignore rules other than style rules
if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {
found = true
throw "found"
}
})
})
} catch(e) {}
return found
}
``` |
79,264 | <p>Is there a program or API I can code against to extract individual files from a Windows Vista Complete PC Backup image?</p>
<p>I like the idea of having a complete image to restore from, but hate the idea that I have to make two backups, one for restoring individual files, and one for restoring my computer in the event of a catastrophic failure.</p>
| [
{
"answer_id": 79306,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 1,
"selected": false,
"text": "<p>Error Console in Firefox. Although, it gives <strong>all</strong> CSS errors, so you have to read through it.</p>\n"
},
{
"answer_id": 79321,
"author": "Swati",
"author_id": 12682,
"author_profile": "https://Stackoverflow.com/users/12682",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.jetbrains.com/idea/features/html_css_editor.html\" rel=\"nofollow noreferrer\" title=\"IntelliJ Idea\">IntelliJ Idea</a> tool does that as well. </p>\n"
},
{
"answer_id": 79433,
"author": "mislav",
"author_id": 11687,
"author_profile": "https://Stackoverflow.com/users/11687",
"pm_score": 3,
"selected": true,
"text": "<p>You can put this JavaScript in the page that can perform this task for you:</p>\n\n<pre><code>function forItems(a, f) {\n for (var i = 0; i < a.length; i++) f(a.item(i))\n}\n\nfunction classExists(className) {\n var pattern = new RegExp('\\\\.' + className + '\\\\b'), found = false\n\n try {\n forItems(document.styleSheets, function(ss) {\n // decompose only screen stylesheets\n if (!ss.media.length || /\\b(all|screen)\\b/.test(ss.media.mediaText))\n forItems(ss.cssRules, function(r) {\n // ignore rules other than style rules\n if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {\n found = true\n throw \"found\"\n }\n })\n })\n } catch(e) {}\n\n\n return found\n}\n</code></pre>\n"
},
{
"answer_id": 97654,
"author": "Buzz",
"author_id": 13113,
"author_profile": "https://Stackoverflow.com/users/13113",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.sitepoint.com/dustmeselectors/\" rel=\"nofollow noreferrer\">This Firefox extension</a> is does exactly what you want.</p>\n\n<p>It locates all unused selectors. </p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581/"
]
| Is there a program or API I can code against to extract individual files from a Windows Vista Complete PC Backup image?
I like the idea of having a complete image to restore from, but hate the idea that I have to make two backups, one for restoring individual files, and one for restoring my computer in the event of a catastrophic failure. | You can put this JavaScript in the page that can perform this task for you:
```
function forItems(a, f) {
for (var i = 0; i < a.length; i++) f(a.item(i))
}
function classExists(className) {
var pattern = new RegExp('\\.' + className + '\\b'), found = false
try {
forItems(document.styleSheets, function(ss) {
// decompose only screen stylesheets
if (!ss.media.length || /\b(all|screen)\b/.test(ss.media.mediaText))
forItems(ss.cssRules, function(r) {
// ignore rules other than style rules
if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {
found = true
throw "found"
}
})
})
} catch(e) {}
return found
}
``` |
79,275 | <p>I have a form like this:</p>
<pre><code><form name="mine">
<input type=text name=one>
<input type=text name=two>
<input type=text name=three>
</form>
</code></pre>
<p>When user types a value in 'one', I sometimes want to skip the field 'two', depending on what he typed. For example, if user types '123' and uses Tab to move to next field, I want to skip it and go to field three.</p>
<p>I tried to use <code>OnBlur</code> and <code>OnEnter</code>, without success. </p>
<p><strong>Try 1:</strong></p>
<pre><code><form name="mine">
<input type=text name=one onBlur="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=two>
<input type=text name=three>
</form>
</code></pre>
<p><strong>Try 2:</strong></p>
<pre><code><form name="mine">
<input type=text name=one>
<input type=text name=two onEnter="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=three>
</form>
</code></pre>
<p>but none of these works. Looks like the browser doesn't allow you to mess with focus while the focus is changing. </p>
<p>BTW, all this tried with Firefox on Linux.</p>
| [
{
"answer_id": 79317,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 3,
"selected": true,
"text": "<p>Try to attach tabindex attribute to your elements and then programmaticaly (in javaScript change it):</p>\n\n<pre><code><INPUT tabindex=\"3\" type=\"submit\" name=\"mySubmit\">\n</code></pre>\n"
},
{
"answer_id": 79323,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>You could use the <a href=\"http://www.w3schools.com/jsref/jsref_onfocus.asp\" rel=\"nofollow noreferrer\">onfocus</a> event on field two, which will be called when it receives focus. At that point, field 1's value should be updated and you can perform your check then.</p>\n"
},
{
"answer_id": 79335,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": "<p>If you used the method you describe, and they worked, the focus would also change when the user clicks on the field, instead of tabbing to it. I can guarantee you that this would result in a frustrated user. (Why exactly it doesn't work is beyond me.)</p>\n\n<p>Instead, as said before, change the tabindex of the appropriate fields as soon as the content of field one changes.</p>\n"
},
{
"answer_id": 79345,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "<pre><code><form name=\"mine\">\n <input type=\"text\" name=\"one\" onkeypress=\"if (mine.one.value == '123') mine.three.focus();\" />\n <input type=\"text\" name=\"two\">\n <input type=\"text\" name=\"three\">\n</form>\n</code></pre>\n"
},
{
"answer_id": 79347,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try <code>onkeypress</code> instead of <code>onblur</code>. Also, on the <code>onfocus</code> of field two is where you should be sending to three. I'm assuming you don't want them typing in two if one is 123 so you can just check that on two's <code>onfocus</code> and send on to three.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
]
| I have a form like this:
```
<form name="mine">
<input type=text name=one>
<input type=text name=two>
<input type=text name=three>
</form>
```
When user types a value in 'one', I sometimes want to skip the field 'two', depending on what he typed. For example, if user types '123' and uses Tab to move to next field, I want to skip it and go to field three.
I tried to use `OnBlur` and `OnEnter`, without success.
**Try 1:**
```
<form name="mine">
<input type=text name=one onBlur="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=two>
<input type=text name=three>
</form>
```
**Try 2:**
```
<form name="mine">
<input type=text name=one>
<input type=text name=two onEnter="if (document.mine.one.value='123') document.three.focus();>
<input type=text name=three>
</form>
```
but none of these works. Looks like the browser doesn't allow you to mess with focus while the focus is changing.
BTW, all this tried with Firefox on Linux. | Try to attach tabindex attribute to your elements and then programmaticaly (in javaScript change it):
```
<INPUT tabindex="3" type="submit" name="mySubmit">
``` |
79,292 | <p>Can databases (MySQL in particular, any SQL--MS, Oracle, Postgres--in general) do mass updates, and figure out on their own what the new value should be? Say for example I've got a database with information about a bunch of computers, and all of these computers have drives of various sizes--anywhere from 20 to 250 GB. Then one day we upgrade every single computer by adding a 120 GB hard drive. Is there a way to say something like</p>
<pre><code>update computers set total_disk_space = (whatever that row's current total_disk_space is plus 120)
</code></pre>
| [
{
"answer_id": 79305,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 2,
"selected": false,
"text": "<p>Yeah:</p>\n\n<pre><code>update computers set total_disk_space = total_disk_space + 120;\n</code></pre>\n"
},
{
"answer_id": 79313,
"author": "Stephen Wrighton",
"author_id": 7516,
"author_profile": "https://Stackoverflow.com/users/7516",
"pm_score": 3,
"selected": false,
"text": "<p>For the entire Table then:</p>\n\n<pre><code>Update Computers \nSet Total_Disk_Space = Total_Disk_Space + 120;\n</code></pre>\n\n<p>If, you only want to update certain ones, then you'd need filters, for example:</p>\n\n<pre><code>Update Computers\nSet Total_Disk_Space = Total_Disk_Space + 120\nWhere PurchaseDate BETWEEN '1/1/2008' AND GETDATE();\n</code></pre>\n"
},
{
"answer_id": 79329,
"author": "Matt Haley",
"author_id": 14142,
"author_profile": "https://Stackoverflow.com/users/14142",
"pm_score": 2,
"selected": false,
"text": "<p>In your example, if total_disk_space is an INT you can use:</p>\n\n<pre><code>UPDATE computers\nSET total_disk_space = total_disk_space + 120;\n</code></pre>\n\n<p>I you're storing character data, then it will be far more interesting.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14701/"
]
| Can databases (MySQL in particular, any SQL--MS, Oracle, Postgres--in general) do mass updates, and figure out on their own what the new value should be? Say for example I've got a database with information about a bunch of computers, and all of these computers have drives of various sizes--anywhere from 20 to 250 GB. Then one day we upgrade every single computer by adding a 120 GB hard drive. Is there a way to say something like
```
update computers set total_disk_space = (whatever that row's current total_disk_space is plus 120)
``` | For the entire Table then:
```
Update Computers
Set Total_Disk_Space = Total_Disk_Space + 120;
```
If, you only want to update certain ones, then you'd need filters, for example:
```
Update Computers
Set Total_Disk_Space = Total_Disk_Space + 120
Where PurchaseDate BETWEEN '1/1/2008' AND GETDATE();
``` |
79,352 | <p>I have a method that can return either a single object or a collection of objects. I want to be able to run object.collect on the result of that method whether or not it is a single object or a collection already. How can i do this?</p>
<pre><code>profiles = ProfileResource.search(params)
output = profiles.collect do | profile |
profile.to_hash
end
</code></pre>
<p>If profiles is a single object, I get a NoMethodError exception when I try to execute collect on that object.</p>
| [
{
"answer_id": 79416,
"author": "Matt Haley",
"author_id": 14142,
"author_profile": "https://Stackoverflow.com/users/14142",
"pm_score": 1,
"selected": false,
"text": "<pre><code>profiles = [ProfileResource.search(params)].flatten\noutput = profiles.collect do |profile|\n profile.to_hash\nend\n</code></pre>\n"
},
{
"answer_id": 79427,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 0,
"selected": false,
"text": "<p>In the <code>search</code> method of the <code>ProfileResource</code> class, always return a collection of objects (usually an Array), even if it contains only one object.</p>\n"
},
{
"answer_id": 79457,
"author": "Mike Tunnicliffe",
"author_id": 13956,
"author_profile": "https://Stackoverflow.com/users/13956",
"pm_score": 4,
"selected": true,
"text": "<p>Careful with the flatten approach, if search() returned nested arrays then unexpected behaviour might result.</p>\n\n<pre><code>profiles = ProfileResource.search(params)\nprofiles = [profiles] if !profiles.respond_to?(:collect)\noutput = profiles.collect do |profile|\n profile.to_hash\nend\n</code></pre>\n"
},
{
"answer_id": 79502,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a one Liner:</p>\n\n<pre><code>[*ProfileResource.search(params)].collect { |profile| profile.to_hash }\n</code></pre>\n\n<p>The trick is the splat (*) that turns both individual elements and enumerables into arguments lists (in this case to the new array operator)</p>\n"
},
{
"answer_id": 79506,
"author": "Zakaria",
"author_id": 3370,
"author_profile": "https://Stackoverflow.com/users/3370",
"pm_score": 0,
"selected": false,
"text": "<p>If the collection is an Array you could use this technique</p>\n\n<pre><code>profiles = [*ProfileResource.search(params)]\noutput = profiles.collect do | profile |\n profile.to_hash\nend\n</code></pre>\n\n<p>That would guaranteed your profiles is always an array.</p>\n"
},
{
"answer_id": 79512,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>profiles = ProfileResource.search(params)\noutput = Array(profiles).collect do |profile|\n profile.to_hash\nend\n</code></pre>\n"
},
{
"answer_id": 79581,
"author": "patrickyoung",
"author_id": 3701,
"author_profile": "https://Stackoverflow.com/users/3701",
"pm_score": 0,
"selected": false,
"text": "<p>You could first check to see if the object responds to the \"collect\" method by using \"pofiles.respond_to?\". </p>\n\n<p>From <a href=\"http://www.ruby-doc.org/docs/ProgrammingRuby/\" rel=\"nofollow noreferrer\">Programming Ruby</a></p>\n\n<blockquote>\n <p>obj.respond_to?(\n aSymbol, includePriv=false ) -> true\n or false </p>\n \n <p>Returns true if obj responds to the\n given method. Private methods are\n included in the search only if the\n optional second parameter evaluates to\n true.</p>\n</blockquote>\n"
},
{
"answer_id": 81655,
"author": "Farrel",
"author_id": 7889,
"author_profile": "https://Stackoverflow.com/users/7889",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the Kernel#Array method as well.</p>\n\n<pre><code>profiles = Array(ProfileResource.search(params))\noutput = profiles.collect do | profile |\n profile.to_hash\nend\n</code></pre>\n"
},
{
"answer_id": 103471,
"author": "fatgeekuk",
"author_id": 17518,
"author_profile": "https://Stackoverflow.com/users/17518",
"pm_score": 0,
"selected": false,
"text": "<p>Another way is to realise that Enumerable requires that you supply an each method.</p>\n\n<p>So. you COULD mix in Enumerable to your class and give it a dummy each that works....</p>\n\n<pre>\nclass YourClass\n include Enumerable\n\n ... really important and earth shattering stuff ...\n\n def each\n yield(self) if block_given?\n end\nend\n</pre>\n\n<p>This way, if you get back a single item on its own from the search, the enumerable methods will still work as expected.</p>\n\n<p>This way has the advantage that all the support for it is inside your class, not outside where it has to be duplicated many many times.</p>\n\n<p>Of course, the better way is to change the implementation of search such that it returns an array irrespective of how many items is being returned.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1486/"
]
| I have a method that can return either a single object or a collection of objects. I want to be able to run object.collect on the result of that method whether or not it is a single object or a collection already. How can i do this?
```
profiles = ProfileResource.search(params)
output = profiles.collect do | profile |
profile.to_hash
end
```
If profiles is a single object, I get a NoMethodError exception when I try to execute collect on that object. | Careful with the flatten approach, if search() returned nested arrays then unexpected behaviour might result.
```
profiles = ProfileResource.search(params)
profiles = [profiles] if !profiles.respond_to?(:collect)
output = profiles.collect do |profile|
profile.to_hash
end
``` |
79,367 | <p>I have a query:</p>
<pre><code>SELECT *
FROM Items
WHERE column LIKE '%foo%'
OR column LIKE '%bar%'
</code></pre>
<p>How do I order the results?</p>
<p>Let's say I have rows that match 'foo' and rows that match 'bar' but I also have a row with 'foobar'.</p>
<p>How do I order the returned rows so that the first results are the ones that matched more LIKEs? </p>
| [
{
"answer_id": 79375,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 0,
"selected": false,
"text": "<p>Which DBMS?</p>\n\n<p>It can be done via CTE or Union for example, but if you are using, for example, MySQL, then you can forget about it.</p>\n"
},
{
"answer_id": 79393,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>Case or the kind of conditional construct your RDBMS supports is a way to do it</p>\n\n<pre><code>select *, case when col like '%foo%' and col like '%bar%' then 2 end \nelse 1 end as ordcol \nfrom items \nwhere col like '%foo%' or col like '%bar%' order by ordcol\n</code></pre>\n"
},
{
"answer_id": 79395,
"author": "Booji Boy",
"author_id": 1433,
"author_profile": "https://Stackoverflow.com/users/1433",
"pm_score": 0,
"selected": false,
"text": "<p>Try this code:</p>\n\n<pre><code>SELECT * FROM Items WHERE column LIKE '%foo%' OR column LIKE '%bar%'\norder by (select count(*) from items i where i.column= item.column) DESC \n</code></pre>\n\n<p>You could also group by <code>column</code> and <code>count(*)</code> then <code>ORDER</code>, if you don't care about the details. </p>\n"
},
{
"answer_id": 79418,
"author": "Mike Tunnicliffe",
"author_id": 13956,
"author_profile": "https://Stackoverflow.com/users/13956",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to give this a go:</p>\n\n<pre><code>SELECT *\nFROM Items\nWHERE column LIKE '%foo%' OR column LIKE '%bar%'\nORDER BY CASE WHEN column LIKE '%foo%' AND column LIKE '%bar%' THEN 1 ELSE 0 END DESC\n</code></pre>\n\n<p>Note: this is drycoded and probably not very portable.</p>\n"
},
{
"answer_id": 79422,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": "<p>You could use a <code>UNION</code>:</p>\n\n<pre><code>SELECT * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%'\nUNION\nSELECT * FROM Items WHERE column LIKE '%foo%' AND NOT (column LIKE '%bar%')\nUNION\nSELECT * FROM Items WHERE column LIKE '%bar%' AND NOT (column LIKE '%foo%');\n</code></pre>\n\n<p>But this may be bad performance-wise. Worse, I'm guessing that you want to use this to construct a search engine that gives the most meaningful results first, and then the number of words does not remain limited to 2.</p>\n\n<p>In that case, you could create a <code>score</code> column which contains the number of matches. Something like this:</p>\n\n<pre><code>SELECT\n *,\n (IF(column LIKE '%bar%', 1, 0) + IF(column LIKE '%foo%', 1, 0)) AS score\nFROM Items\nWHERE column LIKE '%foo%' OR column LIKE '%bar%'\nORDER BY score DESC;\n</code></pre>\n\n<p>My SQL is a bit rusty, but something like this should be possible in at least MySQL 5.0. See also the manual for the <code>IF</code> function:\n<a href=\"http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html</a></p>\n"
},
{
"answer_id": 79430,
"author": "nicudotro",
"author_id": 14635,
"author_profile": "https://Stackoverflow.com/users/14635",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT * FROM Items WHERE column LIKE '%foo%' OR column LIKE '%bar%' \nORDER BY \n(IF(column LIKE '%foo%',1,0) + IF(column LIKE '%bar%',1,0)) \nDESC\n</code></pre>\n\n<p>The syntax for if is </p>\n\n<p><code>IF ( condition, true_value, false_value )</code></p>\n"
},
{
"answer_id": 79473,
"author": "Jolyon",
"author_id": 11740,
"author_profile": "https://Stackoverflow.com/users/11740",
"pm_score": 0,
"selected": false,
"text": "<p>2 Queries: </p>\n\n<pre><code>SELECT * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%';<br/>\nSELECT * FROM Items WHERE (column LIKE '%foo%' AND column NOT LIKE '%bar%') OR (column NOT LIKE '%foo%' AND LIKE '%bar%')</code></pre>\n\n<p>(No XOR in SQL)</p>\n"
},
{
"answer_id": 79497,
"author": "Mark Nold",
"author_id": 4134,
"author_profile": "https://Stackoverflow.com/users/4134",
"pm_score": 0,
"selected": false,
"text": "<p>Not all RDBMS support IF (or DECODE in Oracle) statements. If not you could use a subquery to define table \"a\" and search for all employee's named JO SMITH or a combination.</p>\n\n<pre><code>SELECT \n a.employee_id,\n a.surname,\n sum(a.counter)\nFROM\n\n (SELECT\n employee_id,\n surname,\n 1 as counter\n FROM\n MyTable\n WHERE\n surname like '%SMITH%'\n\n UNION ALL\n\n SELECT\n employee_id,\n surname,\n 1 as counter\n FROM\n MyTable\n WHERE\n surname like '%JO%'\n ) a\n\nGROUP BY \n a.employee_id,\n a.surname\nORDER BY 3,1,2\n</code></pre>\n\n<p>Make sure you use UNION ALL otherwise it will not work. Also you may way to use UPPER() to make your search non-case sensitive.</p>\n"
},
{
"answer_id": 79598,
"author": "Matt",
"author_id": 4154,
"author_profile": "https://Stackoverflow.com/users/4154",
"pm_score": 0,
"selected": false,
"text": "<p>As your query is currently written, the WHERE clause will not give you any information that can be used to sort your results. I like <a href=\"https://stackoverflow.com/questions/79367/sql-text-searching-and-ordering#79380\">Brian's idea</a>; add a constant column and UNION the queries and you could even get everything in one result set. For example:</p>\n\n<pre><code>SELECT 1 as rank, * FROM Items WHERE column LIKE '%foo%' AND column LIKE '%bar%'\nUNION\nSELECT 2 as rank, * FROM Items WHERE column LIKE '%foo%' AND column NOT LIKE '%bar%'\nUNION\nSELECT 2 as rank, * FROM Items WHERE column LIKE '%bar%' AND column NOT LIKE '%foo%'\nORDER BY rank\n</code></pre>\n\n<p>However, this would only give you something like this:</p>\n\n<ul>\n<li>The unordered set of all rows that match foo and match bar</li>\n<li>followed by (the unordered set of) all rows that match foo or bar, but not both (although you could break this up into two separate groups using a different constant in the last SELECT statement).</li>\n</ul>\n\n<p>Which might be just what you're looking for, but it wouldn't tell you which rows matched foo three times, or sort them ahead of rows that only contained one instance of foo. Also all those LIKEs can get expensive. If what you're really looking to do is sort results based on relevance (however you define that) you might be better off using a full text index. If you're using MS SQL Server, it has a built-in service that will do this, and there are also third-party products that will do the same.</p>\n\n<p>EDIT: After looking at all the other answers (there were only <em>two</em> when I started mine - I'm obviously going to have to learn to think faster ;-) ) it's obvious that there are several ways to go about this, depending on exactly what you're trying to accomplish. I would advise you to test and compare solutions based on how they perform <strong>on your system</strong>. I'm not a performance/tuning expert, but functions tend to slow things down, especially if you're sorting on the result of a function. The LIKE operator isn't necessarily spry, either. As a developer, it seems natural to use familiar constructs like \"IF\" and \"CASE\", but queries that use more of a set-based approach usually have better performance in a RDMS. Again, YMMV, so it's best to test if you're at all concerned about performance.</p>\n"
},
{
"answer_id": 81772,
"author": "Andy Irving",
"author_id": 8553,
"author_profile": "https://Stackoverflow.com/users/8553",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT * FROM Items\nWHERE col LIKE '%foo%'\n OR col LIKE '%bar%'\nORDER BY CASE WHEN col LIKE '%foo%' THEN 1\n WHEN col LIKE '%bar%' THEN 2\n END\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a query:
```
SELECT *
FROM Items
WHERE column LIKE '%foo%'
OR column LIKE '%bar%'
```
How do I order the results?
Let's say I have rows that match 'foo' and rows that match 'bar' but I also have a row with 'foobar'.
How do I order the returned rows so that the first results are the ones that matched more LIKEs? | Case or the kind of conditional construct your RDBMS supports is a way to do it
```
select *, case when col like '%foo%' and col like '%bar%' then 2 end
else 1 end as ordcol
from items
where col like '%foo%' or col like '%bar%' order by ordcol
``` |
79,445 | <p>I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute.</p>
<p>I've seen <a href="http://www.gamedev.net/page/resources/_/technical/math-and-physics/beat-detection-algorithms-r1952" rel="noreferrer">this gamedev article</a>, and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working.</p>
<p>I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself.</p>
| [
{
"answer_id": 79480,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": false,
"text": "<p>This is by no means an easy problem. I'll try to give you an overview only.</p>\n\n<p>What you could do is something like the following:</p>\n\n<ol>\n<li>Compute the average (root-mean-square) loudness of the signal over blocks of, say, 5 milliseconds. (Having never done this before, I don't know what a good block size would be.)</li>\n<li>Take the Fourier transform of the \"blocked\" signal, using the FFT algorithm.</li>\n<li>Find the component in the transformed signal that has the largest magnitude.</li>\n</ol>\n\n<p>A Fourier transform is basically a way of computing the strength of all frequencies present in the signal. If you do that over the \"blocked\" signal, the frequency of the beat will hopefully be the strongest one.</p>\n\n<p>Maybe you need to apply a filter first, to focus on specific frequencies (like the bass) that usually contain the most information about the BPM.</p>\n"
},
{
"answer_id": 79532,
"author": "Dan Harper",
"author_id": 14530,
"author_profile": "https://Stackoverflow.com/users/14530",
"pm_score": 3,
"selected": false,
"text": "<p>Not that I have a clue how to implement this, but from an audio engineering perspective you'd need to filter first. Bass drum hits would be the first to check. A low pass filter that gives you anything under about 200Hz should give you a pretty clear picture of the bass drum. A gate might also be necessary to cleanup any clutter from other instruments with harmonics that low.</p>\n\n<p>The next to check would be snare hits. You'd have to EQ this one. The \"crack\" from a snare is around 1.5kHz from memory, but you'd need to definitely gate this one.</p>\n\n<p>The next challenge would be to work out an algorithm for funky beats. How would you programatically find beat 1? I guess you'd keep track of previous beats and use a pattern matching something-or-other. So, you'd probably need a few bars to accurately find the beat. Then there's timing issues like 4/4, 3/4, 6/8, wow, I can't imagine what would be required to do this accurately! I'm sure it'd be worth some serious money to audio hardware/software companies.</p>\n"
},
{
"answer_id": 81462,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 4,
"selected": false,
"text": "<p>There's an excellent project called Dancing Monkeys, which procedurally generates DDR dance steps from music. A large part of what it does is based on (necessarily very accurate) beat analysis, and their project paper goes into much detail describing the various beat detection algorithms and their suitability to the task. They include references to the original papers for each of the algorithms. They've also published the matlab code for their solution. I'm sure that between those you can find what you need.</p>\n\n<p>It's all available here: <a href=\"http://monket.net/dancing-monkeys-v2/Main_Page\" rel=\"noreferrer\">http://monket.net/dancing-monkeys-v2/Main_Page</a></p>\n"
},
{
"answer_id": 81666,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 5,
"selected": false,
"text": "<p>Calculate a powerspectrum with a sliding window FFT:\nTake 1024 samples: </p>\n\n<pre><code>double[] signal = stream.Take(1024);\n</code></pre>\n\n<p>Feed it to an FFT algorithm: </p>\n\n<pre><code>double[] real = new double[signal.Length];\ndouble[] imag = new double[signal.Length);\nFFT(signal, out real, out imag);\n</code></pre>\n\n<p>You will get a real part and an imaginary part. Do NOT throw away the imaginary part. Do the same to the real part as the imaginary. While it is true that the imaginary part is pi / 2 out of phase with the real, it still contains 50% of the spectrum information.</p>\n\n<p>EDIT:</p>\n\n<p>Calculate the power as opposed to the amplitude so that you have a high number when it is loud and close to zero when it is quiet:</p>\n\n<pre><code>for (i=0; i < real.Length; i++) real[i] = real[i] * real[i];\n</code></pre>\n\n<p>Similarly for the imaginary part.</p>\n\n<pre><code>for (i=0; i < imag.Length; i++) imag[i] = imag[i] * imag[i];\n</code></pre>\n\n<p>Now you have a power spectrum for the last 1024 samples. Where the first part of the spectrum is the low frequencies and the last part of the spectrum is the high \nfrequencies.</p>\n\n<p>If you want to find BPM in popular music you should probably focus on the bass. You can pick up the bass intensity by summing the lower part of the power spectrum. Which numbers to use depends on the sampling frequency:</p>\n\n<pre><code>double bassIntensity = 0;\nfor (i=8; i < 96; i++) bassIntensity += real[i];\n</code></pre>\n\n<p>Now do the same again but move the window 256 samples before you calculate a new spectrum. Now you end up with calculating the bassIntensity for every 256 samples. </p>\n\n<p>This is a good input for your BPM analysis. When the bass is quiet you do not have a beat and when it is loud you have a beat. </p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 668127,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The easy way to do it is to have the user tap a button in rhythm with the beat, and count the number of taps divided by the time.</p>\n"
},
{
"answer_id": 4219423,
"author": "pete",
"author_id": 512711,
"author_profile": "https://Stackoverflow.com/users/512711",
"pm_score": 1,
"selected": false,
"text": "<p>First of all, what Hallgrim is producing is not the power spectral density function. Statistical periodicities in any signal can be brought out through an autocorrelation function. The fourier transform of the autocorrelation signal is the power spectral density. Dominant peaks in the PSD other than at 0 Hz will correspond to the effective periodicity in the signal (in Hz)... </p>\n"
},
{
"answer_id": 10342753,
"author": "eandersson",
"author_id": 408182,
"author_profile": "https://Stackoverflow.com/users/408182",
"pm_score": 3,
"selected": false,
"text": "<p>I found this library which seem to have a pretty solid implementation for detecting <strong>Beats per Minute</strong>.\n<a href=\"https://github.com/owoudenberg/soundtouch.net\" rel=\"nofollow noreferrer\">https://github.com/owoudenberg/soundtouch.net</a></p>\n<p>It's based on <a href=\"http://www.surina.net/soundtouch/index.html\" rel=\"nofollow noreferrer\">http://www.surina.net/soundtouch/index.html</a> which is used in quite a few DJ projects <a href=\"http://www.surina.net/soundtouch/applications.html\" rel=\"nofollow noreferrer\">http://www.surina.net/soundtouch/applications.html</a></p>\n"
},
{
"answer_id": 28925534,
"author": "Matt Williams",
"author_id": 3905343,
"author_profile": "https://Stackoverflow.com/users/3905343",
"pm_score": 0,
"selected": false,
"text": "<p>I'd recommend checking out the BASS audio library and the BASS.NET wrapper. It has a built in BPMCounter class. </p>\n\n<p>Details for this specific function can be found at\n<a href=\"http://bass.radio42.com/help/html/0833aa5a-3be9-037c-66f2-9adfd42a8512.htm\" rel=\"nofollow\">http://bass.radio42.com/help/html/0833aa5a-3be9-037c-66f2-9adfd42a8512.htm</a>.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14758/"
]
| I'd like to write a simple C# application to monitor the line-in audio and give me the current (well, the rolling average) beats per minute.
I've seen [this gamedev article](http://www.gamedev.net/page/resources/_/technical/math-and-physics/beat-detection-algorithms-r1952), and that was absolutely no help. I went through and tried to implement what he was doing but it just wasn't working.
I know there have to be tons of solutions for this, because lots of DJ software does it, but I'm not having any luck in finding any open-source library or instructions on doing it myself. | Calculate a powerspectrum with a sliding window FFT:
Take 1024 samples:
```
double[] signal = stream.Take(1024);
```
Feed it to an FFT algorithm:
```
double[] real = new double[signal.Length];
double[] imag = new double[signal.Length);
FFT(signal, out real, out imag);
```
You will get a real part and an imaginary part. Do NOT throw away the imaginary part. Do the same to the real part as the imaginary. While it is true that the imaginary part is pi / 2 out of phase with the real, it still contains 50% of the spectrum information.
EDIT:
Calculate the power as opposed to the amplitude so that you have a high number when it is loud and close to zero when it is quiet:
```
for (i=0; i < real.Length; i++) real[i] = real[i] * real[i];
```
Similarly for the imaginary part.
```
for (i=0; i < imag.Length; i++) imag[i] = imag[i] * imag[i];
```
Now you have a power spectrum for the last 1024 samples. Where the first part of the spectrum is the low frequencies and the last part of the spectrum is the high
frequencies.
If you want to find BPM in popular music you should probably focus on the bass. You can pick up the bass intensity by summing the lower part of the power spectrum. Which numbers to use depends on the sampling frequency:
```
double bassIntensity = 0;
for (i=8; i < 96; i++) bassIntensity += real[i];
```
Now do the same again but move the window 256 samples before you calculate a new spectrum. Now you end up with calculating the bassIntensity for every 256 samples.
This is a good input for your BPM analysis. When the bass is quiet you do not have a beat and when it is loud you have a beat.
Good luck! |
79,454 | <p>Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library).</p>
<p>I chose a mocking library called <a href="http://labix.org/mocker" rel="noreferrer">mocker</a>. I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc.</p>
<p>Anyway, I've got a lot of tests that look like this:</p>
<pre><code>def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]
</code></pre>
<p>Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested:</p>
<pre><code>def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc
</code></pre>
<p>One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.</p>
<p>I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage.</p>
<p>I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests?</p>
<p>Am I violating the core principles of TDD so much that my testing is in vain?</p>
| [
{
"answer_id": 79667,
"author": "etchasketch",
"author_id": 14640,
"author_profile": "https://Stackoverflow.com/users/14640",
"pm_score": -1,
"selected": false,
"text": "<p>Unit tests are really useful when you refactor your code (ie. completely rewrite or move a module). As long as you have unit tests before you do the big changes, you'll have confidence that you havent forgotten to move or include something when you finish.</p>\n"
},
{
"answer_id": 80028,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 3,
"selected": false,
"text": "<p><strong>If you are writing your tests after you've written your code and making them pass, you are not doing TDD</strong> (nor are you getting any benefits of Test-First or Test-Driven development.. check out SO questions for definitive books on TDD)</p>\n\n<blockquote>\n <p>One of the things I've noticed with\n using mocker is that it's easier to\n write the application code first and\n then go back and write the tests\n second, since most of the time I'm\n mocking many method calls and the\n syntax to write the mocked calls is\n much more verbose (thus harder to\n write) than the application code. It's\n easier to write the app code and then\n model the test code off of that.</p>\n</blockquote>\n\n<p>Of course, its easier because you are just testing that the sky is orange after you made it orange by painting it with a specific kind of brush. \nThis is retrofitting tests (for self-assurance). Mocks are good but you should know how and when to use them - Like the saying goes 'When you have a hammer everything looks like a nail' It's also easy to write a whole load of unreadable and not-as-helpful-as-can-be tests. The time spent understanding what the test is about is time lost that can be used to fix broken ones. </p>\n\n<p>And the point is: </p>\n\n<ul>\n<li>Read <a href=\"http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting\" rel=\"nofollow noreferrer\">Mocks aren't stubs - Martin Fowler</a> if you haven't already. Google out some documented instances of good <a href=\"http://martinfowler.com/eaaDev/ModelViewPresenter.html\" rel=\"nofollow noreferrer\">ModelViewPresenter</a> patterned GUIs (Fake/Mock out the UIs if necessary). </li>\n<li>Study your options and choose wisely. I'll play the guy with the halo on your left shoulder in white saying 'Don't do it.' Read this question as to <a href=\"https://stackoverflow.com/questions/59195/how-are-mocks-meant-to-be-used\">my reasons</a> - St. Justin is on your right shoulder. I believe he has also something to say:) </li>\n</ul>\n"
},
{
"answer_id": 82049,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": -1,
"selected": false,
"text": "<p><strong>Please remember that TDD is not a panaceum.</strong> It's hard, it's supposed to be hard, and it's especially hard to write mocking tests \"in advance\".</p>\n\n<p>So I would say - do what works for you. Even it's not \"certified TDD\". I do basically the same thing.</p>\n\n<p>You may want to provide your own API for GUI that would sit between controller code and GUI library code. That could be easier to mock, or you can even add some testing hooks to it.</p>\n\n<p>Last but not least, your code doesn't look too unreadable to me. Code using mocks is generally harder to understand. Fortunately in Python mocking is much easier and cleaner than i n other languages.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10840/"
]
| Recently I've been experimenting with TDD while developing a GUI application in Python. I find it very reassuring to have tests that verify the functionality of my code, but it's been tricky to follow some of the recommened practices of TDD. Namely, writing tests first has been hard. And I'm finding it difficult to make my tests readable (due to extensive use of a mocking library).
I chose a mocking library called [mocker](http://labix.org/mocker). I use it a lot since much of the code I'm testing makes calls to (a) other methods in my application that depend on system state or (b) ObjC/Cocoa objects that cannot exist without an event loop, etc.
Anyway, I've got a lot of tests that look like this:
```
def test_current_window_controller():
def test(config):
ac = AppController()
m = Mocker()
ac.iter_window_controllers = iwc = m.replace(ac.iter_window_controllers)
expect(iwc()).result(iter(config))
with m:
result = ac.current_window_controller()
assert result == (config[0] if config else None)
yield test, []
yield test, [0]
yield test, [1, 0]
```
Notice that this is actually three tests; all use the same parameterized test function. Here's the code that is being tested:
```
def current_window_controller(self):
try:
# iter_window_controllers() iterates in z-order starting
# with the controller of the top-most window
# assumption: the top-most window is the "current" one
wc = self.iter_window_controllers().next()
except StopIteration:
return None
return wc
```
One of the things I've noticed with using mocker is that it's easier to write the application code first and then go back and write the tests second, since most of the time I'm mocking many method calls and the syntax to write the mocked calls is much more verbose (thus harder to write) than the application code. It's easier to write the app code and then model the test code off of that.
I find that with this testing method (and a bit of discipline) I can easily write code with 100% test coverage.
I'm wondering if these tests are good tests? Will I regret doing it this way down the road when I finally discover the secret to writing good tests?
Am I violating the core principles of TDD so much that my testing is in vain? | **If you are writing your tests after you've written your code and making them pass, you are not doing TDD** (nor are you getting any benefits of Test-First or Test-Driven development.. check out SO questions for definitive books on TDD)
>
> One of the things I've noticed with
> using mocker is that it's easier to
> write the application code first and
> then go back and write the tests
> second, since most of the time I'm
> mocking many method calls and the
> syntax to write the mocked calls is
> much more verbose (thus harder to
> write) than the application code. It's
> easier to write the app code and then
> model the test code off of that.
>
>
>
Of course, its easier because you are just testing that the sky is orange after you made it orange by painting it with a specific kind of brush.
This is retrofitting tests (for self-assurance). Mocks are good but you should know how and when to use them - Like the saying goes 'When you have a hammer everything looks like a nail' It's also easy to write a whole load of unreadable and not-as-helpful-as-can-be tests. The time spent understanding what the test is about is time lost that can be used to fix broken ones.
And the point is:
* Read [Mocks aren't stubs - Martin Fowler](http://martinfowler.com/articles/mocksArentStubs.html#ClassicalAndMockistTesting) if you haven't already. Google out some documented instances of good [ModelViewPresenter](http://martinfowler.com/eaaDev/ModelViewPresenter.html) patterned GUIs (Fake/Mock out the UIs if necessary).
* Study your options and choose wisely. I'll play the guy with the halo on your left shoulder in white saying 'Don't do it.' Read this question as to [my reasons](https://stackoverflow.com/questions/59195/how-are-mocks-meant-to-be-used) - St. Justin is on your right shoulder. I believe he has also something to say:) |
79,455 | <p>Given this example:</p>
<pre><code><img class="a" />
<img />
<img class="a" />
<img class="a" id="active" />
<img class="a" />
<img class="a" />
<img />
<img class="a" />
</code></pre>
<p><em>(I've just used img tags as an example, that's not what it is in my code)</em></p>
<p>Using jQuery, how would you select the img tags with class "a" that are adjacent to #active (the middle four, in this example)?</p>
<p>You could do it fairly easily by looping over all the following and preceding elements, stopping when the filter condition fails, but I was wondering if jQuery could it natively?</p>
| [
{
"answer_id": 79471,
"author": "Xenph Yan",
"author_id": 264,
"author_profile": "https://Stackoverflow.com/users/264",
"pm_score": 2,
"selected": false,
"text": "<p>I believe looping is your best bet. But you could try, each active, and then move before and after until the condition breaks, which if the set is large enough would be faster.</p>\n"
},
{
"answer_id": 79767,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 0,
"selected": false,
"text": "<p>The tilde (~) is the <a href=\"http://docs.jquery.com/Selectors/siblings#prevsiblings\" rel=\"nofollow noreferrer\">siblings selector</a>:</p>\n\n<pre><code>$('#active ~ img.a').hide();\n</code></pre>\n"
},
{
"answer_id": 79861,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<p>@Prestaul</p>\n\n<pre><code>$('#active ~ img.a')\n</code></pre>\n\n<p>would only select the <em>following</em> siblings, and would include the non-consecutive siblings too. Docs: <a href=\"http://docs.jquery.com/Selectors/siblings#prevsiblings\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Selectors/siblings#prevsiblings</a></p>\n"
},
{
"answer_id": 79978,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 0,
"selected": false,
"text": "<p>This is another way to do it, though the sibling selector answer is pretty cool:</p>\n\n<pre><code>var next = $('#active').next('.a');\nvar prev = $('#active').prev('.a');\n</code></pre>\n\n<p><strong>Edit:</strong> I re-read your requirements and this isn't quite what you want. You could use nextAll and prevAll, but those, too, would not stop at the IMGs without the class name.</p>\n"
},
{
"answer_id": 80302,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<p>Here's what I came up with in the end.</p>\n\n<pre><code>// here's our active element.\nvar $active = $('#active');\n\n// here is the filter we'll be testing against.\nvar filter = \"img.a\";\n\n// $all will be the final jQuery object with all the consecutively matched elements.\n// start it out by populating it with the current object.\nvar $all = $active;\n\nfor ($curr = $active.prev(filter); $curr.length > 0; $curr = $curr.prev(filter)) {\n $all = $all.add($curr);\n}\nfor ($curr = $td.next(filter); $curr.length > 0; $curr = $curr.next(filter)) {\n $all = $all.add($curr);\n}\n</code></pre>\n\n<p>For a follow up question, I could see how this could easily be generalised by making it into a function which takes two arguments: an initial element, and a filter string - can anyone point me in the right direction to find out how to extend the jQuery object to add such a function?</p>\n\n<hr>\n\n<p><strong>Edit</strong>: I've since found that the each() function would do this rather well for some purposes. In my own case it doesn't work as cleanly, since I want a single jQuery object for all those elements, but here's how you could use each for a different purpose (hiding consecutive \".a\" elements, in this example:)</p>\n\n<pre><code>$('#active')\n .nextAll()\n .each(hideConsecutive)\n .end()\n .prevAll()\n .each(hideConsecutive)\n;\nfunction hideConsecutive(index, element) {\n var $e = $(element);\n if (!$e.is(\".a\")) {\n return false; // this stops the each function.\n } else {\n $e.hide('slow');\n }\n}\n</code></pre>\n\n<p>--</p>\n\n<p>Edit: I've put this together into a plugin now. Take a look at <a href=\"http://plugins.jquery.com/project/Adjacent\" rel=\"nofollow noreferrer\">http://plugins.jquery.com/project/Adjacent</a> if you're interested.</p>\n"
},
{
"answer_id": 763488,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The below code will add two new functions, nextConsecutive() and prevConsecutive(). They should do what you want.</p>\n\n<p>$.each( ['prev', 'next'], function(unusedIndex, name) {\n $.fn[ name + 'Consecutive' ] = function(matchExpr) {</p>\n\n<pre><code> var $all = \n (name == 'prev')\n ? $(this).prevAll()\n : $(this).nextAll();\n if (!matchExpr)\n return $all;\n\n var $notMatch = $($all).not(matchExpr).filter(':first');\n if ($all.index($notMatch) != -1)\n return $allConsecutive = $all.slice(0, $all.index($notMatch));\n\n return $all;\n};\n</code></pre>\n\n<p>});</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
| Given this example:
```
<img class="a" />
<img />
<img class="a" />
<img class="a" id="active" />
<img class="a" />
<img class="a" />
<img />
<img class="a" />
```
*(I've just used img tags as an example, that's not what it is in my code)*
Using jQuery, how would you select the img tags with class "a" that are adjacent to #active (the middle four, in this example)?
You could do it fairly easily by looping over all the following and preceding elements, stopping when the filter condition fails, but I was wondering if jQuery could it natively? | Here's what I came up with in the end.
```
// here's our active element.
var $active = $('#active');
// here is the filter we'll be testing against.
var filter = "img.a";
// $all will be the final jQuery object with all the consecutively matched elements.
// start it out by populating it with the current object.
var $all = $active;
for ($curr = $active.prev(filter); $curr.length > 0; $curr = $curr.prev(filter)) {
$all = $all.add($curr);
}
for ($curr = $td.next(filter); $curr.length > 0; $curr = $curr.next(filter)) {
$all = $all.add($curr);
}
```
For a follow up question, I could see how this could easily be generalised by making it into a function which takes two arguments: an initial element, and a filter string - can anyone point me in the right direction to find out how to extend the jQuery object to add such a function?
---
**Edit**: I've since found that the each() function would do this rather well for some purposes. In my own case it doesn't work as cleanly, since I want a single jQuery object for all those elements, but here's how you could use each for a different purpose (hiding consecutive ".a" elements, in this example:)
```
$('#active')
.nextAll()
.each(hideConsecutive)
.end()
.prevAll()
.each(hideConsecutive)
;
function hideConsecutive(index, element) {
var $e = $(element);
if (!$e.is(".a")) {
return false; // this stops the each function.
} else {
$e.hide('slow');
}
}
```
--
Edit: I've put this together into a plugin now. Take a look at <http://plugins.jquery.com/project/Adjacent> if you're interested. |
79,461 | <p>I have a <code>div</code> with two images and an <code>h1</code>. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be <code>absolute</code> positioned within the <code>div</code>.</p>
<p>What is the CSS needed for this to work on all common browsers?</p>
<pre class="lang-html prettyprint-override"><code><div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
</code></pre>
| [
{
"answer_id": 79513,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": -1,
"selected": false,
"text": "<pre><code><div id=\"header\" style=\"display: table-cell; vertical-align:middle;\">\n</code></pre>\n\n<p>...</p>\n\n<p>or CSS</p>\n\n<pre><code>.someClass\n{\n display: table-cell;\n vertical-align:middle;\n}\n</code></pre>\n\n<p><a href=\"http://caniuse.com/#search=table-cell\" rel=\"noreferrer\"><strong>Browser Coverage</strong></a></p>\n"
},
{
"answer_id": 79550,
"author": "Mike Tunnicliffe",
"author_id": 13956,
"author_profile": "https://Stackoverflow.com/users/13956",
"pm_score": 2,
"selected": false,
"text": "<p>By default h1 is a block element and will render on the line after the first img, and will cause the second img to appear on the line following the block.</p>\n<p>To stop this from occurring you can set the h1 to have inline flow behaviour:</p>\n<pre><code>#header > h1 { display: inline; }\n</code></pre>\n<p>As for absolutely positioning the img <em>inside the div</em>, you need to set the containing div to have a "known size" before this will work properly. In my experience, you also need to change the position attribute away from the default - position: relative works for me:</p>\n<pre><code>#header { position: relative; width: 20em; height: 20em; }\n#img-for-abs-positioning { position: absolute; top: 0; left: 0; }\n</code></pre>\n<p>If you can get that to work, you might want to try progressively removing the height, width, position attributes from div.header to get the minimal required attributes to get the effect you want.</p>\n<p><strong>UPDATE:</strong></p>\n<p>Here is a complete example that works on Firefox 3:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n <html>\n <head>\n <title>Example of vertical positioning inside a div</title>\n <style type=\"text/css\">\n #header > h1 { display: inline; }\n #header { border: solid 1px red; \n position: relative; }\n #img-for-abs-positioning { position: absolute;\n bottom: -1em; right: 2em; }\n </style>\n </head>\n \n <body>\n <div id=\"header\">\n <img src=\"#\" alt=\"Image 1\" width=\"40\" height=\"40\" />\n <h1>Header</h1>\n <img src=\"#\" alt=\"Image 2\" width=\"40\" height=\"40\" \n id=\"img-for-abs-positioning\" />\n </div>\n </body>\n </html></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 80036,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": false,
"text": "<blockquote>\n <p>All of them need to be vertically aligned within the div</p>\n</blockquote>\n\n<p>Aligned <em>how</em>? Tops of the images aligned with the top of the text? </p>\n\n<blockquote>\n <p>One of the images needs to be absolute positioned within the div.</p>\n</blockquote>\n\n<p>Absolutely positioned relative to the DIV? Perhaps you could sketch out what you're looking for...?</p>\n\n<p><a href=\"https://stackoverflow.com/questions/79461/vertical-alignment-of-elements-in-a-div#79550\">fd has described</a> the steps for absolute positioning, as well as adjusting the display of the <code>H1</code> element such that images will appear inline with it. To that, i'll add that you can align the images by use of the <code>vertical-align</code> style:</p>\n\n<pre><code>#header h1 { display: inline; }\n#header img { vertical-align: middle; }\n</code></pre>\n\n<p>...this would put the header and images together, with top edges aligned. Other alignment options exist; <a href=\"http://www.w3.org/TR/CSS2/visudet.html#propdef-vertical-align\" rel=\"nofollow noreferrer\">see the documentation</a>. You might also find it beneficial to drop the DIV and move the images inside the <code>H1</code> element - this provides semantic value to the container, and removes the need to adjust the display of the <code>H1</code>:</p>\n\n<pre><code><h1 id=header\">\n <img src=\"..\" ></img>\n testing...\n <img src=\"...\"></img>\n</h1>\n</code></pre>\n"
},
{
"answer_id": 84616,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 11,
"selected": true,
"text": "<p>Wow, this problem is popular. It's based on a misunderstanding in the <code>vertical-align</code> property. This excellent article explains it:</p>\n<p><a href=\"http://phrogz.net/CSS/vertical-align/index.html\" rel=\"noreferrer\">Understanding <code>vertical-align</code>, or "How (Not) To Vertically Center Content"</a> by Gavin Kistner.</p>\n<p><strong><a href=\"http://howtocenterincss.com/\" rel=\"noreferrer\">“How to center in CSS”</a></strong> is a great web tool which helps to find the necessary CSS centering attributes for different situations.</p>\n<hr />\n<p>In a nutshell <sub><sup>(and to prevent link rot)</sup></sub>:</p>\n<ul>\n<li><strong>Inline elements</strong> (and <em>only</em> inline elements) can be vertically aligned in their context via <code>vertical-align: middle</code>. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. <a href=\"http://jsfiddle.net/jBthq/\" rel=\"noreferrer\">jsfiddle example</a></li>\n<li>For block elements, vertical alignment is harder and strongly depends on the specific situation:\n<ul>\n<li>If the inner element can have a <strong>fixed height</strong>, you can make its position <code>absolute</code> and specify its <code>height</code>, <code>margin-top</code> and <code>top</code> position. <a href=\"http://jsfiddle.net/YFncP/2/\" rel=\"noreferrer\">jsfiddle example</a></li>\n<li>If the centered element <strong>consists of a single line</strong> <em>and</em> <strong>its parent height is fixed</strong> you can simply set the container’s <code>line-height</code> to fill its height. This method is quite versatile in my experience. <a href=\"http://jsfiddle.net/d4zGF/\" rel=\"noreferrer\">jsfiddle example</a></li>\n<li>… there are more such special cases.</li>\n</ul>\n</li>\n</ul>\n"
},
{
"answer_id": 5962720,
"author": "Romain",
"author_id": 305288,
"author_profile": "https://Stackoverflow.com/users/305288",
"pm_score": 6,
"selected": false,
"text": "<p>It worked for me:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.vcontainer {\n min-height: 10em;\n display: table-cell;\n vertical-align: middle;\n}\n</code></pre>\n"
},
{
"answer_id": 9967286,
"author": "Anita Mandal",
"author_id": 1146211,
"author_profile": "https://Stackoverflow.com/users/1146211",
"pm_score": 4,
"selected": false,
"text": "<p>Use this formula, and it will work always without cracks:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#outer {height: 400px; overflow: hidden; position: relative;}\n#outer[id] {display: table; position: static;}\n\n#middle {position: absolute; top: 50%;} /* For explorer only*/\n#middle[id] {display: table-cell; vertical-align: middle; width: 100%;}\n\n#inner {position: relative; top: -50%} /* For explorer only */\n/* Optional: #inner[id] {position: static;} */</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"outer\">\n <div id=\"middle\">\n <div id=\"inner\">\n any text\n any height\n any content, for example generated from DB\n everything is vertically centered\n </div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 10181095,
"author": "abernier",
"author_id": 133327,
"author_profile": "https://Stackoverflow.com/users/133327",
"pm_score": 5,
"selected": false,
"text": "<p>A technique from a friend of mine:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div:before {content:\" \"; display:inline-block; height:100%; vertical-align:middle;}\ndiv p {display:inline-block;}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div style=\"height:100px; border:1px solid;\">\n <p style=\"border:1px dotted;\">I'm vertically centered.</p>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Demo <a href=\"http://dabblet.com/gist/2867324\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 16357586,
"author": "user2346571",
"author_id": 2346571,
"author_profile": "https://Stackoverflow.com/users/2346571",
"pm_score": 7,
"selected": false,
"text": "<p>I used this very simple code:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div.ext-box { display: table; width:100%;}\ndiv.int-box { display: table-cell; vertical-align: middle; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"ext-box\">\n <div class=\"int-box\">\n <h2>Some txt</h2>\n <p>bla bla bla</p>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Obviously, whether you use a <code>.class</code> or an <code>#id</code>, the result won't change.</p>\n"
},
{
"answer_id": 19131573,
"author": "Joel Moses",
"author_id": 2837597,
"author_profile": "https://Stackoverflow.com/users/2837597",
"pm_score": -1,
"selected": false,
"text": "<p>Just this:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><div>\n <table style=\"width: 100%; height: 100%\">\n <tr>\n <td style=\"width: 100%; height: 100%; vertical-align: middle;\">\n What ever you want vertically-aligned\n </td>\n </tr>\n </table>\n</div>\n</code></pre>\n\n<p>A one-cell table inside the div handles the vertical-align and is backward compatible back to the Stone Age!</p>\n"
},
{
"answer_id": 19131774,
"author": "Joel Moses",
"author_id": 2837597,
"author_profile": "https://Stackoverflow.com/users/2837597",
"pm_score": 1,
"selected": false,
"text": "<p>Just use a one-cell table inside the div! Just set the cell and table height and with to 100% and you can use the vertical-align.</p>\n\n<p>A one-cell table inside the div handles the vertical-align and is backward compatible back to the Stone Age!</p>\n"
},
{
"answer_id": 20149753,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Here is just another (responsive) approach:</p>\n\n<pre><code>html,\n body {\n height: 100%;\n }\n body {\n margin: 0;\n }\n\n .table {\n display: table;\n width: auto;\n table-layout:auto;\n height: 100%;\n }\n .table:nth-child(even) {\n background: #a9edc3;\n }\n .table:nth-child(odd) {\n background: #eda9ce;\n }\n\n .tr {\n display: table-row;\n }\n .td {\n display: table-cell;\n width: 50%;\n vertical-align: middle;\n }\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/herrfischerhamburg/JcVxz/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/herrfischerhamburg/JcVxz/</a></p>\n"
},
{
"answer_id": 20920505,
"author": "pr0gg3r",
"author_id": 1159244,
"author_profile": "https://Stackoverflow.com/users/1159244",
"pm_score": -1,
"selected": false,
"text": "<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">\n<html>\n <head>\n <style type=\"text/css\">\n #style_center { position:relative; top:50%; left:50%; }\n #style_center_absolute { position:absolute; top:50px; left:50px; }\n <!--#style_center { position:relative; top:50%; left:50%; height:50px; margin-top:-25px; }-->\n </style>\n </head>\n\n <body>\n <div style=\"height:200px; width:200px; background:#00FF00\">\n <div id=\"style_center\">+</div>\n </div>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 21202703,
"author": "Shadoweb",
"author_id": 1063653,
"author_profile": "https://Stackoverflow.com/users/1063653",
"pm_score": 4,
"selected": false,
"text": "<p>Almost all methods needs to specify the height, but often we don't have any heights.</p>\n<p>So here is a CSS 3 three-line trick that doesn't require to know the height.</p>\n<pre><code>.element {\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n}\n</code></pre>\n<p>It's supported even in IE9.</p>\n<p>with its vendor prefixes:</p>\n<pre><code>.element {\n position: relative;\n top: 50%;\n -webkit-transform: translateY(-50%);\n -ms-transform: translateY(-50%);\n transform: translateY(-50%);\n}\n</code></pre>\n<p>Source: <em><a href=\"http://zerosixthree.se/vertical-align-anything-with-just-3-lines-of-css/\" rel=\"nofollow noreferrer\">Vertical align anything with just 3 lines of CSS</a></em></p>\n"
},
{
"answer_id": 24985086,
"author": "Arsh",
"author_id": 3882353,
"author_profile": "https://Stackoverflow.com/users/3882353",
"pm_score": 0,
"selected": false,
"text": "<p><strong>I have been using the following solution (with no positioning and no line height) since over a year, it works with <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_7\" rel=\"nofollow noreferrer\">Internet Explorer 7</a> and <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_8\" rel=\"nofollow noreferrer\">Internet Explorer 8</a> as well.</strong></p>\n<pre><code><style>\n.outer {\n font-size: 0;\n width: 400px;\n height: 400px;\n background: orange;\n text-align: center;\n display: inline-block;\n}\n\n.outer .emptyDiv {\n height: 100%;\n background: orange;\n visibility: collapse;\n}\n\n.outer .inner {\n padding: 10px;\n background: red;\n font: bold 12px Arial;\n}\n\n.verticalCenter {\n display: inline-block;\n *display: inline;\n zoom: 1;\n vertical-align: middle;\n}\n</style>\n\n<div class="outer">\n <div class="emptyDiv verticalCenter"></div>\n <div class="inner verticalCenter">\n <p>Line 1</p>\n <p>Line 2</p>\n </div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 25867805,
"author": "danigonlinea",
"author_id": 1196978,
"author_profile": "https://Stackoverflow.com/users/1196978",
"pm_score": 0,
"selected": false,
"text": "<p>This is my personal solution for an <code>i</code> element inside a <code>div</code>.</p>\n<p><a href=\"http://jsfiddle.net/3FvxA/683/\" rel=\"nofollow noreferrer\">JSFiddle Example</a></p>\n<h2>HTML</h2>\n<pre><code><div class="circle">\n <i class="fa fa-plus icon">\n</i></div>\n</code></pre>\n<h2>CSS</h2>\n<pre><code>.circle {\n border-radius: 50%;\n color: blue;\n background-color: red;\n height:100px;\n width:100px;\n text-align: center;\n line-height: 100px;\n}\n\n.icon {\n font-size: 50px;\n vertical-align: middle;\n}\n</code></pre>\n"
},
{
"answer_id": 26356771,
"author": "VuesomeDev",
"author_id": 1725325,
"author_profile": "https://Stackoverflow.com/users/1725325",
"pm_score": 5,
"selected": false,
"text": "<p>To position block elements to the center (works in <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_9\" rel=\"nofollow noreferrer\">Internet Explorer 9</a> and above), it needs a wrapper <code>div</code>:</p>\n<pre><code>.vcontainer {\n position: relative;\n top: 50%;\n transform: translateY(-50%);\n -webkit-transform: translateY(-50%);\n}\n</code></pre>\n"
},
{
"answer_id": 26364552,
"author": "joan16v",
"author_id": 1398876,
"author_profile": "https://Stackoverflow.com/users/1398876",
"pm_score": 4,
"selected": false,
"text": "<p>My trick is to put a table inside the div with one row and one column, set 100% of width and height, and the property <em>vertical-align:middle</em>:</p>\n<pre><code><div>\n\n <table style="width:100%; height:100%;">\n <tr>\n <td style="vertical-align:middle;">\n BUTTON TEXT\n </td>\n </tr>\n </table>\n\n</div>\n</code></pre>\n<p>Fiddle:\n<a href=\"http://jsfiddle.net/joan16v/sbqjnn9q/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/joan16v/sbqjnn9q/</a></p>\n"
},
{
"answer_id": 31078418,
"author": "E. Serrano",
"author_id": 1572964,
"author_profile": "https://Stackoverflow.com/users/1572964",
"pm_score": 8,
"selected": false,
"text": "<p>Now that Flexbox support is increasing, this CSS applied to the containing element would vertically center all contained items (except for those items that specify the alignment themselves, e.g. <a href=\"https://developer.mozilla.org/docs/Web/CSS/align-self\" rel=\"noreferrer\"><code>align-self:start</code></a>)</p>\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n display: flex;\n align-items: center;\n}\n</code></pre>\n<p>Use the prefixed version if you also need to target <a href=\"https://en.wikipedia.org/wiki/Internet_Explorer_11#Internet_Explorer_10\" rel=\"noreferrer\">Internet Explorer 10</a>, and older (< <a href=\"https://en.wikipedia.org/wiki/Android_version_history#Android_4.4_KitKat_.28API_level_19.29\" rel=\"noreferrer\">4.4</a> (KitKat)) Android browsers:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n display: -ms-flexbox;\n display: -webkit-flex;\n display: flex;\n\n -ms-flex-align: center;\n -webkit-align-items: center;\n -webkit-box-align: center;\n align-items: center;\n}\n</code></pre>\n"
},
{
"answer_id": 31279382,
"author": "BernieSF",
"author_id": 1689852,
"author_profile": "https://Stackoverflow.com/users/1689852",
"pm_score": 0,
"selected": false,
"text": "<p>For me, it worked this way:</p>\n\n<pre><code><div style=\"width:70px; height:68px; float:right; display: table-cell; line-height: 68px\">\n <a href=\"javascript:void(0)\" style=\"margin-left: 4px; line-height: 2\" class=\"btn btn-primary\">Login</a>\n</div>\n</code></pre>\n\n<p>The \"a\" element converted to a button, using Bootstrap classes, and it is now vertically centered inside an outer \"div\".</p>\n"
},
{
"answer_id": 34320593,
"author": "Henk-Martijn",
"author_id": 4069967,
"author_profile": "https://Stackoverflow.com/users/4069967",
"pm_score": 3,
"selected": false,
"text": "<p>Using CSS to vertical center, you can let the outer containers act like a table, and the content as a table cell. In this format your objects will stay centered. :)</p>\n<p>I nested multiple objects in JSFiddle for an example, but the core idea is like this:</p>\n<p><strong>HTML</strong></p>\n<pre><code><div class="circle">\n <div class="content">\n Some text\n </div>\n</div>\n</code></pre>\n<p><strong>CSS</strong></p>\n<pre class=\"lang-css prettyprint-override\"><code>.circle {\n /* Act as a table so we can center vertically its child */\n display: table;\n /* Set dimensions */\n height: 200px;\n width: 200px;\n /* Horizontal center text */\n text-align: center;\n /* Create a red circle */\n border-radius: 100%;\n background: red;\n}\n\n.content {\n /* Act as a table cell */\n display: table-cell;\n /* And now we can vertically center! */\n vertical-align: middle;\n /* Some basic markup */\n font-size: 30px;\n font-weight: bold;\n color: white;\n}\n</code></pre>\n<p>The multiple objects example:</p>\n<p><strong>HTML</strong></p>\n<pre><code><div class="container">\n <div class="content">\n\n <div class="centerhoriz">\n\n <div class="circle">\n <div class="content">\n Some text\n </div><!-- content -->\n </div><!-- circle -->\n\n <div class="square">\n <div class="content">\n <div id="smallcircle"></div>\n </div><!-- content -->\n </div><!-- square -->\n\n </div><!-- center-horiz -->\n\n </div><!-- content -->\n</div><!-- container -->\n</code></pre>\n<p><strong>CSS</strong></p>\n<pre class=\"lang-css prettyprint-override\"><code>.container {\n display: table;\n height: 500px;\n width: 300px;\n text-align: center;\n background: lightblue;\n}\n\n.centerhoriz {\n display: inline-block;\n}\n\n.circle {\n display: table;\n height: 200px;\n width: 200px;\n text-align: center;\n background: red;\n border-radius: 100%;\n margin: 10px;\n}\n\n.square {\n display: table;\n height: 200px;\n width: 200px;\n text-align: center;\n background: blue;\n margin: 10px;\n}\n\n.content {\n display: table-cell;\n vertical-align: middle;\n font-size: 30px;\n font-weight: bold;\n color: white;\n}\n\n#smallcircle {\n display: inline-block;\n height: 50px;\n width: 50px;\n background: green;\n border-radius: 100%;\n}\n</code></pre>\n<p><strong>Result</strong></p>\n<p><a href=\"https://i.stack.imgur.com/p1Cyh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/p1Cyh.png\" alt=\"Result\" /></a></p>\n<p><a href=\"https://jsfiddle.net/martjemeyer/ybs032uc/1/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/martjemeyer/ybs032uc/1/</a></p>\n"
},
{
"answer_id": 39904652,
"author": "Dashrath",
"author_id": 1510544,
"author_profile": "https://Stackoverflow.com/users/1510544",
"pm_score": 2,
"selected": false,
"text": "<p>We may use a CSS function calculation to calculate the size of the element and then position the child element accordingly.</p>\n<p>Example HTML:</p>\n<pre><code><div class="box">\n <span><a href="#">Some Text</a></span>\n</div>\n</code></pre>\n<p>And CSS:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.box {\n display: block;\n background: #60D3E8;\n position: relative;\n width: 300px;\n height: 200px;\n text-align: center;\n}\n\n.box span {\n font: bold 20px/20px 'source code pro', sans-serif;\n position: absolute;\n left: 0;\n right: 0;\n top: calc(50% - 10px);\n}\n\na {\n color: white;\n text-decoration: none;\n}\n</code></pre>\n<p>Demo created here: <a href=\"https://jsfiddle.net/xnjq1t22/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/xnjq1t22/</a></p>\n<p>This solution works well with responsive <code>div</code> <code>height</code> and <code>width</code> as well.</p>\n<p>Note: The <em>calc</em> function is not tested for compatiblity with old browsers.</p>\n"
},
{
"answer_id": 45458436,
"author": "Shivam",
"author_id": 1592107,
"author_profile": "https://Stackoverflow.com/users/1592107",
"pm_score": 2,
"selected": false,
"text": "<p>I have found a new workaround to vertically align multiple text-lines in a div using CSS 3 (and I am also using bootstrap v3 grid system to beautify the UI), which is as below:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.immediate-parent-of-text-containing-div {\n height: 50px; /* Or any fixed height that suits you. */\n}\n\n.text-containing-div {\n display: inline-grid;\n align-items: center;\n text-align: center;\n height: 100%;\n}\n</code></pre>\n<p>As per my understanding, the immediate parent of text containing element must have some height.</p>\n"
},
{
"answer_id": 48523051,
"author": "WasiF",
"author_id": 4574281,
"author_profile": "https://Stackoverflow.com/users/4574281",
"pm_score": 5,
"selected": false,
"text": "<h2>Vertically and horizontally align element</h2>\n<p>Use either of these. The result would be the same:</p>\n<ol>\n<li>Bootstrap 4</li>\n<li>CSS3</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/MqvVH.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/MqvVH.png\" alt=\"Enter image description here\" /></a></p>\n<h3>1. Bootstrap 4.3+</h3>\n<p>For vertical alignment: <code>d-flex align-items-center</code></p>\n<p>For horizontal alignment: <code>d-flex justify-content-center</code></p>\n<p>For vertical and horizontal alignment: <code>d-flex align-items-center justify-content-center</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.container {\n height: 180px;\n width:100%;\n background-color: blueviolet;\n}\n\n.container > div {\n background-color: white;\n padding: 1rem;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><link href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"\nrel=\"stylesheet\"/>\n\n<div class=\"d-flex align-items-center justify-content-center container\">\n <div>I am in Center</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h3>2. CSS 3</h3>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.container {\n height: 180px;\n width:100%;\n background-color: blueviolet;\n}\n\n.container > div {\n background-color: white;\n padding: 1rem;\n}\n\n.center {\n display: flex;\n align-items: center;\n justify-content: center;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"container center\">\n <div>I am in Center</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 51626821,
"author": "Sameera Prasad Jayasinghe",
"author_id": 5901608,
"author_profile": "https://Stackoverflow.com/users/5901608",
"pm_score": 7,
"selected": false,
"text": "<pre class=\"lang-css prettyprint-override\"><code> .outer {\n display: flex;\n align-items: center; \n justify-content: center;\n }\n</code></pre>\n"
},
{
"answer_id": 55066555,
"author": "Dennis Don",
"author_id": 1367794,
"author_profile": "https://Stackoverflow.com/users/1367794",
"pm_score": 3,
"selected": false,
"text": "<p>Using display flex, first you need to wrap the container of the item that you want to align:</p>\n<pre><code><div class="outdiv">\n <div class="indiv">\n <span>test1</span>\n <span>test2</span>\n </div>\n</div>\n</code></pre>\n<p>Then apply the following CSS content to wrap <em>div</em> or <em>outdiv</em> in my example:</p>\n<pre class=\"lang-css prettyprint-override\"><code>.outdiv {\n display: flex;\n justify-content: center;\n align-items: center;\n}\n</code></pre>\n"
},
{
"answer_id": 57117215,
"author": "Stephen",
"author_id": 558721,
"author_profile": "https://Stackoverflow.com/users/558721",
"pm_score": 2,
"selected": false,
"text": "<p>My new favorite way to do it is with a CSS grid:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/* technique */\r\n\r\n.wrapper {\r\n display: inline-grid;\r\n grid-auto-flow: column;\r\n align-items: center;\r\n justify-content: center;\r\n}\r\n\r\n/* visual emphasis */\r\n\r\n.wrapper {\r\n border: 1px solid red;\r\n height: 180px;\r\n width: 400px;\r\n}\r\n\r\nimg {\r\n width: 100px;\r\n height: 80px;\r\n background: #fafafa;\r\n}\r\n\r\nimg:nth-child(2) {\r\n height: 120px;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"wrapper\">\r\n <img src=\"https://source.unsplash.com/random/100x80/?bear\">\r\n <img src=\"https://source.unsplash.com/random/100x120/?lion\">\r\n <img src=\"https://source.unsplash.com/random/100x80/?tiger\">\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 57247568,
"author": "akhtarvahid",
"author_id": 6544460,
"author_profile": "https://Stackoverflow.com/users/6544460",
"pm_score": 4,
"selected": false,
"text": "<h3>Three ways to make a center child div in a parent div</h3>\n<ul>\n<li>Absolute positioning method</li>\n<li>Flexbox method</li>\n<li>Transform/translate method</li>\n</ul>\n<p><a href=\"https://i.stack.imgur.com/IJ41P.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IJ41P.png\" alt=\"Enter image description here\" /></a></p>\n<p><a href=\"https://jsfiddle.net/vahid_634/Lsvcrf1g/4/\" rel=\"nofollow noreferrer\">Demo</a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>/* Absolute Positioning Method */\n.parent1 {\n background: darkcyan;\n width: 200px;\n height: 200px;\n position: relative;\n}\n.child1 {\n background: white;\n height: 30px;\n width: 30px;\n position: absolute;\n top: 50%;\n left: 50%;\n margin: -15px;\n}\n\n/* Flexbox Method */\n.parent2 {\n display: flex;\n justify-content: center;\n align-items: center;\n background: darkcyan;\n height: 200px;\n width: 200px;\n}\n.child2 {\n background: white;\n height: 30px;\n width: 30px;\n}\n\n/* Transform/Translate Method */\n.parent3 {\n position: relative;\n height: 200px;\n width: 200px;\n background: darkcyan;\n}\n.child3 {\n background: white;\n height: 30px;\n width: 30px;\n position: absolute;\n top: 50%;\n left: 50%;\n transform: translate(-50%, -50%);\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"parent1\">\n <div class=\"child1\"></div>\n</div>\n<hr />\n\n<div class=\"parent2\">\n <div class=\"child2\"></div>\n</div>\n<hr />\n\n<div class=\"parent3\">\n <div class=\"child3\"></div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64780990,
"author": "HASSAN MD TAREQ",
"author_id": 4802664,
"author_profile": "https://Stackoverflow.com/users/4802664",
"pm_score": 2,
"selected": false,
"text": "<p>Using only a Bootstrap class:</p>\n<ul>\n<li>div: <code>class="container d-flex"</code></li>\n<li>element inside div: <code>class="m-auto"</code></li>\n</ul>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css\" crossorigin=\"anonymous\">\n\n<div class=\"container d-flex mt-5\" style=\"height:110px; background-color: #333;\">\n <h2 class=\"m-auto\"><a href=\"https://hovermind.com/\">H➲VER➾M⇡ND</a></h2>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5232/"
]
| I have a `div` with two images and an `h1`. All of them need to be vertically aligned within the div, next to each other. One of the images needs to be `absolute` positioned within the `div`.
What is the CSS needed for this to work on all common browsers?
```html
<div id="header">
<img src=".." ></img>
<h1>testing...</h1>
<img src="..."></img>
</div>
``` | Wow, this problem is popular. It's based on a misunderstanding in the `vertical-align` property. This excellent article explains it:
[Understanding `vertical-align`, or "How (Not) To Vertically Center Content"](http://phrogz.net/CSS/vertical-align/index.html) by Gavin Kistner.
**[“How to center in CSS”](http://howtocenterincss.com/)** is a great web tool which helps to find the necessary CSS centering attributes for different situations.
---
In a nutshell (and to prevent link rot):
* **Inline elements** (and *only* inline elements) can be vertically aligned in their context via `vertical-align: middle`. However, the “context” isn’t the whole parent container height, it’s the height of the text line they’re in. [jsfiddle example](http://jsfiddle.net/jBthq/)
* For block elements, vertical alignment is harder and strongly depends on the specific situation:
+ If the inner element can have a **fixed height**, you can make its position `absolute` and specify its `height`, `margin-top` and `top` position. [jsfiddle example](http://jsfiddle.net/YFncP/2/)
+ If the centered element **consists of a single line** *and* **its parent height is fixed** you can simply set the container’s `line-height` to fill its height. This method is quite versatile in my experience. [jsfiddle example](http://jsfiddle.net/d4zGF/)
+ … there are more such special cases. |
79,466 | <p>(sorry I should have been clearer with the code the first time I posted this. Hope this makes sense)</p>
<p>File "size_specification.rb"</p>
<pre><code>class SizeSpecification
def fits?
end
end
</code></pre>
<p>File "some_module.rb"</p>
<pre><code>require 'size_specification'
module SomeModule
def self.sizes
YAML.load_file(File.dirname(__FILE__) + '/size_specification_data.yml')
end
end
</code></pre>
<p>File "size_specification_data.yml</p>
<pre><code>---
- !ruby/object:SizeSpecification
height: 250
width: 300
</code></pre>
<p>Then when I call</p>
<pre><code>SomeModule.sizes.first.fits?
</code></pre>
<p>I get an exception because "sizes" are Object's not SizeSpecification's so they don't have a "fits" function.</p>
| [
{
"answer_id": 80075,
"author": "robertpostill",
"author_id": 11219,
"author_profile": "https://Stackoverflow.com/users/11219",
"pm_score": 0,
"selected": false,
"text": "<p>On second reading I'm a little confused, you seem to want to mix the class into module, which is porbably not so advisable. Also is the YAML supposed to load an array of the SizeSpecifications?</p>\n\n<p>It appears to be that you're not mixing the Module into your class. If I run the test in irb then the require throws a LoadError. So I assume you've put two files together, if not dump it.</p>\n\n<p>Normally you'd write the functionality in the module, then mix that into the class. so you may modify your code like this:</p>\n\n<pre><code>class SizeSpecification\n include SomeModule\n def fits? \n end\nend\n</code></pre>\n\n<p>Which will allow you to then say:</p>\n\n<pre><code>SizeSpecification::SomeModule.sizes\n</code></pre>\n\n<p>I think you should also be able to say:</p>\n\n<pre><code>SizeSpecification.sizes\n</code></pre>\n\n<p>However that requires you to take the self off the prefix of the sizes method definition.</p>\n\n<p>Does that help?</p>\n"
},
{
"answer_id": 94745,
"author": "anshul",
"author_id": 17674,
"author_profile": "https://Stackoverflow.com/users/17674",
"pm_score": 1,
"selected": false,
"text": "<p>Are your settings and ruby installation ok? I created those 3 files and wrote what follows in \"test.rb\"</p>\n\n<pre><code>require 'yaml'\nrequire \"some_module\"\n\nSomeModule.sizes.first.fits?\n</code></pre>\n\n<p>Then I ran it.</p>\n\n<pre><code>$ ruby --version\nruby 1.8.6 (2008-06-20 patchlevel 230) [i486-linux]\n$ ruby -w test.rb \n$\n</code></pre>\n\n<p>No errors!</p>\n"
},
{
"answer_id": 103678,
"author": "fatgeekuk",
"author_id": 17518,
"author_profile": "https://Stackoverflow.com/users/17518",
"pm_score": 0,
"selected": false,
"text": "<p>The question code got me a little confused.</p>\n\n<p>In general with Ruby, if that happens it's a good sign that I am trying to do things the wrong way.</p>\n\n<p>It might be better to ask a question related to your actual intended outcome, rather than the specifics of a particular 'attack' on your problem. They we can say 'nonono, don't do that, do THIS' or 'ahhhhh, now I understand what you wanna do'</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14796/"
]
| (sorry I should have been clearer with the code the first time I posted this. Hope this makes sense)
File "size\_specification.rb"
```
class SizeSpecification
def fits?
end
end
```
File "some\_module.rb"
```
require 'size_specification'
module SomeModule
def self.sizes
YAML.load_file(File.dirname(__FILE__) + '/size_specification_data.yml')
end
end
```
File "size\_specification\_data.yml
```
---
- !ruby/object:SizeSpecification
height: 250
width: 300
```
Then when I call
```
SomeModule.sizes.first.fits?
```
I get an exception because "sizes" are Object's not SizeSpecification's so they don't have a "fits" function. | Are your settings and ruby installation ok? I created those 3 files and wrote what follows in "test.rb"
```
require 'yaml'
require "some_module"
SomeModule.sizes.first.fits?
```
Then I ran it.
```
$ ruby --version
ruby 1.8.6 (2008-06-20 patchlevel 230) [i486-linux]
$ ruby -w test.rb
$
```
No errors! |
79,474 | <p>I've set up Passenger in development (Mac OS X) and it works flawlessly. The only problem came later: now I have a custom <code>GEM_HOME</code> path and ImageMagick binaries installed in <code>"/usr/local"</code>. I can put them in one of the shell rc files that get sourced and this solves the environment variables for processes spawned from the console; but what about Passenger? The same application cannot find my gems when run this way.</p>
| [
{
"answer_id": 79615,
"author": "Brian Phillips",
"author_id": 7230,
"author_profile": "https://Stackoverflow.com/users/7230",
"pm_score": 1,
"selected": false,
"text": "<p>I've run into this issue as well. It <a href=\"http://groups.google.com/group/phusion-passenger/browse_thread/thread/79474d37028f2a03\" rel=\"nofollow noreferrer\">appears</a> that Passenger doesn't passthrough values set using the <code>SetEnv</code> apache directive - which is unfortunate.</p>\n\n<p>Perhaps it might be possible to set environment variables in your environment.rb or boot.rb (assuming you're talking about a Rails app; I'm not familiar with Rack but presumably it has similar functionality)</p>\n"
},
{
"answer_id": 80003,
"author": "manveru",
"author_id": 8367,
"author_profile": "https://Stackoverflow.com/users/8367",
"pm_score": 2,
"selected": false,
"text": "<p>Before you do any requires (especially before requiring rubygems) you can do:</p>\n\n<pre><code>ENV['GEM_HOME'] = '/foo'\n</code></pre>\n\n<p>This will change the environment variable inside this process.</p>\n"
},
{
"answer_id": 81255,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 5,
"selected": true,
"text": "<p>I know of two solutions. The first (documented <a href=\"http://www.viget.com/extend/rubyinline-in-shared-rails-environments/\" rel=\"noreferrer\">here</a>) is essentially the same as manveru's—set the ENV variable directly in your code.</p>\n\n<p>The second is to create a wrapper around the Ruby interpreter that Passenger uses, and is documented <a href=\"http://blog.rayapps.com/2008/05/21/using-mod_rails-with-rails-applications-on-oracle/\" rel=\"noreferrer\">here</a> (look for passenger_with_ruby). The gist is that you create (and point PassengerRuby in your Apache config to) /usr/bin/ruby_with_env, an executable file consisting of:</p>\n\n<pre><code>#!/bin/bash\nexport ENV_VAR=value\n/usr/bin/ruby $*\n</code></pre>\n\n<p>Both work; the former approach is a little less hackish, I think.</p>\n"
},
{
"answer_id": 363314,
"author": "Raimonds Simanovskis",
"author_id": 16829,
"author_profile": "https://Stackoverflow.com/users/16829",
"pm_score": 2,
"selected": false,
"text": "<p>I found out that if you have root priviledges on computer then you can set necessary environment variables in \"envvars\" file and apachectl will execute this file before starting Apache.</p>\n\n<p>envvars typically is located in the same directory where apachectl is located - on Mac OS X it is located in /usr/sbin. If you cannot find it then look in the source of apachectl script.</p>\n\n<p>After changing envvars file restart Apache with \"apachectl -k restart\".</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79474",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11687/"
]
| I've set up Passenger in development (Mac OS X) and it works flawlessly. The only problem came later: now I have a custom `GEM_HOME` path and ImageMagick binaries installed in `"/usr/local"`. I can put them in one of the shell rc files that get sourced and this solves the environment variables for processes spawned from the console; but what about Passenger? The same application cannot find my gems when run this way. | I know of two solutions. The first (documented [here](http://www.viget.com/extend/rubyinline-in-shared-rails-environments/)) is essentially the same as manveru's—set the ENV variable directly in your code.
The second is to create a wrapper around the Ruby interpreter that Passenger uses, and is documented [here](http://blog.rayapps.com/2008/05/21/using-mod_rails-with-rails-applications-on-oracle/) (look for passenger\_with\_ruby). The gist is that you create (and point PassengerRuby in your Apache config to) /usr/bin/ruby\_with\_env, an executable file consisting of:
```
#!/bin/bash
export ENV_VAR=value
/usr/bin/ruby $*
```
Both work; the former approach is a little less hackish, I think. |
79,490 | <p>How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots.</p>
<p>Update:
Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info. Sounds like a script is my best bet.</p>
<p>Update:
Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application.</p>
| [
{
"answer_id": 79503,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 1,
"selected": false,
"text": "<p>i dont think this information is saved between reboots.</p>\n\n<p>if shutting down properly you could run a command on shutdown that saves the uptime, that way you could read it back after booting back up.</p>\n"
},
{
"answer_id": 79515,
"author": "roo",
"author_id": 716,
"author_profile": "https://Stackoverflow.com/users/716",
"pm_score": 5,
"selected": false,
"text": "<p>the <a href=\"http://linux.about.com/library/cmd/blcmdl1_last.htm\" rel=\"noreferrer\"><code>last</code></a> command will give you the reboot times of the system. You could take the difference between each successive reboot and that should give the uptime of the machine.</p>\n\n<p><strong>update</strong></p>\n\n<p><a href=\"https://stackoverflow.com/questions/79490/linux-uptime-history#79553\">1800 INFORMATION</a> answer is a better solution.</p>\n"
},
{
"answer_id": 79530,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<p>This information is not normally saved. However, you can sign up for an online service that will do this for you. You just install a client that will send your uptime to the server every 5 minutes and the site will present you with a graph of your uptimes:</p>\n\n<p><a href=\"http://uptimes-project.org/\" rel=\"nofollow noreferrer\">http://uptimes-project.org/</a></p>\n"
},
{
"answer_id": 79535,
"author": "Shermozle",
"author_id": 10788,
"author_profile": "https://Stackoverflow.com/users/10788",
"pm_score": 2,
"selected": false,
"text": "<p>This isn't stored between boots, but <a href=\"http://www.uptimes-project.org\" rel=\"nofollow noreferrer\">The Uptimes Project</a> is a third-party option to track it, with software for a range of platforms.</p>\n\n<p>Another tool available on Debian is <a href=\"http://podgorny.cz/moin/Uptimed\" rel=\"nofollow noreferrer\">uptimed</a> which tracks uptimes between boots.</p>\n"
},
{
"answer_id": 79540,
"author": "etchasketch",
"author_id": 14640,
"author_profile": "https://Stackoverflow.com/users/14640",
"pm_score": 6,
"selected": true,
"text": "<p>You could create a simple script which runs uptime and dumps it to a file.</p>\n\n<pre><code>uptime >> uptime.log\n</code></pre>\n\n<p>Then set up a cron job for it.</p>\n"
},
{
"answer_id": 79553,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 6,
"selected": false,
"text": "<p>Install <a href=\"https://github.com/rpodgorny/uptimed\" rel=\"nofollow noreferrer\">uptimed</a>. It does exactly what you want.</p>\n\n<p>Edit:</p>\n\n<p>You can apparantly include it in a PHP page as easily as this:</p>\n\n<pre><code><? system(\"/usr/local/bin/uprecords -a -B\"); ?>\n</code></pre>\n\n<p><a href=\"https://web.archive.org/web/20090228064718/http://www.robertjohnkaper.com/software/uptimed/example.html\" rel=\"nofollow noreferrer\">Examples</a></p>\n"
},
{
"answer_id": 79699,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>I would create a cron job to run at the required resolution (say 10 minutes) by entering the following [on <em>one</em> single line - I've just separated it for formatting purposes] in your crontab (cron -l to list, cron -e to edit).</p>\n\n<pre><code>0,10,20,30,40,50 * * * *\n /bin/echo $(/bin/date +\\%Y-\\%m-\\%d) $(/usr/bin/uptime)\n >>/tmp/uptime.hist 2>&1\n</code></pre>\n\n<p>This appends the date, time and uptime to the uptime.hist file every ten minutes while the machine is running. You can then examine this file manually to figure out the information or write a script to process it as you see fit.</p>\n\n<p>Whenever the uptime reduces, there's been a reboot since the previous record. When there are large gaps between lines (i.e., more than the expected ten minutes), the machine's been down during that time.</p>\n"
},
{
"answer_id": 80135,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Try this out: </p>\n\n<pre><code>last | grep reboot \n</code></pre>\n"
},
{
"answer_id": 6330117,
"author": "Slet",
"author_id": 792504,
"author_profile": "https://Stackoverflow.com/users/792504",
"pm_score": 1,
"selected": false,
"text": "<p>Or you can use tuptime <a href=\"https://sourceforge.net/projects/tuptime/\" rel=\"nofollow\">https://sourceforge.net/projects/tuptime/</a> for a total uptime time.</p>\n"
},
{
"answer_id": 18943901,
"author": "sepehr",
"author_id": 184176,
"author_profile": "https://Stackoverflow.com/users/184176",
"pm_score": 4,
"selected": false,
"text": "<p>according to <code>last</code> manual page:</p>\n\n<blockquote>\n <p>The pseudo user reboot logs in each time the system is rebooted.\n Thus last reboot will show a log of all reboots since the log file\n was created.</p>\n</blockquote>\n\n<p>so last column of <code>#last reboot</code> command gives you uptime history:</p>\n\n<pre><code>#last reboot\nreboot system boot **************** Sat Sep 21 03:31 - 08:27 (1+04:56) \nreboot system boot **************** Wed Aug 7 07:08 - 08:27 (46+01:19)\n</code></pre>\n"
},
{
"answer_id": 20195042,
"author": "peterh",
"author_id": 1783163,
"author_profile": "https://Stackoverflow.com/users/1783163",
"pm_score": 0,
"selected": false,
"text": "<p>Nagios can make even very beautiful diagrams about this.</p>\n"
},
{
"answer_id": 23121600,
"author": "rfmoz",
"author_id": 793908,
"author_profile": "https://Stackoverflow.com/users/793908",
"pm_score": 1,
"selected": false,
"text": "<p>You can use tuptime, a simple command for report the total uptime in linux keeping it betwwen reboots.</p>\n\n<p><a href=\"http://sourceforge.net/projects/tuptime/\" rel=\"nofollow\">http://sourceforge.net/projects/tuptime/</a></p>\n"
},
{
"answer_id": 55663620,
"author": "Jan Schermer",
"author_id": 11355087,
"author_profile": "https://Stackoverflow.com/users/11355087",
"pm_score": 1,
"selected": false,
"text": "<p>Since I haven't found an answer here that would help retroactively, maybe this will help someone.</p>\n\n<p>kern.log (depending on your distribution) should log a timestamp.\nIt will be something like:\n2019-01-28T06:25:25.459477+00:00 someserver kernel: [44114473.614361] somemessage</p>\n\n<p>\"44114473.614361\" represents seconds since last boot, from that you can calculate the uptime without having to install anything.</p>\n"
},
{
"answer_id": 62146140,
"author": "sebisnow",
"author_id": 6207983,
"author_profile": "https://Stackoverflow.com/users/6207983",
"pm_score": 0,
"selected": false,
"text": "<h1>Use Syslog</h1>\n\n<p>For anyone coming here searching for their past uptime.\nThe solution of @1800_Information is a good advise for the future, but I needed to find information for my past uptimes on a specific date.</p>\n\n<p>Therefore I used syslog to determine when that day the system was started (first log entry of that day) and when the system was shutdown again.</p>\n\n<h2>Boot time</h2>\n\n<p>To get the system start time grep for the month and day and show only the first lines:</p>\n\n<pre><code>sudo grep \"May 28\" /var/log/syslog* | head\n</code></pre>\n\n<h2>Shutdown time</h2>\n\n<p>To get the system shutdown time grep for the month and day and show only the last few lines:</p>\n\n<pre><code>sudo grep \"May 28\" /var/log/syslog* | tail\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/777/"
]
| How can I get a history of uptimes for my debian box? After a reboot, I dont see an option for the uptime command to print a history of uptimes. If it matters, I would like to use these uptimes for graphing a page in php to show my webservers uptime lengths between boots.
Update:
Not sure if it is based on a length of time or if last gets reset on reboot but I only get the most recent boot timestamp with the last command. last -x also does not return any further info. Sounds like a script is my best bet.
Update:
Uptimed is the information I am looking for, not sure how to grep that info in code. Managing my own script for a db sounds like the best fit for an application. | You could create a simple script which runs uptime and dumps it to a file.
```
uptime >> uptime.log
```
Then set up a cron job for it. |
79,493 | <p>I want to use Apple's or RedHat's built-in Apache but I want to use Perl 5.10 and mod_perl. What's the least intrusive way to accomplish this? I want the advantage of free security patching for the vendor's Apache, dav, php, etc., but I care a lot about which version of Perl I use and what's in my @INC path. I don't mind compiling my own mod_perl.</p>
| [
{
"answer_id": 79696,
"author": "Ian",
"author_id": 2311,
"author_profile": "https://Stackoverflow.com/users/2311",
"pm_score": 1,
"selected": false,
"text": "<p>You'll want to look into <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_so.html\" rel=\"nofollow noreferrer\">mod_so</a></p>\n"
},
{
"answer_id": 80032,
"author": "Gary Richardson",
"author_id": 2506,
"author_profile": "https://Stackoverflow.com/users/2506",
"pm_score": 1,
"selected": false,
"text": "<p>I've done this before. It wasn't pretty, but it worked, especially since vendor perl's are usually 2-3 years old.</p>\n\n<p>I started with making my own perl RPM that installed perl into a different location, like <code>/opt/</code>. This was pretty straight forward. I mostly started with this because I didn't want the system utilities that used perl to break when I upgraded/installed new modules. I had to modify all my scripts to specify <code>#!/opt/bin/perl</code> at the top and sometimes I even played with the path to make sure my perl came first.</p>\n\n<p>Next, I grabbed a mod_perl source RPM and modified it to use my <code>/opt/bin/perl</code> instead of <code>/usr/bin/perl</code>. I don't have access to the changes I made, since it was at a different gig. It took me a bit of playing around to get it. </p>\n\n<p>It did work, but I'm not an RPM wizard, so dependency checking didn't work out so well. For example, I could uninstall my custom RPM and break everything. It wasn't a big deal for me, so I moved on.</p>\n\n<p>I was also mixing RPM's with CPAN installs of modules (did I mention we built our own custom CPAN mirror with our own code?). This was a bit fragile too. Again, I didn't have the resources (ie, time) to figure out how to bend <a href=\"http://sourceforge.net/projects/cpan2rpm/\" rel=\"nofollow noreferrer\">cpan2rpm</a> to use my perl and not cause RPM conflicts.</p>\n\n<p>If I had it all to do again, I would make a custom 5.10 perl RPM and just replace the system perl. Then I would use <code>cpan2rpm</code> to create the RPM packages I needed for my software and compile my own mod_perl RPM.</p>\n"
},
{
"answer_id": 83080,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 4,
"selected": true,
"text": "<ol>\n<li><p>Build your version of Perl 5.10 following any special instructions from the mod_perl documentation. Tell Perl configurator to install in some non-standard place, like /usr/local/perl/5.10.0</p></li>\n<li><p>Use the instructions to build a shared library (or dynamic, or .so) mod_perl against your distribution's Apache, but make sure you run the Makefile.PL using <em>your</em> version of perl:</p>\n\n<p>/usr/local/perl/5.10.0/bin/perl Makefile.PL APXS=/usr/bin/apxs</p></li>\n<li><p>Install and configure mod_perl like normal.</p></li>\n</ol>\n\n<p>It may be helpful, after step one, to change your path so you don't accidentially get confused about which version of Perl you're using:</p>\n\n<pre><code>export PATH=/usr/local/perl/5.10.0/bin:$PATH\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14783/"
]
| I want to use Apple's or RedHat's built-in Apache but I want to use Perl 5.10 and mod\_perl. What's the least intrusive way to accomplish this? I want the advantage of free security patching for the vendor's Apache, dav, php, etc., but I care a lot about which version of Perl I use and what's in my @INC path. I don't mind compiling my own mod\_perl. | 1. Build your version of Perl 5.10 following any special instructions from the mod\_perl documentation. Tell Perl configurator to install in some non-standard place, like /usr/local/perl/5.10.0
2. Use the instructions to build a shared library (or dynamic, or .so) mod\_perl against your distribution's Apache, but make sure you run the Makefile.PL using *your* version of perl:
/usr/local/perl/5.10.0/bin/perl Makefile.PL APXS=/usr/bin/apxs
3. Install and configure mod\_perl like normal.
It may be helpful, after step one, to change your path so you don't accidentially get confused about which version of Perl you're using:
```
export PATH=/usr/local/perl/5.10.0/bin:$PATH
``` |
79,498 | <p>I have determined that my JSON, coming from the server, is valid (making the ajax call manually), but I would really like to use JQuery. I have also determined that the "post" URL, being sent to the server, is correct, using firebug. However, the error callback is still being triggered (parse error). I also tried datatype: text.</p>
<p>Are there other options that I should include?</p>
<pre><code>$(function() {
$("#submit").bind("click", function() {
$.ajax({
type: "post",
url: "http://myServer/cgi-bin/broker" ,
datatype: "json",
data: {'start' : start,'end' : end},
error: function(request,error){
alert(error);
},
success: function(request) {
alert(request.length);
}
}); // End ajax
}); // End bind
}); // End eventlistener
</code></pre>
| [
{
"answer_id": 79617,
"author": "Adam Weber",
"author_id": 9324,
"author_profile": "https://Stackoverflow.com/users/9324",
"pm_score": 5,
"selected": true,
"text": "<p>Here are a few suggestions I would try:</p>\n\n<p>1) the 'datatype' option you have specified should be 'dataType' (case-sensitive I believe)</p>\n\n<p>2) try using the 'contentType' option as so:</p>\n\n<pre><code>contentType: \"application/json; charset=utf-8\"\n</code></pre>\n\n<p>I'm not sure how much that will help as it's used in the request to your post url, not in the response.\nSee this article for more info: <a href=\"http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax\" rel=\"noreferrer\">http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax</a>\n(It's written for asp.net, but may be applicable)</p>\n\n<p>3) Triple check the output of your post url and run the output through a JSON validator just to be absolutely sure it's valid and can be parsed into a JSON object. <a href=\"http://www.jsonlint.com\" rel=\"noreferrer\">http://www.jsonlint.com</a></p>\n\n<p>Hope some of this helps!</p>\n"
},
{
"answer_id": 6434910,
"author": "Big Al",
"author_id": 809665,
"author_profile": "https://Stackoverflow.com/users/809665",
"pm_score": 0,
"selected": false,
"text": "<p>The data parameter is wrong. Here is an example that works:</p>\n\n<p>data: { index: ddl.selectedIndex },</p>\n\n<p>This contructs an object with property called index with value ddl.selectedIndex.</p>\n\n<p>You need to remove the quotes from your data parameter line</p>\n\n<p>Good luck\nA</p>\n"
},
{
"answer_id": 9664708,
"author": "Bohdan Hdal",
"author_id": 801142,
"author_profile": "https://Stackoverflow.com/users/801142",
"pm_score": 1,
"selected": false,
"text": "<p>Why <code>myResult</code> instead of <code>request</code>?</p>\n\n<pre><code>success: function(request) {\n alert(myResult.length);\n}\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79498",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
]
| I have determined that my JSON, coming from the server, is valid (making the ajax call manually), but I would really like to use JQuery. I have also determined that the "post" URL, being sent to the server, is correct, using firebug. However, the error callback is still being triggered (parse error). I also tried datatype: text.
Are there other options that I should include?
```
$(function() {
$("#submit").bind("click", function() {
$.ajax({
type: "post",
url: "http://myServer/cgi-bin/broker" ,
datatype: "json",
data: {'start' : start,'end' : end},
error: function(request,error){
alert(error);
},
success: function(request) {
alert(request.length);
}
}); // End ajax
}); // End bind
}); // End eventlistener
``` | Here are a few suggestions I would try:
1) the 'datatype' option you have specified should be 'dataType' (case-sensitive I believe)
2) try using the 'contentType' option as so:
```
contentType: "application/json; charset=utf-8"
```
I'm not sure how much that will help as it's used in the request to your post url, not in the response.
See this article for more info: <http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax>
(It's written for asp.net, but may be applicable)
3) Triple check the output of your post url and run the output through a JSON validator just to be absolutely sure it's valid and can be parsed into a JSON object. <http://www.jsonlint.com>
Hope some of this helps! |
79,538 | <p>I just installed Ubuntu 8.04 and I'm taking a course in Java so I figured why not install a IDE while I am installing it. So I pick my IDE of choice, Eclipse, and I make a very simple program, Hello World, to make sure everything is running smoothly. When I go to use Scanner for user input I get a very odd error:</p>
<p><b>My code:</b><pre>import java.util.Scanner;</p>
<p>class test {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("hi");
}
}</pre></p>
<p><b>The output:</b></p>
<pre>
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Scanner cannot be resolved to a type
Scanner cannot be resolved to a type
at test.main(test.java:5)
</pre>
| [
{
"answer_id": 79551,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": true,
"text": "<p>The Scanner class is new in Java 5. I do not know what Hardy's default Java environment is, but it is not Sun's and therefore may be outdated.</p>\n\n<p>I recommend installing the package sun-java6-jdk to get the most up-to-date version, then telling Eclipse to use it.</p>\n"
},
{
"answer_id": 79557,
"author": "tgdavies",
"author_id": 11002,
"author_profile": "https://Stackoverflow.com/users/11002",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using a version of Java before 1.5, java.util.Scanner doesn't exist.</p>\n\n<p>Which version of the JDK is your Eclipse project set up to use?</p>\n\n<p>Have a look at Project, Properties, Java Build Path -- look for the 'JRE System Library' entry, which should have a version number next to it.</p>\n"
},
{
"answer_id": 82475,
"author": "Lee Theobald",
"author_id": 1900,
"author_profile": "https://Stackoverflow.com/users/1900",
"pm_score": 0,
"selected": false,
"text": "<p>It could also be that although you are have JDK 1.5 or higher, the project has some specific settings set that tell it to compile as 1.4. You can test this via Project >> Properties >> Java Compiler and ensure the \"Compiler Compliance Level\" is set to 1.5 or higher.</p>\n"
},
{
"answer_id": 473785,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I know, It's quite a while since the question was posted. But the solution may still be of interest to anyone out there. It's actually quite simple...</p>\n\n<p>Under Ubuntu you need to set the java compiler \"javac\" to use sun's jdk instead of any other alternative. The difference to some of the answers posted so far is that I am talking about javac NOT java. To do so fire up a shell and do the following:</p>\n\n<ol>\n<li>As root or sudo type in at command line:</li>\n</ol>\n\n<p><code># update-alternatives --config javac</code></p>\n\n<ol start=\"2\">\n<li><p>Locate the number pointing to sun's jdk, type in this number, and hit \"ENTER\". </p></li>\n<li><p>You're done! From now on you can enjoy java.util.Scanner under Ubuntu.</p></li>\n</ol>\n\n<p><code>System.out.println(\"Say thank you, Mr.\");\nScanner scanner = java.util.Scanner(System.in);\nString thanks = scanner.next();\nSystem.out.println(\"Your welcome.\");</code></p>\n"
},
{
"answer_id": 60959558,
"author": "boi yeet",
"author_id": 12864849,
"author_profile": "https://Stackoverflow.com/users/12864849",
"pm_score": 0,
"selected": false,
"text": "<p>You imported Scanner but you're not using it. You're using Scanner, which requires user inputs. You're trying to print out one thing, but you're exposing the your program to the fact that you are going to use your own input, so it decides to print \"Hello World\" after you give a user input. But since you are not deciding what the program will print, the system gets confused since it doesn't know what to print. You need something like <code>int a=sc.nextInt();</code> or <code>String b=sc.nextLine();</code> and then give your user input. But you said you want <code>Hello World!</code>, so Scanner is redundant.</p>\n"
},
{
"answer_id": 68014889,
"author": "ailar",
"author_id": 16177997,
"author_profile": "https://Stackoverflow.com/users/16177997",
"pm_score": 0,
"selected": false,
"text": "<pre class=\"lang-java prettyprint-override\"><code>package com.company;\n\nimport java.util.Scanner;\n\npublic class Main {\n\n public static void main(String[] args) {\n Scanner in = new Scanner(System.in);\n System.out.print("Input seconds: ");\n int num = in.nextInt();\n\n for (int i = 1; i <=num; i++) {\n\n if(i%10==3)\n {\n System.out.println(i);\n }\n }\n\n }\n}\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/97220/"
]
| I just installed Ubuntu 8.04 and I'm taking a course in Java so I figured why not install a IDE while I am installing it. So I pick my IDE of choice, Eclipse, and I make a very simple program, Hello World, to make sure everything is running smoothly. When I go to use Scanner for user input I get a very odd error:
**My code:**
```
import java.util.Scanner;
```
class test {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("hi");
}
}
**The output:**
```
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Scanner cannot be resolved to a type
Scanner cannot be resolved to a type
at test.main(test.java:5)
``` | The Scanner class is new in Java 5. I do not know what Hardy's default Java environment is, but it is not Sun's and therefore may be outdated.
I recommend installing the package sun-java6-jdk to get the most up-to-date version, then telling Eclipse to use it. |
79,602 | <p>I am writing a web application that requires user interaction via email. I'm curious if there is a best practice or recommended source for learning about processing email. I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing. I'm also looking for guidance on processing bouncebacks. </p>
| [
{
"answer_id": 79670,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 3,
"selected": true,
"text": "<p>There are some pretty serious concerns here for how to send email automatically, and here are a few:</p>\n\n<p>Use an email library. Python includes one called 'email'. This is your friend, it will stop you from doing anything tragically wrong. Read an example from <a href=\"http://docs.python.org/lib/node161.html\" rel=\"nofollow noreferrer\">the Python Manual</a>.</p>\n\n<p>Some points that will stop you from getting blocked by spam filters:</p>\n\n<p>Always send from a valid email address. You must be able to send email to this address and have it received (it can go into /dev/null after it's received, but it must be possible to /deliver/ there). This will stop spam filters that do Sender Address Verification from blocking your mail.</p>\n\n<p>The email address you send from on the server.sendmail(fromaddr, [toaddr]) line will be where bounces go. The From: line in the email is a totally different address, and that's where mail will go when the user hits 'Reply:'. Use this to your advantage, bounces can go to one place, while reply goes to another.</p>\n\n<p>Send email to a local mail server, I recommend postfix. This local server will receive your mail and be responsible for sending it to your upstream server. Once it has been delivered to the local server, treat it as 'sent' from a programmatic point of view.</p>\n\n<p>If you have a site that is on a static ip in a datacenter of good reputation, don't be afraid to simply relay the mail directly to the internet. If you're in a datacenter full of script kiddies and spammers, you will need to relay this mail via a public MTA of good reputation, hopefully you will be able to work this out without a hassle.</p>\n\n<p>Don't send an email in only HTML. Always send it in Plain and HTML, or just Plain. Be nice, I use a text only email client, and you don't want to annoy me.</p>\n\n<p>Verify that you're not running SPF on your email domain, or get it configured to allow your server to send the mail. Do this by doing a TXT lookup on your domain.</p>\n\n<pre><code>$ dig google.com txt\n...snip...\n;; ANSWER SECTION:\ngoogle.com. 300 IN TXT \"v=spf1 include:_netblocks.google.com ~all\"\n</code></pre>\n\n<p>As you can see from that result, there's an SPF record there. If you don't have SPF, there won't be a TXT record. Read more about <a href=\"http://en.wikipedia.org/wiki/Sender_Policy_Framework\" rel=\"nofollow noreferrer\">SPF on wikipedia</a>.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 79743,
"author": "NotMe",
"author_id": 2424,
"author_profile": "https://Stackoverflow.com/users/2424",
"pm_score": 2,
"selected": false,
"text": "<p>Some general information with regards to automated mail processing...</p>\n\n<p>First, the mail server \"brand\" itself isn't that important for broadcasting or receiving emails. All of them support the standard smtp / pop3 communications protocol. Most even have IMAP support and have some level of spam filtering. That said, try to use a current generation email server.</p>\n\n<p>Second, be aware that in an effort to reduce spam a lot of the receiving mail servers out there will simply throw a message away instead of responding back that a mail account doesn't exist. Which means you may not receive those.</p>\n\n<p>Bear in mind that getting past spam filters is an art. A number of isp's watch for duplicate messages, messages that <em>look</em> like spam based on keywords or other content, etc. This is sometimes independent of the quantity of messages sent; I've seen messages with as few as 50 copies get blocked by AOL even though they were legitimate emails. So, testing is your friend and look into <a href=\"http://en.wikipedia.org/wiki/Anti-spam_techniques_(e-mail)\" rel=\"nofollow noreferrer\">this article on wikipedia</a> on anti-spam techniques. Then make sure your not doing that crap.</p>\n\n<p>**</p>\n\n<p>As far as processing the messages, just remember it's a queued system. Connect to the server via POP3 to retrieve messages, open it, do some action, delete the message or archive it, and move on.</p>\n\n<p>With regards to bouncebacks, let the mail server do most of the work. You should be able to configure it to notify a certain email account on the server in the event that it is unable to deliver a message. You can check that account periodically and process the Non Delivery Reports as necessary.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/322887/"
]
| I am writing a web application that requires user interaction via email. I'm curious if there is a best practice or recommended source for learning about processing email. I am writing my application in Python, but I'm not sure what mail server to use or how to format the message or subject line to account for automated processing. I'm also looking for guidance on processing bouncebacks. | There are some pretty serious concerns here for how to send email automatically, and here are a few:
Use an email library. Python includes one called 'email'. This is your friend, it will stop you from doing anything tragically wrong. Read an example from [the Python Manual](http://docs.python.org/lib/node161.html).
Some points that will stop you from getting blocked by spam filters:
Always send from a valid email address. You must be able to send email to this address and have it received (it can go into /dev/null after it's received, but it must be possible to /deliver/ there). This will stop spam filters that do Sender Address Verification from blocking your mail.
The email address you send from on the server.sendmail(fromaddr, [toaddr]) line will be where bounces go. The From: line in the email is a totally different address, and that's where mail will go when the user hits 'Reply:'. Use this to your advantage, bounces can go to one place, while reply goes to another.
Send email to a local mail server, I recommend postfix. This local server will receive your mail and be responsible for sending it to your upstream server. Once it has been delivered to the local server, treat it as 'sent' from a programmatic point of view.
If you have a site that is on a static ip in a datacenter of good reputation, don't be afraid to simply relay the mail directly to the internet. If you're in a datacenter full of script kiddies and spammers, you will need to relay this mail via a public MTA of good reputation, hopefully you will be able to work this out without a hassle.
Don't send an email in only HTML. Always send it in Plain and HTML, or just Plain. Be nice, I use a text only email client, and you don't want to annoy me.
Verify that you're not running SPF on your email domain, or get it configured to allow your server to send the mail. Do this by doing a TXT lookup on your domain.
```
$ dig google.com txt
...snip...
;; ANSWER SECTION:
google.com. 300 IN TXT "v=spf1 include:_netblocks.google.com ~all"
```
As you can see from that result, there's an SPF record there. If you don't have SPF, there won't be a TXT record. Read more about [SPF on wikipedia](http://en.wikipedia.org/wiki/Sender_Policy_Framework).
Hope that helps. |
79,612 | <p>Looking for a <code>Linux application</code> <em>(or Firefox extension)</em> that will allow me to scrape an HTML mockup and keep the page's integrity.</p>
<p>Firefox does an almost perfect job but doesn't grab images referenced in the CSS.</p>
<p>The Scrapbook extension for Firefox gets everything, but flattens the directory structure. </p>
<p>I wouldn't terribly mind if all folders became children of the <code>index</code> page.</p>
| [
{
"answer_id": 79623,
"author": "etchasketch",
"author_id": 14640,
"author_profile": "https://Stackoverflow.com/users/14640",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried <a href=\"http://linuxreviews.org/quicktips/wget/\" rel=\"nofollow noreferrer\">wget?</a></p>\n"
},
{
"answer_id": 79642,
"author": "X-Cubed",
"author_id": 10808,
"author_profile": "https://Stackoverflow.com/users/10808",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.tenmax.com/teleport/pro/home.htm\" rel=\"nofollow noreferrer\">Teleport Pro</a> is great for this sort of thing. You can point it at complete websites and it will download a copy locally maintaining directory structure, and replacing absolute links with relative ones as necessary. You can also specify whether you want content from other third-party websites linked to from the original site.</p>\n"
},
{
"answer_id": 79645,
"author": "Gilean",
"author_id": 6305,
"author_profile": "https://Stackoverflow.com/users/6305",
"pm_score": 4,
"selected": true,
"text": "<p>See <a href=\"http://www.devarticles.com/c/a/Web-Services/Website-Mirroring-With-wget/1/\" rel=\"noreferrer\">Website Mirroring With wget</a></p>\n\n<pre><code>wget --mirror –w 2 –p --HTML-extension –-convert-links http://www.yourdomain.com\n</code></pre>\n"
},
{
"answer_id": 79657,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 1,
"selected": false,
"text": "<p><code>wget -r</code> does what you want, and if not, there are plenty of flags to configure it. See <code>man wget</code>.</p>\n\n<p>Another option is <code>curl</code>, which is even more powerful. See <a href=\"http://curl.haxx.se/\" rel=\"nofollow noreferrer\">http://curl.haxx.se/</a>.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13320/"
]
| Looking for a `Linux application` *(or Firefox extension)* that will allow me to scrape an HTML mockup and keep the page's integrity.
Firefox does an almost perfect job but doesn't grab images referenced in the CSS.
The Scrapbook extension for Firefox gets everything, but flattens the directory structure.
I wouldn't terribly mind if all folders became children of the `index` page. | See [Website Mirroring With wget](http://www.devarticles.com/c/a/Web-Services/Website-Mirroring-With-wget/1/)
```
wget --mirror –w 2 –p --HTML-extension –-convert-links http://www.yourdomain.com
``` |
79,632 | <p>I have a two tables joined with a join table - this is just pseudo code:</p>
<pre><code>Library
Book
LibraryBooks
</code></pre>
<p>What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.</p>
<p>So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?</p>
<p>I was thinking:</p>
<pre><code>l = Library.find(1)
allLibraries = l.books.libraries
</code></pre>
<p>But that doesn't seem to work. Suggestions?</p>
| [
{
"answer_id": 79646,
"author": "Jim Puls",
"author_id": 6010,
"author_profile": "https://Stackoverflow.com/users/6010",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps:</p>\n\n<pre><code>l.books.map {|b| b.libraries}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>l.books.map {|b| b.libraries}.flatten.uniq\n</code></pre>\n\n<p>if you want it all in a flat array.</p>\n\n<p>Of course, you should really define this as a method on Library, so as to uphold the noble cause of encapsulation.</p>\n"
},
{
"answer_id": 79770,
"author": "bouchard",
"author_id": 14843,
"author_profile": "https://Stackoverflow.com/users/14843",
"pm_score": 2,
"selected": false,
"text": "<p>If you want a one-dimensional array of libraries returned, with duplicates removed.</p>\n\n<pre><code>l.books.map{|b| b.libraries}.flatten.uniq\n</code></pre>\n"
},
{
"answer_id": 81287,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 2,
"selected": false,
"text": "<p>One problem with </p>\n\n<pre><code>l.books.map{|b| b.libraries}.flatten.uniq\n</code></pre>\n\n<p>is that it will generate one SQL call for each book in l. A better approach (assuming I understand your schema) might be:</p>\n\n<pre><code>LibraryBook.find(:all, :conditions => ['book_id IN (?)', l.book_ids]).map(&:library_id).uniq\n</code></pre>\n"
},
{
"answer_id": 81752,
"author": "Ryan Bigg",
"author_id": 15245,
"author_profile": "https://Stackoverflow.com/users/15245",
"pm_score": 4,
"selected": true,
"text": "<pre><code>l = Library.find(:all, :include => :books)\nl.books.map { |b| b.library_ids }.flatten.uniq\n</code></pre>\n\n<p>Note that <code>map(&:library_ids)</code> is slower than <code>map { |b| b.library_ids }</code> in Ruby 1.8.6, and faster in 1.9.0.</p>\n\n<p>I should also mention that if you used <code>:joins</code> instead of <code>include</code> there, it would find the library and related books all in the same query speeding up the database time. <code>:joins</code> will only work however if a library has books. </p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
]
| I have a two tables joined with a join table - this is just pseudo code:
```
Library
Book
LibraryBooks
```
What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.
So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?
I was thinking:
```
l = Library.find(1)
allLibraries = l.books.libraries
```
But that doesn't seem to work. Suggestions? | ```
l = Library.find(:all, :include => :books)
l.books.map { |b| b.library_ids }.flatten.uniq
```
Note that `map(&:library_ids)` is slower than `map { |b| b.library_ids }` in Ruby 1.8.6, and faster in 1.9.0.
I should also mention that if you used `:joins` instead of `include` there, it would find the library and related books all in the same query speeding up the database time. `:joins` will only work however if a library has books. |
79,669 | <p>I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been: </p>
<p>1) creating each destination database<br>
2) using the "<a href="http://msdn.microsoft.com/en-us/library/ms140052.aspx" rel="noreferrer">Tasks->Export Data</a>" command to create and populate tables for each database individually<br>
3) rebuilding all of the indexes for each database with a SQL script </p>
<p>Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice?</p>
| [
{
"answer_id": 79673,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 2,
"selected": false,
"text": "<p>Backup -> Restore is the simplest, if not to use the replication.</p>\n"
},
{
"answer_id": 79679,
"author": "X-Cubed",
"author_id": 10808,
"author_profile": "https://Stackoverflow.com/users/10808",
"pm_score": 1,
"selected": false,
"text": "<p>Backup the databases using the standard SQL backup tool in Enterprise Manager, then when you restore on the second server you can specify the name of the new database.</p>\n\n<p>This is the best way to maintain the schema in its entirety.</p>\n"
},
{
"answer_id": 79682,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>use backups to restore the databases to the new server with the new names.</p>\n"
},
{
"answer_id": 79687,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Maybe the easiest is to detach/reattach. Right-click in the server manager on the DB, tasks --> detach. Then copy the MDF/LDF files to the new server and then reattach by clicking on the server icon and tasks-->attach. It will ask you for the MDF file - make sure the name etc is accurate.</p>\n"
},
{
"answer_id": 79691,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 7,
"selected": true,
"text": "<p>Given that you're performing this on multiple databases -- you want a simple scripted solution, not a point and click solution.</p>\n\n<p>This is a backup script that i keep around. \nGet it working for one file and then modify it for many.</p>\n\n<pre><code>(on source server...)\nBACKUP DATABASE Northwind\n TO DISK = 'c:\\Northwind.bak'\n\n(target server...)\nRESTORE FILELISTONLY\n FROM DISK = 'c:\\Northwind.bak'\n\n(look at the device names... and determine where you want the mdf and\nldf files to go on this target server)\n\nRESTORE DATABASE TestDB\n FROM DISK = 'c:\\Northwind.bak'\n WITH MOVE 'Northwind' TO 'c:\\test\\testdb.mdf',\n MOVE 'Northwind_log' TO 'c:\\test\\testdb.ldf'\nGO\n</code></pre>\n"
},
{
"answer_id": 79703,
"author": "stephbu",
"author_id": 12702,
"author_profile": "https://Stackoverflow.com/users/12702",
"pm_score": 2,
"selected": false,
"text": "<p>In order of ease</p>\n\n<ul>\n<li>stop server/fcopy/attach is probably easiest.</li>\n<li>backup/restore - can be done disconnected pretty simple and easy</li>\n<li>transfer DTS task - needs file copy permissions</li>\n<li>replication - furthest from simple to setup</li>\n</ul>\n\n<p>Things to think about permissions, users and groups at the destination server esp. if you're transferring or restoring.</p>\n"
},
{
"answer_id": 79715,
"author": "Kevin Sheffield",
"author_id": 590,
"author_profile": "https://Stackoverflow.com/users/590",
"pm_score": 0,
"selected": false,
"text": "<p>Redgate SQL Compare and SQL Data Compare. The Comparison Bundle was by far the best investment a company I worked for ever made. Moving e-training content was a breeze with it.</p>\n"
},
{
"answer_id": 80221,
"author": "MotoWilliams",
"author_id": 2730,
"author_profile": "https://Stackoverflow.com/users/2730",
"pm_score": 2,
"selected": false,
"text": "<p><strong><em>There are better answers already but this is an 'also ran' because it is just another option.</em></strong></p>\n\n<p>For the low low price of free you could look at the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en\" rel=\"nofollow noreferrer\">Microsoft SQL Server Database Publishing Wizard</a>. This tool allows you to script the schema, data or data and schema. Plus is can be run from a UI or command line <- think CI process.</p>\n"
},
{
"answer_id": 82212,
"author": "Mike L",
"author_id": 4796,
"author_profile": "https://Stackoverflow.com/users/4796",
"pm_score": 2,
"selected": false,
"text": "<p>If you use the Backup/Restore solution you're likely to have orphaned users so be sure to check out <a href=\"http://technet.microsoft.com/en-us/library/ms175475.aspx\" rel=\"nofollow noreferrer\">this article</a><microsoft> on how to fix them.</p>\n"
},
{
"answer_id": 1064956,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 0,
"selected": false,
"text": "<p>Check those links:</p>\n\n<ul>\n<li><a href=\"http://ysgitdiary.blogspot.com/2009/06/backup-sql-server-2005-2008-databases.html\" rel=\"nofollow noreferrer\">For multiple db's backup</a></li>\n<li><a href=\"http://ysgitdiary.blogspot.com/2009/06/restore-db-from-file-on-sql-server-2005.html\" rel=\"nofollow noreferrer\">and single db restore</a></li>\n</ul>\n"
},
{
"answer_id": 1818024,
"author": "Doug",
"author_id": 115749,
"author_profile": "https://Stackoverflow.com/users/115749",
"pm_score": 2,
"selected": false,
"text": "<p>Another one to check out that is quick and simple:</p>\n\n<p>Simple SQL BULK Copy</p>\n\n<p><a href=\"http://projects.c3o.com/files/3/plugins/entry11.aspx\" rel=\"nofollow noreferrer\">http://projects.c3o.com/files/3/plugins/entry11.aspx</a></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13728/"
]
| I need to copy about 40 databases from one server to another. The new databases should have new names, but all the same tables, data and indexes as the original databases. So far I've been:
1) creating each destination database
2) using the "[Tasks->Export Data](http://msdn.microsoft.com/en-us/library/ms140052.aspx)" command to create and populate tables for each database individually
3) rebuilding all of the indexes for each database with a SQL script
Only three steps per database, but I'll bet there's an easier way. Do any MS SQL Server experts out there have any advice? | Given that you're performing this on multiple databases -- you want a simple scripted solution, not a point and click solution.
This is a backup script that i keep around.
Get it working for one file and then modify it for many.
```
(on source server...)
BACKUP DATABASE Northwind
TO DISK = 'c:\Northwind.bak'
(target server...)
RESTORE FILELISTONLY
FROM DISK = 'c:\Northwind.bak'
(look at the device names... and determine where you want the mdf and
ldf files to go on this target server)
RESTORE DATABASE TestDB
FROM DISK = 'c:\Northwind.bak'
WITH MOVE 'Northwind' TO 'c:\test\testdb.mdf',
MOVE 'Northwind_log' TO 'c:\test\testdb.ldf'
GO
``` |
79,677 | <p>I need to speed up a program for the Nintendo DS which doesn't have an FPU, so I need to change floating-point math (which is emulated and slow) to fixed-point.</p>
<p>How I started was I changed floats to ints and whenever I needed to convert them, I used <strong>x>>8</strong> to convert the fixed-point variable x to the actual number and <strong>x<<8</strong> to convert to fixed-point. Soon I found out it was impossible to keep track of what needed to be converted and I also realized it would be difficult to change the precision of the numbers (8 in this case.)</p>
<p>My question is, how should I make this easier and still fast? Should I make a FixedPoint class, or just a FixedPoint8 typedef or struct with some functions/macros to convert them, or something else? Should I put something in the variable name to show it's fixed-point?</p>
| [
{
"answer_id": 79700,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 0,
"selected": false,
"text": "<p>Whichever way you decide to go (I'd lean toward a typedef and some CPP macros for converting), you will need to be careful to convert back and forth with some discipline.</p>\n\n<p>You might find that you never need to convert back and forth. Just imagine everything in the whole system is x256.</p>\n"
},
{
"answer_id": 79701,
"author": "Bart",
"author_id": 4343,
"author_profile": "https://Stackoverflow.com/users/4343",
"pm_score": 3,
"selected": false,
"text": "<p>Changing fixed point representations is commonly called 'scaling'.</p>\n\n<p>If you can do this with a class with no performance penalty, then that's the way to go. It depends heavily on the compiler and how it inlines. If there is a performance penalty using classes, then you need a more traditional C-style approach. The OOP approach will give you compiler-enforced type safety which the traditional implementation only approximates.</p>\n\n<p>@cibyr has a good OOP implementation. Now for the more traditional one.</p>\n\n<p>To keep track of which variables are scaled, you need to use a consistent convention. Make a notation at the end of each variable name to indicate whether the value is scaled or not, and write macros SCALE() and UNSCALE() that expand to x>>8 and x<<8. </p>\n\n<pre><code>#define SCALE(x) (x>>8)\n#define UNSCALE(x) (x<<8)\n\nxPositionUnscaled = UNSCALE(10);\nxPositionScaled = SCALE(xPositionUnscaled);\n</code></pre>\n\n<p>It may seem like extra work to use so much notation, but notice how you can tell at a glance that any line is correct without looking at other lines. For example:</p>\n\n<pre><code>xPositionScaled = SCALE(xPositionScaled);\n</code></pre>\n\n<p>is obviously wrong, by inspection.</p>\n\n<p>This is a variation of the <strong>Apps Hungarian</strong> idea that <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"nofollow noreferrer\">Joel mentions in this post</a>.</p>\n"
},
{
"answer_id": 79717,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 3,
"selected": false,
"text": "<p>The original version of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0672305070\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Tricks of the Game Programming Gurus</a> has an entire chapter on implementing fixed-point math.</p>\n"
},
{
"answer_id": 79735,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 5,
"selected": false,
"text": "<p>In modern C++ implementations, there will be no performance penalty for using simple and lean abstractions, such as concrete classes. Fixed-point computation is <strong>precisely</strong> the place where using a properly engineered class will save you from lots of bugs.</p>\n\n<p>Therefore, <strong>you should write a FixedPoint8 class</strong>. Test and debug it thoroughly. If you have to convince yourself of its performance as compared to using plain integers, measure it.</p>\n\n<p>It will save you from many a trouble by moving the complexity of fixed-point calculation to a single place.</p>\n\n<p>If you like, you can further increase the utility of your class by making it a template and replacing the old <code>FixedPoint8</code> with, say, <code>typedef FixedPoint<short, 8> FixedPoint8;</code> But on your target architecture this is not probably necessary, so avoid the complexity of templates at first.</p>\n\n<p>There is probably a good fixed point class somewhere in the internet - I'd start looking from the <a href=\"http://www.boost.org/\" rel=\"noreferrer\">Boost</a> libraries.</p>\n"
},
{
"answer_id": 79763,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>template <int precision = 8> class FixedPoint {\nprivate:\n int val_;\npublic:\n inline FixedPoint(int val) : val_ (val << precision) {};\n inline operator int() { return val_ >> precision; }\n // Other operators...\n};\n</code></pre>\n"
},
{
"answer_id": 79771,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>I wouldn't use floating point at all on a CPU without special hardware for handling it. My advice is to treat ALL numbers as integers scaled to a specific factor. For example, all monetary values are in cents as integers rather than dollars as floats. For example, 0.72 is represented as the integer 72.</p>\n\n<p>Addition and subtraction are then a very simple integer operation such as (0.72 + 1 becomes 72 + 100 becomes 172 becomes 1.72).</p>\n\n<p>Multiplication is slightly more complex as it needs an integer multiply followed by a scale back such as (0.72 * 2 becomes 72 * 200 becomes 14400 becomes 144 (scaleback) becomes 1.44).</p>\n\n<p>That may require special functions for performing more complex math (sine, cosine, etc) but even those can be sped up by using lookup tables. Example: since you're using fixed-2 representation, there's only 100 values in the range (0.0,1] (0-99) and sin/cos repeat outside this range so you only need a 100-integer lookup table.</p>\n\n<p>Cheers,\nPax.</p>\n"
},
{
"answer_id": 79784,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Does your floating point code actually make use of the decimal point? If so:</p>\n\n<p>First you have to read Randy Yates's paper on Intro to Fixed Point Math:\n<a href=\"http://www.digitalsignallabs.com/fp.pdf\" rel=\"noreferrer\">http://www.digitalsignallabs.com/fp.pdf</a></p>\n\n<p>Then you need to do \"profiling\" on your floating point code to figure out the appropriate range of fixed-point values required at \"critical\" points in your code, e.g. U(5,3) = 5 bits to the left, 3 bits to the right, unsigned.</p>\n\n<p>At this point, you can apply the arithmetic rules in the paper mentioned above; the rules specify how to interpret the bits which result from arithmetic operations. You can write macros or functions to perform the operations.</p>\n\n<p>It's handy to keep the floating point version around, in order to compare the floating point vs fixed point results.</p>\n"
},
{
"answer_id": 79942,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 6,
"selected": false,
"text": "<p>You can try my fixed point class (Latest available @ <a href=\"https://github.com/eteran/cpp-utilities\" rel=\"noreferrer\">https://github.com/eteran/cpp-utilities</a>)</p>\n\n<pre><code>// From: https://github.com/eteran/cpp-utilities/edit/master/Fixed.h\n// See also: http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math\n/*\n * The MIT License (MIT)\n * \n * Copyright (c) 2015 Evan Teran\n * \n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n * \n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n * \n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\n#ifndef FIXED_H_\n#define FIXED_H_\n\n#include <ostream>\n#include <exception>\n#include <cstddef> // for size_t\n#include <cstdint>\n#include <type_traits>\n\n#include <boost/operators.hpp>\n\nnamespace numeric {\n\ntemplate <size_t I, size_t F>\nclass Fixed;\n\nnamespace detail {\n\n// helper templates to make magic with types :)\n// these allow us to determine resonable types from\n// a desired size, they also let us infer the next largest type\n// from a type which is nice for the division op\ntemplate <size_t T>\nstruct type_from_size {\n static const bool is_specialized = false;\n typedef void value_type;\n};\n\n#if defined(__GNUC__) && defined(__x86_64__)\ntemplate <>\nstruct type_from_size<128> {\n static const bool is_specialized = true;\n static const size_t size = 128;\n typedef __int128 value_type;\n typedef unsigned __int128 unsigned_type;\n typedef __int128 signed_type;\n typedef type_from_size<256> next_size;\n};\n#endif\n\ntemplate <>\nstruct type_from_size<64> {\n static const bool is_specialized = true;\n static const size_t size = 64;\n typedef int64_t value_type;\n typedef uint64_t unsigned_type;\n typedef int64_t signed_type;\n typedef type_from_size<128> next_size;\n};\n\ntemplate <>\nstruct type_from_size<32> {\n static const bool is_specialized = true;\n static const size_t size = 32;\n typedef int32_t value_type;\n typedef uint32_t unsigned_type;\n typedef int32_t signed_type;\n typedef type_from_size<64> next_size;\n};\n\ntemplate <>\nstruct type_from_size<16> {\n static const bool is_specialized = true;\n static const size_t size = 16;\n typedef int16_t value_type;\n typedef uint16_t unsigned_type;\n typedef int16_t signed_type;\n typedef type_from_size<32> next_size;\n};\n\ntemplate <>\nstruct type_from_size<8> {\n static const bool is_specialized = true;\n static const size_t size = 8;\n typedef int8_t value_type;\n typedef uint8_t unsigned_type;\n typedef int8_t signed_type;\n typedef type_from_size<16> next_size;\n};\n\n// this is to assist in adding support for non-native base\n// types (for adding big-int support), this should be fine\n// unless your bit-int class doesn't nicely support casting\ntemplate <class B, class N>\nB next_to_base(const N& rhs) {\n return static_cast<B>(rhs);\n}\n\nstruct divide_by_zero : std::exception {\n};\n\ntemplate <size_t I, size_t F>\nFixed<I,F> divide(const Fixed<I,F> &numerator, const Fixed<I,F> &denominator, Fixed<I,F> &remainder, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::next_type next_type;\n typedef typename Fixed<I,F>::base_type base_type;\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n\n next_type t(numerator.to_raw());\n t <<= fractional_bits;\n\n Fixed<I,F> quotient;\n\n quotient = Fixed<I,F>::from_base(next_to_base<base_type>(t / denominator.to_raw()));\n remainder = Fixed<I,F>::from_base(next_to_base<base_type>(t % denominator.to_raw()));\n\n return quotient;\n}\n\ntemplate <size_t I, size_t F>\nFixed<I,F> divide(Fixed<I,F> numerator, Fixed<I,F> denominator, Fixed<I,F> &remainder, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n // NOTE(eteran): division is broken for large types :-(\n // especially when dealing with negative quantities\n\n typedef typename Fixed<I,F>::base_type base_type;\n typedef typename Fixed<I,F>::unsigned_type unsigned_type;\n\n static const int bits = Fixed<I,F>::total_bits;\n\n if(denominator == 0) {\n throw divide_by_zero();\n } else {\n\n int sign = 0;\n\n Fixed<I,F> quotient;\n\n if(numerator < 0) {\n sign ^= 1;\n numerator = -numerator;\n }\n\n if(denominator < 0) {\n sign ^= 1;\n denominator = -denominator;\n }\n\n base_type n = numerator.to_raw();\n base_type d = denominator.to_raw();\n base_type x = 1;\n base_type answer = 0;\n\n // egyptian division algorithm\n while((n >= d) && (((d >> (bits - 1)) & 1) == 0)) {\n x <<= 1;\n d <<= 1;\n }\n\n while(x != 0) {\n if(n >= d) {\n n -= d;\n answer += x;\n }\n\n x >>= 1;\n d >>= 1;\n }\n\n unsigned_type l1 = n;\n unsigned_type l2 = denominator.to_raw();\n\n // calculate the lower bits (needs to be unsigned)\n // unfortunately for many fractions this overflows the type still :-/\n const unsigned_type lo = (static_cast<unsigned_type>(n) << F) / denominator.to_raw();\n\n quotient = Fixed<I,F>::from_base((answer << F) | lo);\n remainder = n;\n\n if(sign) {\n quotient = -quotient;\n }\n\n return quotient;\n }\n}\n\n// this is the usual implementation of multiplication\ntemplate <size_t I, size_t F>\nvoid multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::next_type next_type;\n typedef typename Fixed<I,F>::base_type base_type;\n\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n\n next_type t(static_cast<next_type>(lhs.to_raw()) * static_cast<next_type>(rhs.to_raw()));\n t >>= fractional_bits;\n result = Fixed<I,F>::from_base(next_to_base<base_type>(t));\n}\n\n// this is the fall back version we use when we don't have a next size\n// it is slightly slower, but is more robust since it doesn't\n// require and upgraded type\ntemplate <size_t I, size_t F>\nvoid multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {\n\n typedef typename Fixed<I,F>::base_type base_type;\n\n static const size_t fractional_bits = Fixed<I,F>::fractional_bits;\n static const size_t integer_mask = Fixed<I,F>::integer_mask;\n static const size_t fractional_mask = Fixed<I,F>::fractional_mask;\n\n // more costly but doesn't need a larger type\n const base_type a_hi = (lhs.to_raw() & integer_mask) >> fractional_bits;\n const base_type b_hi = (rhs.to_raw() & integer_mask) >> fractional_bits;\n const base_type a_lo = (lhs.to_raw() & fractional_mask);\n const base_type b_lo = (rhs.to_raw() & fractional_mask);\n\n const base_type x1 = a_hi * b_hi;\n const base_type x2 = a_hi * b_lo;\n const base_type x3 = a_lo * b_hi;\n const base_type x4 = a_lo * b_lo;\n\n result = Fixed<I,F>::from_base((x1 << fractional_bits) + (x3 + x2) + (x4 >> fractional_bits));\n\n}\n}\n\n/*\n * inheriting from boost::operators enables us to be a drop in replacement for base types\n * without having to specify all the different versions of operators manually\n */\ntemplate <size_t I, size_t F>\nclass Fixed : boost::operators<Fixed<I,F>> {\n static_assert(detail::type_from_size<I + F>::is_specialized, \"invalid combination of sizes\");\n\npublic:\n static const size_t fractional_bits = F;\n static const size_t integer_bits = I;\n static const size_t total_bits = I + F;\n\n typedef detail::type_from_size<total_bits> base_type_info;\n\n typedef typename base_type_info::value_type base_type;\n typedef typename base_type_info::next_size::value_type next_type;\n typedef typename base_type_info::unsigned_type unsigned_type;\n\npublic:\n static const size_t base_size = base_type_info::size;\n static const base_type fractional_mask = ~((~base_type(0)) << fractional_bits);\n static const base_type integer_mask = ~fractional_mask;\n\npublic:\n static const base_type one = base_type(1) << fractional_bits;\n\npublic: // constructors\n Fixed() : data_(0) {\n }\n\n Fixed(long n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(unsigned long n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(int n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(unsigned int n) : data_(base_type(n) << fractional_bits) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(float n) : data_(static_cast<base_type>(n * one)) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(double n) : data_(static_cast<base_type>(n * one)) {\n // TODO(eteran): assert in range!\n }\n\n Fixed(const Fixed &o) : data_(o.data_) {\n }\n\n Fixed& operator=(const Fixed &o) {\n data_ = o.data_;\n return *this;\n }\n\nprivate:\n // this makes it simpler to create a fixed point object from\n // a native type without scaling\n // use \"Fixed::from_base\" in order to perform this.\n struct NoScale {};\n\n Fixed(base_type n, const NoScale &) : data_(n) {\n }\n\npublic:\n static Fixed from_base(base_type n) {\n return Fixed(n, NoScale());\n }\n\npublic: // comparison operators\n bool operator==(const Fixed &o) const {\n return data_ == o.data_;\n }\n\n bool operator<(const Fixed &o) const {\n return data_ < o.data_;\n }\n\npublic: // unary operators\n bool operator!() const {\n return !data_;\n }\n\n Fixed operator~() const {\n Fixed t(*this);\n t.data_ = ~t.data_;\n return t;\n }\n\n Fixed operator-() const {\n Fixed t(*this);\n t.data_ = -t.data_;\n return t;\n }\n\n Fixed operator+() const {\n return *this;\n }\n\n Fixed& operator++() {\n data_ += one;\n return *this;\n }\n\n Fixed& operator--() {\n data_ -= one;\n return *this;\n }\n\npublic: // basic math operators\n Fixed& operator+=(const Fixed &n) {\n data_ += n.data_;\n return *this;\n }\n\n Fixed& operator-=(const Fixed &n) {\n data_ -= n.data_;\n return *this;\n }\n\n Fixed& operator&=(const Fixed &n) {\n data_ &= n.data_;\n return *this;\n }\n\n Fixed& operator|=(const Fixed &n) {\n data_ |= n.data_;\n return *this;\n }\n\n Fixed& operator^=(const Fixed &n) {\n data_ ^= n.data_;\n return *this;\n }\n\n Fixed& operator*=(const Fixed &n) {\n detail::multiply(*this, n, *this);\n return *this;\n }\n\n Fixed& operator/=(const Fixed &n) {\n Fixed temp;\n *this = detail::divide(*this, n, temp);\n return *this;\n }\n\n Fixed& operator>>=(const Fixed &n) {\n data_ >>= n.to_int();\n return *this;\n }\n\n Fixed& operator<<=(const Fixed &n) {\n data_ <<= n.to_int();\n return *this;\n }\n\npublic: // conversion to basic types\n int to_int() const {\n return (data_ & integer_mask) >> fractional_bits;\n }\n\n unsigned int to_uint() const {\n return (data_ & integer_mask) >> fractional_bits;\n }\n\n float to_float() const {\n return static_cast<float>(data_) / Fixed::one;\n }\n\n double to_double() const {\n return static_cast<double>(data_) / Fixed::one;\n }\n\n base_type to_raw() const {\n return data_;\n }\n\npublic:\n void swap(Fixed &rhs) {\n using std::swap;\n swap(data_, rhs.data_);\n }\n\npublic:\n base_type data_;\n};\n\n// if we have the same fractional portion, but differing integer portions, we trivially upgrade the smaller type\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator+(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l + r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator-(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l - r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator*(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l * r;\n}\n\ntemplate <size_t I1, size_t I2, size_t F>\ntypename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator/(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {\n\n typedef typename std::conditional<\n I1 >= I2,\n Fixed<I1,F>,\n Fixed<I2,F>\n >::type T;\n\n const T l = T::from_base(lhs.to_raw());\n const T r = T::from_base(rhs.to_raw());\n return l / r;\n}\n\ntemplate <size_t I, size_t F>\nstd::ostream &operator<<(std::ostream &os, const Fixed<I,F> &f) {\n os << f.to_double();\n return os;\n}\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::fractional_bits;\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::integer_bits;\n\ntemplate <size_t I, size_t F>\nconst size_t Fixed<I,F>::total_bits;\n\n}\n\n#endif\n</code></pre>\n\n<p>It is designed to be a near drop in replacement for floats/doubles and has a choose-able precision. It does make use of boost to add all the necessary math operator overloads, so you will need that as well (I believe for this it is just a header dependency, not a library dependency).</p>\n\n<p>BTW, common usage could be something like this:</p>\n\n<pre><code>using namespace numeric;\ntypedef Fixed<16, 16> fixed;\nfixed f;\n</code></pre>\n\n<p>The only real rule is that the number have to add up to a native size of your system such as 8, 16, 32, 64.</p>\n"
},
{
"answer_id": 80281,
"author": "ryan_s",
"author_id": 13728,
"author_profile": "https://Stackoverflow.com/users/13728",
"pm_score": 3,
"selected": false,
"text": "<p>When I first encountered fixed point numbers I found Joe Lemieux's article, <a href=\"http://www.embedded.com/columns/15201575?_requestid=65598\" rel=\"noreferrer\">Fixed-point Math in C</a>, very helpful, and it does suggest one way of representing fixed-point values.</p>\n\n<p>I didn't wind up using his union representation for fixed-point numbers though. I mostly have experience with fixed-point in C, so I haven't had the option to use a class either. For the most part though, I think that defining your number of fraction bits in a macro and using descriptive variable names makes this fairly easy to work with. Also, I've found that it is best to have macros or functions for multiplication and especially division, or you quickly get unreadable code.</p>\n\n<p>For example, with 24.8 values:</p>\n\n<pre><code> #include \"stdio.h\"\n\n/* Declarations for fixed point stuff */\n\ntypedef int int_fixed;\n\n#define FRACT_BITS 8\n#define FIXED_POINT_ONE (1 << FRACT_BITS)\n#define MAKE_INT_FIXED(x) ((x) << FRACT_BITS)\n#define MAKE_FLOAT_FIXED(x) ((int_fixed)((x) * FIXED_POINT_ONE))\n#define MAKE_FIXED_INT(x) ((x) >> FRACT_BITS)\n#define MAKE_FIXED_FLOAT(x) (((float)(x)) / FIXED_POINT_ONE)\n\n#define FIXED_MULT(x, y) ((x)*(y) >> FRACT_BITS)\n#define FIXED_DIV(x, y) (((x)<<FRACT_BITS) / (y))\n\n/* tests */\nint main()\n{\n int_fixed fixed_x = MAKE_FLOAT_FIXED( 4.5f );\n int_fixed fixed_y = MAKE_INT_FIXED( 2 );\n\n int_fixed fixed_result = FIXED_MULT( fixed_x, fixed_y );\n printf( \"%.1f\\n\", MAKE_FIXED_FLOAT( fixed_result ) );\n\n fixed_result = FIXED_DIV( fixed_result, fixed_y );\n printf( \"%.1f\\n\", MAKE_FIXED_FLOAT( fixed_result ) );\n\n return 0;\n}\n</code></pre>\n\n<p>Which writes out </p>\n\n<pre>\n9.0\n4.5\n</pre>\n\n<p>Note that there are all kinds of integer overflow issues with those macros, I just wanted to keep the macros simple. This is just a quick and dirty example of how I've done this in C. In C++ you could make something a lot cleaner using operator overloading. Actually, you could easily make that C code a lot prettier too...</p>\n\n<p>I guess this is a long-winded way of saying: I think it's OK to use a typedef and macro approach. So long as you're clear about what variables contain fixed point values it isn't too hard to maintain, but it probably won't be as pretty as a C++ class. </p>\n\n<p>If I was in your position, I would try to get some profiling numbers to show where the bottlenecks are. If there are relatively few of them then go with a typedef and macros. If you decide that you need a global replacement of all floats with fixed-point math though, then you'll probably be better off with a class.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/813/"
]
| I need to speed up a program for the Nintendo DS which doesn't have an FPU, so I need to change floating-point math (which is emulated and slow) to fixed-point.
How I started was I changed floats to ints and whenever I needed to convert them, I used **x>>8** to convert the fixed-point variable x to the actual number and **x<<8** to convert to fixed-point. Soon I found out it was impossible to keep track of what needed to be converted and I also realized it would be difficult to change the precision of the numbers (8 in this case.)
My question is, how should I make this easier and still fast? Should I make a FixedPoint class, or just a FixedPoint8 typedef or struct with some functions/macros to convert them, or something else? Should I put something in the variable name to show it's fixed-point? | You can try my fixed point class (Latest available @ <https://github.com/eteran/cpp-utilities>)
```
// From: https://github.com/eteran/cpp-utilities/edit/master/Fixed.h
// See also: http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-point-math
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Evan Teran
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef FIXED_H_
#define FIXED_H_
#include <ostream>
#include <exception>
#include <cstddef> // for size_t
#include <cstdint>
#include <type_traits>
#include <boost/operators.hpp>
namespace numeric {
template <size_t I, size_t F>
class Fixed;
namespace detail {
// helper templates to make magic with types :)
// these allow us to determine resonable types from
// a desired size, they also let us infer the next largest type
// from a type which is nice for the division op
template <size_t T>
struct type_from_size {
static const bool is_specialized = false;
typedef void value_type;
};
#if defined(__GNUC__) && defined(__x86_64__)
template <>
struct type_from_size<128> {
static const bool is_specialized = true;
static const size_t size = 128;
typedef __int128 value_type;
typedef unsigned __int128 unsigned_type;
typedef __int128 signed_type;
typedef type_from_size<256> next_size;
};
#endif
template <>
struct type_from_size<64> {
static const bool is_specialized = true;
static const size_t size = 64;
typedef int64_t value_type;
typedef uint64_t unsigned_type;
typedef int64_t signed_type;
typedef type_from_size<128> next_size;
};
template <>
struct type_from_size<32> {
static const bool is_specialized = true;
static const size_t size = 32;
typedef int32_t value_type;
typedef uint32_t unsigned_type;
typedef int32_t signed_type;
typedef type_from_size<64> next_size;
};
template <>
struct type_from_size<16> {
static const bool is_specialized = true;
static const size_t size = 16;
typedef int16_t value_type;
typedef uint16_t unsigned_type;
typedef int16_t signed_type;
typedef type_from_size<32> next_size;
};
template <>
struct type_from_size<8> {
static const bool is_specialized = true;
static const size_t size = 8;
typedef int8_t value_type;
typedef uint8_t unsigned_type;
typedef int8_t signed_type;
typedef type_from_size<16> next_size;
};
// this is to assist in adding support for non-native base
// types (for adding big-int support), this should be fine
// unless your bit-int class doesn't nicely support casting
template <class B, class N>
B next_to_base(const N& rhs) {
return static_cast<B>(rhs);
}
struct divide_by_zero : std::exception {
};
template <size_t I, size_t F>
Fixed<I,F> divide(const Fixed<I,F> &numerator, const Fixed<I,F> &denominator, Fixed<I,F> &remainder, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {
typedef typename Fixed<I,F>::next_type next_type;
typedef typename Fixed<I,F>::base_type base_type;
static const size_t fractional_bits = Fixed<I,F>::fractional_bits;
next_type t(numerator.to_raw());
t <<= fractional_bits;
Fixed<I,F> quotient;
quotient = Fixed<I,F>::from_base(next_to_base<base_type>(t / denominator.to_raw()));
remainder = Fixed<I,F>::from_base(next_to_base<base_type>(t % denominator.to_raw()));
return quotient;
}
template <size_t I, size_t F>
Fixed<I,F> divide(Fixed<I,F> numerator, Fixed<I,F> denominator, Fixed<I,F> &remainder, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {
// NOTE(eteran): division is broken for large types :-(
// especially when dealing with negative quantities
typedef typename Fixed<I,F>::base_type base_type;
typedef typename Fixed<I,F>::unsigned_type unsigned_type;
static const int bits = Fixed<I,F>::total_bits;
if(denominator == 0) {
throw divide_by_zero();
} else {
int sign = 0;
Fixed<I,F> quotient;
if(numerator < 0) {
sign ^= 1;
numerator = -numerator;
}
if(denominator < 0) {
sign ^= 1;
denominator = -denominator;
}
base_type n = numerator.to_raw();
base_type d = denominator.to_raw();
base_type x = 1;
base_type answer = 0;
// egyptian division algorithm
while((n >= d) && (((d >> (bits - 1)) & 1) == 0)) {
x <<= 1;
d <<= 1;
}
while(x != 0) {
if(n >= d) {
n -= d;
answer += x;
}
x >>= 1;
d >>= 1;
}
unsigned_type l1 = n;
unsigned_type l2 = denominator.to_raw();
// calculate the lower bits (needs to be unsigned)
// unfortunately for many fractions this overflows the type still :-/
const unsigned_type lo = (static_cast<unsigned_type>(n) << F) / denominator.to_raw();
quotient = Fixed<I,F>::from_base((answer << F) | lo);
remainder = n;
if(sign) {
quotient = -quotient;
}
return quotient;
}
}
// this is the usual implementation of multiplication
template <size_t I, size_t F>
void multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<type_from_size<I+F>::next_size::is_specialized>::type* = 0) {
typedef typename Fixed<I,F>::next_type next_type;
typedef typename Fixed<I,F>::base_type base_type;
static const size_t fractional_bits = Fixed<I,F>::fractional_bits;
next_type t(static_cast<next_type>(lhs.to_raw()) * static_cast<next_type>(rhs.to_raw()));
t >>= fractional_bits;
result = Fixed<I,F>::from_base(next_to_base<base_type>(t));
}
// this is the fall back version we use when we don't have a next size
// it is slightly slower, but is more robust since it doesn't
// require and upgraded type
template <size_t I, size_t F>
void multiply(const Fixed<I,F> &lhs, const Fixed<I,F> &rhs, Fixed<I,F> &result, typename std::enable_if<!type_from_size<I+F>::next_size::is_specialized>::type* = 0) {
typedef typename Fixed<I,F>::base_type base_type;
static const size_t fractional_bits = Fixed<I,F>::fractional_bits;
static const size_t integer_mask = Fixed<I,F>::integer_mask;
static const size_t fractional_mask = Fixed<I,F>::fractional_mask;
// more costly but doesn't need a larger type
const base_type a_hi = (lhs.to_raw() & integer_mask) >> fractional_bits;
const base_type b_hi = (rhs.to_raw() & integer_mask) >> fractional_bits;
const base_type a_lo = (lhs.to_raw() & fractional_mask);
const base_type b_lo = (rhs.to_raw() & fractional_mask);
const base_type x1 = a_hi * b_hi;
const base_type x2 = a_hi * b_lo;
const base_type x3 = a_lo * b_hi;
const base_type x4 = a_lo * b_lo;
result = Fixed<I,F>::from_base((x1 << fractional_bits) + (x3 + x2) + (x4 >> fractional_bits));
}
}
/*
* inheriting from boost::operators enables us to be a drop in replacement for base types
* without having to specify all the different versions of operators manually
*/
template <size_t I, size_t F>
class Fixed : boost::operators<Fixed<I,F>> {
static_assert(detail::type_from_size<I + F>::is_specialized, "invalid combination of sizes");
public:
static const size_t fractional_bits = F;
static const size_t integer_bits = I;
static const size_t total_bits = I + F;
typedef detail::type_from_size<total_bits> base_type_info;
typedef typename base_type_info::value_type base_type;
typedef typename base_type_info::next_size::value_type next_type;
typedef typename base_type_info::unsigned_type unsigned_type;
public:
static const size_t base_size = base_type_info::size;
static const base_type fractional_mask = ~((~base_type(0)) << fractional_bits);
static const base_type integer_mask = ~fractional_mask;
public:
static const base_type one = base_type(1) << fractional_bits;
public: // constructors
Fixed() : data_(0) {
}
Fixed(long n) : data_(base_type(n) << fractional_bits) {
// TODO(eteran): assert in range!
}
Fixed(unsigned long n) : data_(base_type(n) << fractional_bits) {
// TODO(eteran): assert in range!
}
Fixed(int n) : data_(base_type(n) << fractional_bits) {
// TODO(eteran): assert in range!
}
Fixed(unsigned int n) : data_(base_type(n) << fractional_bits) {
// TODO(eteran): assert in range!
}
Fixed(float n) : data_(static_cast<base_type>(n * one)) {
// TODO(eteran): assert in range!
}
Fixed(double n) : data_(static_cast<base_type>(n * one)) {
// TODO(eteran): assert in range!
}
Fixed(const Fixed &o) : data_(o.data_) {
}
Fixed& operator=(const Fixed &o) {
data_ = o.data_;
return *this;
}
private:
// this makes it simpler to create a fixed point object from
// a native type without scaling
// use "Fixed::from_base" in order to perform this.
struct NoScale {};
Fixed(base_type n, const NoScale &) : data_(n) {
}
public:
static Fixed from_base(base_type n) {
return Fixed(n, NoScale());
}
public: // comparison operators
bool operator==(const Fixed &o) const {
return data_ == o.data_;
}
bool operator<(const Fixed &o) const {
return data_ < o.data_;
}
public: // unary operators
bool operator!() const {
return !data_;
}
Fixed operator~() const {
Fixed t(*this);
t.data_ = ~t.data_;
return t;
}
Fixed operator-() const {
Fixed t(*this);
t.data_ = -t.data_;
return t;
}
Fixed operator+() const {
return *this;
}
Fixed& operator++() {
data_ += one;
return *this;
}
Fixed& operator--() {
data_ -= one;
return *this;
}
public: // basic math operators
Fixed& operator+=(const Fixed &n) {
data_ += n.data_;
return *this;
}
Fixed& operator-=(const Fixed &n) {
data_ -= n.data_;
return *this;
}
Fixed& operator&=(const Fixed &n) {
data_ &= n.data_;
return *this;
}
Fixed& operator|=(const Fixed &n) {
data_ |= n.data_;
return *this;
}
Fixed& operator^=(const Fixed &n) {
data_ ^= n.data_;
return *this;
}
Fixed& operator*=(const Fixed &n) {
detail::multiply(*this, n, *this);
return *this;
}
Fixed& operator/=(const Fixed &n) {
Fixed temp;
*this = detail::divide(*this, n, temp);
return *this;
}
Fixed& operator>>=(const Fixed &n) {
data_ >>= n.to_int();
return *this;
}
Fixed& operator<<=(const Fixed &n) {
data_ <<= n.to_int();
return *this;
}
public: // conversion to basic types
int to_int() const {
return (data_ & integer_mask) >> fractional_bits;
}
unsigned int to_uint() const {
return (data_ & integer_mask) >> fractional_bits;
}
float to_float() const {
return static_cast<float>(data_) / Fixed::one;
}
double to_double() const {
return static_cast<double>(data_) / Fixed::one;
}
base_type to_raw() const {
return data_;
}
public:
void swap(Fixed &rhs) {
using std::swap;
swap(data_, rhs.data_);
}
public:
base_type data_;
};
// if we have the same fractional portion, but differing integer portions, we trivially upgrade the smaller type
template <size_t I1, size_t I2, size_t F>
typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator+(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {
typedef typename std::conditional<
I1 >= I2,
Fixed<I1,F>,
Fixed<I2,F>
>::type T;
const T l = T::from_base(lhs.to_raw());
const T r = T::from_base(rhs.to_raw());
return l + r;
}
template <size_t I1, size_t I2, size_t F>
typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator-(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {
typedef typename std::conditional<
I1 >= I2,
Fixed<I1,F>,
Fixed<I2,F>
>::type T;
const T l = T::from_base(lhs.to_raw());
const T r = T::from_base(rhs.to_raw());
return l - r;
}
template <size_t I1, size_t I2, size_t F>
typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator*(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {
typedef typename std::conditional<
I1 >= I2,
Fixed<I1,F>,
Fixed<I2,F>
>::type T;
const T l = T::from_base(lhs.to_raw());
const T r = T::from_base(rhs.to_raw());
return l * r;
}
template <size_t I1, size_t I2, size_t F>
typename std::conditional<I1 >= I2, Fixed<I1,F>, Fixed<I2,F>>::type operator/(const Fixed<I1,F> &lhs, const Fixed<I2,F> &rhs) {
typedef typename std::conditional<
I1 >= I2,
Fixed<I1,F>,
Fixed<I2,F>
>::type T;
const T l = T::from_base(lhs.to_raw());
const T r = T::from_base(rhs.to_raw());
return l / r;
}
template <size_t I, size_t F>
std::ostream &operator<<(std::ostream &os, const Fixed<I,F> &f) {
os << f.to_double();
return os;
}
template <size_t I, size_t F>
const size_t Fixed<I,F>::fractional_bits;
template <size_t I, size_t F>
const size_t Fixed<I,F>::integer_bits;
template <size_t I, size_t F>
const size_t Fixed<I,F>::total_bits;
}
#endif
```
It is designed to be a near drop in replacement for floats/doubles and has a choose-able precision. It does make use of boost to add all the necessary math operator overloads, so you will need that as well (I believe for this it is just a header dependency, not a library dependency).
BTW, common usage could be something like this:
```
using namespace numeric;
typedef Fixed<16, 16> fixed;
fixed f;
```
The only real rule is that the number have to add up to a native size of your system such as 8, 16, 32, 64. |
79,688 | <p>What's the best way to calculate percentile rankings (e.g. the 90th percentile or the median score) in MSSQL 2005?</p>
<p>I'd like to be able to select the 25th, median, and 75th percentiles for a single column of scores (preferably in a single record so I can combine with average, max, and min). So for example, table output of the results might be:</p>
<pre><code>Group MinScore MaxScore AvgScore pct25 median pct75
----- -------- -------- -------- ----- ------ -----
T1 52 96 74 68 76 84
T2 48 98 74 68 75 85
</code></pre>
| [
{
"answer_id": 79758,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>i'd probably use a the sql server 2005 </p>\n\n<blockquote>\n <p>row_number() over (order by score ) / (select count(*) from scores)</p>\n</blockquote>\n\n<p>or something along those lines. </p>\n"
},
{
"answer_id": 79766,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>i'd do something like:</p>\n\n<pre><code>select @n = count(*) from tbl1\nselect @median = @n / 2\nselect @p75 = @n * 3 / 4\nselect @p90 = @n * 9 / 10\n\nselect top 1 score from (select top @median score from tbl1 order by score asc) order by score desc\n</code></pre>\n\n<p>is this right?</p>\n"
},
{
"answer_id": 79990,
"author": "Matt",
"author_id": 4154,
"author_profile": "https://Stackoverflow.com/users/4154",
"pm_score": 4,
"selected": false,
"text": "<p>I would think that this would be the simplest solution:</p>\n\n<pre><code>SELECT TOP N PERCENT FROM TheTable ORDER BY TheScore DESC\n</code></pre>\n\n<p>Where N = (100 - desired percentile). So if you wanted all rows in the 90th percentile, you'd select the top 10%.</p>\n\n<p>I'm not sure what you mean by \"preferably in a single record\". Do you mean calculate which percentile a given score for a single record would fall into? e.g. do you want to be able to make statements like \"your score is 83, which puts you in the 91st percentile.\" ?</p>\n\n<p>EDIT: OK, I thought some more about your question and came up with this interpretation. Are you asking how to calculate the cutoff score for a particular percentile? e.g. something like this: to be in the 90th percentile you must have a score greater than 78.</p>\n\n<p>If so, this query works. I dislike sub-queries though, so depending on what it was for, I'd probably try to find a more elegant solution. It does, however, return a single record with a single score.</p>\n\n<pre><code>-- Find the minimum score for all scores in the 90th percentile\nSELECT Min(subq.TheScore) FROM\n(SELECT TOP 10 PERCENT TheScore FROM TheTable\nORDER BY TheScore DESC) AS subq\n</code></pre>\n"
},
{
"answer_id": 342502,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 1,
"selected": false,
"text": "<p>I've been working on this a little more, and here's what I've come up with so far:</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[TestGetPercentile]\n\n@percentile as float,\n@resultval as float output\n\nAS\n\nBEGIN\n\nWITH scores(score, prev_rank, curr_rank, next_rank) AS (\n SELECT dblScore,\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) - 1.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [prev_rank],\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) + 0.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [curr_rank],\n (ROW_NUMBER() OVER ( ORDER BY dblScore ) + 1.0) / ((SELECT COUNT(*) FROM TestScores) + 1) [next_rank]\n FROM TestScores\n)\n\nSELECT @resultval = (\n SELECT TOP 1 \n CASE WHEN t1.score = t2.score\n THEN t1.score\n ELSE\n t1.score + (t2.score - t1.score) * ((@percentile - t1.curr_rank) / (t2.curr_rank - t1.curr_rank))\n END\n FROM scores t1, scores t2\n WHERE (t1.curr_rank = @percentile OR (t1.curr_rank < @percentile AND t1.next_rank > @percentile))\n AND (t2.curr_rank = @percentile OR (t2.curr_rank > @percentile AND t2.prev_rank < @percentile))\n)\n\nEND\n</code></pre>\n\n<p>Then in another stored procedure I do this:</p>\n\n<pre><code>DECLARE @pct25 float;\nDECLARE @pct50 float;\nDECLARE @pct75 float;\n\nexec SurveyGetPercentile .25, @pct25 output\nexec SurveyGetPercentile .50, @pct50 output\nexec SurveyGetPercentile .75, @pct75 output\n\nSelect\n min(dblScore) as minScore,\n max(dblScore) as maxScore,\n avg(dblScore) as avgScore,\n @pct25 as percentile25,\n @pct50 as percentile50,\n @pct75 as percentile75\nFrom TestScores\n</code></pre>\n\n<p>It still doesn't do quite what I'm looking for. This will get the stats for all tests; whereas I would like to be able to select from a TestScores table that has multiple different tests in it and get back the same stats for each different test (like I have in my example table in my question).</p>\n"
},
{
"answer_id": 6504968,
"author": "Kay Aliu",
"author_id": 818956,
"author_profile": "https://Stackoverflow.com/users/818956",
"pm_score": 1,
"selected": false,
"text": "<p>The 50th percentile is same as the median. When computing other percentile, say the 80th, sort the data for the 80 percent of data in ascending order and the other 20 percent in descending order, and take the avg of the two middle value.</p>\n\n<p>NB: The median query has been around for a long time, but cannot remember where exactly I got it from, I have only amended it to compute other percentiles.</p>\n\n<pre><code>DECLARE @Temp TABLE(Id INT IDENTITY(1,1), DATA DECIMAL(10,5))\n\nINSERT INTO @Temp VALUES(0)\nINSERT INTO @Temp VALUES(2)\nINSERT INTO @Temp VALUES(8)\nINSERT INTO @Temp VALUES(4)\nINSERT INTO @Temp VALUES(3)\nINSERT INTO @Temp VALUES(6)\nINSERT INTO @Temp VALUES(6)\nINSERT INTO @Temp VALUES(6) \nINSERT INTO @Temp VALUES(7)\nINSERT INTO @Temp VALUES(0)\nINSERT INTO @Temp VALUES(1)\nINSERT INTO @Temp VALUES(NULL)\n\n\n--50th percentile or median\nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 50 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 50 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n\n\n--90th percentile \nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 90 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 10 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n\n\n--75th percentile\nSELECT ((\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 75 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA\n ) AS A\n ORDER BY DATA DESC) + \n (\n SELECT TOP 1 DATA\n FROM (\n SELECT TOP 25 PERCENT DATA\n FROM @Temp\n WHERE DATA IS NOT NULL\n ORDER BY DATA DESC\n ) AS A\n ORDER BY DATA ASC)) / 2.0\n</code></pre>\n"
},
{
"answer_id": 6512841,
"author": "Elizabeth",
"author_id": 819953,
"author_profile": "https://Stackoverflow.com/users/819953",
"pm_score": 3,
"selected": false,
"text": "<p>Check out the NTILE command -- it will give you percentiles pretty easily!</p>\n\n<pre><code>SELECT SalesOrderID, \n OrderQty,\n RowNum = Row_Number() OVER(Order By OrderQty),\n Rnk = RANK() OVER(ORDER BY OrderQty),\n DenseRnk = DENSE_RANK() OVER(ORDER BY OrderQty),\n NTile4 = NTILE(4) OVER(ORDER BY OrderQty)\nFROM Sales.SalesOrderDetail \nWHERE SalesOrderID IN (43689, 63181)\n</code></pre>\n"
},
{
"answer_id": 12291090,
"author": "Paul",
"author_id": 1650451,
"author_profile": "https://Stackoverflow.com/users/1650451",
"pm_score": 2,
"selected": false,
"text": "<p>How about this:</p>\n\n<pre><code>SELECT\n Group,\n 75_percentile = MAX(case when NTILE(4) OVER(ORDER BY score ASC) = 3 then score else 0 end),\n 90_percentile = MAX(case when NTILE(10) OVER(ORDER BY score ASC) = 9 then score else 0 end) \nFROM TheScore\nGROUP BY Group\n</code></pre>\n"
},
{
"answer_id": 55066450,
"author": "Debasmita",
"author_id": 7025084,
"author_profile": "https://Stackoverflow.com/users/7025084",
"pm_score": 0,
"selected": false,
"text": "<p>Percentile is calculated by </p>\n\n<p><code>(Rank -1) /(total_rows -1)</code> when you sort values in ascending order. </p>\n\n<p>The below query will give you percentile value between 0 and 1. Person with lowest marks will have 0 percentile.</p>\n\n<pre><code>SELECT Name, marks, (rank_1-1)/((select count(*) as total_1 from table)-1)as percentile_rank\nfrom\n(\nSELECT Name,\n Marks,\n RANK() OVER (ORDER BY Marks) AS rank_1\n from table\n) as A\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3420/"
]
| What's the best way to calculate percentile rankings (e.g. the 90th percentile or the median score) in MSSQL 2005?
I'd like to be able to select the 25th, median, and 75th percentiles for a single column of scores (preferably in a single record so I can combine with average, max, and min). So for example, table output of the results might be:
```
Group MinScore MaxScore AvgScore pct25 median pct75
----- -------- -------- -------- ----- ------ -----
T1 52 96 74 68 76 84
T2 48 98 74 68 75 85
``` | I would think that this would be the simplest solution:
```
SELECT TOP N PERCENT FROM TheTable ORDER BY TheScore DESC
```
Where N = (100 - desired percentile). So if you wanted all rows in the 90th percentile, you'd select the top 10%.
I'm not sure what you mean by "preferably in a single record". Do you mean calculate which percentile a given score for a single record would fall into? e.g. do you want to be able to make statements like "your score is 83, which puts you in the 91st percentile." ?
EDIT: OK, I thought some more about your question and came up with this interpretation. Are you asking how to calculate the cutoff score for a particular percentile? e.g. something like this: to be in the 90th percentile you must have a score greater than 78.
If so, this query works. I dislike sub-queries though, so depending on what it was for, I'd probably try to find a more elegant solution. It does, however, return a single record with a single score.
```
-- Find the minimum score for all scores in the 90th percentile
SELECT Min(subq.TheScore) FROM
(SELECT TOP 10 PERCENT TheScore FROM TheTable
ORDER BY TheScore DESC) AS subq
``` |
79,693 | <p>How do you get all the classes in a namespace through reflection in C#?</p>
| [
{
"answer_id": 79706,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 5,
"selected": false,
"text": "<pre><code>using System.Reflection;\nusing System.Collections.Generic;\n//...\n\nstatic List<string> GetClasses(string nameSpace)\n{\n Assembly asm = Assembly.GetExecutingAssembly();\n\n List<string> namespacelist = new List<string>();\n List<string> classlist = new List<string>();\n\n foreach (Type type in asm.GetTypes())\n {\n if (type.Namespace == nameSpace)\n namespacelist.Add(type.Name);\n }\n\n foreach (string classname in namespacelist)\n classlist.Add(classname);\n\n return classlist;\n}\n</code></pre>\n\n<p>NB: The above code illustrates what's going on. Were you to implement it, a simplified version can be used:</p>\n\n<pre><code>using System.Linq;\nusing System.Reflection;\nusing System.Collections.Generic;\n//...\n\nstatic IEnumerable<string> GetClasses(string nameSpace)\n{\n Assembly asm = Assembly.GetExecutingAssembly();\n return asm.GetTypes()\n .Where(type => type.Namespace == nameSpace)\n .Select(type => type.Name);\n}\n</code></pre>\n"
},
{
"answer_id": 79712,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>You won't be able to get all types in a namespace, because a namespace can bridge multiple assemblies, but you can get all classes in an assembly and check to see if they belong to that namespace.</p>\n\n<p><code>Assembly.GetTypes()</code> works on the local assembly, or you can load an assembly first then call <code>GetTypes()</code> on it.</p>\n"
},
{
"answer_id": 79738,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 8,
"selected": false,
"text": "<p>Following code prints names of classes in specified <code>namespace</code> defined in current assembly.<br>\nAs other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.</p>\n\n<pre><code>string nspace = \"...\";\n\nvar q = from t in Assembly.GetExecutingAssembly().GetTypes()\n where t.IsClass && t.Namespace == nspace\n select t;\nq.ToList().ForEach(t => Console.WriteLine(t.Name));\n</code></pre>\n"
},
{
"answer_id": 79785,
"author": "TheXenocide",
"author_id": 8543,
"author_profile": "https://Stackoverflow.com/users/8543",
"pm_score": 2,
"selected": false,
"text": "<p>Namespaces are actually rather passive in the design of the runtime and serve primarily as organizational tools. The Full Name of a type in .NET consists of the Namespace and Class/Enum/Etc. combined. If you only wish to go through a specific assembly, you would simply loop through the types returned by assembly.<a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexportedtypes.aspx\" rel=\"nofollow noreferrer\">GetExportedTypes()</a> checking the value of type.<a href=\"http://msdn.microsoft.com/en-us/library/system.type.namespace.aspx\" rel=\"nofollow noreferrer\">Namespace</a>. If you were trying to go through all assemblies loaded in the current AppDomain it would involve using AppDomain.CurrentDomain.<a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain_members.aspx\" rel=\"nofollow noreferrer\">GetAssemblies()</a></p>\n"
},
{
"answer_id": 79793,
"author": "tsimon",
"author_id": 1685,
"author_profile": "https://Stackoverflow.com/users/1685",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a fix for LoaderException errors you're likely to find if one of the types sublasses a type in another assembly:</p>\n\n<pre><code>// Setup event handler to resolve assemblies\nAppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);\n\nAssembly a = System.Reflection.Assembly.ReflectionOnlyLoadFrom(filename);\na.GetTypes();\n// process types here\n\n// method later in the class:\nstatic Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)\n{\n return System.Reflection.Assembly.ReflectionOnlyLoad(args.Name);\n}\n</code></pre>\n\n<p>That should help with loading types defined in other assemblies.</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 762978,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 2,
"selected": false,
"text": "<pre><code>//a simple combined code snippet \n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Reflection;\n\nnamespace MustHaveAttributes\n{\n class Program\n {\n static void Main ( string[] args )\n {\n Console.WriteLine ( \" START \" );\n\n // what is in the assembly\n Assembly a = Assembly.Load ( \"MustHaveAttributes\" );\n Type[] types = a.GetTypes ();\n foreach (Type t in types)\n {\n\n Console.WriteLine ( \"Type is {0}\", t );\n }\n Console.WriteLine (\n \"{0} types found\", types.Length );\n\n #region Linq\n //#region Action\n\n\n //string @namespace = \"MustHaveAttributes\";\n\n //var q = from t in Assembly.GetExecutingAssembly ().GetTypes ()\n // where t.IsClass && t.Namespace == @namespace\n // select t;\n //q.ToList ().ForEach ( t => Console.WriteLine ( t.Name ) );\n\n\n //#endregion Action \n #endregion\n\n Console.ReadLine ();\n Console.WriteLine ( \" HIT A KEY TO EXIT \" );\n Console.WriteLine ( \" END \" );\n }\n } //eof Program\n\n\n class ClassOne\n {\n\n } //eof class \n\n class ClassTwo\n {\n\n } //eof class\n\n\n [System.AttributeUsage ( System.AttributeTargets.Class |\n System.AttributeTargets.Struct, AllowMultiple = true )]\n public class AttributeClass : System.Attribute\n {\n\n public string MustHaveDescription { get; set; }\n public string MusHaveVersion { get; set; }\n\n\n public AttributeClass ( string mustHaveDescription, string mustHaveVersion )\n {\n MustHaveDescription = mustHaveDescription;\n MusHaveVersion = mustHaveVersion;\n }\n\n } //eof class \n\n} //eof namespace \n</code></pre>\n"
},
{
"answer_id": 14234375,
"author": "JoanComasFdz",
"author_id": 383129,
"author_profile": "https://Stackoverflow.com/users/383129",
"pm_score": 3,
"selected": false,
"text": "<p>Just like @aku answer, but using extension methods:</p>\n\n<pre><code>string @namespace = \"...\";\n\nvar types = Assembly.GetExecutingAssembly().GetTypes()\n .Where(t => t.IsClass && t.Namespace == @namespace)\n .ToList();\n\ntypes.ForEach(t => Console.WriteLine(t.Name));\n</code></pre>\n"
},
{
"answer_id": 16504427,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 7,
"selected": false,
"text": "<p>As FlySwat says, you can have the same namespace spanning in multiple assemblies (for eg <code>System.Collections.Generic</code>). You will have to load all those assemblies if they are not already loaded. So for a complete answer:</p>\n\n<pre><code>AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(t => t.GetTypes())\n .Where(t => t.IsClass && t.Namespace == @namespace)\n</code></pre>\n\n<p>This should work unless you want classes of other domains. To get a list of all domains, follow <a href=\"https://stackoverflow.com/questions/388554/list-appdomains-in-process\">this link.</a></p>\n"
},
{
"answer_id": 27598813,
"author": "Ivo Stoyanov",
"author_id": 2298241,
"author_profile": "https://Stackoverflow.com/users/2298241",
"pm_score": 3,
"selected": false,
"text": "<p>Get all classes by part of Namespace name in just one row:</p>\n\n<pre><code>var allClasses = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.IsClass && a.Namespace != null && a.Namespace.Contains(@\"..your namespace...\")).ToList();\n</code></pre>\n"
},
{
"answer_id": 34869091,
"author": "JWP",
"author_id": 1522548,
"author_profile": "https://Stackoverflow.com/users/1522548",
"pm_score": 5,
"selected": false,
"text": "<p>For a specific Assembly, NameSpace and ClassName:</p>\n\n<pre><code>var assemblyName = \"Some.Assembly.Name\"\nvar nameSpace = \"Some.Namespace.Name\";\nvar className = \"ClassNameFilter\";\n\nvar asm = Assembly.Load(assemblyName);\nvar classes = asm.GetTypes().Where(p =>\n p.Namespace == nameSpace &&\n p.Name.Contains(className) \n).ToList();\n</code></pre>\n\n<p>Note: The project must reference the assembly</p>\n"
},
{
"answer_id": 35707879,
"author": "Antonio Lopes",
"author_id": 4837664,
"author_profile": "https://Stackoverflow.com/users/4837664",
"pm_score": 0,
"selected": false,
"text": "<p>Quite simple</p>\n\n<pre><code>Type[] types = Assembly.Load(new AssemblyName(\"mynamespace.folder\")).GetTypes();\nforeach (var item in types)\n{\n}\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How do you get all the classes in a namespace through reflection in C#? | Following code prints names of classes in specified `namespace` defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.
```
string nspace = "...";
var q = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.IsClass && t.Namespace == nspace
select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));
``` |
79,709 | <p>I have a function inside a loop inside a function. The inner function acquires and stores a large vector of data in memory (as a global variable... I'm using "R" which is like "S-Plus"). The loop loops through a long list of data to be acquired. The outer function starts the process and passes in the list of datasets to be acquired.</p>
<pre><code>for (dataset in list_of_datasets) {
for (datachunk in dataset) {
<process datachunk>
<store result? as vector? where?>
}
}
</code></pre>
<p>I programmed the inner function to store each dataset before moving to the next, so all the work of the outer function occurs as side effects on global variables... a big no-no. Is this better or worse than collecting and returning a giant, memory-hogging vector of vectors? Is there a superior third approach?</p>
<p>Would the answer change if I were storing the data vectors in a database rather than in memory? Ideally, I'd like to be able to terminate the function (or have it fail due to network timeouts) without losing all the information processed prior to termination.</p>
| [
{
"answer_id": 79741,
"author": "Jeffrey",
"author_id": 3259,
"author_profile": "https://Stackoverflow.com/users/3259",
"pm_score": -1,
"selected": false,
"text": "<p>It's tough to say definitively without knowing the language/compiler used. However, if you can simply pass a pointer/reference to the object that you're creating, then the size of the object itself has nothing to do with the speed of the function calls. Manipulating this data down the road could be a different story.</p>\n"
},
{
"answer_id": 79768,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 3,
"selected": false,
"text": "<p>use variables in the outer function instead of global variables. This gets you the best of both approaches: you're not mutating global state, and you're not copying a big wad of data. If you have to exit early, just return the partial results.</p>\n\n<p>(See the \"Scope\" section in the R manual: <a href=\"http://cran.r-project.org/doc/manuals/R-intro.html#Scope\" rel=\"noreferrer\">http://cran.r-project.org/doc/manuals/R-intro.html#Scope</a>)</p>\n"
},
{
"answer_id": 79779,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 0,
"selected": false,
"text": "<p>Third approach: inner function returns a reference to the large array, which the next statement inside the loop then dereferences and stores wherever it's needed (ideally with a single pointer store and not by having to memcopy the entire array).</p>\n\n<p>This gets rid of both the side effect and the passing of large datastructures.</p>\n"
},
{
"answer_id": 79788,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>It's not going to make much difference to memory use, so you might as well make the code clean.</p>\n\n<p>Since R has copy-on-modify for variables, modifying the global object will have the same memory implications as passing something up in return values.</p>\n\n<p>If you store the outputs in a database (or even in a file) you won't have the memory use issues, and the data will be incrementally available as it is created, rather than just at the end. Whether it's faster with the database depends primarily on how much memory you are using: is the reduction is garbage collection going to pay for the cost of writing to disk.</p>\n\n<p>There are both time and memory profilers in R, so you can see empirically what the impacts are.</p>\n"
},
{
"answer_id": 79827,
"author": "leif",
"author_id": 14257,
"author_profile": "https://Stackoverflow.com/users/14257",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure I understand the question, but I have a couple of solutions.</p>\n\n<ol>\n<li><p>Inside the function, create a list of the vectors and return that.</p></li>\n<li><p>Inside the function, create an environment and store all the vectors inside of that. Just make sure that you return the environment in case of errors.</p></li>\n</ol>\n\n<p>in R:</p>\n\n<pre><code>help(environment)\n\n# You might do something like this:\n\nouter <- function(datasets) {\n # create the return environment\n ret.env <- new.env()\n for(set in dataset) {\n tmp <- inner(set)\n # check for errors however you like here. You might have inner return a list, and\n # have the list contain an error component\n assign(set, tmp, envir=ret.env)\n }\n return(ret.env)\n}\n\n#The inner function might be defined like this\n\ninner <- function(dataset) {\n # I don't know what you are doing here, but lets pretend you are reading a data file\n # that is named by dataset\n filedata <- read.table(dataset, header=T)\n return(filedata)\n}\n</code></pre>\n\n<p>leif</p>\n"
},
{
"answer_id": 79893,
"author": "Rob Hansen",
"author_id": 14928,
"author_profile": "https://Stackoverflow.com/users/14928",
"pm_score": 3,
"selected": false,
"text": "<p>Remember your Knuth. \"Premature optimization is the root of all programming evil.\"</p>\n\n<p>Try the side effect free version. See if it meets your performance goals. If it does, great, you don't have a problem in the first place; if it doesn't, then use the side effects, and make a note for the next programmer that your hand was forced.</p>\n"
},
{
"answer_id": 86804,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>FYI, here's a full sample toy solution that avoids side effects:</p>\n\n<pre><code>outerfunc <- function(names) {\n templist <- list()\n for (aname in names) {\n templist[[aname]] <- innerfunc(aname)\n }\n templist\n}\n\ninnerfunc <- function(aname) {\n retval <- NULL\n if (\"one\" %in% aname) retval <- c(1)\n if (\"two\" %in% aname) retval <- c(1,2)\n if (\"three\" %in% aname) retval <- c(1,2,3)\n retval\n}\n\nnames <- c(\"one\",\"two\",\"three\")\n\nname_vals <- outerfunc(names)\n\nfor (name in names) assign(name, name_vals[[name]])\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a function inside a loop inside a function. The inner function acquires and stores a large vector of data in memory (as a global variable... I'm using "R" which is like "S-Plus"). The loop loops through a long list of data to be acquired. The outer function starts the process and passes in the list of datasets to be acquired.
```
for (dataset in list_of_datasets) {
for (datachunk in dataset) {
<process datachunk>
<store result? as vector? where?>
}
}
```
I programmed the inner function to store each dataset before moving to the next, so all the work of the outer function occurs as side effects on global variables... a big no-no. Is this better or worse than collecting and returning a giant, memory-hogging vector of vectors? Is there a superior third approach?
Would the answer change if I were storing the data vectors in a database rather than in memory? Ideally, I'd like to be able to terminate the function (or have it fail due to network timeouts) without losing all the information processed prior to termination. | use variables in the outer function instead of global variables. This gets you the best of both approaches: you're not mutating global state, and you're not copying a big wad of data. If you have to exit early, just return the partial results.
(See the "Scope" section in the R manual: <http://cran.r-project.org/doc/manuals/R-intro.html#Scope>) |
79,737 | <p>This question may be too product specifc but I'd like to know if anyone is exporting bug track data from HP Quality Center.</p>
<p>HP Quality Center (QC) has an old school COM API but I'd rather use a web service or maybe even screen scraper to export the data into an excel spreadsheet.</p>
<p>In any case, what's the best way to export bug tracking data from hosted HP Quality Center?</p>
| [
{
"answer_id": 80813,
"author": "granth",
"author_id": 11210,
"author_profile": "https://Stackoverflow.com/users/11210",
"pm_score": 4,
"selected": true,
"text": "<p>You can use this QC API Code to modify bugs/requirements.</p>\n\n<pre><code>TDAPIOLELib.TDConnection connection = new TDAPIOLELib.TDConnection(); \nconnection.InitConnectionEx(\"http://SERVER:8080/qcbin\"); \nconnection.Login(\"USERNAME\", \"PASSWORD\"); \nconnection.Connect(\"QCDOMAIN\", \"QCPROJECT\"); \nTDAPIOLELib.BugFactory bugFactory = connection.BugFactory as TDAPIOLELib.BugFactory; \nTDAPIOLELib.List bugList = bugFactory.NewList(\"\"); \nforeach (TDAPIOLELib.Bug bug in bugList) \n{ \n // View / Modify the properties \n // bug.ID, bug.Name, etc. \n // Save them when done \n // bug.Post(); \n}\n</code></pre>\n"
},
{
"answer_id": 217898,
"author": "JonnyGold",
"author_id": 2665,
"author_profile": "https://Stackoverflow.com/users/2665",
"pm_score": 1,
"selected": false,
"text": "<p>Personally, I like the COM API and I use it to generate both Word and Excel reports. I have done some experiments with VS2005 and the results are encouraging.</p>\n\n<p>If you don't want to go this route, I have a couple of suggestions.</p>\n\n<ol>\n<li>If you use the charting options (Analysis > Graphs). Each graph has a tab called data grid that lets you export data to Excel and a bunch of other data formats.</li>\n<li>If you are an admin, or friendely with your admin, you can dump the whole database into access and then import into Excel. Of course, you'll loose all your table relationships, but it's better than nothing. It's also a really good way to learn the db schema.</li>\n</ol>\n"
},
{
"answer_id": 217944,
"author": "Tobias Kunze",
"author_id": 6070,
"author_profile": "https://Stackoverflow.com/users/6070",
"pm_score": 0,
"selected": false,
"text": "<p>If manual export (i.e., not using a program) is possible for you, the following will be the easiest way to export defect data.</p>\n\n<p>In QC 9.2 (maybe present in earlier versions, too), there is <code>Export/All</code> in the <code>Defects</code> menu, which exports defects in your defects grid into an Excel sheet.</p>\n\n<p>The fields exported are those shown in the defects grid, which can be customized using the \"Select Columns\" button (looks like a green grid).</p>\n"
},
{
"answer_id": 425057,
"author": "LiorH",
"author_id": 52954,
"author_profile": "https://Stackoverflow.com/users/52954",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately QC doesn't expose any web-services at the moment.\nI think the easiest way would be to query the DB directly. The data you are looking for is in the project's schema in BUG table.</p>\n\n<p>QC also have an excel add-in you might want to try that, but it's mainly for adding defects from excel to QC.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048/"
]
| This question may be too product specifc but I'd like to know if anyone is exporting bug track data from HP Quality Center.
HP Quality Center (QC) has an old school COM API but I'd rather use a web service or maybe even screen scraper to export the data into an excel spreadsheet.
In any case, what's the best way to export bug tracking data from hosted HP Quality Center? | You can use this QC API Code to modify bugs/requirements.
```
TDAPIOLELib.TDConnection connection = new TDAPIOLELib.TDConnection();
connection.InitConnectionEx("http://SERVER:8080/qcbin");
connection.Login("USERNAME", "PASSWORD");
connection.Connect("QCDOMAIN", "QCPROJECT");
TDAPIOLELib.BugFactory bugFactory = connection.BugFactory as TDAPIOLELib.BugFactory;
TDAPIOLELib.List bugList = bugFactory.NewList("");
foreach (TDAPIOLELib.Bug bug in bugList)
{
// View / Modify the properties
// bug.ID, bug.Name, etc.
// Save them when done
// bug.Post();
}
``` |
79,745 | <p>We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available.</p>
| [
{
"answer_id": 79801,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 0,
"selected": false,
"text": "<p>According to the DirectX 9.0 SDK (summer 2004) documentation, see the GetDXVer SDK sample at \\Samples\\Multimedia\\DXMisc\\GetDXVer.</p>\n"
},
{
"answer_id": 79817,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Call DirectXSetupGetVersion: <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion</a></p>\n\n<p>You'll need to include dsetup.h</p>\n\n<p>Here's the sample code from the site:</p>\n\n<pre><code>DWORD dwVersion;\nDWORD dwRevision;\nif (DirectXSetupGetVersion(&dwVersion, &dwRevision))\n{\n printf(\"DirectX version is %d.%d.%d.%d\\n\",\n HIWORD(dwVersion), LOWORD(dwVersion),\n HIWORD(dwRevision), LOWORD(dwRevision));\n}\n</code></pre>\n"
},
{
"answer_id": 79887,
"author": "kooshmoose",
"author_id": 7436,
"author_profile": "https://Stackoverflow.com/users/7436",
"pm_score": 0,
"selected": false,
"text": "<p>A quick Google search turns up <a href=\"http://www.codersource.net/win32_registry_operations.html\" rel=\"nofollow noreferrer\">this article</a> which identifies the location of the version number in the registry and then provides a case statement which maps the internal version number to the version number we're more familiar with.</p>\n\n<p>Another quick Google search turns up an example in C++ for <a href=\"http://www.codersource.net/win32_registry_operations.html\" rel=\"nofollow noreferrer\">reading from the registry</a>.</p>\n\n<p>Enjoy...</p>\n"
},
{
"answer_id": 1141111,
"author": "legalize",
"author_id": 139855,
"author_profile": "https://Stackoverflow.com/users/139855",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, use the mechanism shown in the DirectX Install sample in the March 2009 DirectX SDK. (Look under \"System\" category in the sample browser.)</p>\n\n<p>Do not use the registry! That stuff is undocumented and not guaranteed to work.</p>\n\n<p>The only supported way is to use the DirectSetup API, which is shown in the DirectX Install sample. I also cover this stuff in Chapter 24. Installation and Setup in my book <a href=\"http://www.xmission.com/~legalize/book/download/\" rel=\"nofollow noreferrer\">The Direct3D Graphics Pipeline</a>. You can download that chapter for free at the above URL.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5022/"
]
| We have an application which needs to use Direct3D. Specifically, it needs at least DirectX 9.0c version 4.09.0000.0904. While this should be present on all newer XP machines it might not be installed on older XP machines. How can I programmatically (using C++) determine if it is installed? I want to be able to give an information message to the user that Direct3D will not be available. | Call DirectXSetupGetVersion: <http://msdn.microsoft.com/en-us/library/microsoft.directx_sdk.directsetup.directxsetupgetversion>
You'll need to include dsetup.h
Here's the sample code from the site:
```
DWORD dwVersion;
DWORD dwRevision;
if (DirectXSetupGetVersion(&dwVersion, &dwRevision))
{
printf("DirectX version is %d.%d.%d.%d\n",
HIWORD(dwVersion), LOWORD(dwVersion),
HIWORD(dwRevision), LOWORD(dwRevision));
}
``` |
79,754 | <p>No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.</p>
<pre><code>IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
</code></pre>
| [
{
"answer_id": 79826,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 3,
"selected": false,
"text": "<p>Don't try to run <code>unittest.main()</code> from IDLE. It's trying to access <code>sys.argv</code>, and it's getting the args that IDLE was started with. Either run your tests in a different way from IDLE, or call <code>unittest.main()</code> in its own Python process.</p>\n"
},
{
"answer_id": 79833,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 5,
"selected": true,
"text": "<p>Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing</p>\n\n<pre><code>unittest.main()\n</code></pre>\n\n<p>to</p>\n\n<pre><code>unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))\n</code></pre>\n\n<p>More information is available <a href=\"http://docs.python.org/library/unittest.html#basic-example\" rel=\"noreferrer\">here</a> in the Python Library Reference.</p>\n"
},
{
"answer_id": 79932,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 3,
"selected": false,
"text": "<p>Pop open the source code to <code>unittest.py</code>. <code>unittest.main()</code> is hard-coded to call <code>sys.exit()</code> after running all tests. Use <code>TextTestRunner</code> to run test suites from the prompt.</p>\n"
},
{
"answer_id": 407950,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>try:\n sys.exit()\nexcept SystemExit:\n print('Simple as that, but you should really use a TestRunner instead')\n</code></pre>\n"
},
{
"answer_id": 3215505,
"author": "dmeister",
"author_id": 4194,
"author_profile": "https://Stackoverflow.com/users/4194",
"pm_score": 5,
"selected": false,
"text": "<p>In new Python 2.7 release, <a href=\"http://docs.python.org/library/unittest.html#unittest.main\" rel=\"noreferrer\">unittest.main()</a> has a new argument.</p>\n\n<p>If 'exit' is set to <code>False</code>, <code>sys.exit()</code> is not called during the execution of <code>unittest.main()</code>.</p>\n"
},
{
"answer_id": 21262077,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 3,
"selected": false,
"text": "<p>It's nice to be able to demonstrate that your tests work when first trying out the unittest module, and to know that you won't exit your Python shell. However, these solutions are version dependent.</p>\n\n<h2>Python 2.6</h2>\n\n<p>I'm using Python 2.6 at work, <code>import</code>ing <code>unittest2 as unittest</code> (which is the <code>unittest</code> module supposedly found in Python 2.7). </p>\n\n<p>The <code>unittest.main(exit=False)</code> doesn't work in Python 2.6's unittest2, while JoeSkora's solution does, and to reiterate it:</p>\n\n<pre><code>unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))\n</code></pre>\n\n<p>To break this down into its components and default arguments, with correct semantic names for the various composed objects:</p>\n\n<pre><code>import sys # sys.stderr is used in below default args\n\ntest_loader = unittest.TestLoader()\nloaded_test_suite = test_loader.loadTestsFromTestCase(Test)\n # Default args:\ntext_test_runner = unittest.TextTestRunner(stream=sys.stderr,\n descriptions=True, \n verbosity=1)\ntext_test_runner.run(loaded_test_suite)\n</code></pre>\n\n<h2>Python 2.7 and 3</h2>\n\n<p>In Python 2.7 and higher, the following should work.</p>\n\n<pre><code>unittest.main(exit=False)\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176/"
]
| No matter what I do sys.exit() is called by unittest, even the most trivial examples. I can't tell if my install is messed up or what is going on.
```
IDLE 1.2.2 ==== No Subprocess ====
>>> import unittest
>>>
>>> class Test(unittest.TestCase):
def testA(self):
a = 1
self.assertEqual(a,1)
>>> unittest.main()
option -n not recognized
Usage: idle.pyw [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
idle.pyw - run default set of tests
idle.pyw MyTestSuite - run suite 'MyTestSuite'
idle.pyw MyTestCase.testSomething - run MyTestCase.testSomething
idle.pyw MyTestCase - run all 'test*' test methods
in MyTestCase
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
unittest.main()
File "E:\Python25\lib\unittest.py", line 767, in __init__
self.parseArgs(argv)
File "E:\Python25\lib\unittest.py", line 796, in parseArgs
self.usageExit(msg)
File "E:\Python25\lib\unittest.py", line 773, in usageExit
sys.exit(2)
SystemExit: 2
>>>
``` | Your example is exiting on my install too. I can make it execute the tests and stay within Python by changing
```
unittest.main()
```
to
```
unittest.TextTestRunner().run(unittest.TestLoader().loadTestsFromTestCase(Test))
```
More information is available [here](http://docs.python.org/library/unittest.html#basic-example) in the Python Library Reference. |
79,774 | <p>Ok - a bit of a mouthful. So the problem I have is this - I need to store a Date for expiry where <em>only</em> the date part is required and I don't want any timezone conversion. So for example if I have an expiry set to "08 March 2008" I want that value to be returned to any client - no matter what their timezone is.
The problem with remoting it as a DateTime is that it gets stored/sent as "08 March 2008 00:00", which means for clients connecting from any timezone West of me it gets converted and therefore flipped to "07 March 2008"
Any suggestions for cleanly handling this scenario ? Obviously sending it as a string would work. anything else ?
thanks,
Ian</p>
| [
{
"answer_id": 79792,
"author": "Yitzchok",
"author_id": 5723,
"author_profile": "https://Stackoverflow.com/users/5723",
"pm_score": 0,
"selected": false,
"text": "<p>You can send it as UTC Time</p>\n\n<p>dateTime1.ToUniversalTime()</p>\n"
},
{
"answer_id": 79810,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I think sending as a timestamp string would be the quickest / easiest way although you could look at forcing a locale to stop the time conversion from occuring.</p>\n"
},
{
"answer_id": 79837,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 1,
"selected": true,
"text": "<p>You could create a struct Date that provides access to the details you want/need, like:</p>\n\n<pre><code>public struct Date\n{\n public int Month; //or string instead of int\n public int Day;\n public int Year;\n}\n</code></pre>\n\n<p>This is lightweight, flexible and gives you full control.</p>\n"
},
{
"answer_id": 79839,
"author": "Brettski",
"author_id": 5836,
"author_profile": "https://Stackoverflow.com/users/5836",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you send it as a string then convert it back to a date type as needed? This way it will not be converted over different timezones. Keep it simple.</p>\n\n<p>Edit: I like the Struct idea, allows for good functionality. </p>\n"
},
{
"answer_id": 80059,
"author": "Jonathan Rupp",
"author_id": 12502,
"author_profile": "https://Stackoverflow.com/users/12502",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way I've handled this on apps in the past is to just store the date as a string in yyyy-mm-dd format. It's unambigious and doesn't get automatically translated by anything.</p>\n\n<p>Yes, it's a pain...</p>\n"
},
{
"answer_id": 80764,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure what remoting technology you're referring to, but this is a real problem with WCF, which only currently supports serializing DateTime as xs:DateTime, inappropriate for a date-only value where you are not interested in timezones.</p>\n\n<p>.NET 3.5 introduces the new DateTimeOffset type, which is good for transferring a DateTime between timezones, but doesn't help with the date-only scenario.</p>\n\n<p>Ideally WCF needs to optionally support xs:Date for serializing dates as requested here:</p>\n\n<p><a href=\"http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=349215\" rel=\"nofollow noreferrer\">http://connect.microsoft.com/wcf/feedback/ViewFeedback.aspx?FeedbackID=349215</a></p>\n"
},
{
"answer_id": 81958,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 1,
"selected": false,
"text": "<p>I do it like this: Whenever I have a date in memory or stored in a file it is always in a DateTime in UTC. When I show the date to the user it is always a string. When I convert between the string and the DateTime I also do the time zone conversion.</p>\n\n<p>This way I never have to deal with time zones in my logic, only in the presentation.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14871/"
]
| Ok - a bit of a mouthful. So the problem I have is this - I need to store a Date for expiry where *only* the date part is required and I don't want any timezone conversion. So for example if I have an expiry set to "08 March 2008" I want that value to be returned to any client - no matter what their timezone is.
The problem with remoting it as a DateTime is that it gets stored/sent as "08 March 2008 00:00", which means for clients connecting from any timezone West of me it gets converted and therefore flipped to "07 March 2008"
Any suggestions for cleanly handling this scenario ? Obviously sending it as a string would work. anything else ?
thanks,
Ian | You could create a struct Date that provides access to the details you want/need, like:
```
public struct Date
{
public int Month; //or string instead of int
public int Day;
public int Year;
}
```
This is lightweight, flexible and gives you full control. |
79,780 | <p>I've had a new found interest in building a small, efficient web server in C and have had some trouble parsing POST methods from the HTTP Header. Would anyone have any advice as to how to handle retrieving the name/value pairs from the "posted" data?</p>
<pre><code>POST /test HTTP/1.1
Host: test-domain.com:7017
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://test-domain.com:7017/index.html
Cookie: __utma=43166241.217413299.1220726314.1221171690.1221200181.16; __utmz=43166241.1220726314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
field1=asfd&field2=a3f3f3
// ^-this
</code></pre>
<p>I see no tangible way to retrieve the bottom line as a whole and ensure that it works every time. I'm not a fan of hard-coding in anything.</p>
| [
{
"answer_id": 79812,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 5,
"selected": true,
"text": "<p>You can retrieve the name/value pairs by searching for newline newline or more specifically \\r\\n\\r\\n (after this, the body of the message will start).</p>\n<p>Then you can simply split the list by the &, and then split each of those returned strings between the = for name/value pairs.</p>\n<p>See the <a href=\"https://www.rfc-editor.org/rfc/rfc2616\" rel=\"nofollow noreferrer\">HTTP 1.1 RFC</a>.</p>\n"
},
{
"answer_id": 79836,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 2,
"selected": false,
"text": "<p>You need to keep parsing the stream as headers until you see the blank line. The rest is the POST data.</p>\n\n<p>You need to write a little parser for the post data. You can use C library routines to do something quick and dirty, like index, strtok, and sscanf. If you have room for it in your definition of \"small\", you could do something more elaborate with a regular expression library, or even with flex and bison.</p>\n\n<p>At least, I think this kind of answers your question.</p>\n"
},
{
"answer_id": 386101,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Once you have Content-Length in the header, you know the amount of bytes to be read right after the blank line. If, for any reason (GET or POST) Content-Length is not in the header, it means there's nothing to read after the blank line (crlf).</p>\n"
},
{
"answer_id": 47447856,
"author": "Oliver",
"author_id": 2984198,
"author_profile": "https://Stackoverflow.com/users/2984198",
"pm_score": 0,
"selected": false,
"text": "<p>IETF RFC notwithstanding, here is a more to the point answer. Assuming that you realize that there is always an extra <code>/r/n</code> after the <code>Content-Length</code> line in the header, you should be able to do the work to isolate it into a <code>char*</code> variable named <code>data</code>. This is where we start.</p>\n\n<pre><code>char *data = \"f1=asfd&f2=a3f3f3\";\nchar f1[100], \nchar f2[100];\nsscanf(data, \"%s&%s\", &f1, &f2); // get the field tuples\n\nchar f1_name[50];\nchar f1_data[50];\nsscanf(f1, \"%s=%s\", f1_name, f1_data); \n\nchar f2_name[50];\nchar f2_data[50];\nsscanf(f2, \"%s=%s\", f2_name, f2_data); \n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14877/"
]
| I've had a new found interest in building a small, efficient web server in C and have had some trouble parsing POST methods from the HTTP Header. Would anyone have any advice as to how to handle retrieving the name/value pairs from the "posted" data?
```
POST /test HTTP/1.1
Host: test-domain.com:7017
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://test-domain.com:7017/index.html
Cookie: __utma=43166241.217413299.1220726314.1221171690.1221200181.16; __utmz=43166241.1220726314.1.1.utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 25
field1=asfd&field2=a3f3f3
// ^-this
```
I see no tangible way to retrieve the bottom line as a whole and ensure that it works every time. I'm not a fan of hard-coding in anything. | You can retrieve the name/value pairs by searching for newline newline or more specifically \r\n\r\n (after this, the body of the message will start).
Then you can simply split the list by the &, and then split each of those returned strings between the = for name/value pairs.
See the [HTTP 1.1 RFC](https://www.rfc-editor.org/rfc/rfc2616). |
79,789 | <p>I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day.</p>
<p>For example, if Alice worked a job from 15:30 to 19:30 and Bob worked from 12:15 to 17:00, the chart would look like this:</p>
<p><a href="https://i.stack.imgur.com/HHrs0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HHrs0.png" alt="Example Chart"></a></p>
<p>I have a WTFey solution right now that involves a spreadsheet going out to column DY or something like that. The needed resolution is 15-minute intervals.</p>
<p>I'm assuming this is something best done in the database then exported for chart creation. Let me know if I'm missing any details. Thanks.</p>
| [
{
"answer_id": 80125,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I came up with a pseudocode solution, hope it helps.</p>\n\n<pre><code>create an array named timetable with 24 entries\ninitialise timetable to zero\n\nfor each user in SQLtable\n firsthour = user.firsthour\n lasthour = user.lasthour\n\n firstminutes = 4 - (rounded down integer(user.firstminutes/15))\n lastminutes = rounded down integer(user.lastminutes/15)\n\n timetable(firsthour) = timetable(firsthour) + firstminutes\n timetable(lasthour) = timetable(lasthour) + lastminutes\n\n for index=firsthour+1 to lasthour-1\n timetable(index) = timetable(index) + 4\n next index\n\nnext user\n</code></pre>\n\n<p>Now the timetable array holds the values you desire in 15 minute granularity, ie. a value of 4 = 1 hour, 5 = 1 hour 15 minutes, 14 = 3 hours 30 minutes.</p>\n"
},
{
"answer_id": 80134,
"author": "Mike Farmer",
"author_id": 4082,
"author_profile": "https://Stackoverflow.com/users/4082",
"pm_score": 3,
"selected": true,
"text": "<p>Create a table with just time in it from midnight to midnight containing each minute of the day. In the data warehouse world we would call this a time dimension. Here's an example:</p>\n\n<pre><code>TIME_DIM\n -id\n -time_of_day\n -interval_15 \n -interval_30\n</code></pre>\n\n<p>an example of the data in the table would be</p>\n\n<pre><code>id time_of_day interval_15 interval_30\n1 00:00 00:00 00:00\n...\n30 00:23 00:15 00:00\n...\n100 05:44 05:30 05:30\n</code></pre>\n\n<p>Then all you have to do is join your table to the time dimension and then group by interval_15. For example:</p>\n\n<pre><code>SELECT b.interval_15, count(*) \nFROM my_data_table a\nINNER JOIN time_dim b ON a.time_field = b.time\nWHERE a.date_field = now()\nGROUP BY b.interval_15\n</code></pre>\n"
},
{
"answer_id": 80155,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 0,
"selected": false,
"text": "<p>Here's another pseudocode solution from a different angle; a bit more intensive because it does 96 queries for every 24hr period:</p>\n\n<pre><code>results = []\nfor time in range(0, 24, .25):\n amount = mysql(\"select count(*) from User_Activity_Table where time >= start_time and time <= end_time\")\n results.append(amount)\n</code></pre>\n"
},
{
"answer_id": 81667,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 0,
"selected": false,
"text": "<p>How about this:</p>\n\n<p>Use that \"times\" table, but with two columns, containing the 15-minute intervals. The from_times are the 15-minutely times, the to_times are a second before the next from_times. For example 12:30:00 to 12:44:59.</p>\n\n<p>Now get your person work table, which I've called \"activity\" here, with start_time and end_time columns.</p>\n\n<p>I added values for Alice and Bob as per the original question.</p>\n\n<p>Here's the query from MySQL:</p>\n\n<pre><code>SELECT HOUR(times.from_time) AS 'TIME', count(*) / 4 AS 'HOURS'\nFROM times\n JOIN activity\n ON times.from_time >= activity.start_time AND \n times.to_time <= activity.end_time\nGROUP BY HOUR(times.from_time)\nORDER BY HOUR(times.from_time)\n</code></pre>\n\n<p>which gives me this:</p>\n\n<pre><code>TIME HOURS\n12 0.7500\n13 1.0000\n14 1.0000\n15 1.5000\n16 2.0000\n17 1.0000\n18 1.0000\n19 0.7500\n</code></pre>\n\n<p>Looks about right...</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9867/"
]
| I have a list of timesheet entries that show a start and stop time. This is sitting in a MySQL database. I need to create bar charts based on this data with the 24 hours of the day along the bottom and the amount of man-hours worked for each hour of the day.
For example, if Alice worked a job from 15:30 to 19:30 and Bob worked from 12:15 to 17:00, the chart would look like this:
[](https://i.stack.imgur.com/HHrs0.png)
I have a WTFey solution right now that involves a spreadsheet going out to column DY or something like that. The needed resolution is 15-minute intervals.
I'm assuming this is something best done in the database then exported for chart creation. Let me know if I'm missing any details. Thanks. | Create a table with just time in it from midnight to midnight containing each minute of the day. In the data warehouse world we would call this a time dimension. Here's an example:
```
TIME_DIM
-id
-time_of_day
-interval_15
-interval_30
```
an example of the data in the table would be
```
id time_of_day interval_15 interval_30
1 00:00 00:00 00:00
...
30 00:23 00:15 00:00
...
100 05:44 05:30 05:30
```
Then all you have to do is join your table to the time dimension and then group by interval\_15. For example:
```
SELECT b.interval_15, count(*)
FROM my_data_table a
INNER JOIN time_dim b ON a.time_field = b.time
WHERE a.date_field = now()
GROUP BY b.interval_15
``` |
79,797 | <p>How do I convert a datetime <em>string in local time</em> to a <em>string in UTC time</em>?</p>
<p>I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.</p>
<p><strong>Clarification</strong>: For example, if I have <code>2008-09-17 14:02:00</code> in my local timezone (<code>+10</code>), I'd like to generate a string with the equivalent <code>UTC</code> time: <code>2008-09-17 04:02:00</code>.</p>
<p>Also, from <a href="http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/" rel="noreferrer">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time.</p>
| [
{
"answer_id": 79808,
"author": "Chuck Callebs",
"author_id": 14877,
"author_profile": "https://Stackoverflow.com/users/14877",
"pm_score": 5,
"selected": false,
"text": "<pre><code>def local_to_utc(t):\n secs = time.mktime(t)\n return time.gmtime(secs)\n\ndef utc_to_local(t):\n secs = calendar.timegm(t)\n return time.localtime(secs)\n</code></pre>\n\n<p>Source: <a href=\"http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html\" rel=\"nofollow noreferrer\">http://feihonghsu.blogspot.com/2008/02/converting-from-local-time-to-utc.html</a></p>\n\n<p>Example usage from <a href=\"https://stackoverflow.com/users/8171/bd808\">bd808</a>: If your source is a <code>datetime.datetime</code> object <code>t</code>, call as:</p>\n\n<pre><code>local_to_utc(t.timetuple())\n</code></pre>\n"
},
{
"answer_id": 79877,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 9,
"selected": false,
"text": "<p>First, parse the string into a naive datetime object. This is an instance of <code>datetime.datetime</code> with no attached timezone information. See its <a href=\"https://docs.python.org/3/library/datetime.html#available-types\" rel=\"noreferrer\">documentation</a>.</p>\n<p>Use the <a href=\"http://pytz.sourceforge.net/\" rel=\"noreferrer\"><code>pytz</code></a> module, which comes with a full list of time zones + UTC. Figure out what the local timezone is, construct a timezone object from it, and manipulate and attach it to the naive datetime.</p>\n<p>Finally, use <code>datetime.astimezone()</code> method to convert the datetime to UTC.</p>\n<p>Source code, using local timezone "America/Los_Angeles", for the string "2001-2-3 10:11:12":</p>\n<pre><code>from datetime import datetime \nimport pytz\n\nlocal = pytz.timezone("America/Los_Angeles")\nnaive = datetime.strptime("2001-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")\nlocal_dt = local.localize(naive, is_dst=None)\nutc_dt = local_dt.astimezone(pytz.utc)\n</code></pre>\n<p>From there, you can use the <code>strftime()</code> method to format the UTC datetime as needed:</p>\n<pre><code>utc_dt.strftime("%Y-%m-%d %H:%M:%S")\n</code></pre>\n"
},
{
"answer_id": 79913,
"author": "Tom",
"author_id": 3715,
"author_profile": "https://Stackoverflow.com/users/3715",
"pm_score": 7,
"selected": true,
"text": "<p>Thanks @rofly, the full conversion from string to string is as follows:</p>\n<pre><code>import time\ntime.strftime("%Y-%m-%d %H:%M:%S", \n time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00", \n "%Y-%m-%d %H:%M:%S"))))\n</code></pre>\n<p>My summary of the <code>time</code>/<code>calendar</code> functions:</p>\n<p><code>time.strptime</code><br />\nstring --> tuple (no timezone applied, so matches string)</p>\n<p><code>time.mktime</code><br />\nlocal time tuple --> seconds since epoch (always local time)</p>\n<p><code>time.gmtime</code><br />\nseconds since epoch --> tuple in UTC</p>\n<p>and</p>\n<p><code>calendar.timegm</code><br />\ntuple in UTC --> seconds since epoch</p>\n<p><code>time.localtime</code><br />\nseconds since epoch --> tuple in local timezone</p>\n"
},
{
"answer_id": 1464261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>How about - </p>\n\n<pre><code>time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime(seconds))\n</code></pre>\n\n<p>if seconds is <code>None</code> then it converts the local time to UTC time else converts the passed in time to UTC.</p>\n"
},
{
"answer_id": 2175170,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 8,
"selected": false,
"text": "<p><strong>NOTE</strong> -- As of 2020 you should not be using <code>.utcnow()</code> or <code>.utcfromtimestamp(xxx)</code>. As you've presumably moved on to python3,you should be using timezone aware datetime objects.</p>\n<pre><code>>>> from datetime import timezone\n>>> \n>>> # alternative to '.utcnow()'\n>>> dt_now = datetime.datetime.now(datetime.timezone.utc)\n>>>\n>>> # alternative to '.utcfromtimestamp()'\n>>> dt_ts = datetime.fromtimestamp(1571595618.0, tz=timezone.utc)\n</code></pre>\n<p>For details see: <a href=\"https://blog.ganssle.io/articles/2019/11/utcnow.html\" rel=\"noreferrer\">https://blog.ganssle.io/articles/2019/11/utcnow.html</a></p>\n<h2>original answer (from 2010):</h2>\n<p>The datetime module's <a href=\"http://docs.python.org/library/datetime.html#datetime.datetime.utcnow\" rel=\"noreferrer\">utcnow()</a> function can be used to obtain the current UTC time.</p>\n<pre><code>>>> import datetime\n>>> utc_datetime = datetime.datetime.utcnow()\n>>> utc_datetime.strftime("%Y-%m-%d %H:%M:%S")\n'2010-02-01 06:59:19'\n</code></pre>\n<p>As the link mentioned above by Tom: <a href=\"http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/\" rel=\"noreferrer\">http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/</a> says:</p>\n<blockquote>\n<p>UTC is a timezone without daylight saving time and still a timezone\nwithout configuration changes in the past.</p>\n<p><em>Always measure and store time in UTC</em>.</p>\n<p>If you need to record where the time was taken, store that separately.\n<em><strong>Do not</strong> store the local time + timezone information!</em></p>\n</blockquote>\n<p><strong>NOTE</strong> - If any of your data is in a region that uses DST, use <code>pytz</code> and take a look at John Millikin's answer.</p>\n<p>If you want to obtain the UTC time from a given string and your lucky enough to be in a region in the world that either doesn't use DST, or you have data that is only offset from UTC without DST applied:</p>\n<p>--> using local time as the basis for the offset value:</p>\n<pre><code>>>> # Obtain the UTC Offset for the current system:\n>>> UTC_OFFSET_TIMEDELTA = datetime.datetime.utcnow() - datetime.datetime.now()\n>>> local_datetime = datetime.datetime.strptime("2008-09-17 14:04:00", "%Y-%m-%d %H:%M:%S")\n>>> result_utc_datetime = local_datetime + UTC_OFFSET_TIMEDELTA\n>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")\n'2008-09-17 04:04:00'\n</code></pre>\n<p>--> Or, from a known offset, using datetime.timedelta():</p>\n<pre><code>>>> UTC_OFFSET = 10\n>>> result_utc_datetime = local_datetime - datetime.timedelta(hours=UTC_OFFSET)\n>>> result_utc_datetime.strftime("%Y-%m-%d %H:%M:%S")\n'2008-09-17 04:04:00'\n</code></pre>\n<p>UPDATE:</p>\n<p>Since python 3.2 <code>datetime.timezone</code> is available. You can generate a timezone aware datetime object with the command below:</p>\n<pre><code>import datetime\n\ntimezone_aware_dt = datetime.datetime.now(datetime.timezone.utc)\n</code></pre>\n<p>If your ready to take on timezone conversions go read this:</p>\n<p><a href=\"https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7\" rel=\"noreferrer\">https://medium.com/@eleroy/10-things-you-need-to-know-about-date-and-time-in-python-with-datetime-pytz-dateutil-timedelta-309bfbafb3f7</a></p>\n"
},
{
"answer_id": 2347991,
"author": "user235042",
"author_id": 235042,
"author_profile": "https://Stackoverflow.com/users/235042",
"pm_score": 3,
"selected": false,
"text": "<p>if you prefer datetime.datetime:</p>\n\n<pre><code>dt = datetime.strptime(\"2008-09-17 14:04:00\",\"%Y-%m-%d %H:%M:%S\")\nutc_struct_time = time.gmtime(time.mktime(dt.timetuple()))\nutc_dt = datetime.fromtimestamp(time.mktime(utc_struct_time))\nprint dt.strftime(\"%Y-%m-%d %H:%M:%S\")\n</code></pre>\n"
},
{
"answer_id": 4113872,
"author": "Mohammad Efazati",
"author_id": 471397,
"author_profile": "https://Stackoverflow.com/users/471397",
"pm_score": -1,
"selected": false,
"text": "<p>How about - </p>\n\n<pre><code>time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime(seconds))\n</code></pre>\n\n<p>if seconds is <code>None</code> then it converts the local time to UTC time else converts the passed in time to UTC.</p>\n"
},
{
"answer_id": 4894920,
"author": "Scipythonee",
"author_id": 600738,
"author_profile": "https://Stackoverflow.com/users/600738",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import time\n\nimport datetime\n\ndef Local2UTC(LocalTime):\n\n EpochSecond = time.mktime(LocalTime.timetuple())\n utcTime = datetime.datetime.utcfromtimestamp(EpochSecond)\n\n return utcTime\n\n>>> LocalTime = datetime.datetime.now()\n\n>>> UTCTime = Local2UTC(LocalTime)\n\n>>> LocalTime.ctime()\n\n'Thu Feb 3 22:33:46 2011'\n\n>>> UTCTime.ctime()\n\n'Fri Feb 4 05:33:46 2011'\n</code></pre>\n"
},
{
"answer_id": 8068619,
"author": "Dantalion",
"author_id": 384779,
"author_profile": "https://Stackoverflow.com/users/384779",
"pm_score": 2,
"selected": false,
"text": "<p>For getting around day-light saving, etc.</p>\n\n<p>None of the above answers particularly helped me. The code below works for GMT.</p>\n\n<pre><code>def get_utc_from_local(date_time, local_tz=None):\n assert date_time.__class__.__name__ == 'datetime'\n if local_tz is None:\n local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, \"Europe/London\"\n local_time = local_tz.normalize(local_tz.localize(date_time))\n return local_time.astimezone(pytz.utc)\n\nimport pytz\nfrom datetime import datetime\n\nsummer_11_am = datetime(2011, 7, 1, 11)\nget_utc_from_local(summer_11_am)\n>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)\n\nwinter_11_am = datetime(2011, 11, 11, 11)\nget_utc_from_local(winter_11_am)\n>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)\n</code></pre>\n"
},
{
"answer_id": 8563126,
"author": "Yarin",
"author_id": 165673,
"author_profile": "https://Stackoverflow.com/users/165673",
"pm_score": 5,
"selected": false,
"text": "<p>I'm having good luck with <a href=\"http://labix.org/python-dateutil\" rel=\"noreferrer\">dateutil</a> (which is widely recommended on SO for other related questions):</p>\n\n<pre><code>from datetime import *\nfrom dateutil import *\nfrom dateutil.tz import *\n\n# METHOD 1: Hardcode zones:\nutc_zone = tz.gettz('UTC')\nlocal_zone = tz.gettz('America/Chicago')\n# METHOD 2: Auto-detect zones:\nutc_zone = tz.tzutc()\nlocal_zone = tz.tzlocal()\n\n# Convert time string to datetime\nlocal_time = datetime.strptime(\"2008-09-17 14:02:00\", '%Y-%m-%d %H:%M:%S')\n\n# Tell the datetime object that it's in local time zone since \n# datetime objects are 'naive' by default\nlocal_time = local_time.replace(tzinfo=local_zone)\n# Convert time to UTC\nutc_time = local_time.astimezone(utc_zone)\n# Generate UTC time string\nutc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S')\n</code></pre>\n\n<p>(Code was derived from this answer to <a href=\"https://stackoverflow.com/a/4771733/165673\">Convert UTC datetime string to local datetime</a>)</p>\n"
},
{
"answer_id": 10040725,
"author": "Paulius Sladkevičius",
"author_id": 1316954,
"author_profile": "https://Stackoverflow.com/users/1316954",
"pm_score": 4,
"selected": false,
"text": "<p>One more example with pytz, but includes localize(), which saved my day.</p>\n\n<pre><code>import pytz, datetime\nutc = pytz.utc\nfmt = '%Y-%m-%d %H:%M:%S'\namsterdam = pytz.timezone('Europe/Amsterdam')\n\ndt = datetime.datetime.strptime(\"2012-04-06 10:00:00\", fmt)\nam_dt = amsterdam.localize(dt)\nprint am_dt.astimezone(utc).strftime(fmt)\n'2012-04-06 08:00:00'\n</code></pre>\n"
},
{
"answer_id": 12059267,
"author": "Cristian Salamea",
"author_id": 218604,
"author_profile": "https://Stackoverflow.com/users/218604",
"pm_score": 2,
"selected": false,
"text": "<p>You can do it with:</p>\n\n<pre><code>>>> from time import strftime, gmtime, localtime\n>>> strftime('%H:%M:%S', gmtime()) #UTC time\n>>> strftime('%H:%M:%S', localtime()) # localtime\n</code></pre>\n"
},
{
"answer_id": 12186921,
"author": "Shu Wu",
"author_id": 1084497,
"author_profile": "https://Stackoverflow.com/users/1084497",
"pm_score": 4,
"selected": false,
"text": "<p>I've had the most success with <a href=\"https://dateutil.readthedocs.org/en/latest/relativedelta.html\" rel=\"noreferrer\">python-dateutil</a>:</p>\n\n<pre><code>from dateutil import tz\n\ndef datetime_to_utc(date):\n \"\"\"Returns date in UTC w/o tzinfo\"\"\"\n return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date\n</code></pre>\n"
},
{
"answer_id": 13084428,
"author": "akaihola",
"author_id": 15770,
"author_profile": "https://Stackoverflow.com/users/15770",
"pm_score": 5,
"selected": false,
"text": "<p>Here's a summary of common Python time conversions.</p>\n\n<p>Some methods drop fractions of seconds, and are marked with <em>(s)</em>. An explicit formula such as <code>ts = (d - epoch) / unit</code> can be used instead (thanks jfs).</p>\n\n<ul>\n<li>struct_time (UTC) → POSIX <em>(s)</em>:<br><code>calendar.timegm(struct_time)</code></li>\n<li>Naïve datetime (local) → POSIX <em>(s)</em>:<br><code>calendar.timegm(stz.localize(dt, is_dst=None).utctimetuple())</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → POSIX <em>(s)</em>:<br><code>calendar.timegm(dt.utctimetuple())</code></li>\n<li>Aware datetime → POSIX <em>(s)</em>:<br><code>calendar.timegm(dt.utctimetuple())</code></li>\n<li>POSIX → struct_time (UTC, <em>s</em>):<br><code>time.gmtime(t)</code><br>(see comment from jfs)</li>\n<li>Naïve datetime (local) → struct_time (UTC, <em>s</em>):<br><code>stz.localize(dt, is_dst=None).utctimetuple()</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → struct_time (UTC, <em>s</em>):<br><code>dt.utctimetuple()</code></li>\n<li>Aware datetime → struct_time (UTC, <em>s</em>):<br><code>dt.utctimetuple()</code></li>\n<li>POSIX → Naïve datetime (local):<br><code>datetime.fromtimestamp(t, None)</code><br>(may fail in certain conditions, see comment from jfs below)</li>\n<li>struct_time (UTC) → Naïve datetime (local, <em>s</em>):<br><code>datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz).replace(tzinfo=None)</code><br>(can't represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → Naïve datetime (local):<br><code>dt.replace(tzinfo=UTC).astimezone(tz).replace(tzinfo=None)</code></li>\n<li>Aware datetime → Naïve datetime (local):<br><code>dt.astimezone(tz).replace(tzinfo=None)</code></li>\n<li>POSIX → Naïve datetime (UTC):<br><code>datetime.utcfromtimestamp(t)</code></li>\n<li>struct_time (UTC) → Naïve datetime (UTC, <em>s</em>):<br><code>datetime.datetime(*struct_time[:6])</code><br>(can't represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (local) → Naïve datetime (UTC):<br><code>stz.localize(dt, is_dst=None).astimezone(UTC).replace(tzinfo=None)</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Aware datetime → Naïve datetime (UTC):<br><code>dt.astimezone(UTC).replace(tzinfo=None)</code></li>\n<li>POSIX → Aware datetime:<br><code>datetime.fromtimestamp(t, tz)</code><br>(may fail for non-pytz timezones)</li>\n<li>struct_time (UTC) → Aware datetime <em>(s)</em>:<br><code>datetime.datetime(struct_time[:6], tzinfo=UTC).astimezone(tz)</code><br>(can't represent leap seconds, see comment from jfs)</li>\n<li>Naïve datetime (local) → Aware datetime:<br><code>stz.localize(dt, is_dst=None)</code><br>(exception during DST transitions, see comment from jfs)</li>\n<li>Naïve datetime (UTC) → Aware datetime:<br><code>dt.replace(tzinfo=UTC)</code></li>\n</ul>\n\n<p>Source: <a href=\"http://taaviburns.ca/presentations/what_you_need_to_know_about_datetimes/\" rel=\"noreferrer\">taaviburns.ca</a></p>\n"
},
{
"answer_id": 42348504,
"author": "Yash",
"author_id": 2708266,
"author_profile": "https://Stackoverflow.com/users/2708266",
"pm_score": 2,
"selected": false,
"text": "<p>Using <a href=\"http://crsmithdev.com/arrow/\" rel=\"nofollow noreferrer\">http://crsmithdev.com/arrow/</a></p>\n\n<pre><code>arrowObj = arrow.Arrow.strptime('2017-02-20 10:00:00', '%Y-%m-%d %H:%M:%S' , 'US/Eastern')\n\narrowObj.to('UTC') or arrowObj.to('local') \n</code></pre>\n\n<p>This library makes life easy :)</p>\n"
},
{
"answer_id": 48203190,
"author": "spedy",
"author_id": 2115494,
"author_profile": "https://Stackoverflow.com/users/2115494",
"pm_score": -1,
"selected": false,
"text": "<p>In python3:</p>\n\n<p><code>pip install python-dateutil</code></p>\n\n<pre><code>from dateutil.parser import tz\n\nmydt.astimezone(tz.gettz('UTC')).replace(tzinfo=None) \n</code></pre>\n"
},
{
"answer_id": 50138694,
"author": "uclatommy",
"author_id": 4015330,
"author_profile": "https://Stackoverflow.com/users/4015330",
"pm_score": 3,
"selected": false,
"text": "<h2>Simple</h2>\n\n<p>I did it like this:</p>\n\n<pre><code>>>> utc_delta = datetime.utcnow()-datetime.now()\n>>> utc_time = datetime(2008, 9, 17, 14, 2, 0) + utc_delta\n>>> print(utc_time)\n2008-09-17 19:01:59.999996\n</code></pre>\n\n<h2>Fancy Implementation</h2>\n\n<p>If you want to get fancy, you can turn this into a functor:</p>\n\n<pre><code>class to_utc():\n utc_delta = datetime.utcnow() - datetime.now()\n\n def __call__(cls, t):\n return t + cls.utc_delta\n</code></pre>\n\n<p>Result: </p>\n\n<pre><code>>>> utc_converter = to_utc()\n>>> print(utc_converter(datetime(2008, 9, 17, 14, 2, 0)))\n2008-09-17 19:01:59.999996\n</code></pre>\n"
},
{
"answer_id": 53760225,
"author": "franksands",
"author_id": 289368,
"author_profile": "https://Stackoverflow.com/users/289368",
"pm_score": 1,
"selected": false,
"text": "<p>I found the best answer on another question <a href=\"https://stackoverflow.com/a/1596308/289368\">here</a>. It only uses python built-in libraries and does not require you to input your local timezone (a requirement in my case) </p>\n\n<pre><code>import time\nimport calendar\n\nlocal_time = time.strptime(\"2018-12-13T09:32:00.000\", \"%Y-%m-%dT%H:%M:%S.%f\")\nlocal_seconds = time.mktime(local_time)\nutc_time = time.gmtime(local_seconds)\n</code></pre>\n\n<p>I'm reposting the answer here since this question pops up in google instead of the linked question depending on the search keywords.</p>\n"
},
{
"answer_id": 62237615,
"author": "tobixen",
"author_id": 1452887,
"author_profile": "https://Stackoverflow.com/users/1452887",
"pm_score": 2,
"selected": false,
"text": "<p>I have this code in one of my projects:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>from datetime import datetime\n## datetime.timezone works in newer versions of python\ntry:\n from datetime import timezone\n utc_tz = timezone.utc\nexcept:\n import pytz\n utc_tz = pytz.utc\n\ndef _to_utc_date_string(ts):\n # type (Union[date,datetime]]) -> str\n \"\"\"coerce datetimes to UTC (assume localtime if nothing is given)\"\"\"\n if (isinstance(ts, datetime)):\n try:\n ## in python 3.6 and higher, ts.astimezone() will assume a\n ## naive timestamp is localtime (and so do we)\n ts = ts.astimezone(utc_tz)\n except:\n ## in python 2.7 and 3.5, ts.astimezone() will fail on\n ## naive timestamps, but we'd like to assume they are\n ## localtime\n import tzlocal\n ts = tzlocal.get_localzone().localize(ts).astimezone(utc_tz)\n return ts.strftime(\"%Y%m%dT%H%M%SZ\")\n</code></pre>\n"
},
{
"answer_id": 62816943,
"author": "Philipp",
"author_id": 2782049,
"author_profile": "https://Stackoverflow.com/users/2782049",
"pm_score": 1,
"selected": false,
"text": "<p>If you already have a datetime object <code>my_dt</code> you can change it to UTC with:</p>\n<pre><code>datetime.datetime.utcfromtimestamp(my_dt.timestamp())\n</code></pre>\n"
},
{
"answer_id": 62840310,
"author": "Alperen",
"author_id": 6900838,
"author_profile": "https://Stackoverflow.com/users/6900838",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Briefly</strong>, to convert any <code>datetime</code> date to UTC time:</p>\n<pre><code>from datetime import datetime\n\ndef to_utc(date):\n return datetime(*date.utctimetuple()[:6])\n</code></pre>\n<hr />\n<p>Let's explain with an example. First, we need to create a <code>datetime</code> from the string:</p>\n<pre><code>>>> date = datetime.strptime("11 Feb 2011 17:33:54 -0800", "%d %b %Y %H:%M:%S %z")\n</code></pre>\n<p>Then, we can call the function:</p>\n<pre><code>>>> to_utc(date)\ndatetime.datetime(2011, 2, 12, 1, 33, 54)\n</code></pre>\n<p>Step by step how the function works:</p>\n<pre><code>>>> date.utctimetuple()\ntime.struct_time(tm_year=2011, tm_mon=2, tm_mday=12, tm_hour=1, tm_min=33, tm_sec=54, tm_wday=5, tm_yday=43, tm_isdst=0)\n>>> date.utctimetuple()[:6]\n(2011, 2, 12, 1, 33, 54)\n>>> datetime(*date.utctimetuple()[:6])\ndatetime.datetime(2011, 2, 12, 1, 33, 54)\n</code></pre>\n"
},
{
"answer_id": 64097432,
"author": "FObersteiner",
"author_id": 10197418,
"author_profile": "https://Stackoverflow.com/users/10197418",
"pm_score": 4,
"selected": false,
"text": "<p>An option available since Python 3.6: <code>datetime.astimezone(tz=None)</code> can be used to get an aware datetime object representing local time <a href=\"https://docs.python.org/3/library/datetime.html#datetime.datetime.astimezone\" rel=\"noreferrer\">(docs)</a>. This can then easily be converted to UTC.</p>\n<pre><code>from datetime import datetime, timezone\ns = "2008-09-17 14:02:00"\n\n# to datetime object:\ndt = datetime.fromisoformat(s) # Python 3.7\n\n# I'm on time zone Europe/Berlin; CEST/UTC+2 during summer 2008\ndt = dt.astimezone()\nprint(dt)\n# 2008-09-17 14:02:00+02:00\n\n# ...and to UTC:\ndtutc = dt.astimezone(timezone.utc)\nprint(dtutc)\n# 2008-09-17 12:02:00+00:00\n</code></pre>\n<p>Side-Note: While the described conversion to UTC works perfectly fine, <code>.astimezone()</code> sets <code>tzinfo</code> of the datetime object to a timedelta-derived timezone - so don't expect any "DST-awareness" from it.</p>\n"
},
{
"answer_id": 64626046,
"author": "Zisheng Ye",
"author_id": 8102752,
"author_profile": "https://Stackoverflow.com/users/8102752",
"pm_score": 2,
"selected": false,
"text": "<p>In python 3.9.0, after you've parsed your local time <code>local_time</code> into <code>datetime.datetime</code> object, just use <code>local_time.astimezone(datetime.timezone.utc)</code>.</p>\n"
},
{
"answer_id": 69031527,
"author": "Lalit Sharma",
"author_id": 7756843,
"author_profile": "https://Stackoverflow.com/users/7756843",
"pm_score": 1,
"selected": false,
"text": "<p>For anyone who is confused with the most upvoted answer. You can convert a datetime string to utc time in python by generating a datetime object and then you can use astimezone(pytz.utc) to get datetime in utc.</p>\n<p>For eg.</p>\n<p>let say we have local datetime string as <code>2021-09-02T19:02:00Z</code> in isoformat</p>\n<p>Now to convert this string to utc datetime. we first need to generate datetime object using this string by</p>\n<p><code>dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')</code></p>\n<p>this will give you python datetime object, then you can use <code>astimezone(pytz.utc)</code> to get utc datetime like</p>\n<p><code>dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ') dt = dt.astimezone(pytz.utc)</code></p>\n<p>this will give you datetime object in utc, then you can convert it to string using <code>dt.strftime("%Y-%m-%d %H:%M:%S")</code></p>\n<p>full code eg:</p>\n<pre><code>from datetime import datetime\nimport pytz\n\ndef converLocalToUTC(datetime, getString=True, format="%Y-%m-%d %H:%M:%S"):\n dt = datetime.strptime(dt,'%Y-%m-%dT%H:%M:%SZ')\n dt = dt.astimezone(pytz.utc)\n \n if getString:\n return dt.strftime(format)\n return dt\n</code></pre>\n<p>then you can call it as</p>\n<p><code>converLocalToUTC("2021-09-02T19:02:00Z")</code></p>\n<p>took help from\n<a href=\"https://stackoverflow.com/a/79877/7756843\">https://stackoverflow.com/a/79877/7756843</a></p>\n"
},
{
"answer_id": 69261133,
"author": "Bryce",
"author_id": 11804374,
"author_profile": "https://Stackoverflow.com/users/11804374",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an example with the native <a href=\"https://docs.python.org/3/library/zoneinfo.html\" rel=\"nofollow noreferrer\">zoneinfo</a> module in <strong>Python3.9</strong>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from datetime import datetime\nfrom zoneinfo import ZoneInfo\n\n# Get timezone we're trying to convert from\nlocal_tz = ZoneInfo("America/New_York")\n# UTC timezone\nutc_tz = ZoneInfo("UTC")\n\ndt = datetime.strptime("2021-09-20 17:20:00","%Y-%m-%d %H:%M:%S")\ndt = dt.replace(tzinfo=local_tz)\ndt_utc = dt.astimezone(utc_tz)\n\nprint(dt.strftime("%Y-%m-%d %H:%M:%S"))\nprint(dt_utc.strftime("%Y-%m-%d %H:%M:%S"))\n</code></pre>\n<p>This may be preferred over just using <code>dt.astimezone()</code> in situations where the timezone you're converting from isn't reflective of your system's local timezone. Not having to rely on external libraries is nice too.</p>\n<p><strong>Note</strong>: This may not work on Windows systems, since <a href=\"https://docs.python.org/3/library/zoneinfo.html#data-sources\" rel=\"nofollow noreferrer\">zoneinfo relies on an IANA database</a> that may not be present. The <a href=\"https://tzdata.readthedocs.io/en/latest/\" rel=\"nofollow noreferrer\">tzdata</a> package can be installed as a workaround. It's a first-party package, but is not in the standard library.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3715/"
]
| How do I convert a datetime *string in local time* to a *string in UTC time*?
I'm sure I've done this before, but can't find it and SO will hopefully help me (and others) do that in future.
**Clarification**: For example, if I have `2008-09-17 14:02:00` in my local timezone (`+10`), I'd like to generate a string with the equivalent `UTC` time: `2008-09-17 04:02:00`.
Also, from <http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/>, note that in general this isn't possible as with DST and other issues there is no unique conversion from local time to UTC time. | Thanks @rofly, the full conversion from string to string is as follows:
```
import time
time.strftime("%Y-%m-%d %H:%M:%S",
time.gmtime(time.mktime(time.strptime("2008-09-17 14:04:00",
"%Y-%m-%d %H:%M:%S"))))
```
My summary of the `time`/`calendar` functions:
`time.strptime`
string --> tuple (no timezone applied, so matches string)
`time.mktime`
local time tuple --> seconds since epoch (always local time)
`time.gmtime`
seconds since epoch --> tuple in UTC
and
`calendar.timegm`
tuple in UTC --> seconds since epoch
`time.localtime`
seconds since epoch --> tuple in local timezone |
79,816 | <p>I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.<br>
i.e. user holds down mouse button (x=call function) - x___x___x___x__x__x_x_x_x_xxxxxxx</p>
| [
{
"answer_id": 79830,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 2,
"selected": false,
"text": "<p>When the button is pressed, call <code>window.setTimeout</code> with your intended time and the function <code>x</code>, and set the timer again at the end of <code>x</code> but this time with a smaller interval.</p>\n\n<p>Clear the timeout using <code>window.clearTimeout</code> upon release of the mouse button.</p>\n"
},
{
"answer_id": 79862,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": -1,
"selected": false,
"text": "<p>something like the psuedo code below might work..</p>\n\n<pre><code>var isClicked = false;\nvar clickCounter = 100;\nfunction fnTrackClick(){\n if(isClicked){\n clickCounter--;\n setTimeout(clickCounter * 100, fnTrackClick);\n }\n}\n\n<input type=\"button\" value=\"blah\" onmousedown=\"isClicked=true;\" onmouseover=\"fnTrackClick();\" onmouseup=\"isClicked = false;\" />\n</code></pre>\n"
},
{
"answer_id": 79890,
"author": "Glennular",
"author_id": 14753,
"author_profile": "https://Stackoverflow.com/users/14753",
"pm_score": 2,
"selected": false,
"text": "<p>Just put the below toggleOn in the OnMouseDown and toggleOff in the OnMouseUp of the button.</p>\n\n<pre><code>var tid = 0;\nvar speed = 100;\n\nfunction toggleOn(){\n if(tid==0){\n tid=setInterval('ThingToDo()',speed);\n }\n}\nfunction toggleOff(){\n if(tid!=0){\n clearInterval(tid);\n tid=0;\n }\n}\nfunction ThingToDo{\n\n}\n</code></pre>\n"
},
{
"answer_id": 79970,
"author": "neouser99",
"author_id": 10669,
"author_profile": "https://Stackoverflow.com/users/10669",
"pm_score": 5,
"selected": true,
"text": "<pre><code>function holdit(btn, action, start, speedup) {\n var t;\n\n var repeat = function () {\n action();\n t = setTimeout(repeat, start);\n start = start / speedup;\n }\n\n btn.mousedown = function() {\n repeat();\n }\n\n btn.mouseup = function () {\n clearTimeout(t);\n }\n};\n\n/* to use */\nholdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */\n</code></pre>\n"
},
{
"answer_id": 43407325,
"author": "Phuong Vu",
"author_id": 1014112,
"author_profile": "https://Stackoverflow.com/users/1014112",
"pm_score": 0,
"selected": false,
"text": "<p>I just release a jQuery plugin, check this <a href=\"https://phuong.github.io/jqueryClickAndHold/\" rel=\"nofollow noreferrer\">demo</a> on this <a href=\"https://github.com/phuong/jqueryClickAndHold\" rel=\"nofollow noreferrer\">repo</a>.</p>\n\n<pre><code>$('button').clickAndHold(function (e, n) {\n console.log(\"Call me baby \", n);\n});\n</code></pre>\n"
},
{
"answer_id": 58237538,
"author": "cskwg",
"author_id": 4386189,
"author_profile": "https://Stackoverflow.com/users/4386189",
"pm_score": 0,
"selected": false,
"text": "<p>@glenuular: Thanks for this interesting approach!\nThere were some small problems with it: \n- The start value was not reset, so on the second use it started too fast.\n- The start value was divided without limit, so it became very small after short time.\n- Arguments were not passed to the called method. (Now limited to 6 args, usually sufficient to pass 'ev').</p>\n\n<pre><code> function holdit( btn, method, start, speedup ) {\n var t, keep = start;\n var repeat = function () {\n var args = Array.prototype.slice.call( arguments );\n method.apply( this, args );\n t = setTimeout( repeat, start, args[0], args[1], args[2], args[3], args[4], args[5] );\n if ( start > keep / 20 ) start = start / speedup;\n }\n btn.onmousedown = btn.mousedown = repeat;\n //\n btn.onmouseout = btn.mouseout = btn.onmouseup = btn.mouseup = function () {\n clearTimeout( t );\n start = keep;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 70521675,
"author": "Daniel Cachro",
"author_id": 17790036,
"author_profile": "https://Stackoverflow.com/users/17790036",
"pm_score": 0,
"selected": false,
"text": "<p>I upgraded neouser99 solution because i ran into some problems with it ^^</p>\n<pre><code>let holdIt = (btn, action, start, speedup, limit) => {\n let t;\n let startValue = start;\n\n let repeat = () => {\n action();\n t = setTimeout(repeat, startValue);\n (startValue > limit) ? startValue /= speedup: startValue = limit;\n }\n\n btn.onmousedown = () => {\n repeat();\n }\n\n const stopActionEvents = ['mouseup', 'mouseout'];\n\n stopActionEvents.forEach(event => {\n btn.addEventListener(event, () => {\n clearTimeout(t);\n startValue = start;\n })\n });\n\n};\n\nholdIt(actionButton, functionToDo, 500, 2, 5);\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14907/"
]
| I'd like a short smallest possible javascript routine that when a mousedown occurs on a button it first responds just like a mouseclick and then if the user keeps the button pressed it responds as if the user was continously sending mouseclicks and after a while with the button held down acts as if the user was accelerating their mouseclicks...basically think of it like a keypress repeat with acceleration in time.
i.e. user holds down mouse button (x=call function) - x\_\_\_x\_\_\_x\_\_\_x\_\_x\_\_x\_x\_x\_x\_xxxxxxx | ```
function holdit(btn, action, start, speedup) {
var t;
var repeat = function () {
action();
t = setTimeout(repeat, start);
start = start / speedup;
}
btn.mousedown = function() {
repeat();
}
btn.mouseup = function () {
clearTimeout(t);
}
};
/* to use */
holdit(btn, function () { }, 1000, 2); /* x..1000ms..x..500ms..x..250ms..x */
``` |
79,843 | <p>The situation is this:</p>
<ul>
<li>You have a Hibernate context with an
object graph that has some lazy
loading defined. </li>
<li>You want to use
the Hibernate objects in your UI as
is without having to copy the data
somewhere. </li>
<li>There are different UI
contexts that require different
amounts of data. </li>
<li>The data is too
big to just eager load the whole
graph each time.</li>
</ul>
<p>What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?</p>
<p>Any help.</p>
| [
{
"answer_id": 79933,
"author": "sirrocco",
"author_id": 5246,
"author_profile": "https://Stackoverflow.com/users/5246",
"pm_score": 3,
"selected": true,
"text": "<p>Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orders. </p>\n\n<p>Then I would define a Repository with a fluent interface that will allow me to say something like :</p>\n\n<pre><code>new ClientRepo().LoadClientBy(id)\n .WithOrders()\n .WithBonus()\n .OrderByName();\n</code></pre>\n\n<p>And there you have the client with everything you need. It's preferably that you know in advance what you will need for the current operation. This way you can avoid unwanted trips to the database.(new devs in your team will usually do this - call a property and not be aware of the fact that it's actually a call to the DB)</p>\n"
},
{
"answer_id": 80154,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 1,
"selected": false,
"text": "<p>If it's a webapp and you're using Spring, then OpenSessionInViewFilter could be the solution to your problems.</p>\n"
},
{
"answer_id": 87117,
"author": "Roland Schneider",
"author_id": 16515,
"author_profile": "https://Stackoverflow.com/users/16515",
"pm_score": 1,
"selected": false,
"text": "<p>An approach we use in our projects is to create a service for each view you have. Then the view fetches the sub-graph you need for this specific view, always trying to reduce the number of sqls send to the database. Therefore we are using a lot of joins to get the n:1 associated objects.</p>\n\n<p>If you are using a 2-tier desktop app directly connected to the DB you can just leave the objects attached and load additional data anytime automatically. Otherwise you have to reattach it to the session and initialize the association you need with <code>Hibernate.initialize(Object entity, String propertyName)</code></p>\n\n<p>(Out of memory, maybe not 100% correct)</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14893/"
]
| The situation is this:
* You have a Hibernate context with an
object graph that has some lazy
loading defined.
* You want to use
the Hibernate objects in your UI as
is without having to copy the data
somewhere.
* There are different UI
contexts that require different
amounts of data.
* The data is too
big to just eager load the whole
graph each time.
What is the best means to load all the appropriate objects in the object graph in a configurable way so that they can be accessed without having to go back to the database to load more data?
Any help. | Let's say you have the Client and at one point you have to something with his Orders and maybe he has a Bonus for his Orders.
Then I would define a Repository with a fluent interface that will allow me to say something like :
```
new ClientRepo().LoadClientBy(id)
.WithOrders()
.WithBonus()
.OrderByName();
```
And there you have the client with everything you need. It's preferably that you know in advance what you will need for the current operation. This way you can avoid unwanted trips to the database.(new devs in your team will usually do this - call a property and not be aware of the fact that it's actually a call to the DB) |
79,880 | <p>I'm looking for a variation on the <code>#save</code> method that will only save
attributes that do not have errors attached to them.
So a model can be updated without being valid overall, and this will
still prevent saving invalid data to the database.</p>
<p>By "valid attributes", I mean those attributes that give nil when calling @model_instance.errors.on(:attribute)</p>
<p>Anyone have an idea of how to accomplish this?</p>
<p>So far, I have the following:</p>
<pre><code>def save_valid_attributes
valid?
update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m}
end
</code></pre>
<p>This works if there's no processing done on assignment, which in my case there is.
For example, I have a database column "start_date", and two methods defined:</p>
<pre><code>def nice_start_date=(startdate)
self.start_date = Chronic.parse(startdate) || startdate
end
def nice_start_date
self.start_date.to_s
end
</code></pre>
<p>These two methods allow me to properly parse the user inputted dates using Chronic before saving. So, second way of doing this, one attribute at a time:</p>
<pre><code>def save_valid_attributes(attrib)
valid?
attrib.each{|(k,v)| send("${k}=", v); save; reload)
end
</code></pre>
<p>The model needs to be reloaded each time since, if one of the dates is invalid and doesn't save, it will prevent all further attributes from saving.</p>
<p>Is there a better way to do this? I'm sure this isn't an uncommon problem in the Rails world, I just can't seem to find anything in the Google universe of knowledge.</p>
| [
{
"answer_id": 79900,
"author": "Thomas",
"author_id": 14637,
"author_profile": "https://Stackoverflow.com/users/14637",
"pm_score": 3,
"selected": true,
"text": "<p>Since OpenSSL is Apache-licensed (i.e. BSD-style), you can simply distribute it as a DLL along with your application. (Maybe build it yourself to have only the features you need and all in a single DLL.) Then use p/invoke calls to talk with this DLL.</p>\n\n<p>(Maybe you can even link the native code straight into your .NET executable? Not sure about that.)</p>\n"
},
{
"answer_id": 2228742,
"author": "Guy van den Berg",
"author_id": 189895,
"author_profile": "https://Stackoverflow.com/users/189895",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at BouncyCastle <a href=\"http://www.bouncycastle.org/csharp/\" rel=\"nofollow noreferrer\">http://www.bouncycastle.org/csharp/</a></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14843/"
]
| I'm looking for a variation on the `#save` method that will only save
attributes that do not have errors attached to them.
So a model can be updated without being valid overall, and this will
still prevent saving invalid data to the database.
By "valid attributes", I mean those attributes that give nil when calling @model\_instance.errors.on(:attribute)
Anyone have an idea of how to accomplish this?
So far, I have the following:
```
def save_valid_attributes
valid?
update_atrtibutes attributes.inject({}){|k, v, m| m[k] = v unless errors_on(k.to_sym); m}
end
```
This works if there's no processing done on assignment, which in my case there is.
For example, I have a database column "start\_date", and two methods defined:
```
def nice_start_date=(startdate)
self.start_date = Chronic.parse(startdate) || startdate
end
def nice_start_date
self.start_date.to_s
end
```
These two methods allow me to properly parse the user inputted dates using Chronic before saving. So, second way of doing this, one attribute at a time:
```
def save_valid_attributes(attrib)
valid?
attrib.each{|(k,v)| send("${k}=", v); save; reload)
end
```
The model needs to be reloaded each time since, if one of the dates is invalid and doesn't save, it will prevent all further attributes from saving.
Is there a better way to do this? I'm sure this isn't an uncommon problem in the Rails world, I just can't seem to find anything in the Google universe of knowledge. | Since OpenSSL is Apache-licensed (i.e. BSD-style), you can simply distribute it as a DLL along with your application. (Maybe build it yourself to have only the features you need and all in a single DLL.) Then use p/invoke calls to talk with this DLL.
(Maybe you can even link the native code straight into your .NET executable? Not sure about that.) |
79,935 | <p>Is there an equivalent to Java's Robot class (java.awt.Robot) for Perl?</p>
| [
{
"answer_id": 79976,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 1,
"selected": false,
"text": "<p>There is on Linux/Unix:</p>\n\n<p><a href=\"http://sourceforge.net/projects/x11guitest\" rel=\"nofollow noreferrer\"><a href=\"http://sourceforge.net/projects/x11guitest\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/x11guitest</a></a></p>\n\n<p>I'm not familiar of anything similar for Windows or Mac that uses Perl.</p>\n"
},
{
"answer_id": 80004,
"author": "Fhoxh",
"author_id": 14785,
"author_profile": "https://Stackoverflow.com/users/14785",
"pm_score": 2,
"selected": false,
"text": "<p>If you're looking for a way to control a browser for the purpose of functional testing, Selenium has Perl bindings: <a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">http://selenium.openqa.org/</a></p>\n"
},
{
"answer_id": 80399,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 2,
"selected": false,
"text": "<p>For X (Linux/Unix), there's <a href=\"http://search.cpan.org/perldoc?X11::GUITest\" rel=\"nofollow noreferrer\">X11::GUITest</a>.</p>\n\n<p>For Windows, there's <a href=\"http://search.cpan.org/perldoc?Win32::CtrlGUI\" rel=\"nofollow noreferrer\">Win32::CtrlGUI</a>, although it can be a bit tricky to install its prerequisites.</p>\n"
},
{
"answer_id": 83794,
"author": "Mr. Muskrat",
"author_id": 2657951,
"author_profile": "https://Stackoverflow.com/users/2657951",
"pm_score": 2,
"selected": false,
"text": "<p>On Windows, I've always used <a href=\"http://search.cpan.org/~karasik/Win32-GuiTest-1.54/lib/Win32/GuiTest.pm\" rel=\"nofollow noreferrer\">Win32::GuiTest</a>.</p>\n"
},
{
"answer_id": 87112,
"author": "Bob_Gneu",
"author_id": 16703,
"author_profile": "https://Stackoverflow.com/users/16703",
"pm_score": 3,
"selected": false,
"text": "<p>Alternatively, you can surely use the <a href=\"http://search.cpan.org/~petdance/WWW-Mechanize-1.34/lib/WWW/Mechanize.pm\" rel=\"nofollow noreferrer\">WWW::Mechanize</a> module to create an agent as we do here at work. We have a tool called AppMon that is really just a dramatized wrapper around Mechanize. </p>\n\n<p>The Mechanize module allows you to use scripts that look a lot like this: </p>\n\n<pre><code>use WWW::Mechanize;\n\nmy $Agent = WWW::Mechanize->new(cookie_jar => {});\n\n$Agent->get(\"http://www.google.com/search?q=stack+overflow+mechanize\");\nprint \"Found Mechanize\" $Agent->content =~ /WWW::Mechanize/;\n</code></pre>\n\n<p>and will result in \"Found Mechanize\" being output. This is a very simple script, but rest assured you can interact with forms quite well.</p>\n\n<p>You can also move to Ruby and use Watir, or Selenium as another alternative, albeit not as interesting (in terms of coding) or automate-able. Selenium has a firefox extension that is quite useful for creating the selenium scripts and can change them between the various languages that it supports, which is pretty extensive in terms of automation.</p>\n\n<h2>Update - Nov 2016</h2>\n\n<p>Although I haven't had much of an opportunity to play with it, there are also webdriver packages for most languages, and Perl is no different. </p>\n\n<p><a href=\"http://search.cpan.org/~aivaturi/Selenium-Remote-Driver-0.15/lib/Selenium/Remote/Driver.pm\" rel=\"nofollow noreferrer\">Selenium::Remote::Driver</a></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14948/"
]
| Is there an equivalent to Java's Robot class (java.awt.Robot) for Perl? | Alternatively, you can surely use the [WWW::Mechanize](http://search.cpan.org/~petdance/WWW-Mechanize-1.34/lib/WWW/Mechanize.pm) module to create an agent as we do here at work. We have a tool called AppMon that is really just a dramatized wrapper around Mechanize.
The Mechanize module allows you to use scripts that look a lot like this:
```
use WWW::Mechanize;
my $Agent = WWW::Mechanize->new(cookie_jar => {});
$Agent->get("http://www.google.com/search?q=stack+overflow+mechanize");
print "Found Mechanize" $Agent->content =~ /WWW::Mechanize/;
```
and will result in "Found Mechanize" being output. This is a very simple script, but rest assured you can interact with forms quite well.
You can also move to Ruby and use Watir, or Selenium as another alternative, albeit not as interesting (in terms of coding) or automate-able. Selenium has a firefox extension that is quite useful for creating the selenium scripts and can change them between the various languages that it supports, which is pretty extensive in terms of automation.
Update - Nov 2016
-----------------
Although I haven't had much of an opportunity to play with it, there are also webdriver packages for most languages, and Perl is no different.
[Selenium::Remote::Driver](http://search.cpan.org/~aivaturi/Selenium-Remote-Driver-0.15/lib/Selenium/Remote/Driver.pm) |
79,939 | <p>I have the following (pretty standard) table structure:</p>
<pre><code>Post <-> PostTag <-> Tag
</code></pre>
<p>Suppose I have the following records:</p>
<pre><code>PostID Title
1, 'Foo'
2, 'Bar'
3, 'Baz'
TagID Name
1, 'Foo'
2, 'Bar'
PostID TagID
1 1
1 2
2 2
</code></pre>
<p>In other words, the first post has two tags, the second has one and the third one doesn't have any.</p>
<p><strong>I'd like to load all posts and it's tags in one query</strong> but haven't been able to find the right combination of operators. I've been able to load either <em>posts with tags only</em> or <em>repeated posts when more than one tag</em>.</p>
<p>Given the database above, <strong>I'd like to receive three posts and their tags (if any) in a collection property of the Post objects</strong>. Is it possible at all?</p>
<p>Thanks</p>
| [
{
"answer_id": 79979,
"author": "sirrocco",
"author_id": 5246,
"author_profile": "https://Stackoverflow.com/users/5246",
"pm_score": 0,
"selected": false,
"text": "<p>I've answered this in another post : <a href=\"https://stackoverflow.com/questions/50169/optimizing-a-linq-to-sql-query#50240\">About eager loading</a>. In your case it would probably be something like :</p>\n\n<pre><code>DataLoadOptions options = new DataLoadOptions(); \noptions.LoadWith<Post>(p => p.PostTag);\noptions.LoadWith<PostTag>(pt => pt.Tag); \n</code></pre>\n\n<p>Though be careful - the DataLoadOptions must be set BEFORE ANY query is sent to the database - if not, an exception is thrown (no idea why it's like this in Linq2Sql - probably will be fixed in a later version).</p>\n"
},
{
"answer_id": 80038,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm sorry no, Eager Loading will execute one extra query per tag per post.</p>\n\n<p>Tested with this code:</p>\n\n<pre><code>var options = new DataLoadOptions();\noptions.LoadWith<Post>(p => p.PostTags);\noptions.LoadWith<PostTag>(pt => pt.Tag);\nusing (var db = new BlogDataContext())\n{\n db.LoadOptions = options;\n return (from p in db.Posts\n where p.Status != PostStatus.Closed\n orderby p.PublishDateGmt descending\n select p);\n}\n</code></pre>\n\n<p>In the example database it would execute 4 queries which is not acceptable in production. Can anyone suggest another solution?</p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 80629,
"author": "sirrocco",
"author_id": 5246,
"author_profile": "https://Stackoverflow.com/users/5246",
"pm_score": 1,
"selected": false,
"text": "<p>It's a bit strange because </p>\n\n<pre><code>DataLoadOptions o = new DataLoadOptions ( );\no.LoadWith<Listing> ( l => l.ListingStaffs );\no.LoadWith<ListingStaff> ( ls => ls.MerchantStaff );\nctx.LoadOptions = o;\n\nIQueryable<Listing> listings = (from a in ctx.Listings\n where a.IsActive == false \n select a);\nList<Listing> list = listings.ToList ( );\n</code></pre>\n\n<p>results in a query like : </p>\n\n<pre><code>SELECT [t0].*, [t1].*, [t2].*, (\nSELECT COUNT(*)\nFROM [dbo].[LStaff] AS [t3]\nINNER JOIN [dbo].[MStaff] AS [t4] ON [t4].[MStaffId] = [t3].[MStaffId]\nWHERE [t3].[ListingId] = [t0].[ListingId]\n) AS [value]\nFROM [dbo].[Listing] AS [t0]\nLEFT OUTER JOIN ([dbo].[LStaff] AS [t1]\nINNER JOIN [dbo].[MStaff] AS [t2] ON [t2].[MStaffId] = [t1].[MStaffId]) ON \n[t1].[LId] = [t0].[LId] WHERE NOT ([t0].[IsActive] = 1) \nORDER BY [t0].[LId], [t1].[LStaffId], [t2].[MStaffId]\n</code></pre>\n\n<p>(I've shortened the names and added the * on the select).</p>\n\n<p>So it seems to do the select ok.</p>\n"
},
{
"answer_id": 83396,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I'm sorry. The solution you give works, but I found out that it breaks when paginating with Take(N). The complete method I'm using is the following:</p>\n\n<pre><code>public IList<Post> GetPosts(int page, int records)\n{\n var options = new DataLoadOptions();\n options.LoadWith<Post>(p => p.PostTags);\n options.LoadWith<PostTag>(pt => pt.Tag);\n using (var db = new BlogDataContext())\n {\n db.LoadOptions = options;\n return (from p in db.Posts\n where p.Status != PostStatus.Closed\n orderby p.PublishDateGmt descending\n select p)\n .Skip(page * records)\n //.Take(records)\n .ToList();\n }\n}\n</code></pre>\n\n<p>With the Take() method commented it generates a query similar to to what you posted but if I add the Take() again it generates 1 + N x M queries.</p>\n\n<p>So, I guess my question now is: <strong>Is there a replacement to the Take() method to paginate records?</strong></p>\n\n<p>Thanks</p>\n"
},
{
"answer_id": 83771,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Yay! It worked. </p>\n\n<p>If anyone is having the same problem here's what I did:</p>\n\n<pre><code>public IList<Post> GetPosts(int page, int record)\n{\n var options = new DataLoadOptions();\n options.LoadWith<Post>(p => p.PostTags);\n options.LoadWith<PostTag>(pt => pt.Tag);\n using (var db = new DatabaseDataContext(m_connectionString))\n {\n var publishDateGmt = (from p in db.Posts\n where p.Status != PostStatus.Hidden\n orderby p.PublishDateGmt descending\n select p.PublishDateGmt)\n .Skip(page * record)\n .Take(record)\n .ToList()\n .Last();\n db.LoadOptions = options;\n return (from p in db.Posts\n where p.Status != PostStatus.Closed \n && p.PublishDateGmt >= publishDateGmt\n orderby p.PublishDateGmt descending\n select p)\n .Skip(page * record)\n .ToList();\n }\n}\n</code></pre>\n\n<p>This executes only two queries and loads all tags for each post.</p>\n\n<p>The idea is to get some value to limit the query at the last post that we need (in this case the PublishDateGmt column will suffice) and then limit the second query with that value instead of Take().</p>\n\n<p>Thanks for your help sirrocco.</p>\n"
},
{
"answer_id": 3980733,
"author": "jordanbtucker",
"author_id": 164430,
"author_profile": "https://Stackoverflow.com/users/164430",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is an old post, but I have discovered a way to use Take() while only performing one query. The trick is to perform the Take() inside of a nested query.</p>\n\n<pre><code>var q = from p in db.Posts\n where db.Posts.Take(10).Contains(p)\n select p;\n</code></pre>\n\n<p>Using DataLoadOptions with the query above will give you the first ten posts, including their associated tags, all in one query. The resulting SQL will be a much less concise version of the following:</p>\n\n<pre><code>SELECT p.PostID, p.Title, pt.PostID, pt.TagID, t.TagID, t.Name FROM Posts p\nJOIN PostsTags pt ON p.PostID = pt.PostID\nJOIN Tags t ON pt.TagID = t.TagID\nWHERE p.PostID IN (SELECT TOP 10 PostID FROM Posts)\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have the following (pretty standard) table structure:
```
Post <-> PostTag <-> Tag
```
Suppose I have the following records:
```
PostID Title
1, 'Foo'
2, 'Bar'
3, 'Baz'
TagID Name
1, 'Foo'
2, 'Bar'
PostID TagID
1 1
1 2
2 2
```
In other words, the first post has two tags, the second has one and the third one doesn't have any.
**I'd like to load all posts and it's tags in one query** but haven't been able to find the right combination of operators. I've been able to load either *posts with tags only* or *repeated posts when more than one tag*.
Given the database above, **I'd like to receive three posts and their tags (if any) in a collection property of the Post objects**. Is it possible at all?
Thanks | Yay! It worked.
If anyone is having the same problem here's what I did:
```
public IList<Post> GetPosts(int page, int record)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(p => p.PostTags);
options.LoadWith<PostTag>(pt => pt.Tag);
using (var db = new DatabaseDataContext(m_connectionString))
{
var publishDateGmt = (from p in db.Posts
where p.Status != PostStatus.Hidden
orderby p.PublishDateGmt descending
select p.PublishDateGmt)
.Skip(page * record)
.Take(record)
.ToList()
.Last();
db.LoadOptions = options;
return (from p in db.Posts
where p.Status != PostStatus.Closed
&& p.PublishDateGmt >= publishDateGmt
orderby p.PublishDateGmt descending
select p)
.Skip(page * record)
.ToList();
}
}
```
This executes only two queries and loads all tags for each post.
The idea is to get some value to limit the query at the last post that we need (in this case the PublishDateGmt column will suffice) and then limit the second query with that value instead of Take().
Thanks for your help sirrocco. |
79,960 | <p>I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last <i>word</i> before 200 chars.</p>
| [
{
"answer_id": 79986,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 9,
"selected": true,
"text": "<p>By using the <a href=\"http://www.php.net/wordwrap\" rel=\"noreferrer\">wordwrap</a> function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:</p>\n\n<pre><code>substr($string, 0, strpos(wordwrap($string, $your_desired_width), \"\\n\"));\n</code></pre>\n\n<p>One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:</p>\n\n<pre><code>if (strlen($string) > $your_desired_width) \n{\n $string = wordwrap($string, $your_desired_width);\n $string = substr($string, 0, strpos($string, \"\\n\"));\n}\n</code></pre>\n\n<hr>\n\n<p>The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:</p>\n\n<pre><code>function tokenTruncate($string, $your_desired_width) {\n $parts = preg_split('/([\\s\\n\\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);\n $parts_count = count($parts);\n\n $length = 0;\n $last_part = 0;\n for (; $last_part < $parts_count; ++$last_part) {\n $length += strlen($parts[$last_part]);\n if ($length > $your_desired_width) { break; }\n }\n\n return implode(array_slice($parts, 0, $last_part));\n}\n</code></pre>\n\n<p>Also, here is the PHPUnit testclass used to test the implementation:</p>\n\n<pre><code>class TokenTruncateTest extends PHPUnit_Framework_TestCase {\n public function testBasic() {\n $this->assertEquals(\"1 3 5 7 9 \",\n tokenTruncate(\"1 3 5 7 9 11 14\", 10));\n }\n\n public function testEmptyString() {\n $this->assertEquals(\"\",\n tokenTruncate(\"\", 10));\n }\n\n public function testShortString() {\n $this->assertEquals(\"1 3\",\n tokenTruncate(\"1 3\", 10));\n }\n\n public function testStringTooLong() {\n $this->assertEquals(\"\",\n tokenTruncate(\"toooooooooooolooooong\", 10));\n }\n\n public function testContainingNewline() {\n $this->assertEquals(\"1 3\\n5 7 9 \",\n tokenTruncate(\"1 3\\n5 7 9 11 14\", 10));\n }\n}\n</code></pre>\n\n<h1><strong>EDIT :</strong></h1>\n\n<p>Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:</p>\n\n<p><code>$parts = preg_split('/([\\s\\n\\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);</code></p>\n"
},
{
"answer_id": 80001,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 3,
"selected": false,
"text": "<p>Use strpos and substr:</p>\n\n<pre><code><?php\n\n$longString = \"I have a code snippet written in PHP that pulls a block of text.\";\n$truncated = substr($longString,0,strpos($longString,' ',30));\n\necho $truncated;\n</code></pre>\n\n<p>This will give you a string truncated at the first space after 30 characters.</p>\n"
},
{
"answer_id": 80014,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 3,
"selected": false,
"text": "<p>Here you go:</p>\n\n<pre><code>function neat_trim($str, $n, $delim='…') {\n $len = strlen($str);\n if ($len > $n) {\n preg_match('/(.{' . $n . '}.*?)\\b/', $str, $matches);\n return rtrim($matches[1]) . $delim;\n }\n else {\n return $str;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 80030,
"author": "Justin Poliey",
"author_id": 6967,
"author_profile": "https://Stackoverflow.com/users/6967",
"pm_score": 2,
"selected": false,
"text": "<p>I would use the preg_match function to do this, as what you want is a pretty simple expression.</p>\n\n<pre><code>$matches = array();\n$result = preg_match(\"/^(.{1,199})[\\s]/i\", $text, $matches);\n</code></pre>\n\n<p>The expression means \"match any substring starting from the beginning of length 1-200 that ends with a space.\" The result is in $result, and the match is in $matches. That takes care of your original question, which is specifically ending on any space. If you want to make it end on newlines, change the regular expression to:</p>\n\n<pre><code>$result = preg_match(\"/^(.{1,199})[\\n]/i\", $text, $matches);\n</code></pre>\n"
},
{
"answer_id": 80066,
"author": "mattmac",
"author_id": 14935,
"author_profile": "https://Stackoverflow.com/users/14935",
"pm_score": 7,
"selected": false,
"text": "<p>This will return the first 200 characters of words:</p>\n\n<pre><code>preg_replace('/\\s+?(\\S+)?$/', '', substr($string, 0, 201));\n</code></pre>\n"
},
{
"answer_id": 80450,
"author": "Garrett Albright",
"author_id": 11023,
"author_profile": "https://Stackoverflow.com/users/11023",
"pm_score": 3,
"selected": false,
"text": "<p>Keep in mind whenever you're splitting by \"word\" anywhere that some languages such as Chinese and Japanese do not use a space character to split words. Also, a malicious user could simply enter text without any spaces, or using some Unicode look-alike to the standard space character, in which case any solution you use may end up displaying the entire text anyway. A way around this may be to check the string length after splitting it on spaces as normal, then, if the string is still above an abnormal limit - maybe 225 characters in this case - going ahead and splitting it dumbly at that limit.</p>\n\n<p>One more caveat with things like this when it comes to non-ASCII characters; strings containing them may be interpreted by PHP's standard strlen() as being longer than they really are, because a single character may take two or more bytes instead of just one. If you just use the strlen()/substr() functions to split strings, you may split a string in the middle of a character! When in doubt, <a href=\"http://us3.php.net/manual/en/function.mb-strlen.php\" rel=\"nofollow noreferrer\">mb_strlen()</a>/<a href=\"http://php.net/mb_substr\" rel=\"nofollow noreferrer\">mb_substr()</a> are a little more foolproof.</p>\n"
},
{
"answer_id": 2523223,
"author": "Camsoft",
"author_id": 248848,
"author_profile": "https://Stackoverflow.com/users/248848",
"pm_score": 3,
"selected": false,
"text": "<p>Here is my function based on @Cd-MaN's approach.</p>\n\n<pre><code>function shorten($string, $width) {\n if(strlen($string) > $width) {\n $string = wordwrap($string, $width);\n $string = substr($string, 0, strpos($string, \"\\n\"));\n }\n\n return $string;\n}\n</code></pre>\n"
},
{
"answer_id": 4400574,
"author": "amateur barista",
"author_id": 467453,
"author_profile": "https://Stackoverflow.com/users/467453",
"pm_score": 1,
"selected": false,
"text": "<p>Based on @Justin Poliey's regex:</p>\n\n<pre><code>// Trim very long text to 120 characters. Add an ellipsis if the text is trimmed.\nif(strlen($very_long_text) > 120) {\n $matches = array();\n preg_match(\"/^(.{1,120})[\\s]/i\", $very_long_text, $matches);\n $trimmed_text = $matches[0]. '...';\n}\n</code></pre>\n"
},
{
"answer_id": 4665347,
"author": "Dave",
"author_id": 382927,
"author_profile": "https://Stackoverflow.com/users/382927",
"pm_score": 6,
"selected": false,
"text": "<pre><code>$WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' '));\n</code></pre>\n\n<p>And there you have it — a reliable method of truncating any string to the nearest whole word, while staying under the maximum string length.</p>\n\n<p>I've tried the other examples above and they did not produce the desired results.</p>\n"
},
{
"answer_id": 7904269,
"author": "Yo-L",
"author_id": 310108,
"author_profile": "https://Stackoverflow.com/users/310108",
"pm_score": 2,
"selected": false,
"text": "<p>Ok so I got another version of this based on the above answers but taking more things in account(utf-8, \\n and &nbsp ; ), also a line stripping the wordpress shortcodes commented if used with wp.</p>\n\n<pre><code>function neatest_trim($content, $chars) \n if (strlen($content) > $chars) \n {\n $content = str_replace('&nbsp;', ' ', $content);\n $content = str_replace(\"\\n\", '', $content);\n // use with wordpress \n //$content = strip_tags(strip_shortcodes(trim($content)));\n $content = strip_tags(trim($content));\n $content = preg_replace('/\\s+?(\\S+)?$/', '', mb_substr($content, 0, $chars));\n\n $content = trim($content) . '...';\n return $content;\n }\n</code></pre>\n"
},
{
"answer_id": 8072672,
"author": "tanc",
"author_id": 1037075,
"author_profile": "https://Stackoverflow.com/users/1037075",
"pm_score": 2,
"selected": false,
"text": "<p>This is a small fix for mattmac's answer:</p>\n\n<pre><code>preg_replace('/\\s+?(\\S+)?$/', '', substr($string . ' ', 0, 201));\n</code></pre>\n\n<p>The only difference is to add a space at the end of $string. This ensures the last word isn't cut off as per ReX357's comment.</p>\n\n<p>I don't have enough rep points to add this as a comment.</p>\n"
},
{
"answer_id": 10026115,
"author": "Bud Damyanov",
"author_id": 632524,
"author_profile": "https://Stackoverflow.com/users/632524",
"pm_score": 2,
"selected": false,
"text": "<pre><code>/*\nCut the string without breaking any words, UTF-8 aware \n* param string $str The text string to split\n* param integer $start The start position, defaults to 0\n* param integer $words The number of words to extract, defaults to 15\n*/\nfunction wordCutString($str, $start = 0, $words = 15 ) {\n $arr = preg_split(\"/[\\s]+/\", $str, $words+1);\n $arr = array_slice($arr, $start, $words);\n return join(' ', $arr);\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$input = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna liqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.';\necho wordCutString($input, 0, 10); \n</code></pre>\n\n<p>This will output first 10 words.</p>\n\n<p>The <code>preg_split</code> function is used to split a string into substrings. The boundaries along which the string is to be split, are specified using a regular expressions pattern.</p>\n\n<p><code>preg_split</code> function takes 4 parameters, but only the first 3 are relevant to us right now.</p>\n\n<p>First Parameter – Pattern\nThe first parameter is the regular expressions pattern along which the string is to be split. In our case, we want to split the string across word boundaries. Therefore we use a predefined character class <code>\\s</code> which matches white space characters such as space, tab, carriage return and line feed.</p>\n\n<p>Second Parameter – Input String\nThe second parameter is the long text string which we want to split.</p>\n\n<p>Third Parameter – Limit\nThe third parameter specifies the number of substrings which should be returned. If you set the limit to <code>n</code>, preg_split will return an array of n elements. The first <code>n-1</code> elements will contain the substrings. The last <code>(n th)</code> element will contain the rest of the string.</p>\n"
},
{
"answer_id": 15089518,
"author": "gosukiwi",
"author_id": 1015566,
"author_profile": "https://Stackoverflow.com/users/1015566",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is old, but...</p>\n\n<pre><code>function _truncate($str, $limit) {\n if(strlen($str) < $limit)\n return $str;\n $uid = uniqid();\n return array_shift(explode($uid, wordwrap($str, $limit, $uid)));\n}\n</code></pre>\n"
},
{
"answer_id": 17852480,
"author": "Sergiy Sokolenko",
"author_id": 131337,
"author_profile": "https://Stackoverflow.com/users/131337",
"pm_score": 5,
"selected": false,
"text": "<p>The following solution was born when I've noticed a $break parameter of <a href=\"http://php.net/wordwrap\" rel=\"noreferrer\">wordwrap</a> function:</p>\n\n<blockquote>\n <p>string wordwrap ( string $str [, int $width = 75 [, string $break =\n \"\\n\" [, bool $cut = false ]]] )</p>\n</blockquote>\n\n<p>Here is <strong>the solution</strong>:</p>\n\n<pre><code>/**\n * Truncates the given string at the specified length.\n *\n * @param string $str The input string.\n * @param int $width The number of chars at which the string will be truncated.\n * @return string\n */\nfunction truncate($str, $width) {\n return strtok(wordwrap($str, $width, \"...\\n\"), \"\\n\");\n}\n</code></pre>\n\n<p><strong>Example #1.</strong></p>\n\n<pre><code>print truncate(\"This is very long string with many chars.\", 25);\n</code></pre>\n\n<p>The above example will output:</p>\n\n<pre><code>This is very long string...\n</code></pre>\n\n<p><strong>Example #2.</strong></p>\n\n<pre><code>print truncate(\"This is short string.\", 25);\n</code></pre>\n\n<p>The above example will output:</p>\n\n<pre><code>This is short string.\n</code></pre>\n"
},
{
"answer_id": 21659546,
"author": "Yousef Altaf",
"author_id": 454012,
"author_profile": "https://Stackoverflow.com/users/454012",
"pm_score": -1,
"selected": false,
"text": "<p>I used this before</p>\n\n<pre><code><?php\n $your_desired_width = 200;\n $string = $var->content;\n if (strlen($string) > $your_desired_width) {\n $string = wordwrap($string, $your_desired_width);\n $string = substr($string, 0, strpos($string, \"\\n\")) . \" More...\";\n }\n echo $string;\n?>\n</code></pre>\n"
},
{
"answer_id": 22783274,
"author": "slash3b",
"author_id": 3478120,
"author_profile": "https://Stackoverflow.com/users/3478120",
"pm_score": -1,
"selected": false,
"text": "<p>May be this will help someone:</p>\n\n<pre><code><?php\n\n $string = \"Your line of text\";\n $spl = preg_match(\"/([, \\.\\d\\-''\\\"\\\"_()]*\\w+[, \\.\\d\\-''\\\"\\\"_()]*){50}/\", $string, $matches);\n if (isset($matches[0])) {\n $matches[0] .= \"...\";\n echo \"<br />\" . $matches[0];\n } else {\n echo \"<br />\" . $string;\n }\n\n?>\n</code></pre>\n"
},
{
"answer_id": 24204404,
"author": "Rikudou_Sennin",
"author_id": 3601208,
"author_profile": "https://Stackoverflow.com/users/3601208",
"pm_score": 1,
"selected": false,
"text": "<p>I have a function that does almost what you want, if you'll do a few edits, it will fit exactly:</p>\n\n<pre><code><?php\nfunction stripByWords($string,$length,$delimiter = '<br>') {\n $words_array = explode(\" \",$string);\n $strlen = 0;\n $return = '';\n foreach($words_array as $word) {\n $strlen += mb_strlen($word,'utf8');\n $return .= $word.\" \";\n if($strlen >= $length) {\n $strlen = 0;\n $return .= $delimiter;\n }\n }\n return $return;\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 24557257,
"author": "Artem P",
"author_id": 712308,
"author_profile": "https://Stackoverflow.com/users/712308",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$shorttext = preg_replace('/^([\\s\\S]{1,200})[\\s]+?[\\s\\S]+/', '$1', $fulltext);\n</code></pre>\n\n<p>Description:</p>\n\n<ul>\n<li><code>^</code> - start from beginning of string</li>\n<li><code>([\\s\\S]{1,200})</code> - get from 1 to 200 of any character</li>\n<li><code>[\\s]+?</code> - not include spaces at the end of short text so we can avoid <code>word ...</code> instead of <code>word...</code></li>\n<li><code>[\\s\\S]+</code> - match all other content</li>\n</ul>\n\n<p>Tests:</p>\n\n<ol>\n<li><a href=\"http://regex101.com/r/bV7dJ6/3\" rel=\"nofollow noreferrer\"><code>regex101.com</code></a> let's add to <code>or</code> few other <code>r</code></li>\n<li><a href=\"http://regex101.com/r/bV7dJ6/4\" rel=\"nofollow noreferrer\"><code>regex101.com</code></a> <code>orrrr</code> exactly 200 characters.</li>\n<li><a href=\"http://regex101.com/r/bV7dJ6/5\" rel=\"nofollow noreferrer\"><code>regex101.com</code></a> after fifth <code>r</code> <code>orrrrr</code> excluded.</li>\n</ol>\n\n<p>Enjoy.</p>\n"
},
{
"answer_id": 27420699,
"author": "Shashank Saxena",
"author_id": 2735410,
"author_profile": "https://Stackoverflow.com/users/2735410",
"pm_score": 1,
"selected": false,
"text": "<p>This is how i did it:</p>\n\n<pre><code>$string = \"I appreciate your service & idea to provide the branded toys at a fair rent price. This is really a wonderful to watch the kid not just playing with variety of toys but learning faster compare to the other kids who are not using the BooksandBeyond service. We wish you all the best\";\n\nprint_r(substr($string, 0, strpos(wordwrap($string, 250), \"\\n\")));\n</code></pre>\n"
},
{
"answer_id": 31030129,
"author": "evandro777",
"author_id": 1671683,
"author_profile": "https://Stackoverflow.com/users/1671683",
"pm_score": 0,
"selected": false,
"text": "<p>I create a function more similar to substr, and using the idea of @Dave.</p>\n\n<pre><code>function substr_full_word($str, $start, $end){\n $pos_ini = ($start == 0) ? $start : stripos(substr($str, $start, $end), ' ') + $start;\n if(strlen($str) > $end){ $pos_end = strrpos(substr($str, 0, ($end + 1)), ' '); } // IF STRING SIZE IS LESSER THAN END\n if(empty($pos_end)){ $pos_end = $end; } // FALLBACK\n return substr($str, $pos_ini, $pos_end);\n}\n</code></pre>\n\n<p>Ps.: The full length cut may be less than substr.</p>\n"
},
{
"answer_id": 32227063,
"author": "Abhijeet kumar sharma",
"author_id": 1101353,
"author_profile": "https://Stackoverflow.com/users/1101353",
"pm_score": -1,
"selected": false,
"text": "<p>Here you can try this</p>\n\n<pre><code>substr( $str, 0, strpos($str, ' ', 200) ); \n</code></pre>\n"
},
{
"answer_id": 32340759,
"author": "orrd",
"author_id": 1257764,
"author_profile": "https://Stackoverflow.com/users/1257764",
"pm_score": 2,
"selected": false,
"text": "<p>It's surprising how tricky it is to find the perfect solution to this problem. I haven't yet found an answer on this page that doesn't fail in at least some situations (especially if the string contains newlines or tabs, or if the word break is anything other than a space, or if the string has UTF-8 multibyte characters).</p>\n\n<p>Here is a simple solution that works in all cases. There were similar answers here, but the \"s\" modifier is important if you want it to work with multi-line input, and the \"u\" modifier makes it correctly evaluate UTF-8 multibyte characters.</p>\n\n<pre><code>function wholeWordTruncate($s, $characterCount) \n{\n if (preg_match(\"/^.{1,$characterCount}\\b/su\", $s, $match)) return $match[0];\n return $s;\n}\n</code></pre>\n\n<p>One possible edge case with this... if the string doesn't have any whitespace at all in the first $characterCount characters, it will return the entire string. If you prefer it forces a break at $characterCount even if it isn't a word boundary, you can use this:</p>\n\n<pre><code>function wholeWordTruncate($s, $characterCount) \n{\n if (preg_match(\"/^.{1,$characterCount}\\b/su\", $s, $match)) return $match[0];\n return mb_substr($return, 0, $characterCount);\n}\n</code></pre>\n\n<p>One last option, if you want to have it add ellipsis if it truncates the string... </p>\n\n<pre><code>function wholeWordTruncate($s, $characterCount, $addEllipsis = ' …') \n{\n $return = $s;\n if (preg_match(\"/^.{1,$characterCount}\\b/su\", $s, $match)) \n $return = $match[0];\n else\n $return = mb_substr($return, 0, $characterCount);\n if (strlen($s) > strlen($return)) $return .= $addEllipsis;\n return $return;\n}\n</code></pre>\n"
},
{
"answer_id": 35061022,
"author": "jdorenbush",
"author_id": 2321998,
"author_profile": "https://Stackoverflow.com/users/2321998",
"pm_score": 0,
"selected": false,
"text": "<p>Added IF/ELSEIF statements to the code from <a href=\"https://stackoverflow.com/a/4665347/2321998\">Dave</a> and <a href=\"https://stackoverflow.com/questions/79960/how-to-truncate-a-string-in-php-to-the-word-closest-to-a-certain-number-of-chara/4665347#comment36125374_4665347\">AmalMurali</a> for handling strings without spaces</p>\n\n<pre><code>if ((strpos($string, ' ') !== false) && (strlen($string) > 200)) { \n $WidgetText = substr($string, 0, strrpos(substr($string, 0, 200), ' ')); \n} \nelseif (strlen($string) > 200) {\n $WidgetText = substr($string, 0, 200);\n}\n</code></pre>\n"
},
{
"answer_id": 49194868,
"author": "Namida",
"author_id": 9467793,
"author_profile": "https://Stackoverflow.com/users/9467793",
"pm_score": -1,
"selected": false,
"text": "<p>I believe this is the easiest way to do it:</p>\n\n<pre><code>$lines = explode('♦♣♠',wordwrap($string, $length, '♦♣♠'));\n$newstring = $lines[0] . ' &bull; &bull; &bull;';\n</code></pre>\n\n<p>I'm using the special characters to split the text and cut it.</p>\n"
},
{
"answer_id": 50290843,
"author": "Mat Barnett",
"author_id": 2098954,
"author_profile": "https://Stackoverflow.com/users/2098954",
"pm_score": 0,
"selected": false,
"text": "<p>I find this works:</p>\n<pre><code>function abbreviate_string_to_whole_word($string, $max_length, $buffer) {\n if (strlen($string) > $max_length) {\n $string_cropped = substr($string, 0, $max_length - $buffer);\n $last_space = strrpos($string_cropped, " ");\n if ($last_space > 0) {\n $string_cropped = substr($string_cropped, 0, $last_space);\n }\n $abbreviated_string = $string_cropped . "&nbsp;...";\n }\n else {\n $abbreviated_string = $string;\n }\n return $abbreviated_string;\n}\n</code></pre>\n<p>The buffer allows you to adjust the length of the returned string.</p>\n"
},
{
"answer_id": 53894324,
"author": "Mahbub Alam",
"author_id": 6659365,
"author_profile": "https://Stackoverflow.com/users/6659365",
"pm_score": -1,
"selected": false,
"text": "<p>Use this: </p>\n\n<p>the following code will remove ','. If you have anyother character or sub-string, you may use that instead of ','</p>\n\n<pre><code>substr($string, 0, strrpos(substr($string, 0, $comparingLength), ','))\n</code></pre>\n\n<p>// if you have another string account for </p>\n\n<pre><code>substr($string, 0, strrpos(substr($string, 0, $comparingLength-strlen($currentString)), ','))\n</code></pre>\n"
},
{
"answer_id": 61022066,
"author": "Will B.",
"author_id": 1144627,
"author_profile": "https://Stackoverflow.com/users/1144627",
"pm_score": 1,
"selected": false,
"text": "<p>While this is a rather old question, I figured I would provide an alternative, as it was not mentioned and valid for PHP 4.3+.</p>\n\n<p>You can use the <a href=\"https://www.php.net/manual/en/function.sprintf.php\" rel=\"nofollow noreferrer\"><code>sprintf</code></a> family of functions to truncate text, by using the <code>%.ℕs</code> precision modifier.</p>\n\n<blockquote>\n <p>A period <code>.</code> followed by an integer who's meaning depends on the\n specifier:</p>\n \n <ul>\n <li>For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). </li>\n <li>For g and G specifiers: this is the maximum number of significant digits to be printed.</li>\n <li><strong>For s specifier: it acts as a cutoff point, setting a maximum character limit to the string</strong></li>\n </ul>\n</blockquote>\n\n<h2>Simple Truncation <a href=\"https://3v4l.org/QJDJU\" rel=\"nofollow noreferrer\">https://3v4l.org/QJDJU</a></h2>\n\n<pre class=\"lang-php prettyprint-override\"><code>$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';\nvar_dump(sprintf('%.10s', $string));\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>string(10) \"0123456789\"\n</code></pre>\n\n<hr>\n\n<h2>Expanded Truncation <a href=\"https://3v4l.org/FCD21\" rel=\"nofollow noreferrer\">https://3v4l.org/FCD21</a></h2>\n\n<p>Since <code>sprintf</code> functions similarly to <code>substr</code> and will partially cut off words. The below approach will ensure words are not cutoff by using <code>strpos(wordwrap(..., '[break]'), '[break]')</code> with a special delimiter. This allows us to retrieve the position and ensure we do not match on standard sentence structures.</p>\n\n<p>Returning a string without partially cutting off words and that does not exceed the specified width, while preserving line-breaks if desired.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>function truncate($string, $width, $on = '[break]') {\n if (strlen($string) > $width && false !== ($p = strpos(wordwrap($string, $width, $on), $on))) {\n $string = sprintf('%.'. $p . 's', $string);\n }\n return $string;\n}\nvar_dump(truncate('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 20));\n\nvar_dump(truncate(\"Lorem Ipsum is simply dummy text of the printing and typesetting industry.\", 20));\n\nvar_dump(truncate(\"Lorem Ipsum\\nis simply dummy text of the printing and typesetting industry.\", 20));\n</code></pre>\n\n<p><strong>Result</strong></p>\n\n<pre><code>/* \nstring(36) \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\" \nstring(14) \"Lorem Ipsum is\" \nstring(14) \"Lorem Ipsum\nis\" \n*/\n</code></pre>\n\n<p>Results using <code>wordwrap($string, $width)</code> or <code>strtok(wordwrap($string, $width), \"\\n\")</code></p>\n\n<pre><code>/*\nstring(14) \"Lorem Ipsum is\"\nstring(11) \"Lorem Ipsum\"\n*/\n</code></pre>\n"
},
{
"answer_id": 66559438,
"author": "HOSSEIN B",
"author_id": 14182190,
"author_profile": "https://Stackoverflow.com/users/14182190",
"pm_score": 2,
"selected": false,
"text": "<p>You can use this:</p>\n<pre><code>function word_shortener($text, $words=10, $sp='...'){\n\n $all = explode(' ', $text);\n $str = '';\n $count = 1;\n\n foreach($all as $key){\n $str .= $key . ($count >= $words ? '' : ' ');\n $count++;\n if($count > $words){\n break;\n }\n }\n\n return $str . (count($all) <= $words ? '' : $sp);\n\n}\n</code></pre>\n<p>Examples:</p>\n<pre><code>word_shortener("Hello world, this is a text", 3); // Hello world, this...\nword_shortener("Hello world, this is a text", 3, ''); // Hello world, this\nword_shortener("Hello world, this is a text", 3, '[read more]'); // Hello world, this[read more]\n</code></pre>\n<h1>Edit</h1>\n<p>How it's work:</p>\n<p><strong>1. Explode space from input text:</strong></p>\n<pre><code>$all = explode(' ', $text);\n</code></pre>\n<p>for example, if <code>$text</code> will be "Hello world" then <code>$all</code> is an array with exploded values:</p>\n<p><code>["Hello", "world"]</code></p>\n<p><strong>2. For each word:</strong></p>\n<p>Select each element in exploded text:</p>\n<pre><code>foreach($all as $key){...\n</code></pre>\n<p>Append current word(<code>$key</code>) to <code>$str</code> and space if it's the last word:</p>\n<pre><code>$str .= $key . ($count >= $words ? '' : ' ');\n</code></pre>\n<p>Then add 1 to <code>$count</code> and check if it's greater than max limit(<code>$words</code>) break the loop:</p>\n<pre><code>if($count > $words){\n break;\n}\n</code></pre>\n<p>Then return <code>$str</code> and separator(<code>$sp</code>) only if the final text is less than input text:</p>\n<pre><code>return $str . (count($all) <= $words ? '' : $sp);\n</code></pre>\n"
},
{
"answer_id": 69532106,
"author": "JesusIniesta",
"author_id": 3198983,
"author_profile": "https://Stackoverflow.com/users/3198983",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n<p>As far as I've seen, all the solutions here are only valid for the case when the starting point is fixed.</p>\n<p>Allowing you to turn this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna liqua. Ut enim ad minim veniam.\n</code></pre>\n<p>Into this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>Lorem ipsum dolor sit amet, consectetur...\n</code></pre>\n<h3>What if you want to truncate words surrounding a specific set of keywords?</h3>\n</blockquote>\n<h1>Truncate the text surrounding a specific set of keywords.</h1>\n<p>The goal is to be able to convert this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna liqua. Ut enim ad minim veniam.\n</code></pre>\n<p>Into this:</p>\n<pre class=\"lang-php prettyprint-override\"><code>...consectetur adipisicing elit, sed do eiusmod tempor...\n</code></pre>\n<p>Which is a very common situation when displaying search results, excerpts, etc. To achieve this we can use these two methods combined:</p>\n<pre class=\"lang-php prettyprint-override\"><code> /**\n * Return the index of the $haystack matching $needle,\n * or NULL if there is no match.\n *\n * This function is case-insensitive \n * \n * @param string $needle\n * @param array $haystack\n * @return false|int\n */\n function regexFindInArray(string $needle, array $haystack): ?int\n {\n for ($i = 0; $i < count($haystack); $i++) {\n if (preg_match('/' . preg_quote($needle) . '/i', $haystack[$i]) === 1) {\n return $i;\n }\n }\n return null;\n }\n\n /**\n * If the keyword is not present, it returns the maximum number of full \n * words that the max number of characters provided by $maxLength allow,\n * starting from the left.\n *\n * If the keyword is present, it adds words to both sides of the keyword\n * keeping a balanace between the length of the suffix and the prefix.\n *\n * @param string $text\n * @param string $keyword\n * @param int $maxLength\n * @param string $ellipsis\n * @return string\n */\n function truncateWordSurroundingsByLength(string $text, string $keyword, \n int $maxLength, string $ellipsis): string\n {\n if (strlen($text) < $maxLength) {\n return $text;\n }\n\n $pattern = '/' . '^(.*?)\\s' .\n '([^\\s]*' . preg_quote($keyword) . '[^\\s]*)' .\n '\\s(.*)$' . '/i';\n preg_match($pattern, $text, $matches);\n\n // break everything into words except the matching keywords, \n // which can contain spaces\n if (count($matches) == 4) {\n $words = preg_split("/\\s+/", $matches[1], -1, PREG_SPLIT_NO_EMPTY);\n $words[] = $matches[2];\n $words = array_merge($words, \n preg_split("/\\s+/", $matches[3], -1, PREG_SPLIT_NO_EMPTY));\n } else {\n $words = preg_split("/\\s+/", $text, -1, PREG_SPLIT_NO_EMPTY);\n }\n\n // find the index of the matching word\n $firstMatchingWordIndex = regexFindInArray($keyword, $words) ?? 0;\n\n $length = false;\n $prefixLength = $suffixLength = 0;\n $prefixIndex = $firstMatchingWordIndex - 1;\n $suffixIndex = $firstMatchingWordIndex + 1;\n\n // Initialize the text with the matching word\n $text = $words[$firstMatchingWordIndex];\n\n while (($prefixIndex >= 0 or $suffixIndex <= count($words))\n and strlen($text) < $maxLength and strlen($text) !== $length) {\n $length = strlen($text);\n if (isset($words[$prefixIndex])\n and (strlen($text) + strlen($words[$prefixIndex]) <= $maxLength)\n and ($prefixLength <= $suffixLength \n or strlen($text) + strlen($words[$suffixIndex]) <= $maxLength)) {\n $prefixLength += strlen($words[$prefixIndex]);\n $text = $words[$prefixIndex] . ' ' . $text;\n $prefixIndex--;\n }\n if (isset($words[$suffixIndex])\n and (strlen($text) + strlen($words[$suffixIndex]) <= $maxLength)\n and ($suffixLength <= $prefixLength \n or strlen($text) + strlen($words[$prefixIndex]) <= $maxLength)) {\n $suffixLength += strlen($words[$suffixIndex]);\n $text = $text . ' ' . $words[$suffixIndex];\n $suffixIndex++;\n }\n }\n\n if ($prefixIndex > 0) {\n $text = $ellipsis . ' ' . $text;\n }\n if ($suffixIndex < count($words)) {\n $text = $text . ' ' . $ellipsis;\n }\n\n return $text;\n }\n</code></pre>\n<p>Now you can do:</p>\n<pre class=\"lang-php prettyprint-override\"><code>$text = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do' .\n 'iusmod tempor incididunt ut labore et dolore magna liqua. Ut enim' .\n 'ad minim veniam.';\n\n$text = truncateWordSurroundingsByLength($text, 'elit', 25, '...');\n\nvar_dump($text); // string(32) "... adipisicing elit, sed do ..."\n</code></pre>\n<p><a href=\"http://sandbox.onlinephpfunctions.com/code/4f8a17dba1b7937c00a496424731b17917b9af9e\" rel=\"nofollow noreferrer\">Run code</a>.</p>\n"
},
{
"answer_id": 70406161,
"author": "younghallaji",
"author_id": 16925848,
"author_profile": "https://Stackoverflow.com/users/16925848",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function trunc($phrase, $max_words) {\n $phrase_array = explode(' ',$phrase);\n if(count($phrase_array) > $max_words && $max_words > 0)\n $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...';\n return $phrase;\n }\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14956/"
]
| I have a code snippet written in PHP that pulls a block of text from a database and sends it out to a widget on a webpage. The original block of text can be a lengthy article or a short sentence or two; but for this widget I can't display more than, say, 200 characters. I could use substr() to chop off the text at 200 chars, but the result would be cutting off in the middle of words-- what I really want is to chop the text at the end of the last *word* before 200 chars. | By using the [wordwrap](http://www.php.net/wordwrap) function. It splits the texts in multiple lines such that the maximum width is the one you specified, breaking at word boundaries. After splitting, you simply take the first line:
```
substr($string, 0, strpos(wordwrap($string, $your_desired_width), "\n"));
```
One thing this oneliner doesn't handle is the case when the text itself is shorter than the desired width. To handle this edge-case, one should do something like:
```
if (strlen($string) > $your_desired_width)
{
$string = wordwrap($string, $your_desired_width);
$string = substr($string, 0, strpos($string, "\n"));
}
```
---
The above solution has the problem of prematurely cutting the text if it contains a newline before the actual cutpoint. Here a version which solves this problem:
```
function tokenTruncate($string, $your_desired_width) {
$parts = preg_split('/([\s\n\r]+)/', $string, null, PREG_SPLIT_DELIM_CAPTURE);
$parts_count = count($parts);
$length = 0;
$last_part = 0;
for (; $last_part < $parts_count; ++$last_part) {
$length += strlen($parts[$last_part]);
if ($length > $your_desired_width) { break; }
}
return implode(array_slice($parts, 0, $last_part));
}
```
Also, here is the PHPUnit testclass used to test the implementation:
```
class TokenTruncateTest extends PHPUnit_Framework_TestCase {
public function testBasic() {
$this->assertEquals("1 3 5 7 9 ",
tokenTruncate("1 3 5 7 9 11 14", 10));
}
public function testEmptyString() {
$this->assertEquals("",
tokenTruncate("", 10));
}
public function testShortString() {
$this->assertEquals("1 3",
tokenTruncate("1 3", 10));
}
public function testStringTooLong() {
$this->assertEquals("",
tokenTruncate("toooooooooooolooooong", 10));
}
public function testContainingNewline() {
$this->assertEquals("1 3\n5 7 9 ",
tokenTruncate("1 3\n5 7 9 11 14", 10));
}
}
```
**EDIT :**
==========
Special UTF8 characters like 'à' are not handled. Add 'u' at the end of the REGEX to handle it:
`$parts = preg_split('/([\s\n\r]+)/u', $string, null, PREG_SPLIT_DELIM_CAPTURE);` |
79,968 | <p>I have a string which is like this:</p>
<pre><code>this is "a test"
</code></pre>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:</p>
<pre><code>['this', 'is', 'a test']
</code></pre>
<p>PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen.</p>
| [
{
"answer_id": 79985,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 10,
"selected": true,
"text": "<p>You want <code>split</code>, from the built-in <a href=\"https://docs.python.org/library/shlex.html\" rel=\"noreferrer\"><code>shlex</code></a> module.</p>\n<pre><code>>>> import shlex\n>>> shlex.split('this is "a test"')\n['this', 'is', 'a test']\n</code></pre>\n<p>This should do exactly what you want.</p>\n<p>If you want to preserve the quotation marks, then you can pass the <code>posix=False</code> kwarg.</p>\n<pre><code>>>> shlex.split('this is "a test"', posix=False)\n['this', 'is', '"a test"']\n</code></pre>\n"
},
{
"answer_id": 79989,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 6,
"selected": false,
"text": "<p>Have a look at the <code>shlex</code> module, particularly <code>shlex.split</code>.</p>\n\n<pre><code>>>> import shlex\n>>> shlex.split('This is \"a test\"')\n['This', 'is', 'a test']\n</code></pre>\n"
},
{
"answer_id": 80015,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code> def adamsplit(s):\n result = []\n inquotes = False\n for substring in s.split('\"'):\n if not inquotes:\n result.extend(substring.split())\n else:\n result.append(substring)\n inquotes = not inquotes\n return result\n</code></pre>\n\n<p>Some test strings:</p>\n\n<pre><code>'This is \"a test\"' -> ['This', 'is', 'a test']\n'\"This is \\'a test\\'\"' -> [\"This is 'a test'\"]\n</code></pre>\n"
},
{
"answer_id": 80361,
"author": "Gregory",
"author_id": 14351,
"author_profile": "https://Stackoverflow.com/users/14351",
"pm_score": -1,
"selected": false,
"text": "<p>If you don't care about sub strings than a simple</p>\n\n<pre><code>>>> 'a short sized string with spaces '.split()\n</code></pre>\n\n<p>Performance:</p>\n\n<pre><code>>>> s = \" ('a short sized string with spaces '*100).split() \"\n>>> t = timeit.Timer(stmt=s)\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n171.39 usec/pass\n</code></pre>\n\n<p>Or string module</p>\n\n<pre><code>>>> from string import split as stringsplit; \n>>> stringsplit('a short sized string with spaces '*100)\n</code></pre>\n\n<p>Performance: String module seems to perform better than string methods</p>\n\n<pre><code>>>> s = \"stringsplit('a short sized string with spaces '*100)\"\n>>> t = timeit.Timer(s, \"from string import split as stringsplit\")\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n154.88 usec/pass\n</code></pre>\n\n<p>Or you can use RE engine</p>\n\n<pre><code>>>> from re import split as resplit\n>>> regex = '\\s+'\n>>> medstring = 'a short sized string with spaces '*100\n>>> resplit(regex, medstring)\n</code></pre>\n\n<p>Performance</p>\n\n<pre><code>>>> s = \"resplit(regex, medstring)\"\n>>> t = timeit.Timer(s, \"from re import split as resplit; regex='\\s+'; medstring='a short sized string with spaces '*100\")\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n540.21 usec/pass\n</code></pre>\n\n<p>For very long strings you should not load the entire string into memory and instead either split the lines or use an iterative loop</p>\n"
},
{
"answer_id": 80449,
"author": "elifiner",
"author_id": 15109,
"author_profile": "https://Stackoverflow.com/users/15109",
"pm_score": 3,
"selected": false,
"text": "<p>Since this question is tagged with regex, I decided to try a regex approach. I first replace all the spaces in the quotes parts with \\x00, then split by spaces, then replace the \\x00 back to spaces in each part.</p>\n\n<p>Both versions do the same thing, but splitter is a bit more readable then splitter2.</p>\n\n<pre><code>import re\n\ns = 'this is \"a test\" some text \"another test\"'\n\ndef splitter(s):\n def replacer(m):\n return m.group(0).replace(\" \", \"\\x00\")\n parts = re.sub('\".+?\"', replacer, s).split()\n parts = [p.replace(\"\\x00\", \" \") for p in parts]\n return parts\n\ndef splitter2(s):\n return [p.replace(\"\\x00\", \" \") for p in re.sub('\".+?\"', lambda m: m.group(0).replace(\" \", \"\\x00\"), s).split()]\n\nprint splitter2(s)\n</code></pre>\n"
},
{
"answer_id": 524796,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>I see regex approaches here that look complex and/or wrong. This surprises me, because regex syntax can easily describe \"whitespace or thing-surrounded-by-quotes\", and most regex engines (including Python's) can split on a regex. So if you're going to use regexes, why not just say exactly what you mean?:</p>\n\n<pre><code>test = 'this is \"a test\"' # or \"this is 'a test'\"\n# pieces = [p for p in re.split(\"( |[\\\\\\\"'].*[\\\\\\\"'])\", test) if p.strip()]\n# From comments, use this:\npieces = [p for p in re.split(\"( |\\\\\\\".*?\\\\\\\"|'.*?')\", test) if p.strip()]\n</code></pre>\n\n<p>Explanation:</p>\n\n<pre><code>[\\\\\\\"'] = double-quote or single-quote\n.* = anything\n( |X) = space or X\n.strip() = remove space and empty-string separators\n</code></pre>\n\n<p>shlex probably provides more features, though.</p>\n"
},
{
"answer_id": 525011,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 5,
"selected": false,
"text": "<p>Depending on your use case, you may also want to check out the <a href=\"https://docs.python.org/library/csv.html\" rel=\"noreferrer\"><code>csv</code></a> module:</p>\n\n<pre><code>import csv\nlines = ['this is \"a string\"', 'and more \"stuff\"']\nfor row in csv.reader(lines, delimiter=\" \"):\n print(row)\n</code></pre>\n\n<p>Output: </p>\n\n<pre><code>['this', 'is', 'a string']\n['and', 'more', 'stuff']\n</code></pre>\n"
},
{
"answer_id": 2159337,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm, can't seem to find the \"Reply\" button... anyway, this answer is based on the approach by Kate, but correctly splits strings with substrings containing escaped quotes and also removes the start and end quotes of the substrings:</p>\n\n<pre><code> [i.strip('\"').strip(\"'\") for i in re.split(r'(\\s+|(?<!\\\\)\".*?(?<!\\\\)\"|(?<!\\\\)\\'.*?(?<!\\\\)\\')', string) if i.strip()]\n</code></pre>\n\n<p>This works on strings like <code>'This is \" a \\\\\\\"test\\\\\\\"\\\\\\'s substring\"'</code> (the insane markup is unfortunately necessary to keep Python from removing the escapes).</p>\n\n<p>If the resulting escapes in the strings in the returned list are not wanted, you can use this slightly altered version of the function:</p>\n\n<pre><code>[i.strip('\"').strip(\"'\").decode('string_escape') for i in re.split(r'(\\s+|(?<!\\\\)\".*?(?<!\\\\)\"|(?<!\\\\)\\'.*?(?<!\\\\)\\')', string) if i.strip()]\n</code></pre>\n"
},
{
"answer_id": 11194593,
"author": "moschlar",
"author_id": 1175818,
"author_profile": "https://Stackoverflow.com/users/1175818",
"pm_score": 1,
"selected": false,
"text": "<p>To get around the unicode issues in some Python 2 versions, I suggest:</p>\n\n<pre><code>from shlex import split as _split\nsplit = lambda a: [b.decode('utf-8') for b in _split(a.encode('utf-8'))]\n</code></pre>\n"
},
{
"answer_id": 23155180,
"author": "Daniel Dai",
"author_id": 1089262,
"author_profile": "https://Stackoverflow.com/users/1089262",
"pm_score": 4,
"selected": false,
"text": "<p>I use shlex.split to process 70,000,000 lines of squid log, it's so slow. So I switched to re.</p>\n\n<p>Please try this, if you have performance problem with shlex.</p>\n\n<pre><code>import re\n\ndef line_split(line):\n return re.findall(r'[^\"\\s]\\S*|\".+?\"', line)\n</code></pre>\n"
},
{
"answer_id": 32480710,
"author": "hussic",
"author_id": 4111130,
"author_profile": "https://Stackoverflow.com/users/4111130",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest:</p>\n\n<p>test string:</p>\n\n<pre><code>s = 'abc \"ad\" \\'fg\\' \"kk\\'rdt\\'\" zzz\"34\"zzz \"\" \\'\\''\n</code></pre>\n\n<p>to capture also \"\" and '':</p>\n\n<pre><code>import re\nre.findall(r'\"[^\"]*\"|\\'[^\\']*\\'|[^\"\\'\\s]+',s)\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>['abc', '\"ad\"', \"'fg'\", '\"kk\\'rdt\\'\"', 'zzz', '\"34\"', 'zzz', '\"\"', \"''\"]\n</code></pre>\n\n<p>to ignore empty \"\" and '':</p>\n\n<pre><code>import re\nre.findall(r'\"[^\"]+\"|\\'[^\\']+\\'|[^\"\\'\\s]+',s)\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>['abc', '\"ad\"', \"'fg'\", '\"kk\\'rdt\\'\"', 'zzz', '\"34\"', 'zzz']\n</code></pre>\n"
},
{
"answer_id": 43035638,
"author": "THE_MAD_KING",
"author_id": 7771160,
"author_profile": "https://Stackoverflow.com/users/7771160",
"pm_score": 2,
"selected": false,
"text": "<p>To preserve quotes use this function:</p>\n\n<pre><code>def getArgs(s):\n args = []\n cur = ''\n inQuotes = 0\n for char in s.strip():\n if char == ' ' and not inQuotes:\n args.append(cur)\n cur = ''\n elif char == '\"' and not inQuotes:\n inQuotes = 1\n cur += char\n elif char == '\"' and inQuotes:\n inQuotes = 0\n cur += char\n else:\n cur += char\n args.append(cur)\n return args\n</code></pre>\n"
},
{
"answer_id": 49791573,
"author": "har777",
"author_id": 1851428,
"author_profile": "https://Stackoverflow.com/users/1851428",
"pm_score": 3,
"selected": false,
"text": "<p>Speed test of different answers:</p>\n\n<pre><code>import re\nimport shlex\nimport csv\n\nline = 'this is \"a test\"'\n\n%timeit [p for p in re.split(\"( |\\\\\\\".*?\\\\\\\"|'.*?')\", line) if p.strip()]\n100000 loops, best of 3: 5.17 µs per loop\n\n%timeit re.findall(r'[^\"\\s]\\S*|\".+?\"', line)\n100000 loops, best of 3: 2.88 µs per loop\n\n%timeit list(csv.reader([line], delimiter=\" \"))\nThe slowest run took 9.62 times longer than the fastest. This could mean that an intermediate result is being cached.\n100000 loops, best of 3: 2.4 µs per loop\n\n%timeit shlex.split(line)\n10000 loops, best of 3: 50.2 µs per loop\n</code></pre>\n"
},
{
"answer_id": 51560564,
"author": "Ton van den Heuvel",
"author_id": 79111,
"author_profile": "https://Stackoverflow.com/users/79111",
"pm_score": 3,
"selected": false,
"text": "<p>The main problem with the accepted <code>shlex</code> approach is that it does not ignore escape characters outside quoted substrings, and gives slightly unexpected results in some corner cases.</p>\n<p>I have the following use case, where I need a split function that splits input strings such that either single-quoted or double-quoted substrings are preserved, with the ability to escape quotes within such a substring. Quotes within an unquoted string should not be treated differently from any other character. Some example test cases with the expected output:</p>\n<pre> input string | expected output\n===============================================\n 'abc def' | ['abc', 'def']\n \"abc \\\\s def\" | ['abc', '\\\\s', 'def']\n '\"abc def\" ghi' | ['abc def', 'ghi']\n \"'abc def' ghi\" | ['abc def', 'ghi']\n '\"abc \\\\\" def\" ghi' | ['abc \" def', 'ghi']\n \"'abc \\\\' def' ghi\" | [\"abc ' def\", 'ghi']\n \"'abc \\\\s def' ghi\" | ['abc \\\\s def', 'ghi']\n '\"abc \\\\s def\" ghi' | ['abc \\\\s def', 'ghi']\n '\"\" test' | ['', 'test']\n \"'' test\" | ['', 'test']\n \"abc'def\" | [\"abc'def\"]\n \"abc'def'\" | [\"abc'def'\"]\n \"abc'def' ghi\" | [\"abc'def'\", 'ghi']\n \"abc'def'ghi\" | [\"abc'def'ghi\"]\n 'abc\"def' | ['abc\"def']\n 'abc\"def\"' | ['abc\"def\"']\n 'abc\"def\" ghi' | ['abc\"def\"', 'ghi']\n 'abc\"def\"ghi' | ['abc\"def\"ghi']\n \"r'AA' r'.*_xyz$'\" | [\"r'AA'\", \"r'.*_xyz$'\"]\n 'abc\"def ghi\"' | ['abc\"def ghi\"']\n 'abc\"def ghi\"\"jkl\"' | ['abc\"def ghi\"\"jkl\"']\n 'a\"b c\"d\"e\"f\"g h\"' | ['a\"b c\"d\"e\"f\"g h\"']\n 'c=\"ls /\" type key' | ['c=\"ls /\"', 'type', 'key']\n \"abc'def ghi'\" | [\"abc'def ghi'\"]\n \"c='ls /' type key\" | [\"c='ls /'\", 'type', 'key']</pre>\n<p>I ended up with the following function to split a string such that the expected output results for all input strings:</p>\n<pre><code>import re\n\ndef quoted_split(s):\n def strip_quotes(s):\n if s and (s[0] == '\"' or s[0] == \"'\") and s[0] == s[-1]:\n return s[1:-1]\n return s\n return [strip_quotes(p).replace('\\\\\"', '\"').replace(\"\\\\'\", \"'\") \\\n for p in re.findall(r'(?:[^\"\\s]*\"(?:\\\\.|[^\"])*\"[^\"\\s]*)+|(?:[^\\'\\s]*\\'(?:\\\\.|[^\\'])*\\'[^\\'\\s]*)+|[^\\s]+', s)]\n</code></pre>\n<p>It ain't pretty; but it works. The following test application checks the results of other approaches (<code>shlex</code> and <code>csv</code> for now) and the custom split implementation:</p>\n<pre><code>#!/bin/python2.7\n\nimport csv\nimport re\nimport shlex\n\nfrom timeit import timeit\n\ndef test_case(fn, s, expected):\n try:\n if fn(s) == expected:\n print '[ OK ] %s -> %s' % (s, fn(s))\n else:\n print '[FAIL] %s -> %s' % (s, fn(s))\n except Exception as e:\n print '[FAIL] %s -> exception: %s' % (s, e)\n\ndef test_case_no_output(fn, s, expected):\n try:\n fn(s)\n except:\n pass\n\ndef test_split(fn, test_case_fn=test_case):\n test_case_fn(fn, 'abc def', ['abc', 'def'])\n test_case_fn(fn, \"abc \\\\s def\", ['abc', '\\\\s', 'def'])\n test_case_fn(fn, '\"abc def\" ghi', ['abc def', 'ghi'])\n test_case_fn(fn, \"'abc def' ghi\", ['abc def', 'ghi'])\n test_case_fn(fn, '\"abc \\\\\" def\" ghi', ['abc \" def', 'ghi'])\n test_case_fn(fn, \"'abc \\\\' def' ghi\", [\"abc ' def\", 'ghi'])\n test_case_fn(fn, \"'abc \\\\s def' ghi\", ['abc \\\\s def', 'ghi'])\n test_case_fn(fn, '\"abc \\\\s def\" ghi', ['abc \\\\s def', 'ghi'])\n test_case_fn(fn, '\"\" test', ['', 'test'])\n test_case_fn(fn, \"'' test\", ['', 'test'])\n test_case_fn(fn, \"abc'def\", [\"abc'def\"])\n test_case_fn(fn, \"abc'def'\", [\"abc'def'\"])\n test_case_fn(fn, \"abc'def' ghi\", [\"abc'def'\", 'ghi'])\n test_case_fn(fn, \"abc'def'ghi\", [\"abc'def'ghi\"])\n test_case_fn(fn, 'abc\"def', ['abc\"def'])\n test_case_fn(fn, 'abc\"def\"', ['abc\"def\"'])\n test_case_fn(fn, 'abc\"def\" ghi', ['abc\"def\"', 'ghi'])\n test_case_fn(fn, 'abc\"def\"ghi', ['abc\"def\"ghi'])\n test_case_fn(fn, \"r'AA' r'.*_xyz$'\", [\"r'AA'\", \"r'.*_xyz$'\"])\n test_case_fn(fn, 'abc\"def ghi\"', ['abc\"def ghi\"'])\n test_case_fn(fn, 'abc\"def ghi\"\"jkl\"', ['abc\"def ghi\"\"jkl\"'])\n test_case_fn(fn, 'a\"b c\"d\"e\"f\"g h\"', ['a\"b c\"d\"e\"f\"g h\"'])\n test_case_fn(fn, 'c=\"ls /\" type key', ['c=\"ls /\"', 'type', 'key'])\n test_case_fn(fn, \"abc'def ghi'\", [\"abc'def ghi'\"])\n test_case_fn(fn, \"c='ls /' type key\", [\"c='ls /'\", 'type', 'key'])\n\ndef csv_split(s):\n return list(csv.reader([s], delimiter=' '))[0]\n\ndef re_split(s):\n def strip_quotes(s):\n if s and (s[0] == '\"' or s[0] == \"'\") and s[0] == s[-1]:\n return s[1:-1]\n return s\n return [strip_quotes(p).replace('\\\\\"', '\"').replace(\"\\\\'\", \"'\") for p in re.findall(r'(?:[^\"\\s]*\"(?:\\\\.|[^\"])*\"[^\"\\s]*)+|(?:[^\\'\\s]*\\'(?:\\\\.|[^\\'])*\\'[^\\'\\s]*)+|[^\\s]+', s)]\n\nif __name__ == '__main__':\n print 'shlex\\n'\n test_split(shlex.split)\n print\n\n print 'csv\\n'\n test_split(csv_split)\n print\n\n print 're\\n'\n test_split(re_split)\n print\n\n iterations = 100\n setup = 'from __main__ import test_split, test_case_no_output, csv_split, re_split\\nimport shlex, re'\n def benchmark(method, code):\n print '%s: %.3fms per iteration' % (method, (1000 * timeit(code, setup=setup, number=iterations) / iterations))\n benchmark('shlex', 'test_split(shlex.split, test_case_no_output)')\n benchmark('csv', 'test_split(csv_split, test_case_no_output)')\n benchmark('re', 'test_split(re_split, test_case_no_output)')\n</code></pre>\n<p>Output:</p>\n<pre>\nshlex\n\n[ OK ] abc def -> ['abc', 'def']\n[FAIL] abc \\s def -> ['abc', 's', 'def']\n[ OK ] \"abc def\" ghi -> ['abc def', 'ghi']\n[ OK ] 'abc def' ghi -> ['abc def', 'ghi']\n[ OK ] \"abc \\\" def\" ghi -> ['abc \" def', 'ghi']\n[FAIL] 'abc \\' def' ghi -> exception: No closing quotation\n[ OK ] 'abc \\s def' ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"abc \\s def\" ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"\" test -> ['', 'test']\n[ OK ] '' test -> ['', 'test']\n[FAIL] abc'def -> exception: No closing quotation\n[FAIL] abc'def' -> ['abcdef']\n[FAIL] abc'def' ghi -> ['abcdef', 'ghi']\n[FAIL] abc'def'ghi -> ['abcdefghi']\n[FAIL] abc\"def -> exception: No closing quotation\n[FAIL] abc\"def\" -> ['abcdef']\n[FAIL] abc\"def\" ghi -> ['abcdef', 'ghi']\n[FAIL] abc\"def\"ghi -> ['abcdefghi']\n[FAIL] r'AA' r'.*_xyz$' -> ['rAA', 'r.*_xyz$']\n[FAIL] abc\"def ghi\" -> ['abcdef ghi']\n[FAIL] abc\"def ghi\"\"jkl\" -> ['abcdef ghijkl']\n[FAIL] a\"b c\"d\"e\"f\"g h\" -> ['ab cdefg h']\n[FAIL] c=\"ls /\" type key -> ['c=ls /', 'type', 'key']\n[FAIL] abc'def ghi' -> ['abcdef ghi']\n[FAIL] c='ls /' type key -> ['c=ls /', 'type', 'key']\n\ncsv\n\n[ OK ] abc def -> ['abc', 'def']\n[ OK ] abc \\s def -> ['abc', '\\\\s', 'def']\n[ OK ] \"abc def\" ghi -> ['abc def', 'ghi']\n[FAIL] 'abc def' ghi -> [\"'abc\", \"def'\", 'ghi']\n[FAIL] \"abc \\\" def\" ghi -> ['abc \\\\', 'def\"', 'ghi']\n[FAIL] 'abc \\' def' ghi -> [\"'abc\", \"\\\\'\", \"def'\", 'ghi']\n[FAIL] 'abc \\s def' ghi -> [\"'abc\", '\\\\s', \"def'\", 'ghi']\n[ OK ] \"abc \\s def\" ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"\" test -> ['', 'test']\n[FAIL] '' test -> [\"''\", 'test']\n[ OK ] abc'def -> [\"abc'def\"]\n[ OK ] abc'def' -> [\"abc'def'\"]\n[ OK ] abc'def' ghi -> [\"abc'def'\", 'ghi']\n[ OK ] abc'def'ghi -> [\"abc'def'ghi\"]\n[ OK ] abc\"def -> ['abc\"def']\n[ OK ] abc\"def\" -> ['abc\"def\"']\n[ OK ] abc\"def\" ghi -> ['abc\"def\"', 'ghi']\n[ OK ] abc\"def\"ghi -> ['abc\"def\"ghi']\n[ OK ] r'AA' r'.*_xyz$' -> [\"r'AA'\", \"r'.*_xyz$'\"]\n[FAIL] abc\"def ghi\" -> ['abc\"def', 'ghi\"']\n[FAIL] abc\"def ghi\"\"jkl\" -> ['abc\"def', 'ghi\"\"jkl\"']\n[FAIL] a\"b c\"d\"e\"f\"g h\" -> ['a\"b', 'c\"d\"e\"f\"g', 'h\"']\n[FAIL] c=\"ls /\" type key -> ['c=\"ls', '/\"', 'type', 'key']\n[FAIL] abc'def ghi' -> [\"abc'def\", \"ghi'\"]\n[FAIL] c='ls /' type key -> [\"c='ls\", \"/'\", 'type', 'key']\n\nre\n\n[ OK ] abc def -> ['abc', 'def']\n[ OK ] abc \\s def -> ['abc', '\\\\s', 'def']\n[ OK ] \"abc def\" ghi -> ['abc def', 'ghi']\n[ OK ] 'abc def' ghi -> ['abc def', 'ghi']\n[ OK ] \"abc \\\" def\" ghi -> ['abc \" def', 'ghi']\n[ OK ] 'abc \\' def' ghi -> [\"abc ' def\", 'ghi']\n[ OK ] 'abc \\s def' ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"abc \\s def\" ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"\" test -> ['', 'test']\n[ OK ] '' test -> ['', 'test']\n[ OK ] abc'def -> [\"abc'def\"]\n[ OK ] abc'def' -> [\"abc'def'\"]\n[ OK ] abc'def' ghi -> [\"abc'def'\", 'ghi']\n[ OK ] abc'def'ghi -> [\"abc'def'ghi\"]\n[ OK ] abc\"def -> ['abc\"def']\n[ OK ] abc\"def\" -> ['abc\"def\"']\n[ OK ] abc\"def\" ghi -> ['abc\"def\"', 'ghi']\n[ OK ] abc\"def\"ghi -> ['abc\"def\"ghi']\n[ OK ] r'AA' r'.*_xyz$' -> [\"r'AA'\", \"r'.*_xyz$'\"]\n[ OK ] abc\"def ghi\" -> ['abc\"def ghi\"']\n[ OK ] abc\"def ghi\"\"jkl\" -> ['abc\"def ghi\"\"jkl\"']\n[ OK ] a\"b c\"d\"e\"f\"g h\" -> ['a\"b c\"d\"e\"f\"g h\"']\n[ OK ] c=\"ls /\" type key -> ['c=\"ls /\"', 'type', 'key']\n[ OK ] abc'def ghi' -> [\"abc'def ghi'\"]\n[ OK ] c='ls /' type key -> [\"c='ls /'\", 'type', 'key']\n\nshlex: 0.335ms per iteration\ncsv: 0.036ms per iteration\nre: 0.068ms per iteration\n</pre>\n<p>So performance is much better than <code>shlex</code>, and can be improved further by precompiling the regular expression, in which case it will outperform the <code>csv</code> approach.</p>\n"
},
{
"answer_id": 53210803,
"author": "hochl",
"author_id": 589206,
"author_profile": "https://Stackoverflow.com/users/589206",
"pm_score": 4,
"selected": false,
"text": "<p>It seems that for performance reasons <code>re</code> is faster. Here is my solution using a least greedy operator that preserves the outer quotes:</p>\n\n<pre><code>re.findall(\"(?:\\\".*?\\\"|\\S)+\", s)\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>['this', 'is', '\"a test\"']\n</code></pre>\n\n<p>It leaves constructs like <code>aaa\"bla blub\"bbb</code> together as these tokens are not separated by spaces. If the string contains escaped characters, you can match like that:</p>\n\n<pre><code>>>> a = \"She said \\\"He said, \\\\\\\"My name is Mark.\\\\\\\"\\\"\"\n>>> a\n'She said \"He said, \\\\\"My name is Mark.\\\\\"\"'\n>>> for i in re.findall(\"(?:\\\".*?[^\\\\\\\\]\\\"|\\S)+\", a): print(i)\n...\nShe\nsaid\n\"He said, \\\"My name is Mark.\\\"\"\n</code></pre>\n\n<p>Please note that this also matches the empty string <code>\"\"</code> by means of the <code>\\S</code> part of the pattern.</p>\n"
},
{
"answer_id": 60929888,
"author": "Mikhail Zakharov",
"author_id": 9127614,
"author_profile": "https://Stackoverflow.com/users/9127614",
"pm_score": 1,
"selected": false,
"text": "<p>As an option try tssplit:</p>\n\n<pre><code>In [1]: from tssplit import tssplit\nIn [2]: tssplit('this is \"a test\"', quote='\"', delimiter='')\nOut[2]: ['this', 'is', 'a test']\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
]
| I have a string which is like this:
```
this is "a test"
```
I'm trying to write something in Python to split it up by space while ignoring spaces within quotes. The result I'm looking for is:
```
['this', 'is', 'a test']
```
PS. I know you are going to ask "what happens if there are quotes within the quotes, well, in my application, that will never happen. | You want `split`, from the built-in [`shlex`](https://docs.python.org/library/shlex.html) module.
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
This should do exactly what you want.
If you want to preserve the quotation marks, then you can pass the `posix=False` kwarg.
```
>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']
``` |
79,992 | <p>Ideally the reader has upgraded a native C++ program to Visual Studio 2008, which contains an OpenClipboard() block. Why not try setting a breakpoint just after getting a successful return-code from OpenClipboard() and step through your code. According to the Internet it may work on your system, but of course, not on mine, thanks for trying. </p>
<p>Googling on e.g. (( OpenClipboard 1418 vc6 )) finds articles like "GetClipboardData fails in debugger" and "No Error in VC++6 but Error in VC++ 2005". Pragmatically for-the-moment, problem solved - I simply cannot set breakpoints within such code, I need to squirrel information and set the breakpoint after the clipboard operations are done. Error 1418 is "Thread does not have a clipboard open" but it works fine as long as you don't step with VS.NET, or like I say if you keep breakpoints outside of the clipboard-open-close-block.<p>
I would feel better knowing what the exact issue is with the VS.NET debugger.<p>
Being a C++ person I am only dimly aware that you are not supposed to think in terms of threads when doing dot-Net. Anyway I did not find a guru-quality explanation of what's really going on, whether in-fact the problem is that the dot-Net debugger is subtly interfering with the thread-information somehow, when you single-step thru native C++ code. <P></p>
<p>System-wise: about a year old, two dual-core Xeon's, 4 CPU's according to XP-pro.
I had just finished debugging the code by single-stepping thru it in vc6 under XP-SP2-32-bit. So I know the code was pretty-much-fine under vc6. However when I tested with a 10-megabyte CF_TEXT I got exceptions. I thought to try debugging under the nicer exception model of XP-x64.<p>
Recompiled with visual-studio-2008, I could not get the code to single-step at all. OpenClipboard worked, but EnumClipboardFormats() did not work, nothing worked when single-stepped. However, when I set the breakpoint below the complete block of code, everything worked fine. And <em>YES</em> vc2008 made a pinpoint diagnostic 'stack frame corruption around szBuf. There is a lot to like about vc2008. It would be nice if this were somehow merely a clipboard problem - without knowing that I would feel compelled to worry about stepping thru ANYTHING, whether thread-context-issues might be due to the dot-Net-debugger.</p>
| [
{
"answer_id": 79985,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 10,
"selected": true,
"text": "<p>You want <code>split</code>, from the built-in <a href=\"https://docs.python.org/library/shlex.html\" rel=\"noreferrer\"><code>shlex</code></a> module.</p>\n<pre><code>>>> import shlex\n>>> shlex.split('this is "a test"')\n['this', 'is', 'a test']\n</code></pre>\n<p>This should do exactly what you want.</p>\n<p>If you want to preserve the quotation marks, then you can pass the <code>posix=False</code> kwarg.</p>\n<pre><code>>>> shlex.split('this is "a test"', posix=False)\n['this', 'is', '"a test"']\n</code></pre>\n"
},
{
"answer_id": 79989,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 6,
"selected": false,
"text": "<p>Have a look at the <code>shlex</code> module, particularly <code>shlex.split</code>.</p>\n\n<pre><code>>>> import shlex\n>>> shlex.split('This is \"a test\"')\n['This', 'is', 'a test']\n</code></pre>\n"
},
{
"answer_id": 80015,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code> def adamsplit(s):\n result = []\n inquotes = False\n for substring in s.split('\"'):\n if not inquotes:\n result.extend(substring.split())\n else:\n result.append(substring)\n inquotes = not inquotes\n return result\n</code></pre>\n\n<p>Some test strings:</p>\n\n<pre><code>'This is \"a test\"' -> ['This', 'is', 'a test']\n'\"This is \\'a test\\'\"' -> [\"This is 'a test'\"]\n</code></pre>\n"
},
{
"answer_id": 80361,
"author": "Gregory",
"author_id": 14351,
"author_profile": "https://Stackoverflow.com/users/14351",
"pm_score": -1,
"selected": false,
"text": "<p>If you don't care about sub strings than a simple</p>\n\n<pre><code>>>> 'a short sized string with spaces '.split()\n</code></pre>\n\n<p>Performance:</p>\n\n<pre><code>>>> s = \" ('a short sized string with spaces '*100).split() \"\n>>> t = timeit.Timer(stmt=s)\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n171.39 usec/pass\n</code></pre>\n\n<p>Or string module</p>\n\n<pre><code>>>> from string import split as stringsplit; \n>>> stringsplit('a short sized string with spaces '*100)\n</code></pre>\n\n<p>Performance: String module seems to perform better than string methods</p>\n\n<pre><code>>>> s = \"stringsplit('a short sized string with spaces '*100)\"\n>>> t = timeit.Timer(s, \"from string import split as stringsplit\")\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n154.88 usec/pass\n</code></pre>\n\n<p>Or you can use RE engine</p>\n\n<pre><code>>>> from re import split as resplit\n>>> regex = '\\s+'\n>>> medstring = 'a short sized string with spaces '*100\n>>> resplit(regex, medstring)\n</code></pre>\n\n<p>Performance</p>\n\n<pre><code>>>> s = \"resplit(regex, medstring)\"\n>>> t = timeit.Timer(s, \"from re import split as resplit; regex='\\s+'; medstring='a short sized string with spaces '*100\")\n>>> print \"%.2f usec/pass\" % (1000000 * t.timeit(number=100000)/100000)\n540.21 usec/pass\n</code></pre>\n\n<p>For very long strings you should not load the entire string into memory and instead either split the lines or use an iterative loop</p>\n"
},
{
"answer_id": 80449,
"author": "elifiner",
"author_id": 15109,
"author_profile": "https://Stackoverflow.com/users/15109",
"pm_score": 3,
"selected": false,
"text": "<p>Since this question is tagged with regex, I decided to try a regex approach. I first replace all the spaces in the quotes parts with \\x00, then split by spaces, then replace the \\x00 back to spaces in each part.</p>\n\n<p>Both versions do the same thing, but splitter is a bit more readable then splitter2.</p>\n\n<pre><code>import re\n\ns = 'this is \"a test\" some text \"another test\"'\n\ndef splitter(s):\n def replacer(m):\n return m.group(0).replace(\" \", \"\\x00\")\n parts = re.sub('\".+?\"', replacer, s).split()\n parts = [p.replace(\"\\x00\", \" \") for p in parts]\n return parts\n\ndef splitter2(s):\n return [p.replace(\"\\x00\", \" \") for p in re.sub('\".+?\"', lambda m: m.group(0).replace(\" \", \"\\x00\"), s).split()]\n\nprint splitter2(s)\n</code></pre>\n"
},
{
"answer_id": 524796,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>I see regex approaches here that look complex and/or wrong. This surprises me, because regex syntax can easily describe \"whitespace or thing-surrounded-by-quotes\", and most regex engines (including Python's) can split on a regex. So if you're going to use regexes, why not just say exactly what you mean?:</p>\n\n<pre><code>test = 'this is \"a test\"' # or \"this is 'a test'\"\n# pieces = [p for p in re.split(\"( |[\\\\\\\"'].*[\\\\\\\"'])\", test) if p.strip()]\n# From comments, use this:\npieces = [p for p in re.split(\"( |\\\\\\\".*?\\\\\\\"|'.*?')\", test) if p.strip()]\n</code></pre>\n\n<p>Explanation:</p>\n\n<pre><code>[\\\\\\\"'] = double-quote or single-quote\n.* = anything\n( |X) = space or X\n.strip() = remove space and empty-string separators\n</code></pre>\n\n<p>shlex probably provides more features, though.</p>\n"
},
{
"answer_id": 525011,
"author": "Ryan Ginstrom",
"author_id": 10658,
"author_profile": "https://Stackoverflow.com/users/10658",
"pm_score": 5,
"selected": false,
"text": "<p>Depending on your use case, you may also want to check out the <a href=\"https://docs.python.org/library/csv.html\" rel=\"noreferrer\"><code>csv</code></a> module:</p>\n\n<pre><code>import csv\nlines = ['this is \"a string\"', 'and more \"stuff\"']\nfor row in csv.reader(lines, delimiter=\" \"):\n print(row)\n</code></pre>\n\n<p>Output: </p>\n\n<pre><code>['this', 'is', 'a string']\n['and', 'more', 'stuff']\n</code></pre>\n"
},
{
"answer_id": 2159337,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Hmm, can't seem to find the \"Reply\" button... anyway, this answer is based on the approach by Kate, but correctly splits strings with substrings containing escaped quotes and also removes the start and end quotes of the substrings:</p>\n\n<pre><code> [i.strip('\"').strip(\"'\") for i in re.split(r'(\\s+|(?<!\\\\)\".*?(?<!\\\\)\"|(?<!\\\\)\\'.*?(?<!\\\\)\\')', string) if i.strip()]\n</code></pre>\n\n<p>This works on strings like <code>'This is \" a \\\\\\\"test\\\\\\\"\\\\\\'s substring\"'</code> (the insane markup is unfortunately necessary to keep Python from removing the escapes).</p>\n\n<p>If the resulting escapes in the strings in the returned list are not wanted, you can use this slightly altered version of the function:</p>\n\n<pre><code>[i.strip('\"').strip(\"'\").decode('string_escape') for i in re.split(r'(\\s+|(?<!\\\\)\".*?(?<!\\\\)\"|(?<!\\\\)\\'.*?(?<!\\\\)\\')', string) if i.strip()]\n</code></pre>\n"
},
{
"answer_id": 11194593,
"author": "moschlar",
"author_id": 1175818,
"author_profile": "https://Stackoverflow.com/users/1175818",
"pm_score": 1,
"selected": false,
"text": "<p>To get around the unicode issues in some Python 2 versions, I suggest:</p>\n\n<pre><code>from shlex import split as _split\nsplit = lambda a: [b.decode('utf-8') for b in _split(a.encode('utf-8'))]\n</code></pre>\n"
},
{
"answer_id": 23155180,
"author": "Daniel Dai",
"author_id": 1089262,
"author_profile": "https://Stackoverflow.com/users/1089262",
"pm_score": 4,
"selected": false,
"text": "<p>I use shlex.split to process 70,000,000 lines of squid log, it's so slow. So I switched to re.</p>\n\n<p>Please try this, if you have performance problem with shlex.</p>\n\n<pre><code>import re\n\ndef line_split(line):\n return re.findall(r'[^\"\\s]\\S*|\".+?\"', line)\n</code></pre>\n"
},
{
"answer_id": 32480710,
"author": "hussic",
"author_id": 4111130,
"author_profile": "https://Stackoverflow.com/users/4111130",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest:</p>\n\n<p>test string:</p>\n\n<pre><code>s = 'abc \"ad\" \\'fg\\' \"kk\\'rdt\\'\" zzz\"34\"zzz \"\" \\'\\''\n</code></pre>\n\n<p>to capture also \"\" and '':</p>\n\n<pre><code>import re\nre.findall(r'\"[^\"]*\"|\\'[^\\']*\\'|[^\"\\'\\s]+',s)\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>['abc', '\"ad\"', \"'fg'\", '\"kk\\'rdt\\'\"', 'zzz', '\"34\"', 'zzz', '\"\"', \"''\"]\n</code></pre>\n\n<p>to ignore empty \"\" and '':</p>\n\n<pre><code>import re\nre.findall(r'\"[^\"]+\"|\\'[^\\']+\\'|[^\"\\'\\s]+',s)\n</code></pre>\n\n<p>result:</p>\n\n<pre><code>['abc', '\"ad\"', \"'fg'\", '\"kk\\'rdt\\'\"', 'zzz', '\"34\"', 'zzz']\n</code></pre>\n"
},
{
"answer_id": 43035638,
"author": "THE_MAD_KING",
"author_id": 7771160,
"author_profile": "https://Stackoverflow.com/users/7771160",
"pm_score": 2,
"selected": false,
"text": "<p>To preserve quotes use this function:</p>\n\n<pre><code>def getArgs(s):\n args = []\n cur = ''\n inQuotes = 0\n for char in s.strip():\n if char == ' ' and not inQuotes:\n args.append(cur)\n cur = ''\n elif char == '\"' and not inQuotes:\n inQuotes = 1\n cur += char\n elif char == '\"' and inQuotes:\n inQuotes = 0\n cur += char\n else:\n cur += char\n args.append(cur)\n return args\n</code></pre>\n"
},
{
"answer_id": 49791573,
"author": "har777",
"author_id": 1851428,
"author_profile": "https://Stackoverflow.com/users/1851428",
"pm_score": 3,
"selected": false,
"text": "<p>Speed test of different answers:</p>\n\n<pre><code>import re\nimport shlex\nimport csv\n\nline = 'this is \"a test\"'\n\n%timeit [p for p in re.split(\"( |\\\\\\\".*?\\\\\\\"|'.*?')\", line) if p.strip()]\n100000 loops, best of 3: 5.17 µs per loop\n\n%timeit re.findall(r'[^\"\\s]\\S*|\".+?\"', line)\n100000 loops, best of 3: 2.88 µs per loop\n\n%timeit list(csv.reader([line], delimiter=\" \"))\nThe slowest run took 9.62 times longer than the fastest. This could mean that an intermediate result is being cached.\n100000 loops, best of 3: 2.4 µs per loop\n\n%timeit shlex.split(line)\n10000 loops, best of 3: 50.2 µs per loop\n</code></pre>\n"
},
{
"answer_id": 51560564,
"author": "Ton van den Heuvel",
"author_id": 79111,
"author_profile": "https://Stackoverflow.com/users/79111",
"pm_score": 3,
"selected": false,
"text": "<p>The main problem with the accepted <code>shlex</code> approach is that it does not ignore escape characters outside quoted substrings, and gives slightly unexpected results in some corner cases.</p>\n<p>I have the following use case, where I need a split function that splits input strings such that either single-quoted or double-quoted substrings are preserved, with the ability to escape quotes within such a substring. Quotes within an unquoted string should not be treated differently from any other character. Some example test cases with the expected output:</p>\n<pre> input string | expected output\n===============================================\n 'abc def' | ['abc', 'def']\n \"abc \\\\s def\" | ['abc', '\\\\s', 'def']\n '\"abc def\" ghi' | ['abc def', 'ghi']\n \"'abc def' ghi\" | ['abc def', 'ghi']\n '\"abc \\\\\" def\" ghi' | ['abc \" def', 'ghi']\n \"'abc \\\\' def' ghi\" | [\"abc ' def\", 'ghi']\n \"'abc \\\\s def' ghi\" | ['abc \\\\s def', 'ghi']\n '\"abc \\\\s def\" ghi' | ['abc \\\\s def', 'ghi']\n '\"\" test' | ['', 'test']\n \"'' test\" | ['', 'test']\n \"abc'def\" | [\"abc'def\"]\n \"abc'def'\" | [\"abc'def'\"]\n \"abc'def' ghi\" | [\"abc'def'\", 'ghi']\n \"abc'def'ghi\" | [\"abc'def'ghi\"]\n 'abc\"def' | ['abc\"def']\n 'abc\"def\"' | ['abc\"def\"']\n 'abc\"def\" ghi' | ['abc\"def\"', 'ghi']\n 'abc\"def\"ghi' | ['abc\"def\"ghi']\n \"r'AA' r'.*_xyz$'\" | [\"r'AA'\", \"r'.*_xyz$'\"]\n 'abc\"def ghi\"' | ['abc\"def ghi\"']\n 'abc\"def ghi\"\"jkl\"' | ['abc\"def ghi\"\"jkl\"']\n 'a\"b c\"d\"e\"f\"g h\"' | ['a\"b c\"d\"e\"f\"g h\"']\n 'c=\"ls /\" type key' | ['c=\"ls /\"', 'type', 'key']\n \"abc'def ghi'\" | [\"abc'def ghi'\"]\n \"c='ls /' type key\" | [\"c='ls /'\", 'type', 'key']</pre>\n<p>I ended up with the following function to split a string such that the expected output results for all input strings:</p>\n<pre><code>import re\n\ndef quoted_split(s):\n def strip_quotes(s):\n if s and (s[0] == '\"' or s[0] == \"'\") and s[0] == s[-1]:\n return s[1:-1]\n return s\n return [strip_quotes(p).replace('\\\\\"', '\"').replace(\"\\\\'\", \"'\") \\\n for p in re.findall(r'(?:[^\"\\s]*\"(?:\\\\.|[^\"])*\"[^\"\\s]*)+|(?:[^\\'\\s]*\\'(?:\\\\.|[^\\'])*\\'[^\\'\\s]*)+|[^\\s]+', s)]\n</code></pre>\n<p>It ain't pretty; but it works. The following test application checks the results of other approaches (<code>shlex</code> and <code>csv</code> for now) and the custom split implementation:</p>\n<pre><code>#!/bin/python2.7\n\nimport csv\nimport re\nimport shlex\n\nfrom timeit import timeit\n\ndef test_case(fn, s, expected):\n try:\n if fn(s) == expected:\n print '[ OK ] %s -> %s' % (s, fn(s))\n else:\n print '[FAIL] %s -> %s' % (s, fn(s))\n except Exception as e:\n print '[FAIL] %s -> exception: %s' % (s, e)\n\ndef test_case_no_output(fn, s, expected):\n try:\n fn(s)\n except:\n pass\n\ndef test_split(fn, test_case_fn=test_case):\n test_case_fn(fn, 'abc def', ['abc', 'def'])\n test_case_fn(fn, \"abc \\\\s def\", ['abc', '\\\\s', 'def'])\n test_case_fn(fn, '\"abc def\" ghi', ['abc def', 'ghi'])\n test_case_fn(fn, \"'abc def' ghi\", ['abc def', 'ghi'])\n test_case_fn(fn, '\"abc \\\\\" def\" ghi', ['abc \" def', 'ghi'])\n test_case_fn(fn, \"'abc \\\\' def' ghi\", [\"abc ' def\", 'ghi'])\n test_case_fn(fn, \"'abc \\\\s def' ghi\", ['abc \\\\s def', 'ghi'])\n test_case_fn(fn, '\"abc \\\\s def\" ghi', ['abc \\\\s def', 'ghi'])\n test_case_fn(fn, '\"\" test', ['', 'test'])\n test_case_fn(fn, \"'' test\", ['', 'test'])\n test_case_fn(fn, \"abc'def\", [\"abc'def\"])\n test_case_fn(fn, \"abc'def'\", [\"abc'def'\"])\n test_case_fn(fn, \"abc'def' ghi\", [\"abc'def'\", 'ghi'])\n test_case_fn(fn, \"abc'def'ghi\", [\"abc'def'ghi\"])\n test_case_fn(fn, 'abc\"def', ['abc\"def'])\n test_case_fn(fn, 'abc\"def\"', ['abc\"def\"'])\n test_case_fn(fn, 'abc\"def\" ghi', ['abc\"def\"', 'ghi'])\n test_case_fn(fn, 'abc\"def\"ghi', ['abc\"def\"ghi'])\n test_case_fn(fn, \"r'AA' r'.*_xyz$'\", [\"r'AA'\", \"r'.*_xyz$'\"])\n test_case_fn(fn, 'abc\"def ghi\"', ['abc\"def ghi\"'])\n test_case_fn(fn, 'abc\"def ghi\"\"jkl\"', ['abc\"def ghi\"\"jkl\"'])\n test_case_fn(fn, 'a\"b c\"d\"e\"f\"g h\"', ['a\"b c\"d\"e\"f\"g h\"'])\n test_case_fn(fn, 'c=\"ls /\" type key', ['c=\"ls /\"', 'type', 'key'])\n test_case_fn(fn, \"abc'def ghi'\", [\"abc'def ghi'\"])\n test_case_fn(fn, \"c='ls /' type key\", [\"c='ls /'\", 'type', 'key'])\n\ndef csv_split(s):\n return list(csv.reader([s], delimiter=' '))[0]\n\ndef re_split(s):\n def strip_quotes(s):\n if s and (s[0] == '\"' or s[0] == \"'\") and s[0] == s[-1]:\n return s[1:-1]\n return s\n return [strip_quotes(p).replace('\\\\\"', '\"').replace(\"\\\\'\", \"'\") for p in re.findall(r'(?:[^\"\\s]*\"(?:\\\\.|[^\"])*\"[^\"\\s]*)+|(?:[^\\'\\s]*\\'(?:\\\\.|[^\\'])*\\'[^\\'\\s]*)+|[^\\s]+', s)]\n\nif __name__ == '__main__':\n print 'shlex\\n'\n test_split(shlex.split)\n print\n\n print 'csv\\n'\n test_split(csv_split)\n print\n\n print 're\\n'\n test_split(re_split)\n print\n\n iterations = 100\n setup = 'from __main__ import test_split, test_case_no_output, csv_split, re_split\\nimport shlex, re'\n def benchmark(method, code):\n print '%s: %.3fms per iteration' % (method, (1000 * timeit(code, setup=setup, number=iterations) / iterations))\n benchmark('shlex', 'test_split(shlex.split, test_case_no_output)')\n benchmark('csv', 'test_split(csv_split, test_case_no_output)')\n benchmark('re', 'test_split(re_split, test_case_no_output)')\n</code></pre>\n<p>Output:</p>\n<pre>\nshlex\n\n[ OK ] abc def -> ['abc', 'def']\n[FAIL] abc \\s def -> ['abc', 's', 'def']\n[ OK ] \"abc def\" ghi -> ['abc def', 'ghi']\n[ OK ] 'abc def' ghi -> ['abc def', 'ghi']\n[ OK ] \"abc \\\" def\" ghi -> ['abc \" def', 'ghi']\n[FAIL] 'abc \\' def' ghi -> exception: No closing quotation\n[ OK ] 'abc \\s def' ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"abc \\s def\" ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"\" test -> ['', 'test']\n[ OK ] '' test -> ['', 'test']\n[FAIL] abc'def -> exception: No closing quotation\n[FAIL] abc'def' -> ['abcdef']\n[FAIL] abc'def' ghi -> ['abcdef', 'ghi']\n[FAIL] abc'def'ghi -> ['abcdefghi']\n[FAIL] abc\"def -> exception: No closing quotation\n[FAIL] abc\"def\" -> ['abcdef']\n[FAIL] abc\"def\" ghi -> ['abcdef', 'ghi']\n[FAIL] abc\"def\"ghi -> ['abcdefghi']\n[FAIL] r'AA' r'.*_xyz$' -> ['rAA', 'r.*_xyz$']\n[FAIL] abc\"def ghi\" -> ['abcdef ghi']\n[FAIL] abc\"def ghi\"\"jkl\" -> ['abcdef ghijkl']\n[FAIL] a\"b c\"d\"e\"f\"g h\" -> ['ab cdefg h']\n[FAIL] c=\"ls /\" type key -> ['c=ls /', 'type', 'key']\n[FAIL] abc'def ghi' -> ['abcdef ghi']\n[FAIL] c='ls /' type key -> ['c=ls /', 'type', 'key']\n\ncsv\n\n[ OK ] abc def -> ['abc', 'def']\n[ OK ] abc \\s def -> ['abc', '\\\\s', 'def']\n[ OK ] \"abc def\" ghi -> ['abc def', 'ghi']\n[FAIL] 'abc def' ghi -> [\"'abc\", \"def'\", 'ghi']\n[FAIL] \"abc \\\" def\" ghi -> ['abc \\\\', 'def\"', 'ghi']\n[FAIL] 'abc \\' def' ghi -> [\"'abc\", \"\\\\'\", \"def'\", 'ghi']\n[FAIL] 'abc \\s def' ghi -> [\"'abc\", '\\\\s', \"def'\", 'ghi']\n[ OK ] \"abc \\s def\" ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"\" test -> ['', 'test']\n[FAIL] '' test -> [\"''\", 'test']\n[ OK ] abc'def -> [\"abc'def\"]\n[ OK ] abc'def' -> [\"abc'def'\"]\n[ OK ] abc'def' ghi -> [\"abc'def'\", 'ghi']\n[ OK ] abc'def'ghi -> [\"abc'def'ghi\"]\n[ OK ] abc\"def -> ['abc\"def']\n[ OK ] abc\"def\" -> ['abc\"def\"']\n[ OK ] abc\"def\" ghi -> ['abc\"def\"', 'ghi']\n[ OK ] abc\"def\"ghi -> ['abc\"def\"ghi']\n[ OK ] r'AA' r'.*_xyz$' -> [\"r'AA'\", \"r'.*_xyz$'\"]\n[FAIL] abc\"def ghi\" -> ['abc\"def', 'ghi\"']\n[FAIL] abc\"def ghi\"\"jkl\" -> ['abc\"def', 'ghi\"\"jkl\"']\n[FAIL] a\"b c\"d\"e\"f\"g h\" -> ['a\"b', 'c\"d\"e\"f\"g', 'h\"']\n[FAIL] c=\"ls /\" type key -> ['c=\"ls', '/\"', 'type', 'key']\n[FAIL] abc'def ghi' -> [\"abc'def\", \"ghi'\"]\n[FAIL] c='ls /' type key -> [\"c='ls\", \"/'\", 'type', 'key']\n\nre\n\n[ OK ] abc def -> ['abc', 'def']\n[ OK ] abc \\s def -> ['abc', '\\\\s', 'def']\n[ OK ] \"abc def\" ghi -> ['abc def', 'ghi']\n[ OK ] 'abc def' ghi -> ['abc def', 'ghi']\n[ OK ] \"abc \\\" def\" ghi -> ['abc \" def', 'ghi']\n[ OK ] 'abc \\' def' ghi -> [\"abc ' def\", 'ghi']\n[ OK ] 'abc \\s def' ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"abc \\s def\" ghi -> ['abc \\\\s def', 'ghi']\n[ OK ] \"\" test -> ['', 'test']\n[ OK ] '' test -> ['', 'test']\n[ OK ] abc'def -> [\"abc'def\"]\n[ OK ] abc'def' -> [\"abc'def'\"]\n[ OK ] abc'def' ghi -> [\"abc'def'\", 'ghi']\n[ OK ] abc'def'ghi -> [\"abc'def'ghi\"]\n[ OK ] abc\"def -> ['abc\"def']\n[ OK ] abc\"def\" -> ['abc\"def\"']\n[ OK ] abc\"def\" ghi -> ['abc\"def\"', 'ghi']\n[ OK ] abc\"def\"ghi -> ['abc\"def\"ghi']\n[ OK ] r'AA' r'.*_xyz$' -> [\"r'AA'\", \"r'.*_xyz$'\"]\n[ OK ] abc\"def ghi\" -> ['abc\"def ghi\"']\n[ OK ] abc\"def ghi\"\"jkl\" -> ['abc\"def ghi\"\"jkl\"']\n[ OK ] a\"b c\"d\"e\"f\"g h\" -> ['a\"b c\"d\"e\"f\"g h\"']\n[ OK ] c=\"ls /\" type key -> ['c=\"ls /\"', 'type', 'key']\n[ OK ] abc'def ghi' -> [\"abc'def ghi'\"]\n[ OK ] c='ls /' type key -> [\"c='ls /'\", 'type', 'key']\n\nshlex: 0.335ms per iteration\ncsv: 0.036ms per iteration\nre: 0.068ms per iteration\n</pre>\n<p>So performance is much better than <code>shlex</code>, and can be improved further by precompiling the regular expression, in which case it will outperform the <code>csv</code> approach.</p>\n"
},
{
"answer_id": 53210803,
"author": "hochl",
"author_id": 589206,
"author_profile": "https://Stackoverflow.com/users/589206",
"pm_score": 4,
"selected": false,
"text": "<p>It seems that for performance reasons <code>re</code> is faster. Here is my solution using a least greedy operator that preserves the outer quotes:</p>\n\n<pre><code>re.findall(\"(?:\\\".*?\\\"|\\S)+\", s)\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>['this', 'is', '\"a test\"']\n</code></pre>\n\n<p>It leaves constructs like <code>aaa\"bla blub\"bbb</code> together as these tokens are not separated by spaces. If the string contains escaped characters, you can match like that:</p>\n\n<pre><code>>>> a = \"She said \\\"He said, \\\\\\\"My name is Mark.\\\\\\\"\\\"\"\n>>> a\n'She said \"He said, \\\\\"My name is Mark.\\\\\"\"'\n>>> for i in re.findall(\"(?:\\\".*?[^\\\\\\\\]\\\"|\\S)+\", a): print(i)\n...\nShe\nsaid\n\"He said, \\\"My name is Mark.\\\"\"\n</code></pre>\n\n<p>Please note that this also matches the empty string <code>\"\"</code> by means of the <code>\\S</code> part of the pattern.</p>\n"
},
{
"answer_id": 60929888,
"author": "Mikhail Zakharov",
"author_id": 9127614,
"author_profile": "https://Stackoverflow.com/users/9127614",
"pm_score": 1,
"selected": false,
"text": "<p>As an option try tssplit:</p>\n\n<pre><code>In [1]: from tssplit import tssplit\nIn [2]: tssplit('this is \"a test\"', quote='\"', delimiter='')\nOut[2]: ['this', 'is', 'a test']\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/79992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10972/"
]
| Ideally the reader has upgraded a native C++ program to Visual Studio 2008, which contains an OpenClipboard() block. Why not try setting a breakpoint just after getting a successful return-code from OpenClipboard() and step through your code. According to the Internet it may work on your system, but of course, not on mine, thanks for trying.
Googling on e.g. (( OpenClipboard 1418 vc6 )) finds articles like "GetClipboardData fails in debugger" and "No Error in VC++6 but Error in VC++ 2005". Pragmatically for-the-moment, problem solved - I simply cannot set breakpoints within such code, I need to squirrel information and set the breakpoint after the clipboard operations are done. Error 1418 is "Thread does not have a clipboard open" but it works fine as long as you don't step with VS.NET, or like I say if you keep breakpoints outside of the clipboard-open-close-block.
I would feel better knowing what the exact issue is with the VS.NET debugger.
Being a C++ person I am only dimly aware that you are not supposed to think in terms of threads when doing dot-Net. Anyway I did not find a guru-quality explanation of what's really going on, whether in-fact the problem is that the dot-Net debugger is subtly interfering with the thread-information somehow, when you single-step thru native C++ code.
System-wise: about a year old, two dual-core Xeon's, 4 CPU's according to XP-pro.
I had just finished debugging the code by single-stepping thru it in vc6 under XP-SP2-32-bit. So I know the code was pretty-much-fine under vc6. However when I tested with a 10-megabyte CF\_TEXT I got exceptions. I thought to try debugging under the nicer exception model of XP-x64.
Recompiled with visual-studio-2008, I could not get the code to single-step at all. OpenClipboard worked, but EnumClipboardFormats() did not work, nothing worked when single-stepped. However, when I set the breakpoint below the complete block of code, everything worked fine. And *YES* vc2008 made a pinpoint diagnostic 'stack frame corruption around szBuf. There is a lot to like about vc2008. It would be nice if this were somehow merely a clipboard problem - without knowing that I would feel compelled to worry about stepping thru ANYTHING, whether thread-context-issues might be due to the dot-Net-debugger. | You want `split`, from the built-in [`shlex`](https://docs.python.org/library/shlex.html) module.
```
>>> import shlex
>>> shlex.split('this is "a test"')
['this', 'is', 'a test']
```
This should do exactly what you want.
If you want to preserve the quotation marks, then you can pass the `posix=False` kwarg.
```
>>> shlex.split('this is "a test"', posix=False)
['this', 'is', '"a test"']
``` |
80,031 | <p>I have a asp:menu object which I set up to use a <em>SiteMapDataSource</em> but everytime I try to run the site, I get a yellow screen from firefox saying it cannot find the <code>web.sitemap</code>. Here's the code for the <em>sitemapdatasource</em> and the menu. The Web.sitemap file is sitting in the root directory of the website.</p>
<pre><code><div>
<asp:Menu ID="MainMenu" CssClass="wTheme" Orientation="Horizontal" runat="server" DataSourceID="SiteMapDataSource1">
</asp:Menu>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="Web.sitemap" />
</div>
</code></pre>
<p>And this is the Web.sitemap looks like so:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
</code></pre>
<p>
</p>
| [
{
"answer_id": 80060,
"author": "Encoder",
"author_id": 14629,
"author_profile": "https://Stackoverflow.com/users/14629",
"pm_score": 3,
"selected": true,
"text": "<p>I had a similar problem where I was specifying the path to the SiteMap from within my DataSource control. I tried removing it and it worked.</p>\n\n<p>Try removing the path from the SiteMapDataSource and ensure that web.sitemap is in the root directory and see if that fixes it.</p>\n"
},
{
"answer_id": 80061,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 0,
"selected": false,
"text": "<p>You need to specify in web.config to use XmlSiteMapProvider and provide it with correct path to .sitemap file.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4298/"
]
| I have a asp:menu object which I set up to use a *SiteMapDataSource* but everytime I try to run the site, I get a yellow screen from firefox saying it cannot find the `web.sitemap`. Here's the code for the *sitemapdatasource* and the menu. The Web.sitemap file is sitting in the root directory of the website.
```
<div>
<asp:Menu ID="MainMenu" CssClass="wTheme" Orientation="Horizontal" runat="server" DataSourceID="SiteMapDataSource1">
</asp:Menu>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="Web.sitemap" />
</div>
```
And this is the Web.sitemap looks like so:
```
<?xml version="1.0" encoding="utf-8" ?>
``` | I had a similar problem where I was specifying the path to the SiteMap from within my DataSource control. I tried removing it and it worked.
Try removing the path from the SiteMapDataSource and ensure that web.sitemap is in the root directory and see if that fixes it. |
80,042 | <p>Can you provide an example of a byte buffer transferred between two java classes via UDP datagram?</p>
| [
{
"answer_id": 80071,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 3,
"selected": true,
"text": "<p>Hows' this ?</p>\n\n<pre>\nimport java.io.IOException;\nimport java.net.DatagramPacket;\nimport java.net.DatagramSocket;\nimport java.net.InetSocketAddress;\n\n\npublic class Server {\n\n public static void main(String[] args) throws IOException {\n DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000));\n byte[] message = new byte[512];\n DatagramPacket packet = new DatagramPacket(message, message.length);\n socket.receive(packet);\n System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength()));\n }\n}\n</pre>\n\n<pre>\nimport java.io.IOException;\nimport java.net.DatagramPacket;\nimport java.net.DatagramSocket;\nimport java.net.InetSocketAddress;\n\n\npublic class Client {\n\n public static void main(String[] args) throws IOException {\n DatagramSocket socket = new DatagramSocket();\n socket.connect(new InetSocketAddress(5000));\n byte[] message = \"Oh Hai!\".getBytes();\n DatagramPacket packet = new DatagramPacket(message, message.length);\n socket.send(packet);\n }\n}\n</pre>\n"
},
{
"answer_id": 80139,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 0,
"selected": false,
"text": "<p>@none</p>\n\n<p>The DatagramSocket classes sure need a polish up, DatagramChannel is slightly better for clients, but confusing for server programming. For example:</p>\n\n<pre>\nimport java.io.IOException;\nimport java.net.InetSocketAddress;\nimport java.nio.ByteBuffer;\nimport java.nio.channels.DatagramChannel;\n\n\npublic class Client {\n\n public static void main(String[] args) throws IOException {\n DatagramChannel channel = DatagramChannel.open();\n ByteBuffer buffer = ByteBuffer.wrap(\"Oh Hai!\".getBytes());\n channel.send(buffer, new InetSocketAddress(\"localhost\", 5000));\n }\n}\n</pre>\n\n<p>Bring on <a href=\"http://jcp.org/en/jsr/detail?id=203\" rel=\"nofollow noreferrer\" title=\"JSR-203\">JSR-203</a> I say</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| Can you provide an example of a byte buffer transferred between two java classes via UDP datagram? | Hows' this ?
```
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Server {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(new InetSocketAddress(5000));
byte[] message = new byte[512];
DatagramPacket packet = new DatagramPacket(message, message.length);
socket.receive(packet);
System.out.println(new String(packet.getData(), packet.getOffset(), packet.getLength()));
}
}
```
```
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
public class Client {
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket();
socket.connect(new InetSocketAddress(5000));
byte[] message = "Oh Hai!".getBytes();
DatagramPacket packet = new DatagramPacket(message, message.length);
socket.send(packet);
}
}
``` |
80,084 | <p>In JavaScript, the "this" operator can refer to different things under different scenarios. </p>
<p>Typically in a method within a JavaScript "object", it refers to the current object.</p>
<p>But when used as a callback, it becomes a reference to the calling object.</p>
<p>I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.</p>
<p>Can someone clarify usage and best practices regarding how to get around this problem?</p>
<pre><code> function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}
TestObject.prototype.callBack = function(o){
// do something with "this"
//when method is called directly, "this" resolves to the current object
//when invoked by the asyncRequest callback, "this" is not the current object
//what design patterns can make this consistent?
this.secondMethod();
}
TestObject.prototype.secondMethod = function() {
alert('test');
}
}
</code></pre>
| [
{
"answer_id": 80095,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 0,
"selected": false,
"text": "<p>I believe this may be due to how the idea of [closures](<a href=\"http://en.wikipedia.org/wiki/Closure_(computer_science)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Closure_(computer_science)</a> work in Javascript.</p>\n\n<p>I am just getting to grips with closures myself. Have a read of the linked wikipedia article.</p>\n\n<p>Here's <a href=\"http://www.javascriptkit.com/javatutors/closures.shtml\" rel=\"nofollow noreferrer\">another article</a> with more information.</p>\n\n<p>Anyone out there able to confirm this?</p>\n"
},
{
"answer_id": 80119,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 0,
"selected": false,
"text": "<p>As soon as callback methods are called from other context I'm usually using something that I'm call callback context:</p>\n\n<pre><code>var ctx = function CallbackContext()\n{\n_callbackSender\n...\n}\n\nfunction DoCallback(_sender, delegate, callbackFunc)\n{\n ctx = _callbackSender = _sender;\n delegate();\n}\n\nfunction TestObject()\n{\n test = function()\n {\n DoCallback(otherFunc, callbackHandler);\n }\n\n callbackHandler = function()\n{\n ctx._callbackSender;\n //or this = ctx._callbacjHandler;\n}\n}\n</code></pre>\n"
},
{
"answer_id": 80127,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 5,
"selected": true,
"text": "<p>In JavaScript, <code>this</code> always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, <code>this</code> will refer to the node that fired the event. But if you have an object and call a function on it like:</p>\n\n<pre><code>myObject.myFunction();\n</code></pre>\n\n<p>Then <code>this</code> inside <code>myFunction</code> will refer to <code>myObject</code>. Does it make sense?</p>\n\n<p>To get around it you need to use closures. You can change your code as follows:</p>\n\n<pre><code>function TestObject() {\n TestObject.prototype.firstMethod = function(){\n this.callback();\n YAHOO.util.Connect.asyncRequest(method, uri, callBack);\n } \n\n var that = this;\n TestObject.prototype.callBack = function(o){\n that.secondMethod();\n }\n\n TestObject.prototype.secondMethod = function() {\n alert('test');\n }\n}\n</code></pre>\n"
},
{
"answer_id": 80159,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<p><code>this</code> corresponds to the context for the function call. For functions not called as part of an object (no <code>.</code> operator), this is the global context (<code>window</code> in web pages). For functions called as object methods (via the . operator), it's the object.</p>\n\n<p>But, you can make it whatever you want. All functions have .call() and .apply() methods that can be used to invoke them with a custom context. So if i set up an object Chile like so:</p>\n\n<pre><code>var Chile = { name: 'booga', stuff: function() { console.log(this.name); } };\n</code></pre>\n\n<p>...and invoke Chile.stuff(), it'll produce the obvious result:</p>\n\n<pre><code>booga\n</code></pre>\n\n<p>But if i want, i can take and <em>really screw with it</em>:</p>\n\n<pre><code>Chile.stuff.apply({ name: 'supercalifragilistic' });\n</code></pre>\n\n<p>This is actually quite useful...</p>\n"
},
{
"answer_id": 80177,
"author": "jeannicolas",
"author_id": 14981,
"author_profile": "https://Stackoverflow.com/users/14981",
"pm_score": 0,
"selected": false,
"text": "<p>You can also use Function.Apply(<em>thisArg</em>, <em>argsArray</em>)... Where thisArg determines the value of <em>this</em> inside your function...the second parameter is an optional arguments array that you can also pass to your function. </p>\n\n<p>If you don't plan on using the second argument, don't pass anything to it. Internet Explorer will throw a TypeError at you if you pass <em>null</em> (or anything that is not an array) to function.apply()'s second argument...</p>\n\n<p>With the example code you gave it would look something like:</p>\n\n<pre><code>YAHOO.util.Connect.asyncRequest(method, uri, callBack.Apply(this));\n</code></pre>\n"
},
{
"answer_id": 80478,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 6,
"selected": false,
"text": "<p>Quick advice on best practices before I babble on about the magic <em>this</em> variable. If you want Object-oriented programming (OOP) in Javascript that closely mirrors more traditional/classical inheritance patterns, pick a framework, learn its quirks, and don't try to get clever. If you want to get clever, learn javascript as a functional language, and avoid thinking about things like classes.</p>\n\n<p>Which brings up one of the most important things to keep in mind about Javascript, and to repeat to yourself when it doesn't make sense. Javascript does not have classes. If something looks like a class, it's a clever trick. Javascript has <strong>objects</strong> (no derisive quotes needed) and <strong>functions</strong>. (that's not 100% accurate, functions are just objects, but it can sometimes be helpful to think of them as separate things)</p>\n\n<p>The <em>this</em> variable is attached to functions. Whenever you invoke a function, <em>this</em> is given a certain value, depending on how you invoke the function. This is often called the invocation pattern.</p>\n\n<p>There are four ways to invoke functions in javascript. You can invoke the function as a <em>method</em>, as a <em>function</em>, as a <em>constructor</em>, and with <em>apply</em>.</p>\n\n<h2>As a Method</h2>\n\n<p>A method is a function that's attached to an object</p>\n\n<pre><code>var foo = {};\nfoo.someMethod = function(){\n alert(this);\n}\n</code></pre>\n\n<p>When invoked as a method, <em>this</em> will be bound to the object the function/method is a part of. In this example, this will be bound to foo.</p>\n\n<h2>As A Function</h2>\n\n<p>If you have a stand alone function, the <em>this</em> variable will be bound to the \"global\" object, almost always the <em>window</em> object in the context of a browser.</p>\n\n<pre><code> var foo = function(){\n alert(this);\n }\n foo();\n</code></pre>\n\n<p><strong>This may be what's tripping you up</strong>, but don't feel bad. Many people consider this a bad design decision. Since a callback is invoked as a function and not as a method, that's why you're seeing what appears to be inconsistent behaviour.</p>\n\n<p>Many people get around the problem by doing something like, um, this</p>\n\n<pre><code>var foo = {};\nfoo.someMethod = function (){\n var that=this;\n function bar(){\n alert(that);\n }\n}\n</code></pre>\n\n<p>You define a variable <em>that</em> which points to <em>this</em>. Closure (a topic all it's own) keeps <code>that</code> around, so if you call bar as a callback, it still has a reference.</p>\n\n<h2>As a Constructor</h2>\n\n<p>You can also invoke a function as a constructor. Based on the naming convention you're using (<code>TestObject</code>) this also <strong>may be what you're doing and is what's tripping you up</strong>.</p>\n\n<p>You invoke a function as a Constructor with the <code>new</code> keyword.</p>\n\n<pre><code>function Foo(){\n this.confusing = 'hell yeah';\n}\nvar myObject = new Foo();\n</code></pre>\n\n<p>When invoked as a constructor, a new Object will be created, and <em>this</em> will be bound to that object. Again, if you have inner functions and they're used as callbacks, you'll be invoking them as functions, and <em>this</em> will be bound to the global object. Use that <code>var that = this;</code> trick/pattern.</p>\n\n<p>Some people think the constructor/new keyword was a bone thrown to Java/traditional OOP programmers as a way to create something similar to classes.</p>\n\n<h2>With the Apply Method.</h2>\n\n<p>Finally, every function has a method (yes, functions are objects in Javascript) named <code>apply</code>. Apply lets you determine what the value of <em>this</em> will be, and also lets you pass in an array of arguments. Here's a useless example.</p>\n\n<pre><code>function foo(a,b){\n alert(a);\n alert(b);\n alert(this);\n}\nvar args = ['ah','be'];\nfoo.apply('omg',args);\n</code></pre>\n"
},
{
"answer_id": 81646,
"author": "ujh",
"author_id": 4936,
"author_profile": "https://Stackoverflow.com/users/4936",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using Prototype you can use <a href=\"http://www.prototypejs.org/api/function/bind\" rel=\"nofollow noreferrer\">bind()</a> and <a href=\"http://www.prototypejs.org/api/function/bindAsEventListener\" rel=\"nofollow noreferrer\">bindAsEventListener()</a> to get around that problem.</p>\n"
},
{
"answer_id": 83730,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using a javascript framework, there may be a handy method for dealing with this. In Prototype, for example, you can call a method and scope it to a particular \"this\" object:</p>\n\n<pre><code>var myObject = new TestObject();\nmyObject.firstMethod.bind(myObject);\n</code></pre>\n\n<p>Note: bind() returns a function, so you can also use it to pre-scope callbacks inside your class:</p>\n\n<pre><code>callBack.bind(this);\n</code></pre>\n\n<p><a href=\"http://www.prototypejs.org/api/function/bind\" rel=\"nofollow noreferrer\">http://www.prototypejs.org/api/function/bind</a></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| In JavaScript, the "this" operator can refer to different things under different scenarios.
Typically in a method within a JavaScript "object", it refers to the current object.
But when used as a callback, it becomes a reference to the calling object.
I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.
Can someone clarify usage and best practices regarding how to get around this problem?
```
function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}
TestObject.prototype.callBack = function(o){
// do something with "this"
//when method is called directly, "this" resolves to the current object
//when invoked by the asyncRequest callback, "this" is not the current object
//what design patterns can make this consistent?
this.secondMethod();
}
TestObject.prototype.secondMethod = function() {
alert('test');
}
}
``` | In JavaScript, `this` always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, `this` will refer to the node that fired the event. But if you have an object and call a function on it like:
```
myObject.myFunction();
```
Then `this` inside `myFunction` will refer to `myObject`. Does it make sense?
To get around it you need to use closures. You can change your code as follows:
```
function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}
var that = this;
TestObject.prototype.callBack = function(o){
that.secondMethod();
}
TestObject.prototype.secondMethod = function() {
alert('test');
}
}
``` |
80,152 | <p>What are the potential pros and cons of each of these queries given different databases, configurations, etc? Is there ever a time when one would be more efficient than the other? Vice versa? Is there an even better way to do it? Can you explain why?</p>
<p>Query 1:</p>
<pre><code>SELECT
*
FROM
table_a, table_b, table_c
WHERE
table_a.id = table_b.id AND
table_a.id = table_c.id AND
table_a.create_date > DATE('1998-01-01');
</code></pre>
<p>Query 2:</p>
<pre><code>SELECT
*
FROM
table_a
INNER JOIN table_b ON
table_a.id = table_b.id
INNER JOIN table_c ON
table_a.id = table_c.id
WHERE
table_a.create_date > DATE('1998-01-01');
</code></pre>
| [
{
"answer_id": 80169,
"author": "Encoder",
"author_id": 14629,
"author_profile": "https://Stackoverflow.com/users/14629",
"pm_score": -1,
"selected": false,
"text": "<p>I agree, it's sounding a bit too much like Homework!</p>\n\n<p>If it isn't homework then I guess the simplest answer is readability.</p>\n\n<p>As stated before, both queries will produce the same execution plan. If this is the case then the only thing you need to worry about it maintainability.</p>\n"
},
{
"answer_id": 80172,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>Same query, different revision of SQL spec. The query optimizer should come up with the same query plan for those.</p>\n"
},
{
"answer_id": 80180,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Nope. I'm just sharing a large, overwhelmed database with some coworkers and am trying to come up with some ways to get more processor bang for our buck. I've been looking around online but haven't found a good explanation for some questions like this.</p>\n\n<p>Sorry for sounding homework-y. I guess I spent too many years as a TA.</p>\n"
},
{
"answer_id": 80219,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I think query 2's more readable. Think about when you get to say 5,6, or 7 tables when you hit the where clause in query one. Following the joins could get messy.</p>\n\n<p>As for performance, I have no idea. I bet if you go to the MySQL website, there would be info there - probably examples of joins.</p>\n\n<p>Professionally, I've only worked on one project. But it was a big one, and they always followed query 2's format. This was using Microsoft SQL Server though.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| What are the potential pros and cons of each of these queries given different databases, configurations, etc? Is there ever a time when one would be more efficient than the other? Vice versa? Is there an even better way to do it? Can you explain why?
Query 1:
```
SELECT
*
FROM
table_a, table_b, table_c
WHERE
table_a.id = table_b.id AND
table_a.id = table_c.id AND
table_a.create_date > DATE('1998-01-01');
```
Query 2:
```
SELECT
*
FROM
table_a
INNER JOIN table_b ON
table_a.id = table_b.id
INNER JOIN table_c ON
table_a.id = table_c.id
WHERE
table_a.create_date > DATE('1998-01-01');
``` | Same query, different revision of SQL spec. The query optimizer should come up with the same query plan for those. |
80,175 | <p>This is somewhat similar to <a href="https://stackoverflow.com/questions/25653/hide-a-column-in-aspnet-dynamic-data">this question</a>.</p>
<p>However, rather than wanting to hide a column all together, I am just looking to hide the column on the List.aspx page.</p>
<p>My specific example is that fields that are long (or at least nvarchar(MAX)) automatically hide from the List.aspx page as is but are still visible on the Edit.aspx page.</p>
<p>I would like to replicate this behaviour for other (shorter) columns.</p>
<p>Is this possible?</p>
| [
{
"answer_id": 81806,
"author": "Mark Pattison",
"author_id": 15519,
"author_profile": "https://Stackoverflow.com/users/15519",
"pm_score": 4,
"selected": true,
"text": "<p>You can create a custom page for the particular table you want to change. There's an example <a href=\"http://davidhayden.com/blog/dave/archive/2007/12/30/ASPNETDynamicDataWebsitesCustomizingPagesValidation.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Within your custom page, you can then set <code>AutoGenerateColumns=\"false\"</code> within the <code>asp:GridView</code> control, and then define exactly the columns you want, like this:</p>\n\n<pre><code><Columns>\n ...\n <asp:DynamicField DataField=\"Product\" HeaderText=\"Product\" />\n <asp:DynamicField DataField=\"Colour\" HeaderText=\"Colour\" />\n</Columns>\n</code></pre>\n"
},
{
"answer_id": 2527099,
"author": "Irwin",
"author_id": 27483,
"author_profile": "https://Stackoverflow.com/users/27483",
"pm_score": 2,
"selected": false,
"text": "<p>I think this solution is a really useful one, because it allow you to use the attribute model to specify which columns go where:\n<a href=\"http://csharpbits.notaclue.net/2008/10/dynamic-data-hiding-columns-in-selected.html\" rel=\"nofollow noreferrer\">http://csharpbits.notaclue.net/2008/10/dynamic-data-hiding-columns-in-selected.html</a></p>\n"
},
{
"answer_id": 33539874,
"author": "iamtonyzhou",
"author_id": 1027127,
"author_profile": "https://Stackoverflow.com/users/1027127",
"pm_score": 0,
"selected": false,
"text": "<p>if u r using bootstrap u can set like this</p>\n\n<pre><code><asp:DynamicField DataField=\"Id\" ItemStyle-CssClass=\"hidden\" HeaderStyle-CssClass=\"hidden\" FooterStyle-CssClass=\"hidden\"/>\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
| This is somewhat similar to [this question](https://stackoverflow.com/questions/25653/hide-a-column-in-aspnet-dynamic-data).
However, rather than wanting to hide a column all together, I am just looking to hide the column on the List.aspx page.
My specific example is that fields that are long (or at least nvarchar(MAX)) automatically hide from the List.aspx page as is but are still visible on the Edit.aspx page.
I would like to replicate this behaviour for other (shorter) columns.
Is this possible? | You can create a custom page for the particular table you want to change. There's an example [here](http://davidhayden.com/blog/dave/archive/2007/12/30/ASPNETDynamicDataWebsitesCustomizingPagesValidation.aspx).
Within your custom page, you can then set `AutoGenerateColumns="false"` within the `asp:GridView` control, and then define exactly the columns you want, like this:
```
<Columns>
...
<asp:DynamicField DataField="Product" HeaderText="Product" />
<asp:DynamicField DataField="Colour" HeaderText="Colour" />
</Columns>
``` |
80,186 | <p>I can't seem to find much documentation on X-Sendfile or example code for PHP (there is some rails code).</p>
<p>Anyone used it before and would mind giving a quick snippet of code and a brief description?</p>
| [
{
"answer_id": 80201,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 5,
"selected": false,
"text": "<p>X-Sendfile is an HTTP header, so you want something like this:</p>\n\n<pre><code>header(\"X-Sendfile: $filename\");\n</code></pre>\n\n<p>Your web server picks it up if correctly configured. Here's some more details:</p>\n\n<p><a href=\"http://www.jasny.net/articles/how-i-php-x-sendfile/\" rel=\"noreferrer\">http://www.jasny.net/articles/how-i-php-x-sendfile/</a></p>\n"
},
{
"answer_id": 80422,
"author": "Garrett Albright",
"author_id": 11023,
"author_profile": "https://Stackoverflow.com/users/11023",
"pm_score": 2,
"selected": false,
"text": "<p>If tweaking the web server configuration is not an option, consider PHP's standard <a href=\"http://us3.php.net/manual/en/function.readfile.php\" rel=\"nofollow noreferrer\">readfile() function</a>. It won't be quite as fast as sendfiling, but it will be more widely compatible. Also note that when doing this, you should also send a Content-Type header at the very least.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I can't seem to find much documentation on X-Sendfile or example code for PHP (there is some rails code).
Anyone used it before and would mind giving a quick snippet of code and a brief description? | X-Sendfile is an HTTP header, so you want something like this:
```
header("X-Sendfile: $filename");
```
Your web server picks it up if correctly configured. Here's some more details:
<http://www.jasny.net/articles/how-i-php-x-sendfile/> |
80,195 | <p>I would like to make 2 TB or so available via NFS and CIFS. I am looking for a 2 (or more) server solution for high availability and the ability to load balance across the servers if possible. Any suggestions for clustering or high availability solutions?</p>
<p>This is business use, planning on growing to 5-10 TB over next few years. Our facility is almost 24 hours a day, six days a week. We could have 15-30 minutes of downtime, but we want to minimize data loss. I want to minimize 3 AM calls. </p>
<p>We are currently running one server with ZFS on Solaris and we are looking at AVS for the HA part, but we have had minor issues with Solaris (CIFS implementation doesn't work with Vista, etc) that have held us up. </p>
<p>We have started looking at </p>
<ul>
<li>DRDB over GFS (GFS for distributed
lock capability)</li>
<li>Gluster (needs
client pieces, no native CIFS
support?)</li>
<li>Windows DFS (doc says only
replicates after file closes?)</li>
</ul>
<p>We are looking for a "black box" that serves up data.</p>
<p>We currently snapshot the data in ZFS and send the snapshot over the net to a remote datacenter for offsite backup.</p>
<p>Our original plan was to have a 2nd machine and rsync every 10 - 15 min. The issue on a failure would be that ongoing production processes would lose 15 minutes of data and be left "in the middle". They would almost be easier to start from the beginning than to figure out where to pickup in the middle. That is what drove us to look at HA solutions.</p>
| [
{
"answer_id": 80211,
"author": "David Ackerman",
"author_id": 2504,
"author_profile": "https://Stackoverflow.com/users/2504",
"pm_score": 0,
"selected": false,
"text": "<p>Are you looking for an \"enterprise\" solution or a \"home\" solution? It is hard to tell from your question, because 2TB is very small for an enterprise and a little on the high end for a home user (especially two servers). Could you clarify the need so we can discuss tradeoffs?</p>\n"
},
{
"answer_id": 80212,
"author": "Sev",
"author_id": 83819,
"author_profile": "https://Stackoverflow.com/users/83819",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend <strong>NAS Storage. (Network Attached Storage).</strong></p>\n\n<p>HP has some nice ones you can choose from.</p>\n\n<p><a href=\"http://h18006.www1.hp.com/storage/aiostorage.html\" rel=\"nofollow noreferrer\">http://h18006.www1.hp.com/storage/aiostorage.html</a></p>\n\n<p>as well as Clustered versions:</p>\n\n<p><a href=\"http://h18006.www1.hp.com/storage/software/clusteredfs/index.html?jumpid=reg_R1002_USEN\" rel=\"nofollow noreferrer\">http://h18006.www1.hp.com/storage/software/clusteredfs/index.html?jumpid=reg_R1002_USEN</a></p>\n"
},
{
"answer_id": 80218,
"author": "pjz",
"author_id": 8002,
"author_profile": "https://Stackoverflow.com/users/8002",
"pm_score": 2,
"selected": false,
"text": "<p>These days 2TB fits in one machine, so you've got options, from simple to complex. These all presume linux servers:</p>\n\n<ul>\n<li>You can get poor-man's HA by setting up two machines and doing a periodic rsync from the main one to the backup.</li>\n<li>You can use <a href=\"http://www.drbd.org\" rel=\"nofollow noreferrer\">DRBD</a> to mirror one from the other at the block level. This has the disadvantage of being somewhat difficult to expand in the future.</li>\n<li>You can use <a href=\"http://oss.oracle.com/projects/ocfs2/\" rel=\"nofollow noreferrer\">OCFS2</a> to cluster the disks instead, for future expandability.</li>\n</ul>\n\n<p>There are also plenty of commercial solutions, but 2TB is a bit small for most of them these days.</p>\n\n<p>You haven't mentioned your application yet, but if hot failover isn't necessary, and all you really want is something that will stand up to losing a disk or two, find a NAS that support RAID-5, at least 4 drives, and hotswap and you should be good to go.</p>\n"
},
{
"answer_id": 80270,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 0,
"selected": false,
"text": "<p>There's two ways to go at this. The first is to just go buy a SAN or a NAS from Dell or HP and throw money at the problem. Modern storage hardware just makes all of this easy to do, saving your expertise for more core problems.</p>\n\n<p>If you want to roll your own, take a look at using Linux with DRBD.</p>\n\n<p><a href=\"http://www.drbd.org/\" rel=\"nofollow noreferrer\"><a href=\"http://www.drbd.org/\" rel=\"nofollow noreferrer\">http://www.drbd.org/</a></a></p>\n\n<p>DRBD allows you to create networked block devices. Think RAID 1 across two servers instead of just two disks. DRBD deployments are usually done using Heartbeat for failover in case one system dies.</p>\n\n<p>I'm not sure about load balancing, but you might investigate and see if LVS can be used to load balance across your DRBD hosts:</p>\n\n<p><a href=\"http://www.linuxvirtualserver.org/\" rel=\"nofollow noreferrer\"><a href=\"http://www.linuxvirtualserver.org/\" rel=\"nofollow noreferrer\">http://www.linuxvirtualserver.org/</a></a></p>\n\n<p>To conclude, let me just reiterate that you're probably going to save yourself a lot of time in the long run just forking out the money for a NAS.</p>\n"
},
{
"answer_id": 80473,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I assume from the body of your question is you're a business user? I purchased a 6TB RAID 5 unit from Silicon Mechanics and have it NAS attached and my engineer installed NFS on our servers. Backups performed via rsync to another large capacity NAS.</p>\n"
},
{
"answer_id": 80520,
"author": "pro",
"author_id": 352728,
"author_profile": "https://Stackoverflow.com/users/352728",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at Amazon Simple Storage Service (Amazon S3)</p>\n\n<p><a href=\"http://www.amazon.com/S3-AWS-home-page-Money/b/ref=sc_fe_l_2?ie=UTF8&node=16427261&no=3435361&me=A36L942TSJ2AJA\" rel=\"nofollow noreferrer\">http://www.amazon.com/S3-AWS-home-page-Money/b/ref=sc_fe_l_2?ie=UTF8&node=16427261&no=3435361&me=A36L942TSJ2AJA</a></p>\n\n<p>--\nThis may be of interest re. High Availability</p>\n\n<p>Dear AWS Customer:</p>\n\n<p>Many of you have asked us to let you know ahead of time about features and services that are currently under development so that you can better plan for how that functionality might integrate with your applications. To that end, we are excited to share some early details with you about a new offering we have under development here at AWS -- a content delivery service.</p>\n\n<p>This new service will provide you a high performance method of distributing content to end users, giving your customers low latency and high data transfer rates when they access your objects. The initial release will help developers and businesses who need to deliver popular, publicly readable content over HTTP connections. Our goal is to create a content delivery service that:</p>\n\n<p>Lets developers and businesses get started easily - there are no minimum fees and no commitments. You will only pay for what you actually use. \nIs simple and easy to use - a single, simple API call is all that is needed to get started delivering your content. \nWorks seamlessly with Amazon S3 - this gives you durable storage for the original, definitive versions of your files while making the content delivery service easier to use. \nHas a global presence - we use a global network of edge locations on three continents to deliver your content from the most appropriate location.</p>\n\n<p>You'll start by storing the original version of your objects in Amazon S3, making sure they are publicly readable. Then, you'll make a simple API call to register your bucket with the new content delivery service. This API call will return a new domain name for you to include in your web pages or application. When clients request an object using this domain name, they will be automatically routed to the nearest edge location for high performance delivery of your content. It's that simple.</p>\n\n<p>We're currently working with a small group of private beta customers, and expect to have this service widely available before the end of the year. If you'd like to be notified when we launch, please let us know by clicking here.</p>\n\n<p>Sincerely,</p>\n\n<p>The Amazon Web Services Team </p>\n"
},
{
"answer_id": 85518,
"author": "ben",
"author_id": 7561,
"author_profile": "https://Stackoverflow.com/users/7561",
"pm_score": 0,
"selected": false,
"text": "<p>Your best bet maybe to work with experts who do this sort of thing for a living. These guys are actually in our office complex...I've had a chance to work with them on a similar project I was lead on.</p>\n\n<p><a href=\"http://www.deltasquare.com/About\" rel=\"nofollow noreferrer\">http://www.deltasquare.com/About</a></p>\n"
},
{
"answer_id": 85606,
"author": "Tony Dodd",
"author_id": 16465,
"author_profile": "https://Stackoverflow.com/users/16465",
"pm_score": 3,
"selected": false,
"text": "<p>I've recently deployed hanfs using DRBD as the backend, in my situation, I'm running active/standby mode, but I've tested it successfully using OCFS2 in primary/primary mode too. There unfortunately isn't much documentation out there on how best to achieve this, most that exists is barely useful at best. If you do go along the drbd route, I highly recommend joining the drbd mailing list, and reading all of the documentation. Here's my ha/drbd setup and script I wrote to handle ha's failures:</p>\n\n<hr>\n\n<p>DRBD8 is required - this is provided by drbd8-utils and drbd8-source. Once these are installed (I believe they're provided by backports), you can use module-assistant to install it - m-a a-i drbd8. Either depmod -a or reboot at this point, if you depmod -a, you'll need to modprobe drbd.</p>\n\n<p>You'll require a backend partition to use for drbd, do not make this partition LVM, or you'll hit all sorts of problems. Do not put LVM on the drbd device or you'll hit all sorts of problems.</p>\n\n<p>Hanfs1:</p>\n\n<pre><code>\n/etc/drbd.conf\n\nglobal {\n usage-count no;\n}\ncommon {\n protocol C;\n disk { on-io-error detach; }\n}\nresource export {\n syncer {\n rate 125M;\n }\n on hanfs2 {\n address 172.20.1.218:7789;\n device /dev/drbd1;\n disk /dev/sda3;\n meta-disk internal;\n }\n on hanfs1 {\n address 172.20.1.219:7789;\n device /dev/drbd1;\n disk /dev/sda3;\n meta-disk internal;\n }\n}</code></pre>\n\n<p>Hanfs2's /etc/drbd.conf:</p>\n\n<p><pre><code>\nglobal {\n usage-count no;\n}\ncommon {\n protocol C;\n disk { on-io-error detach; }\n}\nresource export {\n syncer {\n rate 125M;\n }\n on hanfs2 {\n address 172.20.1.218:7789;\n device /dev/drbd1;\n disk /dev/sda3;\n meta-disk internal;\n }\n on hanfs1 {\n address 172.20.1.219:7789;\n device /dev/drbd1;\n disk /dev/sda3;\n meta-disk internal;\n }\n}</pre></code></p>\n\n<p>Once configured, we need to bring up drbd next.</p>\n\n<pre>\ndrbdadm create-md export\ndrbdadm attach export\ndrbdadm connect export\n</pre>\n\n<p>We must now perform an initial synchronization of data - obviously, if this is a brand new drbd cluster, it doesn't matter which node you choose.</p>\n\n<p></p>\n\n<p>Once done, you'll need to mkfs.yourchoiceoffilesystem on your drbd device - the device in our config above is /dev/drbd1. <a href=\"http://www.drbd.org/users-guide/p-work.html\" rel=\"noreferrer\">http://www.drbd.org/users-guide/p-work.html</a> is a useful document to read while working with drbd.</p>\n\n<p>Heartbeat</p>\n\n<p>Install heartbeat2. (Pretty simple, apt-get install heartbeat2).</p>\n\n<p>/etc/ha.d/ha.cf on each machine should consist of:</p>\n\n<p>hanfs1:\n<pre><code>\nlogfacility local0\nkeepalive 2\nwarntime 10\ndeadtime 30\ninitdead 120</p>\n\n<p>ucast eth1 172.20.1.218</p>\n\n<p>auto_failback no</p>\n\n<p>node hanfs1\nnode hanfs2\n</pre></code></p>\n\n<p>hanfs2:</p>\n\n<p><pre><code>\nlogfacility local0\nkeepalive 2\nwarntime 10\ndeadtime 30\ninitdead 120</p>\n\n<p>ucast eth1 172.20.1.219</p>\n\n<p>auto_failback no</p>\n\n<p>node hanfs1\nnode hanfs2\n</pre></code></p>\n\n<p>/etc/ha.d/haresources should be the same on both ha boxes:</p>\n\n<pre>\nhanfs1 IPaddr::172.20.1.230/24/eth1\nhanfs1 HeartBeatWrapper</pre>\n\n<p>I wrote a wrapper script to deal with the idiosyncracies caused by nfs and drbd in a failover scenario. This script should exist within /etc/ha.d/resources.d/ on each machine.</p>\n\n<p><pre><code></p>\n\n<h1>!/bin/bash</h1>\n\n<h1>heartbeat fails hard.</h1>\n\n<h1>so this is a wrapper</h1>\n\n<h1>to get around that stupidity</h1>\n\n<h1>I'm just wrapping the heartbeat scripts, except for in the case of umount</h1>\n\n<h1>as they work, mostly</h1>\n\n<p>if [[ -e /tmp/heartbeatwrapper ]]; then\n runningpid=$(cat /tmp/heartbeatwrapper)\n if [[ -z $(ps --no-heading -p $runningpid) ]]; then\n echo \"PID found, but process seems dead. Continuing.\"\n else<br>\n echo \"PID found, process is alive, exiting.\"<br>\n exit 7<br>\n fi<br>\nfi </p>\n\n<p>echo $$ > /tmp/heartbeatwrapper</p>\n\n<p>if [[ x$1 == \"xstop\" ]]; then</p>\n\n<p>/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&1</p>\n\n<h1>NFS init script isn't LSB compatible, exit codes are 0 no matter what happens.</h1>\n\n<h1>Thanks guys, you really make my day with this bullshit.</h1>\n\n<h1>Because of the above, we just have to hope that nfs actually catches the signal</h1>\n\n<h1>to exit, and manages to shut down its connections.</h1>\n\n<h1>If it doesn't, we'll kill it later, then term any other nfs stuff afterwards.</h1>\n\n<h1>I found this to be an interesting insight into just how badly NFS is written.</h1>\n\n<p>sleep 1</p>\n\n<pre><code>#we don't want to shutdown nfs first!\n#The lock files might go away, which would be bad.\n\n#The above seems to not matter much, the only thing I've determined\n#is that if you have anything mounted synchronously, it's going to break\n#no matter what I do. Basically, sync == screwed; in NFSv3 terms. \n#End result of failing over while a client that's synchronous is that \n#the client hangs waiting for its nfs server to come back - thing doesn't\n#even bother to time out, or attempt a reconnect. \n#async works as expected - it insta-reconnects as soon as a connection seems\n#to be unstable, and continues to write data. In all tests, md5sums have \n#remained the same with/without failover during transfer. \n\n#So, we first unmount /export - this prevents drbd from having a shit-fit\n#when we attempt to turn this node secondary. \n\n#That's a lie too, to some degree. LVM is entirely to blame for why DRBD\n#was refusing to unmount. Don't get me wrong, having /export mounted doesn't\n#help either, but still. \n#fix a usecase where one or other are unmounted already, which causes us to terminate early.\n\nif [[ \"$(grep -o /varlibnfs/rpc_pipefs /etc/mtab)\" ]]; then \n for ((test=1; test <= 10; test++)); do \n umount /export/varlibnfs/rpc_pipefs >/dev/null 2>&1 \n if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then \n break \n fi \n if [[ $? -ne 0 ]]; then \n #try again, harder this time \n umount -l /var/lib/nfs/rpc_pipefs >/dev/null 2>&1 \n if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then \n break \n fi \n fi \n done \n if [[ $test -eq 10 ]]; then \n rm -f /tmp/heartbeatwrapper \n echo \"Problem unmounting rpc_pipefs\" \n exit 1 \n fi \nfi \n\nif [[ \"$(grep -o /dev/drbd1 /etc/mtab)\" ]]; then \n for ((test=1; test <= 10; test++)); do \n umount /export >/dev/null 2>&1 \n if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then \n break \n fi \n if [[ $? -ne 0 ]]; then \n #try again, harder this time \n umount -l /export >/dev/null 2>&1 \n if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then \n break \n fi \n fi \n done \n if [[ $test -eq 10 ]]; then \n rm -f /tmp/heartbeatwrapper \n echo \"Problem unmount /export\" \n exit 1 \n fi \nfi \n\n\n#now, it's important that we shut down nfs. it can't write to /export anymore, so that's fine.\n#if we leave it running at this point, then drbd will screwup when trying to go to secondary. \n#See contradictory comment above for why this doesn't matter anymore. These comments are left in\n#entirely to remind me of the pain this caused me to resolve. A bit like why churches have Jesus\n#nailed onto a cross instead of chilling in a hammock. \n\npidof nfsd | xargs kill -9 >/dev/null 2>&1\n\nsleep 1 \n\nif [[ -n $(ps aux | grep nfs | grep -v grep) ]]; then\n echo \"nfs still running, trying to kill again\" \n pidof nfsd | xargs kill -9 >/dev/null 2>&1 \nfi \n\nsleep 1\n\n/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&1\n\nsleep 1\n\n#next we need to tear down drbd - easy with the heartbeat scripts\n#it takes input as resourcename start|stop|status \n#First, we'll check to see if it's stopped \n\n/etc/ha.d/resource.d/drbddisk export status >/dev/null 2>&1\nif [[ $? -eq 2 ]]; then \n echo \"resource is already stopped for some reason...\" \nelse \n for ((i=1; i <= 10; i++)); do \n /etc/ha.d/resource.d/drbddisk export stop >/dev/null 2>&1\n if [[ $(egrep -o \"st:[A-Za-z/]*\" /proc/drbd | cut -d: -f2) == \"Secondary/Secondary\" ]] || [[ $(egrep -o \"st:[A-Za-z/]*\" /proc/drbd | cut -d: -f2) == \"Secondary/Unknown\" ]]; then \n echo \"Successfully stopped DRBD\" \n break \n else \n echo \"Failed to stop drbd for some reason\" \n cat /proc/drbd \n if [[ $i -eq 10 ]]; then \n exit 50 \n fi \n fi \n done \nfi \n\nrm -f /tmp/heartbeatwrapper \nexit 0 \n</code></pre>\n\n<p>elif [[ x$1 == \"xstart\" ]]; then</p>\n\n<pre><code>#start up drbd first\n/etc/ha.d/resource.d/drbddisk export start >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then \n echo \"Something seems to have broken. Let's check possibilities...\"\n testvar=$(egrep -o \"st:[A-Za-z/]*\" /proc/drbd | cut -d: -f2) \n if [[ $testvar == \"Primary/Unknown\" ]] || [[ $testvar == \"Primary/Secondary\" ]]\n then \n echo \"All is fine, we are already the Primary for some reason\" \n elif [[ $testvar == \"Secondary/Unknown\" ]] || [[ $testvar == \"Secondary/Secondary\" ]]\n then \n echo \"Trying to assume Primary again\" \n /etc/ha.d/resource.d/drbddisk export start >/dev/null 2>&1 \n if [[ $? -ne 0 ]]; then \n echo \"I give up, something's seriously broken here, and I can't help you to fix it.\"\n rm -f /tmp/heartbeatwrapper \n exit 127 \n fi \n fi \nfi \n\nsleep 1 \n\n#now we remount our partitions \n\nfor ((test=1; test <= 10; test++)); do \n mount /dev/drbd1 /export >/tmp/mountoutput \n if [[ -n $(grep -o export /etc/mtab) ]]; then \n break \n fi \ndone \n\nif [[ $test -eq 10 ]]; then \n rm -f /tmp/heartbeatwrapper \n exit 125 \nfi \n\n\n#I'm really unsure at this point of the side-effects of not having rpc_pipefs mounted. \n#The issue here, is that it cannot be mounted without nfs running, and we don't really want to start\n#nfs up at this point, lest it ruin everything. \n#For now, I'm leaving mine unmounted, it doesn't seem to cause any problems. \n\n#Now we start up nfs.\n\n/etc/init.d/nfs-kernel-server start >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then\n echo \"There's not really that much that I can do to debug nfs issues.\"\n echo \"probably your configuration is broken. I'm terminating here.\"\n rm -f /tmp/heartbeatwrapper\n exit 129\nfi\n\n#And that's it, done.\n\nrm -f /tmp/heartbeatwrapper\nexit 0\n</code></pre>\n\n<p>elif [[ \"x$1\" == \"xstatus\" ]]; then</p>\n\n<pre><code>#Lets check to make sure nothing is broken.\n\n#DRBD first\n/etc/ha.d/resource.d/drbddisk export status >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then\n echo \"stopped\"\n rm -f /tmp/heartbeatwrapper\n exit 3\nfi\n\n#mounted?\ngrep -q drbd /etc/mtab >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then\n echo \"stopped\"\n rm -f /tmp/heartbeatwrapper\n exit 3\nfi\n\n#nfs running?\n/etc/init.d/nfs-kernel-server status >/dev/null 2>&1\nif [[ $? -ne 0 ]]; then\n echo \"stopped\"\n rm -f /tmp/heartbeatwrapper\n exit 3\nfi\n\necho \"running\"\nrm -f /tmp/heartbeatwrapper\nexit 0\n</code></pre>\n\n<p>fi\n</pre></code></p>\n\n<p>With all of the above done, you'll then just want to configure /etc/exports</p>\n\n<pre>/export 172.20.1.0/255.255.255.0(rw,sync,fsid=1,no_root_squash)</pre>\n\n<p>Then it's just a case of starting up heartbeat on both machines and issuing hb_takeover on one of them. You can test that it's working by making sure the one you issued the takeover on is primary - check /proc/drbd, that the device is mounted correctly, and that you can access nfs. </p>\n\n<p>--</p>\n\n<p>Best of luck man. Setting it up from the ground up was, for me, an extremely painful experience.</p>\n"
},
{
"answer_id": 764265,
"author": "McGovernTheory",
"author_id": 85095,
"author_profile": "https://Stackoverflow.com/users/85095",
"pm_score": 0,
"selected": false,
"text": "<p>May I suggest you visit the F5 site and check out <a href=\"http://www.f5.com/solutions/virtualization/file/\" rel=\"nofollow noreferrer\">http://www.f5.com/solutions/virtualization/file/</a></p>\n"
},
{
"answer_id": 2167246,
"author": "fish.ada94",
"author_id": 262384,
"author_profile": "https://Stackoverflow.com/users/262384",
"pm_score": 0,
"selected": false,
"text": "<p>You can look at Mirror File System. It does the file replication on file system level.\nThe same file on both primary and backup systems are live file.</p>\n\n<p><a href=\"http://www.linux-ha.org/RelatedTechnologies/Filesystems\" rel=\"nofollow noreferrer\">http://www.linux-ha.org/RelatedTechnologies/Filesystems</a></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15020/"
]
| I would like to make 2 TB or so available via NFS and CIFS. I am looking for a 2 (or more) server solution for high availability and the ability to load balance across the servers if possible. Any suggestions for clustering or high availability solutions?
This is business use, planning on growing to 5-10 TB over next few years. Our facility is almost 24 hours a day, six days a week. We could have 15-30 minutes of downtime, but we want to minimize data loss. I want to minimize 3 AM calls.
We are currently running one server with ZFS on Solaris and we are looking at AVS for the HA part, but we have had minor issues with Solaris (CIFS implementation doesn't work with Vista, etc) that have held us up.
We have started looking at
* DRDB over GFS (GFS for distributed
lock capability)
* Gluster (needs
client pieces, no native CIFS
support?)
* Windows DFS (doc says only
replicates after file closes?)
We are looking for a "black box" that serves up data.
We currently snapshot the data in ZFS and send the snapshot over the net to a remote datacenter for offsite backup.
Our original plan was to have a 2nd machine and rsync every 10 - 15 min. The issue on a failure would be that ongoing production processes would lose 15 minutes of data and be left "in the middle". They would almost be easier to start from the beginning than to figure out where to pickup in the middle. That is what drove us to look at HA solutions. | I've recently deployed hanfs using DRBD as the backend, in my situation, I'm running active/standby mode, but I've tested it successfully using OCFS2 in primary/primary mode too. There unfortunately isn't much documentation out there on how best to achieve this, most that exists is barely useful at best. If you do go along the drbd route, I highly recommend joining the drbd mailing list, and reading all of the documentation. Here's my ha/drbd setup and script I wrote to handle ha's failures:
---
DRBD8 is required - this is provided by drbd8-utils and drbd8-source. Once these are installed (I believe they're provided by backports), you can use module-assistant to install it - m-a a-i drbd8. Either depmod -a or reboot at this point, if you depmod -a, you'll need to modprobe drbd.
You'll require a backend partition to use for drbd, do not make this partition LVM, or you'll hit all sorts of problems. Do not put LVM on the drbd device or you'll hit all sorts of problems.
Hanfs1:
```
/etc/drbd.conf
global {
usage-count no;
}
common {
protocol C;
disk { on-io-error detach; }
}
resource export {
syncer {
rate 125M;
}
on hanfs2 {
address 172.20.1.218:7789;
device /dev/drbd1;
disk /dev/sda3;
meta-disk internal;
}
on hanfs1 {
address 172.20.1.219:7789;
device /dev/drbd1;
disk /dev/sda3;
meta-disk internal;
}
}
```
Hanfs2's /etc/drbd.conf:
```
global {
usage-count no;
}
common {
protocol C;
disk { on-io-error detach; }
}
resource export {
syncer {
rate 125M;
}
on hanfs2 {
address 172.20.1.218:7789;
device /dev/drbd1;
disk /dev/sda3;
meta-disk internal;
}
on hanfs1 {
address 172.20.1.219:7789;
device /dev/drbd1;
disk /dev/sda3;
meta-disk internal;
}
}
```
Once configured, we need to bring up drbd next.
```
drbdadm create-md export
drbdadm attach export
drbdadm connect export
```
We must now perform an initial synchronization of data - obviously, if this is a brand new drbd cluster, it doesn't matter which node you choose.
Once done, you'll need to mkfs.yourchoiceoffilesystem on your drbd device - the device in our config above is /dev/drbd1. <http://www.drbd.org/users-guide/p-work.html> is a useful document to read while working with drbd.
Heartbeat
Install heartbeat2. (Pretty simple, apt-get install heartbeat2).
/etc/ha.d/ha.cf on each machine should consist of:
hanfs1:
```
logfacility local0
keepalive 2
warntime 10
deadtime 30
initdead 120
```
ucast eth1 172.20.1.218
auto\_failback no
node hanfs1
node hanfs2
hanfs2:
```
logfacility local0
keepalive 2
warntime 10
deadtime 30
initdead 120
```
ucast eth1 172.20.1.219
auto\_failback no
node hanfs1
node hanfs2
/etc/ha.d/haresources should be the same on both ha boxes:
```
hanfs1 IPaddr::172.20.1.230/24/eth1
hanfs1 HeartBeatWrapper
```
I wrote a wrapper script to deal with the idiosyncracies caused by nfs and drbd in a failover scenario. This script should exist within /etc/ha.d/resources.d/ on each machine.
!/bin/bash
==========
heartbeat fails hard.
=====================
so this is a wrapper
====================
to get around that stupidity
============================
I'm just wrapping the heartbeat scripts, except for in the case of umount
=========================================================================
as they work, mostly
====================
if [[ -e /tmp/heartbeatwrapper ]]; then
runningpid=$(cat /tmp/heartbeatwrapper)
if [[ -z $(ps --no-heading -p $runningpid) ]]; then
echo "PID found, but process seems dead. Continuing."
else
echo "PID found, process is alive, exiting."
exit 7
fi
fi
echo $$ > /tmp/heartbeatwrapper
if [[ x$1 == "xstop" ]]; then
/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&1
NFS init script isn't LSB compatible, exit codes are 0 no matter what happens.
==============================================================================
Thanks guys, you really make my day with this bullshit.
=======================================================
Because of the above, we just have to hope that nfs actually catches the signal
===============================================================================
to exit, and manages to shut down its connections.
==================================================
If it doesn't, we'll kill it later, then term any other nfs stuff afterwards.
=============================================================================
I found this to be an interesting insight into just how badly NFS is written.
=============================================================================
sleep 1
```
#we don't want to shutdown nfs first!
#The lock files might go away, which would be bad.
#The above seems to not matter much, the only thing I've determined
#is that if you have anything mounted synchronously, it's going to break
#no matter what I do. Basically, sync == screwed; in NFSv3 terms.
#End result of failing over while a client that's synchronous is that
#the client hangs waiting for its nfs server to come back - thing doesn't
#even bother to time out, or attempt a reconnect.
#async works as expected - it insta-reconnects as soon as a connection seems
#to be unstable, and continues to write data. In all tests, md5sums have
#remained the same with/without failover during transfer.
#So, we first unmount /export - this prevents drbd from having a shit-fit
#when we attempt to turn this node secondary.
#That's a lie too, to some degree. LVM is entirely to blame for why DRBD
#was refusing to unmount. Don't get me wrong, having /export mounted doesn't
#help either, but still.
#fix a usecase where one or other are unmounted already, which causes us to terminate early.
if [[ "$(grep -o /varlibnfs/rpc_pipefs /etc/mtab)" ]]; then
for ((test=1; test <= 10; test++)); do
umount /export/varlibnfs/rpc_pipefs >/dev/null 2>&1
if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then
break
fi
if [[ $? -ne 0 ]]; then
#try again, harder this time
umount -l /var/lib/nfs/rpc_pipefs >/dev/null 2>&1
if [[ -z $(grep -o /varlibnfs/rpc_pipefs /etc/mtab) ]]; then
break
fi
fi
done
if [[ $test -eq 10 ]]; then
rm -f /tmp/heartbeatwrapper
echo "Problem unmounting rpc_pipefs"
exit 1
fi
fi
if [[ "$(grep -o /dev/drbd1 /etc/mtab)" ]]; then
for ((test=1; test <= 10; test++)); do
umount /export >/dev/null 2>&1
if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then
break
fi
if [[ $? -ne 0 ]]; then
#try again, harder this time
umount -l /export >/dev/null 2>&1
if [[ -z $(grep -o /dev/drbd1 /etc/mtab) ]]; then
break
fi
fi
done
if [[ $test -eq 10 ]]; then
rm -f /tmp/heartbeatwrapper
echo "Problem unmount /export"
exit 1
fi
fi
#now, it's important that we shut down nfs. it can't write to /export anymore, so that's fine.
#if we leave it running at this point, then drbd will screwup when trying to go to secondary.
#See contradictory comment above for why this doesn't matter anymore. These comments are left in
#entirely to remind me of the pain this caused me to resolve. A bit like why churches have Jesus
#nailed onto a cross instead of chilling in a hammock.
pidof nfsd | xargs kill -9 >/dev/null 2>&1
sleep 1
if [[ -n $(ps aux | grep nfs | grep -v grep) ]]; then
echo "nfs still running, trying to kill again"
pidof nfsd | xargs kill -9 >/dev/null 2>&1
fi
sleep 1
/etc/init.d/nfs-kernel-server stop #>/dev/null 2>&1
sleep 1
#next we need to tear down drbd - easy with the heartbeat scripts
#it takes input as resourcename start|stop|status
#First, we'll check to see if it's stopped
/etc/ha.d/resource.d/drbddisk export status >/dev/null 2>&1
if [[ $? -eq 2 ]]; then
echo "resource is already stopped for some reason..."
else
for ((i=1; i <= 10; i++)); do
/etc/ha.d/resource.d/drbddisk export stop >/dev/null 2>&1
if [[ $(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) == "Secondary/Secondary" ]] || [[ $(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2) == "Secondary/Unknown" ]]; then
echo "Successfully stopped DRBD"
break
else
echo "Failed to stop drbd for some reason"
cat /proc/drbd
if [[ $i -eq 10 ]]; then
exit 50
fi
fi
done
fi
rm -f /tmp/heartbeatwrapper
exit 0
```
elif [[ x$1 == "xstart" ]]; then
```
#start up drbd first
/etc/ha.d/resource.d/drbddisk export start >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "Something seems to have broken. Let's check possibilities..."
testvar=$(egrep -o "st:[A-Za-z/]*" /proc/drbd | cut -d: -f2)
if [[ $testvar == "Primary/Unknown" ]] || [[ $testvar == "Primary/Secondary" ]]
then
echo "All is fine, we are already the Primary for some reason"
elif [[ $testvar == "Secondary/Unknown" ]] || [[ $testvar == "Secondary/Secondary" ]]
then
echo "Trying to assume Primary again"
/etc/ha.d/resource.d/drbddisk export start >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "I give up, something's seriously broken here, and I can't help you to fix it."
rm -f /tmp/heartbeatwrapper
exit 127
fi
fi
fi
sleep 1
#now we remount our partitions
for ((test=1; test <= 10; test++)); do
mount /dev/drbd1 /export >/tmp/mountoutput
if [[ -n $(grep -o export /etc/mtab) ]]; then
break
fi
done
if [[ $test -eq 10 ]]; then
rm -f /tmp/heartbeatwrapper
exit 125
fi
#I'm really unsure at this point of the side-effects of not having rpc_pipefs mounted.
#The issue here, is that it cannot be mounted without nfs running, and we don't really want to start
#nfs up at this point, lest it ruin everything.
#For now, I'm leaving mine unmounted, it doesn't seem to cause any problems.
#Now we start up nfs.
/etc/init.d/nfs-kernel-server start >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "There's not really that much that I can do to debug nfs issues."
echo "probably your configuration is broken. I'm terminating here."
rm -f /tmp/heartbeatwrapper
exit 129
fi
#And that's it, done.
rm -f /tmp/heartbeatwrapper
exit 0
```
elif [[ "x$1" == "xstatus" ]]; then
```
#Lets check to make sure nothing is broken.
#DRBD first
/etc/ha.d/resource.d/drbddisk export status >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "stopped"
rm -f /tmp/heartbeatwrapper
exit 3
fi
#mounted?
grep -q drbd /etc/mtab >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "stopped"
rm -f /tmp/heartbeatwrapper
exit 3
fi
#nfs running?
/etc/init.d/nfs-kernel-server status >/dev/null 2>&1
if [[ $? -ne 0 ]]; then
echo "stopped"
rm -f /tmp/heartbeatwrapper
exit 3
fi
echo "running"
rm -f /tmp/heartbeatwrapper
exit 0
```
fi
With all of the above done, you'll then just want to configure /etc/exports
```
/export 172.20.1.0/255.255.255.0(rw,sync,fsid=1,no_root_squash)
```
Then it's just a case of starting up heartbeat on both machines and issuing hb\_takeover on one of them. You can test that it's working by making sure the one you issued the takeover on is primary - check /proc/drbd, that the device is mounted correctly, and that you can access nfs.
--
Best of luck man. Setting it up from the ground up was, for me, an extremely painful experience. |
80,202 | <p>I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p></p>
<p>Now I want to insert an element in to the text so that it will become:</p>
<p><p>Hello <span id=span1>new</span> world!</p></p>
<p>I need the span tag because I want to handle it later.Show or hide.
But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world".</p>
| [
{
"answer_id": 80228,
"author": "Sev",
"author_id": 83819,
"author_profile": "https://Stackoverflow.com/users/83819",
"pm_score": 0,
"selected": false,
"text": "<p>Include the class definition that's defined in CSS on your JavaScript version of the <code><span></code> tag as well.</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><span class=\"class_defined_in_css\">\n</code></pre>\n\n<p>(where this <code><span></code> tag would be part of your JavaScript code.)</p>\n"
},
{
"answer_id": 80231,
"author": "dreamlax",
"author_id": 10320,
"author_profile": "https://Stackoverflow.com/users/10320",
"pm_score": 0,
"selected": false,
"text": "<p>Why not give the paragraph an id and then use Javascript to add the word, or remove it, if necessary? Surely it will retain the same formatting as the paragraph when you insert the word \"new\", or change the contents of the paragraph entirely.</p>\n"
},
{
"answer_id": 80251,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 1,
"selected": false,
"text": "<p>Well, I don't know how married you are to using a <span> tag, but why not do this?</p>\n\n<pre><code><p style=\"display: inline\">Hello <p id=\"myIdValue\" style=\"display: inline\">new</p> World</p>\n</code></pre>\n\n<p>That way the inserted html retains the same styling as the outer, and you can still have a handle to it, etc. Granted, you will have to add the inline CSS style, but it would work.</p>\n"
},
{
"answer_id": 80262,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 1,
"selected": false,
"text": "<p>The only way to do this is to either modify the other spans to include a class name and only apply the styles to spans with that class, or override the styles set for all spans for your new span.</p>\n\n<p>So if you've done:</p>\n\n<pre><code>span {\n display: block;\n margin: 10px;\n padding: 10px;\n}\n</code></pre>\n\n<p>You could override with:</p>\n\n<pre><code><span style=\"display: inline; margin: 0; padding: 0;\">New Span</span>\n</code></pre>\n"
},
{
"answer_id": 80408,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 2,
"selected": true,
"text": "<p>Simply override any span styles. Set layout properties back to browser defaults and set formating to inherit from the parent:</p>\n\n<pre><code>span#yourSpan {\n /* defaults */\n position: static;\n display: inline;\n margin: 0;\n padding: 0;\n background: transparent;\n border: none;\n\n /* inherit from parent node */\n font: inherit;\n color: inherit;\n text-decoration: inherit;\n line-height: inherit;\n letter-spacing: inherit;\n text-transform: inherit;\n white-space: inherit;\n word-spacing: inherit;\n}\n</code></pre>\n\n<p>This should be sufficient, although you may need to add !important if you are not using an id:</p>\n\n<pre><code><span class=\"hello-node\">hello</span>\n\nspan.hello-node {\n /* defaults */\n position: static !important;\n display: inline !important;\n ...\n}\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15023/"
]
| I want to use javascript to insert some elements into the current page.
Such as this is the original document:
<p>Hello world!</p>
Now I want to insert an element in to the text so that it will become:
<p>Hello <span id=span1>new</span> world!</p>
I need the span tag because I want to handle it later.Show or hide.
But now problem comes out, if the original page has already defined a strange CSS style on all <span> tags, the "new" I just inserted will not appear to be the same as "Hello" and "world". How can I avoid this? I want the "new" be exactly the same as the "Hello" and "world". | Simply override any span styles. Set layout properties back to browser defaults and set formating to inherit from the parent:
```
span#yourSpan {
/* defaults */
position: static;
display: inline;
margin: 0;
padding: 0;
background: transparent;
border: none;
/* inherit from parent node */
font: inherit;
color: inherit;
text-decoration: inherit;
line-height: inherit;
letter-spacing: inherit;
text-transform: inherit;
white-space: inherit;
word-spacing: inherit;
}
```
This should be sufficient, although you may need to add !important if you are not using an id:
```
<span class="hello-node">hello</span>
span.hello-node {
/* defaults */
position: static !important;
display: inline !important;
...
}
``` |
80,247 | <p>How can I get all implementations of an interface through reflection in C#?</p>
| [
{
"answer_id": 80325,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 1,
"selected": false,
"text": "<p>Do you mean all interfaces a Type implements?</p>\n\n<p>Like this:</p>\n\n<pre><code>ObjX foo = new ObjX();\nType tFoo = foo.GetType();\nType[] tFooInterfaces = tFoo.GetInterfaces();\nforeach(Type tInterface in tFooInterfaces)\n{\n // do something with it\n}\n</code></pre>\n\n<p>Hope tha helpts.</p>\n"
},
{
"answer_id": 80343,
"author": "Anton",
"author_id": 6464,
"author_profile": "https://Stackoverflow.com/users/6464",
"pm_score": 3,
"selected": false,
"text": "<p>Have a look at <code>Assembly.GetTypes()</code> method. It returns all the types that can be found in an assembly. All you have to do is to iterate through every returned type and check if it implements necessary interface.</p>\n\n<p>On of the way to do so is using <code>Type.IsAssignableFrom</code> method.</p>\n\n<p>Here is the example. <code>myInterface</code> is the interface, implementations of which you are searching for.</p>\n\n<pre><code>Assembly myAssembly;\nType myInterface;\nforeach (Type type in myAssembly.GetTypes())\n{\n if (myInterface.IsAssignableFrom(type))\n Console.WriteLine(type.FullName);\n}\n</code></pre>\n\n<p>I do believe that it is not a very efficient way to solve your problem, but at least, it is a good place to start.</p>\n"
},
{
"answer_id": 80375,
"author": "Adam Driscoll",
"author_id": 13688,
"author_profile": "https://Stackoverflow.com/users/13688",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Assembly assembly = Assembly.GetExecutingAssembly();\nList<Type> types = assembly.GetTypes();\nList<Type> childTypes = new List<Type>();\nforeach (Type type in Types) {\n foreach (Type interfaceType in type.GetInterfaces()) {\n if (interfaceType.Equals(typeof([yourinterfacetype)) {\n childTypes.Add(type)\n break;\n }\n }\n}\n</code></pre>\n\n<p>Maybe something like that....</p>\n"
},
{
"answer_id": 80467,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 6,
"selected": false,
"text": "<p>The answer is this; it searches through the entire application domain -- that is, every assembly currently loaded by your application.</p>\n\n<pre><code>/// <summary>\n/// Returns all types in the current AppDomain implementing the interface or inheriting the type. \n/// </summary>\npublic static IEnumerable<Type> TypesImplementingInterface(Type desiredType)\n{\n return AppDomain\n .CurrentDomain\n .GetAssemblies()\n .SelectMany(assembly => assembly.GetTypes())\n .Where(type => desiredType.IsAssignableFrom(type));\n}\n</code></pre>\n\n<p>It is used like this;</p>\n\n<pre><code>var disposableTypes = TypesImplementingInterface(typeof(IDisposable));\n</code></pre>\n\n<p>You may also want this function to find actual concrete types -- i.e., filtering out abstracts, interfaces, and generic type definitions.</p>\n\n<pre><code>public static bool IsRealClass(Type testType)\n{\n return testType.IsAbstract == false\n && testType.IsGenericTypeDefinition == false\n && testType.IsInterface == false;\n}\n</code></pre>\n"
},
{
"answer_id": 81707,
"author": "Hallgrim",
"author_id": 15454,
"author_profile": "https://Stackoverflow.com/users/15454",
"pm_score": 1,
"selected": false,
"text": "<p>You have to loop over all assemblies that you are interested in. From the assembly you can get all the types it defines. Note that when you do AppDomain.CurrentDomain.Assemblies you only get the assemblies that are loaded. Assemblies are not loaded until they are needed, so that means that you have to explicitly load the assemblies before you start searching.</p>\n"
},
{
"answer_id": 17267339,
"author": "Sam",
"author_id": 238753,
"author_profile": "https://Stackoverflow.com/users/238753",
"pm_score": 2,
"selected": false,
"text": "<p>Here are some <a href=\"http://msdn.microsoft.com/en-us/library/system.type.aspx\" rel=\"nofollow noreferrer\"><code>Type</code></a> extension methods that may be useful for this, as suggested by <a href=\"https://stackoverflow.com/users/35047/simon-farrow\">Simon Farrow</a>. This code is just a restructuring of the accepted answer.</p>\n\n<h3>Code</h3>\n\n<pre><code>/// <summary>\n/// Returns all types in <paramref name=\"assembliesToSearch\"/> that directly or indirectly implement or inherit from the given type. \n/// </summary>\npublic static IEnumerable<Type> GetImplementors(this Type abstractType, params Assembly[] assembliesToSearch)\n{\n var typesInAssemblies = assembliesToSearch.SelectMany(assembly => assembly.GetTypes());\n return typesInAssemblies.Where(abstractType.IsAssignableFrom);\n}\n\n/// <summary>\n/// Returns the results of <see cref=\"GetImplementors\"/> that match <see cref=\"IsInstantiable\"/>.\n/// </summary>\npublic static IEnumerable<Type> GetInstantiableImplementors(this Type abstractType, params Assembly[] assembliesToSearch)\n{\n var implementors = abstractType.GetImplementors(assembliesToSearch);\n return implementors.Where(IsInstantiable);\n}\n\n/// <summary>\n/// Determines whether <paramref name=\"type\"/> is a concrete, non-open-generic type.\n/// </summary>\npublic static bool IsInstantiable(this Type type)\n{\n return !(type.IsAbstract || type.IsGenericTypeDefinition || type.IsInterface);\n}\n</code></pre>\n\n<h3>Examples</h3>\n\n<p>To get the instantiable implementors in the calling assembly:</p>\n\n<pre><code>var callingAssembly = Assembly.GetCallingAssembly();\nvar httpModules = typeof(IHttpModule).GetInstantiableImplementors(callingAssembly);\n</code></pre>\n\n<p>To get the implementors in the current AppDomain:</p>\n\n<pre><code>var appDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies();\nvar httpModules = typeof(IHttpModule).GetImplementors(appDomainAssemblies);\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How can I get all implementations of an interface through reflection in C#? | The answer is this; it searches through the entire application domain -- that is, every assembly currently loaded by your application.
```
/// <summary>
/// Returns all types in the current AppDomain implementing the interface or inheriting the type.
/// </summary>
public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)
{
return AppDomain
.CurrentDomain
.GetAssemblies()
.SelectMany(assembly => assembly.GetTypes())
.Where(type => desiredType.IsAssignableFrom(type));
}
```
It is used like this;
```
var disposableTypes = TypesImplementingInterface(typeof(IDisposable));
```
You may also want this function to find actual concrete types -- i.e., filtering out abstracts, interfaces, and generic type definitions.
```
public static bool IsRealClass(Type testType)
{
return testType.IsAbstract == false
&& testType.IsGenericTypeDefinition == false
&& testType.IsInterface == false;
}
``` |
80,278 | <p>I am trying to use the Google Maps API in a ColdFusion template that is a border type cflayoutarea container. However, the map simply doesn't show up:</p>
<pre><code><cfif isdefined("url.lat")>
<cfset lat="#url.lat#">
<cfset lng="#url.lng#">
</cfif>
<head>
<script src= "http://maps.google.com/maps?file=api&amp;v=2&amp;key=xxxx" type="text/javascript">
function getMap(lat,lng){
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var pt= new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
</head>
<cfoutput>
<body onLoad="getMap(#lat#,#lng#)" onUnload="GUnload()">
Map:<br>
<div id="map_canvas" style="width: 500px; height: 300px"/>
</body>
</cfoutput>"
</code></pre>
<p>where lat and lng are the co-ordinates in degree.decimal format. I have traced down to the line where GBrowserIsCompatible() somehow never returns TRUE and thus no further action was taken.</p>
<p>If opened separately the template works perfectly but just not when opened as a cflayoutarea container. Anyone has experience in this? Any suggestions is much appreciated.</p>
<p>Lawrence</p>
<p>Using CF 8.01, Dreamweaver 8</p>
<hr>
<p>Tried your suggestion but still doesn't work; the map only shows when the calling code is inline. However, if this container page was called from yet another div the map disappears again.</p>
<p>I suspect this issue is related to the cflayout container; I'll look up the Extjs doc to see if there're any leads to a solution.</p>
| [
{
"answer_id": 80298,
"author": "convex hull",
"author_id": 10747,
"author_profile": "https://Stackoverflow.com/users/10747",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe the layout area doesn't have the right <strong>style</strong>. I think you may have to give the map_canvas a</p>\n\n<pre><code>position: absolute\n</code></pre>\n\n<p>or </p>\n\n<pre><code>position: relative\n</code></pre>\n\n<p>That's just a hunch.</p>\n"
},
{
"answer_id": 82887,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 0,
"selected": false,
"text": "<p>CFLayoutArea is a new AJAX tag added with ColdFusion version 8. (In addition to tags like CFWindow, CFDiv, etc.)</p>\n\n<p>Within the AJAX-loaded content of any of these new tags, external JavaScript must be included from the containing page. In your case, that would be the page that includes the <cflayout> tag.</p>\n\n<p>Try something like this:</p>\n\n<p>in index.cfm (or whatever your containing file is):</p>\n\n<pre><code><script src=\"http://maps.google.com/maps?file=api&amp;v=2&amp;key=xxxx\" type=\"text/javascript\">\n function getMap(lat,lng){ \n if (GBrowserIsCompatible()) { \n var map = new GMap2(document.getElementById(\"map_canvas\"));\n var pt= new GLatLng(lat,lng);\n map.setCenter(pt, 18,G_HYBRID_MAP); \n map.addOverlay(new GMarker(pt));\n } \n }\n</script>\n<cflayout>...</cflayout>\n</code></pre>\n\n<p>map.cfm (content of your map CFLayout tab):</p>\n\n<pre><code><cfif structKeyExists(url, \"lat\")>\n <cfset variables.lat = url.lat />\n <cfset variables.lng = url.lng />\n</cfif> \n<head></head> \n<cfoutput>\n <body onLoad=\"getMap(#variables.lat#,#variables.lng#)\" onUnload=\"GUnload()\">\n Map:<br>\n <div id=\"map_canvas\" style=\"width: 500px; height: 300px\"/>\n </body>\n</cfoutput>\n</code></pre>\n"
},
{
"answer_id": 100406,
"author": "lawrencem49",
"author_id": 15007,
"author_profile": "https://Stackoverflow.com/users/15007",
"pm_score": 2,
"selected": true,
"text": "<p>Success! (sort of...)</p>\n\n<p>Finally got it working, but not in the way Adam suggested:</p>\n\n<pre><code><script src= \"http://maps.google.com/maps?file=api&amp;v=2&amp;key=xxxx\" type=\"text/javascript\"></script>\n<script type=\"text/javascript\">\n getMap=function(lat,lng){ \n if (GBrowserIsCompatible()){\n var map = new GMap2(document.getElementById(\"map_canvas\"));\n var pt = new GLatLng(lat,lng);\n map.setCenter(pt, 18,G_HYBRID_MAP); \n map.addOverlay(new GMarker(pt)); \n } \n }\n</script> \n\n <cflayout name=\"testlayout\" type=\"border\">\n <cflayoutarea name=\"left\" position=\"left\" size=\"250\"/>\n <cflayoutarea name=\"center\" position=\"center\"> \n <!--- sample hard-coded co-ordinates --->\n <body onLoad=\"getMap(22.280161,114.185096)\">\n Map:<br />\n <div id=\"map_canvas\" style=\"width:500px; height: 300px\"/>\n </body>\n </cflayoutarea> \n<!--- <cflayoutarea name=\"center\" position=\"center\" source=\"map_content.cfm?lat=22.280161&lng=114.185096\"/> --->\n</cflayout> \n</code></pre>\n\n<p>The whole thing must be contained within the same file or it would not work. My suspicion is that the getElementByID function, as it stands, cannot not reference an element that is outside of its own file. If the div is in another file (as in Adam's exmaple), it results in an undefined map, ie a map object is created but with nothing in it.</p>\n\n<p>So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container? </p>\n"
},
{
"answer_id": 101544,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container?</p>\n</blockquote>\n\n<p>It should be possible reference an element loaded via AJAX -- just not until the element is on screen (so not on page load). It looks like getMap() triggers everything. (Is that right?)</p>\n\n<p>Try this: Take exactly what you have as your inline-content for the map tab, and make it the content of map_content.cfm; <strong>then</strong> instead of using body onload to fire the event, write it inline, after the div is defined:</p>\n\n<pre><code><body>\n Map:<br />\n <div id=\"map_canvas\" style=\"width:500px; height: 300px\"/>\n <script type=\"text/javascript\">\n getMap(22.280161,114.185096);\n </script>\n</body>\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15007/"
]
| I am trying to use the Google Maps API in a ColdFusion template that is a border type cflayoutarea container. However, the map simply doesn't show up:
```
<cfif isdefined("url.lat")>
<cfset lat="#url.lat#">
<cfset lng="#url.lng#">
</cfif>
<head>
<script src= "http://maps.google.com/maps?file=api&v=2&key=xxxx" type="text/javascript">
function getMap(lat,lng){
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
var pt= new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
</head>
<cfoutput>
<body onLoad="getMap(#lat#,#lng#)" onUnload="GUnload()">
Map:<br>
<div id="map_canvas" style="width: 500px; height: 300px"/>
</body>
</cfoutput>"
```
where lat and lng are the co-ordinates in degree.decimal format. I have traced down to the line where GBrowserIsCompatible() somehow never returns TRUE and thus no further action was taken.
If opened separately the template works perfectly but just not when opened as a cflayoutarea container. Anyone has experience in this? Any suggestions is much appreciated.
Lawrence
Using CF 8.01, Dreamweaver 8
---
Tried your suggestion but still doesn't work; the map only shows when the calling code is inline. However, if this container page was called from yet another div the map disappears again.
I suspect this issue is related to the cflayout container; I'll look up the Extjs doc to see if there're any leads to a solution. | Success! (sort of...)
Finally got it working, but not in the way Adam suggested:
```
<script src= "http://maps.google.com/maps?file=api&v=2&key=xxxx" type="text/javascript"></script>
<script type="text/javascript">
getMap=function(lat,lng){
if (GBrowserIsCompatible()){
var map = new GMap2(document.getElementById("map_canvas"));
var pt = new GLatLng(lat,lng);
map.setCenter(pt, 18,G_HYBRID_MAP);
map.addOverlay(new GMarker(pt));
}
}
</script>
<cflayout name="testlayout" type="border">
<cflayoutarea name="left" position="left" size="250"/>
<cflayoutarea name="center" position="center">
<!--- sample hard-coded co-ordinates --->
<body onLoad="getMap(22.280161,114.185096)">
Map:<br />
<div id="map_canvas" style="width:500px; height: 300px"/>
</body>
</cflayoutarea>
<!--- <cflayoutarea name="center" position="center" source="map_content.cfm?lat=22.280161&lng=114.185096"/> --->
</cflayout>
```
The whole thing must be contained within the same file or it would not work. My suspicion is that the getElementByID function, as it stands, cannot not reference an element that is outside of its own file. If the div is in another file (as in Adam's exmaple), it results in an undefined map, ie a map object is created but with nothing in it.
So I think this question is now elevated to a different level: how do you reference an element that is inside an ajax container? |
80,291 | <p>In Sql Server 2000/2005, I have a few NT user groups that need to be granted access to hundreds of stored procedures.</p>
<p>Is there a nice easy way to do that?</p>
| [
{
"answer_id": 80340,
"author": "Leon Bambrick",
"author_id": 49,
"author_profile": "https://Stackoverflow.com/users/49",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>Create a role in sql server.</li>\n<li>Write a\nscript that grants that role\npermission to use those sprocs.</li>\n<li>Add those NT user groups to that role.</li>\n</ul>\n"
},
{
"answer_id": 83079,
"author": "Paul G",
"author_id": 162,
"author_profile": "https://Stackoverflow.com/users/162",
"pm_score": 2,
"selected": true,
"text": "<p>Here's a script that I use for granting permissions to lots of procedures:</p>\n\n<pre><code>DECLARE @DB sysname ; set @DB = DB_NAME()\nDECLARE @U sysname ; set @U = QUOTENAME('UserID')\n\nDECLARE @ID integer,\n @LAST_ID integer,\n @NAME varchar(1000),\n @SQL varchar(4000)\n\nSET @LAST_ID = 0\n\nWHILE @LAST_ID IS NOT NULL\nBEGIN\n SELECT @ID = MIN(id)\n FROM dbo.sysobjects\n WHERE id > @LAST_ID AND type = 'P' AND category = 0\n\n SET @LAST_ID = @ID\n\n -- We have a record so go get the name\n IF @ID IS NOT NULL\n BEGIN\n SELECT @NAME = name\n FROM dbo.sysobjects\n WHERE id = @ID\n\n -- Build the DCL to do the GRANT\n SET @SQL = 'GRANT EXECUTE ON ' + @NAME + ' TO ' + @U\n\n -- Run the SQL Statement you just generated\n EXEC master.dbo.xp_execresultset @SQL, @DB\n\n END \nEND\n</code></pre>\n\n<p>You can modify the select to get to a more specific group of stored procs.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3276/"
]
| In Sql Server 2000/2005, I have a few NT user groups that need to be granted access to hundreds of stored procedures.
Is there a nice easy way to do that? | Here's a script that I use for granting permissions to lots of procedures:
```
DECLARE @DB sysname ; set @DB = DB_NAME()
DECLARE @U sysname ; set @U = QUOTENAME('UserID')
DECLARE @ID integer,
@LAST_ID integer,
@NAME varchar(1000),
@SQL varchar(4000)
SET @LAST_ID = 0
WHILE @LAST_ID IS NOT NULL
BEGIN
SELECT @ID = MIN(id)
FROM dbo.sysobjects
WHERE id > @LAST_ID AND type = 'P' AND category = 0
SET @LAST_ID = @ID
-- We have a record so go get the name
IF @ID IS NOT NULL
BEGIN
SELECT @NAME = name
FROM dbo.sysobjects
WHERE id = @ID
-- Build the DCL to do the GRANT
SET @SQL = 'GRANT EXECUTE ON ' + @NAME + ' TO ' + @U
-- Run the SQL Statement you just generated
EXEC master.dbo.xp_execresultset @SQL, @DB
END
END
```
You can modify the select to get to a more specific group of stored procs. |
80,292 | <p>I was writing a database handler class in PHP using the mysqli class and prepared statements. I was attempting to print out the result. It didn't work right off the bat so I decided to do some debugging. I tried to use the <code>num_rows()</code> method from the <code>mysqli_statement</code> class, but it kept returning 0. I decided to write a small portion of the test code to keep it simpler so I could see what was going wrong. I was then able to return the data I wanted, but the <code>num_rows()</code> method still returns 0 even when it is actually selecting and retrieving some data. Here is the code:</p>
<pre><code>$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno())
{
die('connection failed');
}
$statement = $mysqli->stmt_init();
$query = "SELECT name FROM table WHERE id = '2000'";
if($statement->prepare($query))
{
$statement->execute();
$statement->bind_result($name);
$statement->fetch();
$statement->store_result();
echo $statement->num_rows();
echo $name;
}
else
{
echo 'prepare statement failed';
exit();
}
</code></pre>
<p>The expected result is:</p>
<pre><code>1name
</code></pre>
<p>And the actual result is:</p>
<pre><code>0name
</code></pre>
<p>Can anyone tell me why this is?</p>
| [
{
"answer_id": 80382,
"author": "Cetra",
"author_id": 15087,
"author_profile": "https://Stackoverflow.com/users/15087",
"pm_score": -1,
"selected": false,
"text": "<p>It doesn't look like you've declared $name.</p>\n\n<p>Also, try removing bind_result() and fetch() so it reads something like this:</p>\n\n<pre><code>$statement->execute();\n\n$statement->store_result();\n\nprintf(\"Number of rows: %d.\\n\", $statement->num_rows);\n</code></pre>\n"
},
{
"answer_id": 80400,
"author": "Nathan Strong",
"author_id": 9780,
"author_profile": "https://Stackoverflow.com/users/9780",
"pm_score": 4,
"selected": true,
"text": "<p>I wonder if num_rows() is reporting relative to the current resultset. Try capturing num_rows() prior to fetching the data. e.g.</p>\n\n<pre><code>if($statement->prepare($query))\n{\n $statement->execute();\n $statement->store_result();\n echo $statement->num_rows();\n $statement->bind_result($name);\n $statement->fetch();\n echo $name; \n}\n</code></pre>\n\n<p>Does that have any effect?</p>\n"
},
{
"answer_id": 624630,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><code>num_rows</code> is not a method, it's a property.</p>\n"
},
{
"answer_id": 66500988,
"author": "Dharman",
"author_id": 1839439,
"author_profile": "https://Stackoverflow.com/users/1839439",
"pm_score": 0,
"selected": false,
"text": "<p>In order to be able to use <code>mysqli_stmt::num_rows(),</code> you need to fetch all rows into PHP. There are two ways to fetch everything: buffering using <code>store_result()</code> or manual fetching of all rows using <code>fetch()</code>.</p>\n<p>In your case, you have started manual fetching by calling <code>fetch()</code> once. You can't call <code>store_result()</code> when another fetch process is ongoing. The call to <code>store_result()</code> fails with an error*.</p>\n<pre><code>$statement->fetch();\n$statement->store_result(); // produces error. See $mysqli->error;\necho $statement->num_rows();\n</code></pre>\n<p>The easiest solution is to swap the order in which you call these two methods.</p>\n<pre><code>$statement->store_result();\n$statement->fetch(); // This will initiate fetching from PHP buffer instead of MySQL buffer\necho $statement->num_rows(); // This will tell you the total number of rows fetched to PHP\n</code></pre>\n<p><sub>* Due to a bug in PHP, this error will not trigger an exception in the exception error reporting mode. The error message can only be seen with <code>mysqli_error()</code> function or its corresponding property.</sub></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3831/"
]
| I was writing a database handler class in PHP using the mysqli class and prepared statements. I was attempting to print out the result. It didn't work right off the bat so I decided to do some debugging. I tried to use the `num_rows()` method from the `mysqli_statement` class, but it kept returning 0. I decided to write a small portion of the test code to keep it simpler so I could see what was going wrong. I was then able to return the data I wanted, but the `num_rows()` method still returns 0 even when it is actually selecting and retrieving some data. Here is the code:
```
$mysqli = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno())
{
die('connection failed');
}
$statement = $mysqli->stmt_init();
$query = "SELECT name FROM table WHERE id = '2000'";
if($statement->prepare($query))
{
$statement->execute();
$statement->bind_result($name);
$statement->fetch();
$statement->store_result();
echo $statement->num_rows();
echo $name;
}
else
{
echo 'prepare statement failed';
exit();
}
```
The expected result is:
```
1name
```
And the actual result is:
```
0name
```
Can anyone tell me why this is? | I wonder if num\_rows() is reporting relative to the current resultset. Try capturing num\_rows() prior to fetching the data. e.g.
```
if($statement->prepare($query))
{
$statement->execute();
$statement->store_result();
echo $statement->num_rows();
$statement->bind_result($name);
$statement->fetch();
echo $name;
}
```
Does that have any effect? |
80,307 | <p>I've read in a couple of places that the desktop wallpaper can be set to an HTML document. Has anyone had any success changing it programmatically? </p>
<p>The following snippet of VB6 helps me set things up for BMPs but when I try to use it for HTML, I get a nice blue background and nothing else.</p>
<pre><code>Dim reg As New StdRegistry
Public Function CurrentWallpaper() As String
CurrentWallpaper = reg.ValueEx(HKEY_CURRENT_USER, "Control Panel\Desktop", "Wallpaper", REG_SZ, "")
End Function
Public Sub SetWallpaper(cFilename As Variant)
reg.ClassKey = HKEY_CURRENT_USER
reg.SectionKey = "Control Panel\Desktop"
reg.ValueKey = "Wallpaper"
reg.ValueType = REG_SZ
reg.Default = ""
reg.Value = cFilename
End Sub
Public Sub RefreshDesktop()
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
oShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True
End Sub
</code></pre>
<p>Perhaps there's some other setting that's required. Any ideas?</p>
| [
{
"answer_id": 80334,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 2,
"selected": false,
"text": "<p>I think you need to make sure \"Active Desktop\" is turned on.</p>\n\n<p>You might try setting <code>HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\ForceActiveDesktopOn</code> to <code>1</code> (found <a href=\"http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/regentry/93205.mspx?mfr=true\" rel=\"nofollow noreferrer\">here</a>).</p>\n\n<p>I haven't tried it, so no guarantees.</p>\n"
},
{
"answer_id": 83921,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>Getting closer: <a href=\"http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/w2rkbook/gp.mspx?mfr=true\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/w2rkbook/gp.mspx?mfr=true</a>\n<hr />\nBut it turns out that I was getting sidetracked in Policy space. What I really wanted was to set the desktop in the userspace and let the Policy settings stand. Some helpful stuff was found here: <a href=\"http://blogs.msdn.com/coding4fun/archive/2006/10/31/912569.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/coding4fun/archive/2006/10/31/912569.aspx</a>. </p>\n\n<p>This isn't the final solution, however. The control of HTML desktops is still out of reach.\n<hr />\nSeems that HTML settings are stored in HKCU\\Software\\Microsoft\\Internet Explorer\\Desktop\\General. However, just storing them here doesn't seem to be enough. I still need to find the mechanism that lets Windows know which set of registry values to use.</p>\n"
},
{
"answer_id": 84359,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I recomend only BMP format. Do not use ActiveDesctop, because you PC will work slowly after that.</p>\n"
},
{
"answer_id": 84489,
"author": "Matt",
"author_id": 2338,
"author_profile": "https://Stackoverflow.com/users/2338",
"pm_score": 2,
"selected": true,
"text": "<p>I'm not sure if there's an official API for this, but if you have your heart set on it you could use Sysinternal's <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx\" rel=\"nofollow noreferrer\">Process Monitor</a> and see what registry keys get touched when you set an HTML desktop background via the UI. Then you'd just need to repeat those edits in your code. However, an API call would be far preferable in terms of backward/forward compatibility.</p>\n"
},
{
"answer_id": 89333,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, I've discovered the answer to my question, thanks to egl1044 on <a href=\"http://www.experts-exchange.com/OS/Microsoft_Operating_Systems/Windows/XP/Q_23739345.html\" rel=\"nofollow noreferrer\">Experts Exchange</a>. Essentially, one must talk to the IActiveDesktop object. A good implementation of that, in VB6, can be found at <a href=\"http://www.vbforums.com/showthread.php?t=367342\" rel=\"nofollow noreferrer\">VB6 - JPEGs as wallpapers (without conversion)</a>.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426/"
]
| I've read in a couple of places that the desktop wallpaper can be set to an HTML document. Has anyone had any success changing it programmatically?
The following snippet of VB6 helps me set things up for BMPs but when I try to use it for HTML, I get a nice blue background and nothing else.
```
Dim reg As New StdRegistry
Public Function CurrentWallpaper() As String
CurrentWallpaper = reg.ValueEx(HKEY_CURRENT_USER, "Control Panel\Desktop", "Wallpaper", REG_SZ, "")
End Function
Public Sub SetWallpaper(cFilename As Variant)
reg.ClassKey = HKEY_CURRENT_USER
reg.SectionKey = "Control Panel\Desktop"
reg.ValueKey = "Wallpaper"
reg.ValueType = REG_SZ
reg.Default = ""
reg.Value = cFilename
End Sub
Public Sub RefreshDesktop()
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
oShell.Run "%windir%\System32\RUNDLL32.EXE user32.dll,UpdatePerUserSystemParameters", 1, True
End Sub
```
Perhaps there's some other setting that's required. Any ideas? | I'm not sure if there's an official API for this, but if you have your heart set on it you could use Sysinternal's [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) and see what registry keys get touched when you set an HTML desktop background via the UI. Then you'd just need to repeat those edits in your code. However, an API call would be far preferable in terms of backward/forward compatibility. |
80,319 | <p>I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.</p>
<p>What would be the best approach?</p>
| [
{
"answer_id": 80366,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 2,
"selected": false,
"text": "<p>Something like this?</p>\n\n<pre><code>$vals = explode(':', $duration);\n\nif ( $vals[0] == 0 )\n $result = $vals[1] . ' minutes, ' . $vals[2] . ' seconds';\nelse\n $result = $vals[0] . 'hours, ' . $vals[1] . ' minutes, ' . $vals[2] . ' seconds';\n</code></pre>\n"
},
{
"answer_id": 80380,
"author": "paan",
"author_id": 2976,
"author_profile": "https://Stackoverflow.com/users/2976",
"pm_score": 3,
"selected": true,
"text": "<p>try using split </p>\n\n<pre><code>list($hh,$mm,$ss)= split(':',$duration);\n</code></pre>\n"
},
{
"answer_id": 80389,
"author": "Mladen Mihajlovic",
"author_id": 11421,
"author_profile": "https://Stackoverflow.com/users/11421",
"pm_score": 1,
"selected": false,
"text": "<p>One little change could be:</p>\n\n<pre><code>$vals = explode(':', $duration);\n\nif ( $vals[0] == 0 )\n $result = \"{$vals[1]} minutes, {$vals[2]} seconds\";\nelse\n $result = \"{$vals[0]} hours, {$vals[1]} minutes, {$vals[2]} seconds\";\n</code></pre>\n"
},
{
"answer_id": 80395,
"author": "Garrett Albright",
"author_id": 11023,
"author_profile": "https://Stackoverflow.com/users/11023",
"pm_score": -1,
"selected": false,
"text": "<p>explode() is for pansies. This is a job for <a href=\"http://regular-expressions.info\" rel=\"nofollow noreferrer\">regular expressions</a>!</p>\n\n<pre><code><?php\npreg_match('/^(\\d\\d):(\\d\\d):(\\d\\d)$/', $video_duration, $parts);\nif ($parts[1] !== '00') {\n echo(\"{$parts[1]} hours, {$parts[2]} minutes, {$parts[3]} seconds\");\n}\nelse {\n echo(\"{$parts[2]} minutes, {$parts[3]} seconds\");\n}\n</code></pre>\n\n<p>Totally untested, but something like that ought to work. Note that this code assumes that the hour fragment will <em>always</em> be two digits (eg, a three-hour video would be <code>03:00:00</code> instead of <code>3:00:00</code>).</p>\n\n<p><strong>EDIT:</strong> In retrospect, using regular expressions for this is probably a case of over-engineering; explode() will do the job just as well and probably even be faster in this case. But it was the first method to come to mind when I read the question.</p>\n"
},
{
"answer_id": 80442,
"author": "Nathan Strong",
"author_id": 9780,
"author_profile": "https://Stackoverflow.com/users/9780",
"pm_score": 1,
"selected": false,
"text": "<p>Pretty simple:</p>\n\n<pre><code>list( $h, $m, $s) = explode(':', $hms);\necho ($h ? \"$h hours, \" : \"\").($m ? \"$m minutes, \" : \"\").(($h || $m) ? \"and \" : \"\").\"$s seconds\";\n</code></pre>\n\n<p>This will only display the hours or minutes if there are any, and inserts an \"and\" before the seconds if there are hours, minutes, or both to display. If you wanted to get really fancy, you could add some code to display \"hour\" vs. \"hours\" as appropriate, ditto for minutes and seconds.</p>\n"
},
{
"answer_id": 80459,
"author": "Steve Obbayi",
"author_id": 11190,
"author_profile": "https://Stackoverflow.com/users/11190",
"pm_score": 0,
"selected": false,
"text": "<p>Heres a different way, with different functions which is more open and a more step by step for newbies. it also handles the 1 hour and many hours... you could try use the same logic to handle the 0 minutes and 0 seconds.</p>\n\n<pre><code><?php\n// your time\n$var = \"00:00:00\";\n\nif(substr($var, 0, 2) == 0){\n $myTime = substr_replace(substr_replace($var, '', 0, 3), ' Minutes, ', 2, 1);\n}\nelseif(substr($var, 1, 1) == 1){\n$myTime = substr_replace(substr_replace($var, ' Hour, ', 2, 1), ' Minutes, ', 11, 1); \n }\nelse{\n$myTime = substr_replace(substr_replace($var, ' Hours, ', 2, 1), ' Minutes, ', 12, 1);\n}\n// work with your variable\necho $myTime .' Seconds';\n\n?>\n</code></pre>\n"
},
{
"answer_id": 80704,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you really want to use a built-in function, perhaps for robustness, you can try </p>\n\n<pre><code> date_default_timezone_set('UTC'); \n $date = strtotime($hms,0); \n</code></pre>\n\n<p>and use any of the date formatting functions (<code>date()</code>, <code>strftime()</code>, etc) to format the time in any way you wish. Or you can use the output of <code>strptime($hms,'%T')</code>. Either may be overkill for the simple scenario you have.</p>\n"
},
{
"answer_id": 80776,
"author": "Curtis Lassam",
"author_id": 9337,
"author_profile": "https://Stackoverflow.com/users/9337",
"pm_score": -1,
"selected": false,
"text": "<p>Converting 00:00:00 to hours, minutes, and seconds in PHP is really easy.</p>\n\n<p>$hours = 0; \n$minutes = 0;\n$seconds = 0; </p>\n"
},
{
"answer_id": 80981,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'll reply with a different approach of the problem. My approach is to store the lengths in seconds. Then depending the needs, it's easy to render these seconds as hh:mm:ss by using :</p>\n\n<p><code>print gmdate($seconds >= 3600 ? 'H:i:s' : 'i:s', $seconds);</code> (for your question)</p>\n\n<p>or to search on the length in a database:</p>\n\n<p><code>SELECT * FROM videos WHERE length > 300;</code> for example, to search for video with a length higher than 5 minutes.</p>\n"
},
{
"answer_id": 83497,
"author": "enobrev",
"author_id": 14651,
"author_profile": "https://Stackoverflow.com/users/14651",
"pm_score": 1,
"selected": false,
"text": "<p>Why bother with regex or explodes when php handles time just fine?</p>\n\n<pre><code>$sTime = '04:20:00';\n$oTime = new DateTime($sTime);\n$aOutput = array();\nif ($oTime->format('G') > 0) {\n $aOutput[] = $oTime->format('G') . ' hours';\n}\n$aOutput[] = $oTime->format('i') . ' minutes';\n$aOutput[] = $oTime->format('s') . ' seconds';\necho implode(', ', $aOutput);\n</code></pre>\n\n<p>The benefit is that you can reformat the time however you like (including am/pm, adjustments for timezone, addition / subtraction, etc).</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80319",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have video durations stored in HH:MM:SS format. I'd like to display it as HH hours, MM minutes, SS seconds. It shouldn't display hours if it's less than 1.
What would be the best approach? | try using split
```
list($hh,$mm,$ss)= split(':',$duration);
``` |
80,348 | <p>In C++0x I would like to write a function like this:</p>
<pre><code>template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
//Put things into the tuple
}
</code></pre>
<p>I first tried to use a for loop on <code>int i</code> and then do:</p>
<pre><code>get<i>(my_tuple);
</code></pre>
<p>And then store some value in the result. However, <code>get</code> only works on <code>constexpr</code>.</p>
<p>If I could get the variables out of the <code>tuple</code> and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without <code>get</code>. Any ideas on how to do that? Or does anyone have another way of modifying this <code>tuple</code>?</p>
| [
{
"answer_id": 80573,
"author": "Adam Mitz",
"author_id": 2574,
"author_profile": "https://Stackoverflow.com/users/2574",
"pm_score": 3,
"selected": true,
"text": "<p>Since the \"i\" in</p>\n\n<pre><code>get<i>(tup)\n</code></pre>\n\n<p>needs to be a compile-time constant, template instantiation is used to \"iterate\" (actually recurse) through the values. Boost tuples have the \"length\" and \"element\" meta-functions that can be helpful here -- I assume C++0x has these too.</p>\n"
},
{
"answer_id": 80687,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.boost.org/doc/libs/release/libs/fusion/doc/html/index.html\" rel=\"nofollow noreferrer\">Boost.Fusion</a> is worth a look. It can 'iterate' over <code>std::pair</code>, <code>boost::tuple</code>, some other containers and its own tuple types, although I don't think it supports <code>std::tuple</code> yet.</p>\n"
},
{
"answer_id": 103372,
"author": "Timmie Smith",
"author_id": 8405,
"author_profile": "https://Stackoverflow.com/users/8405",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at section 6.1.3.4 of TR1, <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf\" rel=\"nofollow noreferrer\">http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf</a></p>\n\n<p>get is defined for both const and non-const qualified tuples and returns the appropriate reference type. If you change your function declaration to the following:</p>\n\n<pre><code>template \nvoid fun(typename std::tuple& my_tuple) {\n //Put things into the tuple\n}</code></pre>\n\n<p>Then the argument to your function is a non-const tuple and get will allow you to make the necessary assignments once you've written the iteration using the information provided in previous responses.</p>\n"
},
{
"answer_id": 103401,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 0,
"selected": false,
"text": "<p>AFAICT, C++ tuples basically need to be handled with recursion; there don't seem to be any real ways of packing/unpacking tuples <em>except</em> using the typesystem's only variadic template handling.</p>\n"
},
{
"answer_id": 1611301,
"author": "David",
"author_id": 193481,
"author_profile": "https://Stackoverflow.com/users/193481",
"pm_score": 0,
"selected": false,
"text": "<p>Have a look at my answer here for an example of template recursion to unwind tuple arguments to a function call.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/687490/c0x-how-do-i-expand-a-tuple-into-variadic-template-function-arguments\">How do I expand a tuple into variadic template function's arguments?</a></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| In C++0x I would like to write a function like this:
```
template <typename... Types>
void fun(typename std::tuple<Types...> my_tuple) {
//Put things into the tuple
}
```
I first tried to use a for loop on `int i` and then do:
```
get<i>(my_tuple);
```
And then store some value in the result. However, `get` only works on `constexpr`.
If I could get the variables out of the `tuple` and pass them to a variadic templated function I could recurse through the arguments very easily, but I have no idea how to get the variables out of the tuple without `get`. Any ideas on how to do that? Or does anyone have another way of modifying this `tuple`? | Since the "i" in
```
get<i>(tup)
```
needs to be a compile-time constant, template instantiation is used to "iterate" (actually recurse) through the values. Boost tuples have the "length" and "element" meta-functions that can be helpful here -- I assume C++0x has these too. |
80,357 | <p>Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail.</p>
| [
{
"answer_id": 80387,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 11,
"selected": true,
"text": "<p>Using <a href=\"http://ruby-doc.org/core-1.9.3/String.html#method-i-scan\" rel=\"noreferrer\"><code>scan</code></a> should do the trick:</p>\n\n<pre><code>string.scan(/regex/)\n</code></pre>\n"
},
{
"answer_id": 35964234,
"author": "sudo bangbang",
"author_id": 3951782,
"author_profile": "https://Stackoverflow.com/users/3951782",
"pm_score": 6,
"selected": false,
"text": "<p>To find all the matching strings, use String's <a href=\"http://ruby-doc.org/core-2.2.0/String.html#method-i-scan\" rel=\"noreferrer\"><code>scan</code></a> method.</p>\n\n<pre><code>str = \"A 54mpl3 string w1th 7 numb3rs scatter36 ar0und\"\nstr.scan(/\\d+/)\n#=> [\"54\", \"3\", \"1\", \"7\", \"3\", \"36\", \"0\"]\n</code></pre>\n\n<p>If you want, <a href=\"http://ruby-doc.org/core-1.9.3/MatchData.html\" rel=\"noreferrer\"><code>MatchData</code></a>, which is the type of the object returned by the Regexp <code>match</code> method, use:</p>\n\n<pre><code>str.to_enum(:scan, /\\d+/).map { Regexp.last_match }\n#=> [#<MatchData \"54\">, #<MatchData \"3\">, #<MatchData \"1\">, #<MatchData \"7\">, #<MatchData \"3\">, #<MatchData \"36\">, #<MatchData \"0\">]\n</code></pre>\n\n<p>The benefit of using <code>MatchData</code> is that you can use methods like <code>offset</code>:</p>\n\n<pre><code>match_datas = str.to_enum(:scan, /\\d+/).map { Regexp.last_match }\nmatch_datas[0].offset(0)\n#=> [2, 4]\nmatch_datas[1].offset(0)\n#=> [7, 8]\n</code></pre>\n\n<p>See these questions if you'd like to know more:</p>\n\n<ul>\n<li>\"<a href=\"https://stackoverflow.com/questions/6804557/how-do-i-get-the-match-data-for-all-occurrences-of-a-ruby-regular-expression-in?lq=1\">How do I get the match data for all occurrences of a Ruby regular expression in a string?</a>\"</li>\n<li>\"<a href=\"https://stackoverflow.com/questions/19596382/ruby-regular-expression-matching-enumerator-with-named-capture-support?lq=1\">Ruby regular expression matching enumerator with named capture support</a>\"</li>\n<li>\"<a href=\"https://stackoverflow.com/questions/17185943/how-to-find-out-the-starting-point-for-each-match-in-ruby?lq=1\">How to find out the starting point for each match in ruby</a>\"</li>\n</ul>\n\n<p>Reading about special variables <code>$&</code>, <code>$'</code>, <code>$1</code>, <code>$2</code> in Ruby will be helpful too.</p>\n"
},
{
"answer_id": 36751235,
"author": "MVP",
"author_id": 6231595,
"author_profile": "https://Stackoverflow.com/users/6231595",
"pm_score": 4,
"selected": false,
"text": "<p>if you have a regexp with groups:</p>\n\n<pre><code>str=\"A 54mpl3 string w1th 7 numbers scatter3r ar0und\"\nre=/(\\d+)[m-t]/\n</code></pre>\n\n<p>you can use String's <code>scan</code> method to find matching groups:</p>\n\n<pre><code>str.scan re\n#> [[\"54\"], [\"1\"], [\"3\"]]\n</code></pre>\n\n<p>To find the matching pattern:</p>\n\n<pre><code>str.to_enum(:scan,re).map {$&}\n#> [\"54m\", \"1t\", \"3r\"]\n</code></pre>\n"
},
{
"answer_id": 60586543,
"author": "Datt",
"author_id": 1398515,
"author_profile": "https://Stackoverflow.com/users/1398515",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <code>string.scan(your_regex).flatten</code>. If your regex contains groups, it will return in a single plain array. </p>\n\n<pre><code>string = \"A 54mpl3 string w1th 7 numbers scatter3r ar0und\"\nyour_regex = /(\\d+)[m-t]/\nstring.scan(your_regex).flatten\n=> [\"54\", \"1\", \"3\"]\n</code></pre>\n\n<p>Regex can be a named group as well.</p>\n\n<pre><code>string = 'group_photo.jpg'\nregex = /\\A(?<name>.*)\\.(?<ext>.*)\\z/\nstring.scan(regex).flatten\n</code></pre>\n\n<p>You can also use <code>gsub</code>, it's just one more way if you want MatchData.</p>\n\n<pre><code>str.gsub(/\\d/).map{ Regexp.last_match }\n</code></pre>\n"
},
{
"answer_id": 72266342,
"author": "Victor",
"author_id": 7644846,
"author_profile": "https://Stackoverflow.com/users/7644846",
"pm_score": 0,
"selected": false,
"text": "<p>If you have capture groups <code>()</code> inside the regex for other purposes, the proposed solutions with <code>String#scan</code> and <code>String#match</code> are problematic:</p>\n<ol>\n<li><code>String#scan</code> only get what is inside the <a href=\"https://docs.ruby-lang.org/en/2.4.0/syntax/refinements_rdoc.html\" rel=\"nofollow noreferrer\">capture groups</a>;</li>\n<li><code>String#match</code> only get the first match, rejecting all the others;</li>\n<li><code>String#matches</code> (proposed function) get all the matches.</li>\n</ol>\n<p>On this case, we need a solution to match the regex without considering the capture groups.</p>\n<h1><code>String#matches</code></h1>\n<p>With the <a href=\"https://docs.ruby-lang.org/en/2.4.0/syntax/refinements_rdoc.html\" rel=\"nofollow noreferrer\">Refinements</a> you can monkey patch the <code>String</code> class, implement the <code>String#matches</code> and this method will be available inside the scope of the class that is using the refinement. It is an incredible way to Monkey Patch classes on Ruby.</p>\n<h3>Setup</h3>\n<ul>\n<li><code>/lib/refinements/string_matches.rb</code></li>\n</ul>\n<pre class=\"lang-rb prettyprint-override\"><code># This module add a String refinement to enable multiple String#match()s\n# 1. `String#scan` only get what is inside the capture groups (inside the parens)\n# 2. `String#match` only get the first match\n# 3. `String#matches` (proposed function) get all the matches\nmodule StringMatches\n refine String do\n def matches(regex)\n scan(/(?<matching>#{regex})/).flatten\n end\n end\nend\n\n</code></pre>\n<p>Used: <a href=\"https://ruby-doc.org/core-2.4.3/Regexp.html\" rel=\"nofollow noreferrer\">named capture groups</a></p>\n<h3>Usage</h3>\n<ul>\n<li><code>rails c</code></li>\n</ul>\n<pre class=\"lang-rb prettyprint-override\"><code>> require 'refinements/string_matches'\n\n> using StringMatches\n\n> 'function(1, 2, 3) + function(4, 5, 6)'.matches(/function\\((\\d), (\\d), (\\d)\\)/)\n=> ["function(1, 2, 3)", "function(4, 5, 6)"]\n\n> 'function(1, 2, 3) + function(4, 5, 6)'.scan(/function\\((\\d), (\\d), (\\d)\\)/)\n=> [["1", "2", "3"], ["4", "5", "6"]]\n\n> 'function(1, 2, 3) + function(4, 5, 6)'.match(/function\\((\\d), (\\d), (\\d)\\)/)[0]\n=> "function(1, 2, 3)"\n</code></pre>\n"
},
{
"answer_id": 73542998,
"author": "some_guy",
"author_id": 4019925,
"author_profile": "https://Stackoverflow.com/users/4019925",
"pm_score": -1,
"selected": false,
"text": "<h1>Return an array of <code>MatchData</code> objects</h1>\n<p><code>#scan</code> is very limited--only returns a simple array of strings!</p>\n<p>Far more powerful/flexible for us to get an array of <code>MatchData</code> objects.</p>\n<p>I'll provide two approaches (using same logic), one using a PORO and one using a monkey patch:</p>\n<h2>PORO:</h2>\n<pre><code>class MatchAll\n def initialize(string, pattern)\n raise ArgumentError, 'must pass a String' unless string.is_a?(String)\n\n raise ArgumentError, 'must pass a Regexp pattern' unless pattern.is_a?(Regexp)\n\n @string = string\n @pattern = pattern\n @matches = []\n end\n\n def match_all\n recursive_match\n end\n\n private\n\n def recursive_match(prev_match = nil)\n index = prev_match.nil? ? 0 : prev_match.offset(0)[1]\n\n matching_item = @string.match(@pattern, index)\n return @matches unless matching_item.present?\n\n @matches << matching_item\n recursive_match(matching_item)\n end\nend\n</code></pre>\n<p><strong>USAGE:</strong></p>\n<pre><code>test_string = 'a green frog jumped on a green lilypad'\n\nMatchAll.new(test_string, /green/).match_all\n=> [#<MatchData "green", #<MatchData "green"]\n</code></pre>\n<hr />\n<h2>Monkey patch</h2>\n<p>I don't typically condone monkey-patching, but in this case:</p>\n<ul>\n<li>we're doing it the right way by "quarantining" our patch into its own module</li>\n<li>I prefer this approach because <code>'string'.match_all(/pattern/)</code> is more intuitive (and looks a lot nicer) than <code>MatchAll.new('string', /pattern/).match_all</code></li>\n</ul>\n<pre><code>module RubyCoreExtensions\n module String\n module MatchAll\n def match_all(pattern)\n raise ArgumentError, 'must pass a Regexp pattern' unless pattern.is_a?(Regexp)\n\n recursive_match(pattern)\n end\n\n private\n\n def recursive_match(pattern, matches = [], prev_match = nil)\n index = prev_match.nil? ? 0 : prev_match.offset(0)[1]\n\n matching_item = self.match(pattern, index)\n return matches unless matching_item.present?\n\n matches << matching_item\n recursive_match(pattern, matches, matching_item)\n end\n end\n end\nend\n\n</code></pre>\n<p>I recommend creating a new file and putting the patch (assuming you're using Rails) there <code>/lib/ruby_core_extensions/string/match_all.rb</code></p>\n<p>To use our patch we need to make it available:</p>\n<pre><code># within application.rb\nrequire './lib/ruby_core_extensions/string/match_all.rb'\n</code></pre>\n<p>Then be sure to include it in the <code>String</code> class (you could put this wherever you want; but for example, right under the require statement we just wrote above. After you <code>include</code> it once, it will be available everywhere, even outside the class where you included it).</p>\n<pre><code>String.include RubyCoreExtensions::String::MatchAll\n</code></pre>\n<p><strong>USAGE: And now when you use <code>#match_all</code> you get results like:</strong></p>\n<pre><code>test_string = 'hello foo, what foo are you going to foo today?'\n\ntest_string.match_all /foo/\n=> [#<MatchData "foo", #<MatchData "foo", #<MatchData "foo"]\n\ntest_string.match_all /hello/\n=> [#<MatchData "hello"]\n\ntest_string.match_all /none/\n=> []\n</code></pre>\n<hr />\n<p>I find this particularly useful when I want to match multiple occurrences, and then get useful information about each occurrence, such as which index the occurrence starts and ends (e.g. <code>match.offset(0) => [first_index, last_index]</code>)</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
| Is there a quick way to find every match of a regular expression in Ruby? I've looked through the Regex object in the Ruby STL and searched on Google to no avail. | Using [`scan`](http://ruby-doc.org/core-1.9.3/String.html#method-i-scan) should do the trick:
```
string.scan(/regex/)
``` |
80,388 | <p>I'm trying to trigger a progress animation when ever the ViewModel/Presentation Model is Busy. I have an IsBusy Property, and the ViewModel is set as the DataContext of the UserControl. What is the best way to trigger a "progressAnimation" storyboard when the IsBusy property is true? Blend only lets me add event triggers at the UserControl level, and I can only create property triggers in my data templates.</p>
<p>The "progressAnimation" is defined as a resource in the user control.</p>
<p>I tried adding the DataTriggers as a Style on the UserControl, but when I try to start the StoryBoard I get the following error:</p>
<blockquote>
<p>'System.Windows.Style' value cannot be assigned to property 'Style'
of object'Colorful.Control.SearchPanel'. A Storyboard tree in a Style
cannot specify a TargetName. Remove TargetName 'progressWheel'.</p>
</blockquote>
<p>ProgressWheel is the name of the object I'm trying to animate, so removing the target name is obviously NOT what I want.</p>
<p>I was hoping to solve this in XAML using data binding techniques, instead of having to expose events and start/stop the animation through code.</p>
| [
{
"answer_id": 80455,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend to use RoutedEvent instead of your IsBusy property. Just fire OnBusyStarted and OnBusyStopped event and use Event trigger on the appropriate elements.</p>\n"
},
{
"answer_id": 80794,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 1,
"selected": false,
"text": "<p>You can subscribe to the PropertyChanged event of the DataObject class and make a RoutedEvent fire from Usercontrol level. </p>\n\n<p>For RoutedEvent to work we need to have the class derived from DependancyObject</p>\n"
},
{
"answer_id": 81175,
"author": "ligaz",
"author_id": 6409,
"author_profile": "https://Stackoverflow.com/users/6409",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Trigger.EnterAction to start an animation when a property is changed.</p>\n\n<pre><code><Trigger Property=\"IsBusy\" Value=\"true\">\n <Trigger.EnterActions>\n <BeginStoryboard x:Name=\"BeginBusy\" Storyboard=\"{StaticResource MyStoryboard}\" />\n </Trigger.EnterActions>\n <Trigger.ExitActions>\n <StopStoryboard BeginStoryboardName=\"BeginBusy\" />\n </Trigger.ExitActions>\n</Trigger>\n</code></pre>\n"
},
{
"answer_id": 1735810,
"author": "Dabblernl",
"author_id": 108493,
"author_profile": "https://Stackoverflow.com/users/108493",
"pm_score": 7,
"selected": true,
"text": "<p>What you want is possible by declaring the animation on the progressWheel itself:\nThe XAML:</p>\n\n<pre><code><UserControl x:Class=\"TriggerSpike.UserControl1\"\nxmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\nxmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\nHeight=\"300\" Width=\"300\">\n<UserControl.Resources>\n <DoubleAnimation x:Key=\"SearchAnimation\" Storyboard.TargetProperty=\"Opacity\" To=\"1\" Duration=\"0:0:4\"/>\n <DoubleAnimation x:Key=\"StopSearchAnimation\" Storyboard.TargetProperty=\"Opacity\" To=\"0\" Duration=\"0:0:4\"/>\n</UserControl.Resources>\n<StackPanel>\n <TextBlock Name=\"progressWheel\" TextAlignment=\"Center\" Opacity=\"0\">\n <TextBlock.Style>\n <Style>\n <Style.Triggers>\n <DataTrigger Binding=\"{Binding IsBusy}\" Value=\"True\">\n <DataTrigger.EnterActions>\n <BeginStoryboard>\n <Storyboard>\n <StaticResource ResourceKey=\"SearchAnimation\"/>\n </Storyboard>\n </BeginStoryboard>\n </DataTrigger.EnterActions>\n <DataTrigger.ExitActions>\n <BeginStoryboard>\n <Storyboard>\n <StaticResource ResourceKey=\"StopSearchAnimation\"/> \n </Storyboard>\n </BeginStoryboard>\n </DataTrigger.ExitActions>\n </DataTrigger>\n </Style.Triggers>\n </Style>\n </TextBlock.Style>\n Searching\n </TextBlock>\n <Label Content=\"Here your search query\"/>\n <TextBox Text=\"{Binding SearchClause}\"/>\n <Button Click=\"Button_Click\">Search!</Button>\n <TextBlock Text=\"{Binding Result}\"/>\n</StackPanel>\n</code></pre>\n\n<p></p>\n\n<p>Code behind:</p>\n\n<pre><code> using System.Windows;\nusing System.Windows.Controls;\n\nnamespace TriggerSpike\n{\n public partial class UserControl1 : UserControl\n {\n private MyViewModel myModel;\n\n public UserControl1()\n {\n myModel=new MyViewModel();\n DataContext = myModel;\n InitializeComponent();\n }\n\n private void Button_Click(object sender, RoutedEventArgs e)\n {\n myModel.Search(myModel.SearchClause);\n }\n }\n}\n</code></pre>\n\n<p>The viewmodel:</p>\n\n<pre><code> using System.ComponentModel;\nusing System.Threading;\nusing System.Windows;\n\nnamespace TriggerSpike\n{\n class MyViewModel:DependencyObject\n {\n\n public string SearchClause{ get;set;}\n\n public bool IsBusy\n {\n get { return (bool)GetValue(IsBusyProperty); }\n set { SetValue(IsBusyProperty, value); }\n }\n\n public static readonly DependencyProperty IsBusyProperty =\n DependencyProperty.Register(\"IsBusy\", typeof(bool), typeof(MyViewModel), new UIPropertyMetadata(false));\n\n\n\n public string Result\n {\n get { return (string)GetValue(ResultProperty); }\n set { SetValue(ResultProperty, value); }\n }\n\n public static readonly DependencyProperty ResultProperty =\n DependencyProperty.Register(\"Result\", typeof(string), typeof(MyViewModel), new UIPropertyMetadata(string.Empty));\n\n public void Search(string search_clause)\n {\n Result = string.Empty;\n SearchClause = search_clause;\n var worker = new BackgroundWorker();\n worker.DoWork += worker_DoWork;\n worker.RunWorkerCompleted += worker_RunWorkerCompleted;\n IsBusy = true;\n worker.RunWorkerAsync();\n }\n\n void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n {\n IsBusy=false;\n Result = \"Sorry, no results found for: \" + SearchClause;\n }\n\n void worker_DoWork(object sender, DoWorkEventArgs e)\n {\n Thread.Sleep(5000);\n }\n }\n}\n</code></pre>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 24774823,
"author": "Ian Griffiths",
"author_id": 497397,
"author_profile": "https://Stackoverflow.com/users/497397",
"pm_score": 4,
"selected": false,
"text": "<p>Although the answer that proposes attaching the animation directly to the element to be animated solves this problem in simple cases, this isn't really workable when you have a complex animation that needs to target multiple elements. (You can attach an animation to each element of course, but it gets pretty horrible to manage.)</p>\n\n<p>So there's an alternative way to solve this that lets you use a <code>DataTrigger</code> to run an animation that targets named elements.</p>\n\n<p>There are three places you can attach triggers in WPF: elements, styles, and templates. However, the first two options don't work here. The first is ruled out because WPF doesn't support the use of a <code>DataTrigger</code> directly on an element. (There's no particularly good reason for this, as far as I know. As far as I remember, when I asked people on the WPF team about this many years ago, they said they'd have liked to have supported it but didn't have time to make it work.) And styles are out because, as the error message you've reported says, you can't target named elements in an animation associated with a style.</p>\n\n<p>So that leaves templates. And you can use either control or data templates for this.</p>\n\n<pre><code><ContentControl>\n <ContentControl.Template>\n <ControlTemplate TargetType=\"ContentControl\">\n <ControlTemplate.Resources>\n <Storyboard x:Key=\"myAnimation\">\n\n <!-- Your animation goes here... -->\n\n </Storyboard>\n </ControlTemplate.Resources>\n <ControlTemplate.Triggers>\n <DataTrigger\n Binding=\"{Binding MyProperty}\"\n Value=\"DesiredValue\">\n <DataTrigger.EnterActions>\n <BeginStoryboard\n x:Name=\"beginAnimation\"\n Storyboard=\"{StaticResource myAnimation}\" />\n </DataTrigger.EnterActions>\n <DataTrigger.ExitActions>\n <StopStoryboard\n BeginStoryboardName=\"beginAnimation\" />\n </DataTrigger.ExitActions>\n </DataTrigger>\n </ControlTemplate.Triggers>\n\n <!-- Content to be animated goes here -->\n\n </ControlTemplate>\n </ContentControl.Template>\n<ContentControl>\n</code></pre>\n\n<p>With this construction, WPF is happy to let the animation refer to named elements inside the template. (I've left both the animation and the template content empty here - obviously you'd populate that with your actual animation nd content.)</p>\n\n<p>The reason this works in a template but not a style is that when you apply a template, the named elements it defines will always be present, and so it's safe for animations defined within that template's scope to refer to those elements. This is not generally the case with a style, because styles can be applied to multiple different elements, each of which may have quite different visual trees. (It's a little frustrating that it prevents you from doing this even in scenarios when you can be certain that the required elements will be there, but perhaps there's something that makes it very difficult for the animation to be bound to the named elements at the right time. I know there are quite a lot of optimizations in WPF to enable elements of a style to be reused efficiently, so perhaps one of those is what makes this difficult to support.)</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199387/"
]
| I'm trying to trigger a progress animation when ever the ViewModel/Presentation Model is Busy. I have an IsBusy Property, and the ViewModel is set as the DataContext of the UserControl. What is the best way to trigger a "progressAnimation" storyboard when the IsBusy property is true? Blend only lets me add event triggers at the UserControl level, and I can only create property triggers in my data templates.
The "progressAnimation" is defined as a resource in the user control.
I tried adding the DataTriggers as a Style on the UserControl, but when I try to start the StoryBoard I get the following error:
>
> 'System.Windows.Style' value cannot be assigned to property 'Style'
> of object'Colorful.Control.SearchPanel'. A Storyboard tree in a Style
> cannot specify a TargetName. Remove TargetName 'progressWheel'.
>
>
>
ProgressWheel is the name of the object I'm trying to animate, so removing the target name is obviously NOT what I want.
I was hoping to solve this in XAML using data binding techniques, instead of having to expose events and start/stop the animation through code. | What you want is possible by declaring the animation on the progressWheel itself:
The XAML:
```
<UserControl x:Class="TriggerSpike.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<UserControl.Resources>
<DoubleAnimation x:Key="SearchAnimation" Storyboard.TargetProperty="Opacity" To="1" Duration="0:0:4"/>
<DoubleAnimation x:Key="StopSearchAnimation" Storyboard.TargetProperty="Opacity" To="0" Duration="0:0:4"/>
</UserControl.Resources>
<StackPanel>
<TextBlock Name="progressWheel" TextAlignment="Center" Opacity="0">
<TextBlock.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsBusy}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<StaticResource ResourceKey="SearchAnimation"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<StaticResource ResourceKey="StopSearchAnimation"/>
</Storyboard>
</BeginStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
Searching
</TextBlock>
<Label Content="Here your search query"/>
<TextBox Text="{Binding SearchClause}"/>
<Button Click="Button_Click">Search!</Button>
<TextBlock Text="{Binding Result}"/>
</StackPanel>
```
Code behind:
```
using System.Windows;
using System.Windows.Controls;
namespace TriggerSpike
{
public partial class UserControl1 : UserControl
{
private MyViewModel myModel;
public UserControl1()
{
myModel=new MyViewModel();
DataContext = myModel;
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
myModel.Search(myModel.SearchClause);
}
}
}
```
The viewmodel:
```
using System.ComponentModel;
using System.Threading;
using System.Windows;
namespace TriggerSpike
{
class MyViewModel:DependencyObject
{
public string SearchClause{ get;set;}
public bool IsBusy
{
get { return (bool)GetValue(IsBusyProperty); }
set { SetValue(IsBusyProperty, value); }
}
public static readonly DependencyProperty IsBusyProperty =
DependencyProperty.Register("IsBusy", typeof(bool), typeof(MyViewModel), new UIPropertyMetadata(false));
public string Result
{
get { return (string)GetValue(ResultProperty); }
set { SetValue(ResultProperty, value); }
}
public static readonly DependencyProperty ResultProperty =
DependencyProperty.Register("Result", typeof(string), typeof(MyViewModel), new UIPropertyMetadata(string.Empty));
public void Search(string search_clause)
{
Result = string.Empty;
SearchClause = search_clause;
var worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
IsBusy = true;
worker.RunWorkerAsync();
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
IsBusy=false;
Result = "Sorry, no results found for: " + SearchClause;
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
Thread.Sleep(5000);
}
}
}
```
Hope this helps! |
80,415 | <p>I have a string which starts with <code>//#...</code> goes upto the newline characater. I have figured out the regex for the which is this <code>..#([^\n]*)</code>.</p>
<p>My question is how do you remove this line from a file if the following condition matches</p>
| [
{
"answer_id": 80444,
"author": "EricSchaefer",
"author_id": 8976,
"author_profile": "https://Stackoverflow.com/users/8976",
"pm_score": 0,
"selected": false,
"text": "<p>Read the file line by line and only write those lines to a new file that don't match the regex.\nYou cannot just remove a line.</p>\n"
},
{
"answer_id": 80445,
"author": "baudtack",
"author_id": 10738,
"author_profile": "https://Stackoverflow.com/users/10738",
"pm_score": 0,
"selected": false,
"text": "<p>Does it start at the begining of a line or can it appear anywhere? If the former s/old/new is what you want. If the latter, I'll have to figure that out. I suspect that back referances could be used somehow.</p>\n"
},
{
"answer_id": 80498,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think your regex is correct.</p>\n\n<p>First you need to start with ^ or else it will match this pattern anywhere on the line.</p>\n\n<p>Second, the <code>..</code> should be <code>\\/\\/</code> or else it will match any two characters.</p>\n\n<p><code>^\\/\\/#[^\\n]*</code> is probably what you want.</p>\n\n<p>Then do what EricSchaefer says and read the file line by line only writing lines that don't match.</p>\n\n<p>--<br>\nbmb</p>\n"
},
{
"answer_id": 80703,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "<p>Try the following:</p>\n\n<pre><code>perl -ne 'print unless m{^//#}' input.txt > output.txt\n</code></pre>\n\n<p>If you are using windows you need double quotes instead of single quotes.</p>\n\n<p>You can do the same with grep</p>\n\n<pre><code>grep -v -e '^//#' input.txt > output.txt\n</code></pre>\n"
},
{
"answer_id": 80711,
"author": "David Precious",
"author_id": 4040,
"author_profile": "https://Stackoverflow.com/users/4040",
"pm_score": 0,
"selected": false,
"text": "<p>Iterate over each line in the file, and skip the line if it matches the pattern:</p>\n\n<pre>\nmy $fh = new FileHandle 'filename'\n or die \"Failed to open file - $!\";\n\nwhile (my $line = $fh->getline) {\n next if $line =~ m{^//#};\n print $line;\n}\nclose $fh;\n</pre>\n\n<p>This will print all lines from the file, except the line that starts with '//#'.</p>\n"
},
{
"answer_id": 80791,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 1,
"selected": false,
"text": "<p>You really don't need perl for this.</p>\n\n<pre><code>sed '/^\\/\\/#/d' inputfile > outputfile\n</code></pre>\n\n<p>I <3 sed.</p>\n"
},
{
"answer_id": 80853,
"author": "kixx",
"author_id": 11260,
"author_profile": "https://Stackoverflow.com/users/11260",
"pm_score": 3,
"selected": false,
"text": "<p>To filter out all the lines in a file that match a certain regex:</p>\n\n<pre><code>perl -n -i.orig -e 'print unless /^#/' file1 file2 file3\n</code></pre>\n\n<p>The '.orig' after the -i switch creates a backup of the file with the given extension (.orig). You can skip it if you don't need a backup (just use -i).</p>\n\n<p>The -n switch causes perl to execute your instructions (-e ' ... ') for each line in the file. The line is stored in $_ (which is also the default argument for many instructions, in this case: print and regex matching).</p>\n\n<p>Finally, the argument to the -e switch says \"print the line unless it matches a # character at the start of the line.</p>\n\n<p>PS. There is also a -p switch which behaves like -n, except the lines are always printed (good for searching and replacing)</p>\n"
},
{
"answer_id": 80948,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 6,
"selected": true,
"text": "<p>Your regex is badly chosen on several points:</p>\n\n<ol>\n<li><p>Instead of matching two slashes specifically, you use <code>..</code> to match two characters that can be anything at all, presumably because you don’t know how to match slashes when you’re also using them as delimiters. (Actually, dots match <em>almost</em> anything, as we’ll see in #3.)</p>\n\n<p>Within a slash-delimited regex literal, <code>//</code>, you can match slashes simply by protecting them with backslashes, eg. <code>/\\/\\//</code>. The nicer variant, however, is to use the longer form of regex literal, <code>m//</code>, where you can choose the delimiter, eg. <code>m!!</code>. Since you use something other than slashes for delimitation, you can then write them without escaping them: <code>m!//!</code>. See <a href=\"http://p3rl.org/op#Quote-and-Quote-like-Operators\" rel=\"noreferrer\">perldoc perlop</a>.</p></li>\n<li><p>It’s not anchored to the start of the string so it will match anywhere. Use the <code>^</code> start-of-string assertion in front.</p></li>\n<li><p>You wrote <code>[^\\n]</code> to match “any character except newline” when there is a much simpler way to write that, which is just the <code>.</code> wildcard. It does exactly that – match any character except newline.</p></li>\n<li><p>You are using parentheses to group a part of the match, but the group is neither quantified (you are not specifying that it can match any other number of times than exactly once) nor are you interested in keeping it. So the parentheses are superfluous.</p></li>\n</ol>\n\n<p>Altogether, that makes it <code>m!^//#.*!</code>. But putting an uncaptured <code>.*</code> (or anything with a <code>*</code> quantifier) at the end of a regex is meaningless, since it never changes whether a string will match or not: the <code>*</code> is happy to match nothing at all.</p>\n\n<p>So that leaves you with <code>m!^//#!</code>.</p>\n\n<p>As for removing the line from the file, as everyone else explained, read it in line by line and print all the lines you want to keep back to another file. If you are not doing this within a larger program, use perl’s command line switches to do it easily:</p>\n\n<pre><code>perl -ni.bak -e'print unless m!^//#!' somefile.txt\n</code></pre>\n\n<p>Here, the <code>-n</code> switch makes perl put a loop around the code you provide which will read all the files you pass on the command line in sequence. The <code>-i</code> switch (for “in-place”) says to collect the output from your script and overwrite the original contents of each file with it. The <code>.bak</code> parameter to the <code>-i</code> option tells perl to keep a backup of the original file in a file named after the original file name with <code>.bak</code> appended. For all of these bits, see <a href=\"http://p3rl.org/run\" rel=\"noreferrer\">perldoc perlrun</a>.</p>\n\n<p>If you want to do this within the context of a larger program, the easiest way to do it safely is to open the file twice, once for reading, and separately, with <a href=\"http://p3rl.org/IO::AtomicFile\" rel=\"noreferrer\">IO::AtomicFile</a>, another time for writing. IO::AtomicFile will replace the original file only if it’s successfully closed.</p>\n"
},
{
"answer_id": 81383,
"author": "arclight",
"author_id": 13366,
"author_profile": "https://Stackoverflow.com/users/13366",
"pm_score": 2,
"selected": false,
"text": "<p>As others have pointed out, if the end goal is only to remove lines starting with <code>//#</code>, for performance reasons you are probably better off using <code>grep</code> or <code>sed</code>:</p>\n\n<pre><code>grep -v '^\\/\\/#' filename.txt > filename.stripped.txt\n\nsed '/^\\/\\/#/d' filename.txt > filename.stripped.txt\n</code></pre>\n\n<p>or</p>\n\n<pre><code>sed -i '/^\\/\\/#/d' filename.txt\n</code></pre>\n\n<p>if you prefer in-place editing.</p>\n\n<p>Note that in perl your regex would be</p>\n\n<pre><code>m{^//#}\n</code></pre>\n\n<p>which matches two slashes followed by a # at the start of the string.</p>\n\n<p>Note that you avoid \"backslashitis\" by using the match operator <code>m{pattern}</code> instead of the more familiar <code>/pattern/</code>. Train yourself on this syntax early since it's a simple way to avoid excessive escaping. You could write <code>m{^//#}</code> just as effectively as <code>m%^//#%</code> or <code>m#^//\\##</code>, depending on what you want to match. Strive for clarity - regular expressions are hard enough to decipher without a prickly forest of avoidable backslashes killing readability. Seriously, <code>m/^\\/\\/#/</code> looks like an alligator with a chipped tooth and a filling or a tiny ASCII painting of the Alps.</p>\n\n<p>One problem that might come up in your script is if the entire file is slurped up into a string, newlines and all. To defend against that case, use the /m (multiline) modifier on the regex:</p>\n\n<pre><code>m{^//#}m\n</code></pre>\n\n<p>This allows ^ to match at the beginning of the string <em>and</em> after a newline. You would think there was a way to strip or match the lines matching <code>m{^//#.*$}</code> using the regex modifiers <code>/g</code>, <code>/m</code>, and <code>/s</code> in the case where you've slurped the file into a string but you don't want to make a copy of it (begging the question of why it was slurped into a string in the first place.) It <em>should</em> be possible, but it's late and I'm not seeing the answer. However, one 'simple' way of doing it is:</p>\n\n<pre><code>my $cooked = join qq{\\n}, (grep { ! m{^//} } (split m{\\n}, $raw));\n</code></pre>\n\n<p>even though that creates a copy instead of an in-place edit on the original string <code>$raw</code>.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13046/"
]
| I have a string which starts with `//#...` goes upto the newline characater. I have figured out the regex for the which is this `..#([^\n]*)`.
My question is how do you remove this line from a file if the following condition matches | Your regex is badly chosen on several points:
1. Instead of matching two slashes specifically, you use `..` to match two characters that can be anything at all, presumably because you don’t know how to match slashes when you’re also using them as delimiters. (Actually, dots match *almost* anything, as we’ll see in #3.)
Within a slash-delimited regex literal, `//`, you can match slashes simply by protecting them with backslashes, eg. `/\/\//`. The nicer variant, however, is to use the longer form of regex literal, `m//`, where you can choose the delimiter, eg. `m!!`. Since you use something other than slashes for delimitation, you can then write them without escaping them: `m!//!`. See [perldoc perlop](http://p3rl.org/op#Quote-and-Quote-like-Operators).
2. It’s not anchored to the start of the string so it will match anywhere. Use the `^` start-of-string assertion in front.
3. You wrote `[^\n]` to match “any character except newline” when there is a much simpler way to write that, which is just the `.` wildcard. It does exactly that – match any character except newline.
4. You are using parentheses to group a part of the match, but the group is neither quantified (you are not specifying that it can match any other number of times than exactly once) nor are you interested in keeping it. So the parentheses are superfluous.
Altogether, that makes it `m!^//#.*!`. But putting an uncaptured `.*` (or anything with a `*` quantifier) at the end of a regex is meaningless, since it never changes whether a string will match or not: the `*` is happy to match nothing at all.
So that leaves you with `m!^//#!`.
As for removing the line from the file, as everyone else explained, read it in line by line and print all the lines you want to keep back to another file. If you are not doing this within a larger program, use perl’s command line switches to do it easily:
```
perl -ni.bak -e'print unless m!^//#!' somefile.txt
```
Here, the `-n` switch makes perl put a loop around the code you provide which will read all the files you pass on the command line in sequence. The `-i` switch (for “in-place”) says to collect the output from your script and overwrite the original contents of each file with it. The `.bak` parameter to the `-i` option tells perl to keep a backup of the original file in a file named after the original file name with `.bak` appended. For all of these bits, see [perldoc perlrun](http://p3rl.org/run).
If you want to do this within the context of a larger program, the easiest way to do it safely is to open the file twice, once for reading, and separately, with [IO::AtomicFile](http://p3rl.org/IO::AtomicFile), another time for writing. IO::AtomicFile will replace the original file only if it’s successfully closed. |
80,424 | <p>I have a few models that need to have custom find conditions placed on them. For example, if I have a Contact model, every time Contact.find is called, I want to restrict the contacts returned that only belong to the Account in use.</p>
<p>I found this via Google (which I've customized a little):</p>
<pre><code>def self.find(*args)
with_scope(:find => { :conditions => "account_id = #{$account.id}" }) do
super(*args)
end
end
</code></pre>
<p>This works great, except for a few occasions where account_id is ambiguous so I adapted it to:</p>
<pre><code>def self.find(*args)
with_scope(:find => { :conditions => "#{self.to_s.downcase.pluralize}.account_id = #{$account.id}" }) do
super(*args)
end
end
</code></pre>
<p>This also works great, however, I want it to be DRY. Now I have a few different models that I want this kind of function to be used. What is the best way to do this?</p>
<p>When you answer, please include the code to help our minds grasp the metaprogramming Ruby-fu.</p>
<p>(I'm using Rails v2.1)</p>
| [
{
"answer_id": 80440,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 4,
"selected": true,
"text": "<p>You don't tell us which version of rails you are using [edit - it is on rails 2.1 thus following advice is fully operational], but I would recommand you use the following form instead of overloading find yourself : </p>\n\n<pre><code>account.contacts.find(...) \n</code></pre>\n\n<p>this will automatically wrap the find in a scope where the user clause is included (since you have the account_id I assume you have the account somewhere close)</p>\n\n<p>I suggest you check the following resources on scopes</p>\n\n<ul>\n<li><a href=\"http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality\" rel=\"nofollow noreferrer\">http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality</a>\n(this is not edge anymore :) )</li>\n<li><a href=\"http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know\" rel=\"nofollow noreferrer\">http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know</a></li>\n</ul>\n"
},
{
"answer_id": 80610,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>to give a specific answer to your problem, I'd suggest moving the above mentioned method into a module to be included by the models in question; so you'd have </p>\n\n<pre><code>class Contact\n include NarrowFind\n ...\nend\n</code></pre>\n\n<p>PS. watch out for sql escaping of the account_id, you should probably use the <code>:conditions=>[\".... =?\", $account_id]</code> syntax.</p>\n"
},
{
"answer_id": 83010,
"author": "Nathan de Vries",
"author_id": 11109,
"author_profile": "https://Stackoverflow.com/users/11109",
"pm_score": 3,
"selected": false,
"text": "<p>Jean's advice is sound. Assuming your models look like this:</p>\n\n<pre><code>class Contact < ActiveRecord::Base\n belongs_to :account\nend\n\nclass Account < ActiveRecord::Base\n has_many :contacts\nend\n</code></pre>\n\n<p>You should be using the <code>contacts</code> association of the current account to ensure that you're only getting <code>Contact</code> records scoped to that account, like so:</p>\n\n<pre><code>@account.contacts\n</code></pre>\n\n<p>If you would like to add further conditions to your contacts query, you can specify them using find:</p>\n\n<pre><code>@account.contacts.find(:conditions => { :activated => true })\n</code></pre>\n\n<p>And if you find yourself constantly querying for activated users, you can refactor it into a named scope:</p>\n\n<pre><code>class Contact < ActiveRecord::Base\n belongs_to :account\n named_scope :activated, :conditions => { :activated => true }\nend\n</code></pre>\n\n<p>Which you would then use like this:</p>\n\n<pre><code>@account.contacts.activated\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14530/"
]
| I have a few models that need to have custom find conditions placed on them. For example, if I have a Contact model, every time Contact.find is called, I want to restrict the contacts returned that only belong to the Account in use.
I found this via Google (which I've customized a little):
```
def self.find(*args)
with_scope(:find => { :conditions => "account_id = #{$account.id}" }) do
super(*args)
end
end
```
This works great, except for a few occasions where account\_id is ambiguous so I adapted it to:
```
def self.find(*args)
with_scope(:find => { :conditions => "#{self.to_s.downcase.pluralize}.account_id = #{$account.id}" }) do
super(*args)
end
end
```
This also works great, however, I want it to be DRY. Now I have a few different models that I want this kind of function to be used. What is the best way to do this?
When you answer, please include the code to help our minds grasp the metaprogramming Ruby-fu.
(I'm using Rails v2.1) | You don't tell us which version of rails you are using [edit - it is on rails 2.1 thus following advice is fully operational], but I would recommand you use the following form instead of overloading find yourself :
```
account.contacts.find(...)
```
this will automatically wrap the find in a scope where the user clause is included (since you have the account\_id I assume you have the account somewhere close)
I suggest you check the following resources on scopes
* <http://ryandaigle.com/articles/2008/3/24/what-s-new-in-edge-rails-has-finder-functionality>
(this is not edge anymore :) )
* <http://ryandaigle.com/articles/2008/8/20/named-scope-it-s-not-just-for-conditions-ya-know> |
80,427 | <p>Code I have:</p>
<pre><code>cell_val = CStr(Nz(fld.value, ""))
Dim iter As Long
For iter = 0 To Len(cell_val) - 1 Step 1
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next iter
</code></pre>
<p>This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA.</p>
| [
{
"answer_id": 80457,
"author": "jan.vdbergh",
"author_id": 9540,
"author_profile": "https://Stackoverflow.com/users/9540",
"pm_score": 5,
"selected": true,
"text": "<p>I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following:</p>\n\n<pre><code>For iter = 1 To Len(cell_val) \n If Asc(Mid(cell_val, iter, 1)) > 127 Then\n addlog \"Export contains ascii character > 127\"\n End If\nNext\n</code></pre>\n"
},
{
"answer_id": 80460,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 0,
"selected": false,
"text": "<p>Did you debug it? ;) Are you sure the cell_val is not empty? Also you don't need the 'Step 1' in the For loop since it's default. Also what do you expect to acomplish with your code? It logs if any ascii values are above 127? But that's it - there is no branching depending on the result?</p>\n"
},
{
"answer_id": 80462,
"author": "Scott Evernden",
"author_id": 11397,
"author_profile": "https://Stackoverflow.com/users/11397",
"pm_score": 0,
"selected": false,
"text": "<p>Try AscW()</p>\n"
},
{
"answer_id": 80472,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 0,
"selected": false,
"text": "<p>VB/VBA strings are based from one rather than zero so you need to use:</p>\n\n<pre><code>For iter = 1 To Len(cell_val)\n</code></pre>\n\n<p>I've also left off the <code>step 1</code> since that's the default.</p>\n"
},
{
"answer_id": 80489,
"author": "vzczc",
"author_id": 224,
"author_profile": "https://Stackoverflow.com/users/224",
"pm_score": 2,
"selected": false,
"text": "<p>Your example should be modfied so it does not have external dependencies, it now depends on Nz and addLog.</p>\n\n<p>Anyway, the problem here seems to be that you are looping from 0 to len()-1. In VBA this would be 1 to n.</p>\n\n<pre><code> Dim cell_val As String\n cell_val = \"øabcdæøå~!#%&/()\"\n Dim iter As Long\n For iter = 1 To Len(cell_val)\n If Asc(Mid(cell_val, iter, 1)) > 127 Then\n 'addlog \"Export contains ascii character > 127\"\n Debug.Print iter, \"Export contains ascii character > 127\"\n End If\n Next iter\n</code></pre>\n"
},
{
"answer_id": 80530,
"author": "bfabry",
"author_id": 924607,
"author_profile": "https://Stackoverflow.com/users/924607",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>Did you debug it? ;) Are you sure the\n cell_val is not empty? Also you don't\n need the 'Step 1' in the For loop\n since it's default. Also what do you\n expect to acomplish with your code? It\n logs if any ascii values are above\n 127? But that's it - there is no\n branching depending on the result?</p>\n</blockquote>\n\n<p>I didn't debug it, I have no idea how to use vba or any of the tools that go along with it.\nYes I am sure cell_val is not empty.\nThe code was representative, I was ensuring the branch condition works before writing the branch itself.</p>\n\n<blockquote>\n <p>I believe your problem is that in VBA string indexes start at 1 and not at 0.</p>\n</blockquote>\n\n<p>Ah, the exact kind of thing that goes along with vba that I was bound to miss, thank you.</p>\n"
},
{
"answer_id": 80531,
"author": "Sam",
"author_id": 9406,
"author_profile": "https://Stackoverflow.com/users/9406",
"pm_score": 2,
"selected": false,
"text": "<p>With VBA, VB6 you can just declare a byte array and assign a string value to it and it will be converted for you. Then you can just iterate through it like a regular array.</p>\n\n<p>e.g.</p>\n\n<pre><code>Dim b() as byte\nDim iter As Long\nb = CStr(Nz(fld.value, \"\"))\n\nFor iter = 0 To UBound(b)\n if b(iter) > 127 then\n addlog \"Export contains ascii character > 127\"\n end if\nnext\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/924607/"
]
| Code I have:
```
cell_val = CStr(Nz(fld.value, ""))
Dim iter As Long
For iter = 0 To Len(cell_val) - 1 Step 1
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next iter
```
This code doesn't work. Anyone know how to do this? I've simply got no idea with VB or VBA. | I believe your problem is that in VBA string indexes start at 1 and not at 0. Try the following:
```
For iter = 1 To Len(cell_val)
If Asc(Mid(cell_val, iter, 1)) > 127 Then
addlog "Export contains ascii character > 127"
End If
Next
``` |
80,476 | <p>I need to concatenate two <code>String</code> arrays in Java.</p>
<pre><code>void f(String[] first, String[] second) {
String[] both = ???
}
</code></pre>
<p>Which is the easiest way to do this?</p>
| [
{
"answer_id": 80503,
"author": "jeannicolas",
"author_id": 14981,
"author_profile": "https://Stackoverflow.com/users/14981",
"pm_score": 10,
"selected": false,
"text": "<p>Here's a simple method that will concatenate two arrays and return the result:</p>\n\n<pre><code>public <T> T[] concatenate(T[] a, T[] b) {\n int aLen = a.length;\n int bLen = b.length;\n\n @SuppressWarnings(\"unchecked\")\n T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);\n System.arraycopy(a, 0, c, 0, aLen);\n System.arraycopy(b, 0, c, aLen, bLen);\n\n return c;\n}\n</code></pre>\n\n<p>Note that it will not work with primitive data types, only with object types.</p>\n\n<p>The following slightly more complicated version works with both object and primitive arrays. It does this by using <code>T</code> instead of <code>T[]</code> as the argument type.</p>\n\n<p>It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.</p>\n\n<pre><code>public static <T> T concatenate(T a, T b) {\n if (!a.getClass().isArray() || !b.getClass().isArray()) {\n throw new IllegalArgumentException();\n }\n\n Class<?> resCompType;\n Class<?> aCompType = a.getClass().getComponentType();\n Class<?> bCompType = b.getClass().getComponentType();\n\n if (aCompType.isAssignableFrom(bCompType)) {\n resCompType = aCompType;\n } else if (bCompType.isAssignableFrom(aCompType)) {\n resCompType = bCompType;\n } else {\n throw new IllegalArgumentException();\n }\n\n int aLen = Array.getLength(a);\n int bLen = Array.getLength(b);\n\n @SuppressWarnings(\"unchecked\")\n T result = (T) Array.newInstance(resCompType, aLen + bLen);\n System.arraycopy(a, 0, result, 0, aLen);\n System.arraycopy(b, 0, result, aLen, bLen); \n\n return result;\n}\n</code></pre>\n\n<p>Here is an example:</p>\n\n<pre><code>Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));\nAssert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));\n</code></pre>\n"
},
{
"answer_id": 80559,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 10,
"selected": false,
"text": "<p>I found a one-line solution from the good old Apache Commons Lang library.<br> <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/ArrayUtils.html#addAll%28T%5B%5D,%20T...%29\" rel=\"noreferrer\"><code>ArrayUtils.addAll(T[], T...)</code></a></p>\n\n<p>Code:</p>\n\n<pre><code>String[] both = ArrayUtils.addAll(first, second);\n</code></pre>\n"
},
{
"answer_id": 80621,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"http://functionaljava.org\" rel=\"noreferrer\">Functional Java</a> library has an array wrapper class that equips arrays with handy methods like concatenation.</p>\n\n<pre><code>import static fj.data.Array.array;\n</code></pre>\n\n<p>...and then</p>\n\n<pre><code>Array<String> both = array(first).append(array(second));\n</code></pre>\n\n<p>To get the unwrapped array back out, call</p>\n\n<pre><code>String[] s = both.array();\n</code></pre>\n"
},
{
"answer_id": 80977,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Using only Javas own API:</p>\n\n<pre><code>\nString[] join(String[]... arrays) {\n // calculate size of target array\n int size = 0;\n for (String[] array : arrays) {\n size += array.length;\n }\n\n // create list of appropriate size\n java.util.List list = new java.util.ArrayList(size);\n\n // add arrays\n for (String[] array : arrays) {\n list.addAll(java.util.Arrays.asList(array));\n }\n\n // create and return final array\n return list.toArray(new String[size]);\n}\n</code></pre>\n\n<p>Now, this code ist not the most efficient, but it relies only on standard java classes and is easy to understand. It works for any number of String[] (even zero arrays).</p>\n"
},
{
"answer_id": 85216,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 4,
"selected": false,
"text": "<p>Here's an adaptation of silvertab's solution, with generics retrofitted:</p>\n\n<pre><code>static <T> T[] concat(T[] a, T[] b) {\n final int alen = a.length;\n final int blen = b.length;\n final T[] result = (T[]) java.lang.reflect.Array.\n newInstance(a.getClass().getComponentType(), alen + blen);\n System.arraycopy(a, 0, result, 0, alen);\n System.arraycopy(b, 0, result, alen, blen);\n return result;\n}\n</code></pre>\n\n<p>NOTE: See <a href=\"https://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java/784842#784842\">Joachim's answer</a> for a Java 6 solution. Not only does it eliminate the warning; it's also shorter, more efficient and easier to read!</p>\n"
},
{
"answer_id": 85266,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 5,
"selected": false,
"text": "<p>I've recently fought problems with excessive memory rotation. If a and/or b are known to be commonly empty, here is another adaption of silvertab's code (generified too):</p>\n\n<pre><code>private static <T> T[] concatOrReturnSame(T[] a, T[] b) {\n final int alen = a.length;\n final int blen = b.length;\n if (alen == 0) {\n return b;\n }\n if (blen == 0) {\n return a;\n }\n final T[] result = (T[]) java.lang.reflect.Array.\n newInstance(a.getClass().getComponentType(), alen + blen);\n System.arraycopy(a, 0, result, 0, alen);\n System.arraycopy(b, 0, result, alen, blen);\n return result;\n}\n</code></pre>\n\n<p>Edit: A previous version of this post stated that array re-usage like this shall be clearly documented. As Maarten points out in the comments it would in general be better to just remove the if statements, thus voiding the need for having documentation. But then again, those if statements were the whole point of this particular optimization in the first place. I'll leave this answer here, but be wary!</p>\n"
},
{
"answer_id": 96892,
"author": "Fabian Steeg",
"author_id": 18154,
"author_profile": "https://Stackoverflow.com/users/18154",
"pm_score": 6,
"selected": false,
"text": "<p>Using the Java API:</p>\n\n<pre><code>String[] f(String[] first, String[] second) {\n List<String> both = new ArrayList<String>(first.length + second.length);\n Collections.addAll(both, first);\n Collections.addAll(both, second);\n return both.toArray(new String[both.size()]);\n}\n</code></pre>\n"
},
{
"answer_id": 135237,
"author": "Bob Cross",
"author_id": 5812,
"author_profile": "https://Stackoverflow.com/users/5812",
"pm_score": 2,
"selected": false,
"text": "<p>If you'd like to work with ArrayLists in the solution, you can try this:</p>\n\n<pre><code>public final String [] f(final String [] first, final String [] second) {\n // Assuming non-null for brevity.\n final ArrayList<String> resultList = new ArrayList<String>(Arrays.asList(first));\n resultList.addAll(new ArrayList<String>(Arrays.asList(second)));\n return resultList.toArray(new String [resultList.size()]);\n}\n</code></pre>\n"
},
{
"answer_id": 707558,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I tested below code and worked ok</p>\n\n<p>Also I'm using library: org.apache.commons.lang.ArrayUtils</p>\n\n<pre><code>public void testConcatArrayString(){\n String[] a = null;\n String[] b = null;\n String[] c = null;\n a = new String[] {\"1\",\"2\",\"3\",\"4\",\"5\"};\n b = new String[] {\"A\",\"B\",\"C\",\"D\",\"E\"};\n\n c = (String[]) ArrayUtils.addAll(a, b);\n if(c!=null){\n for(int i=0; i<c.length; i++){\n System.out.println(\"c[\" + (i+1) + \"] = \" + c[i]);\n }\n }\n}\n</code></pre>\n\n<p>Regards</p>\n"
},
{
"answer_id": 784813,
"author": "glue",
"author_id": 94685,
"author_profile": "https://Stackoverflow.com/users/94685",
"pm_score": 3,
"selected": false,
"text": "<p>This works, but you need to insert your own error checking.</p>\n\n<pre><code>public class StringConcatenate {\n\n public static void main(String[] args){\n\n // Create two arrays to concatenate and one array to hold both\n String[] arr1 = new String[]{\"s\",\"t\",\"r\",\"i\",\"n\",\"g\"};\n String[] arr2 = new String[]{\"s\",\"t\",\"r\",\"i\",\"n\",\"g\"};\n String[] arrBoth = new String[arr1.length+arr2.length];\n\n // Copy elements from first array into first part of new array\n for(int i = 0; i < arr1.length; i++){\n arrBoth[i] = arr1[i];\n }\n\n // Copy elements from second array into last part of new array\n for(int j = arr1.length;j < arrBoth.length;j++){\n arrBoth[j] = arr2[j-arr1.length];\n }\n\n // Print result\n for(int k = 0; k < arrBoth.length; k++){\n System.out.print(arrBoth[k]);\n }\n\n // Additional line to make your terminal look better at completion!\n System.out.println();\n }\n}\n</code></pre>\n\n<p>\nIt's probably not the most efficient, but it doesn't rely on anything other than Java's own API.</p>\n"
},
{
"answer_id": 784842,
"author": "Joachim Sauer",
"author_id": 40342,
"author_profile": "https://Stackoverflow.com/users/40342",
"pm_score": 9,
"selected": false,
"text": "<p>It's possible to write a fully generic version that can even be extended to concatenate any number of arrays. This versions require Java 6, as they use <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf%28T[],%20int%29\" rel=\"noreferrer\"><code>Arrays.copyOf()</code></a></p>\n\n<p>Both versions avoid creating any intermediary <code>List</code> objects and use <code>System.arraycopy()</code> to ensure that copying large arrays is as fast as possible.</p>\n\n<p>For two arrays it looks like this:</p>\n\n<pre><code>public static <T> T[] concat(T[] first, T[] second) {\n T[] result = Arrays.copyOf(first, first.length + second.length);\n System.arraycopy(second, 0, result, first.length, second.length);\n return result;\n}\n</code></pre>\n\n<p>And for a arbitrary number of arrays (>= 1) it looks like this:</p>\n\n<pre><code>public static <T> T[] concatAll(T[] first, T[]... rest) {\n int totalLength = first.length;\n for (T[] array : rest) {\n totalLength += array.length;\n }\n T[] result = Arrays.copyOf(first, totalLength);\n int offset = first.length;\n for (T[] array : rest) {\n System.arraycopy(array, 0, result, offset, array.length);\n offset += array.length;\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 786450,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 2,
"selected": false,
"text": "<p>An easy, but inefficient, way to do this (generics not included):</p>\n\n<pre><code>ArrayList baseArray = new ArrayList(Arrays.asList(array1));\nbaseArray.addAll(Arrays.asList(array2));\nString concatenated[] = (String []) baseArray.toArray(new String[baseArray.size()]);\n</code></pre>\n"
},
{
"answer_id": 1012285,
"author": "Damo",
"author_id": 2955,
"author_profile": "https://Stackoverflow.com/users/2955",
"pm_score": 3,
"selected": false,
"text": "<p>A simple variation allowing the joining of more than one array:</p>\n\n<pre><code>public static String[] join(String[]...arrays) {\n\n final List<String> output = new ArrayList<String>();\n\n for(String[] array : arrays) {\n output.addAll(Arrays.asList(array));\n }\n\n return output.toArray(new String[output.size()]);\n}\n</code></pre>\n"
},
{
"answer_id": 1012309,
"author": "Damo",
"author_id": 2955,
"author_profile": "https://Stackoverflow.com/users/2955",
"pm_score": 2,
"selected": false,
"text": "<p>A type independent variation (UPDATED - thanks to Volley for instantiating T):</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\npublic static <T> T[] join(T[]...arrays) {\n\n final List<T> output = new ArrayList<T>();\n\n for(T[] array : arrays) {\n output.addAll(Arrays.asList(array));\n }\n\n return output.toArray((T[])Array.newInstance(\n arrays[0].getClass().getComponentType(), output.size()));\n}\n</code></pre>\n"
},
{
"answer_id": 4552278,
"author": "Sujay",
"author_id": 556856,
"author_profile": "https://Stackoverflow.com/users/556856",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public String[] concat(String[]... arrays)\n{\n int length = 0;\n for (String[] array : arrays) {\n length += array.length;\n }\n String[] result = new String[length];\n int destPos = 0;\n for (String[] array : arrays) {\n System.arraycopy(array, 0, result, destPos, array.length);\n destPos += array.length;\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 4574691,
"author": "Doug",
"author_id": 543770,
"author_profile": "https://Stackoverflow.com/users/543770",
"pm_score": 2,
"selected": false,
"text": "<p>Another one based on SilverTab's suggestion, but made to support x number of arguments and not require Java 6. It is also not generic, but I'm sure it could be made generic.</p>\n\n<pre><code>private byte[] concat(byte[]... args)\n{\n int fulllength = 0;\n for (byte[] arrItem : args)\n {\n fulllength += arrItem.length;\n }\n byte[] retArray = new byte[fulllength];\n int start = 0;\n for (byte[] arrItem : args)\n {\n System.arraycopy(arrItem, 0, retArray, start, arrItem.length);\n start += arrItem.length;\n }\n return retArray;\n}\n</code></pre>\n"
},
{
"answer_id": 5247896,
"author": "KARASZI István",
"author_id": 221213,
"author_profile": "https://Stackoverflow.com/users/221213",
"pm_score": 8,
"selected": false,
"text": "<p>Or with the beloved <a href=\"https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/ObjectArrays.html#concat(T%5B%5D,%20T%5B%5D,%20java.lang.Class)\" rel=\"noreferrer\">Guava</a>:</p>\n\n<pre><code>String[] both = ObjectArrays.concat(first, second, String.class);\n</code></pre>\n\n<p>Also, there are versions for primitive arrays:</p>\n\n<ul>\n<li><code>Booleans.concat(first, second)</code></li>\n<li><code>Bytes.concat(first, second)</code></li>\n<li><code>Chars.concat(first, second)</code></li>\n<li><code>Doubles.concat(first, second)</code></li>\n<li><code>Shorts.concat(first, second)</code></li>\n<li><code>Ints.concat(first, second)</code></li>\n<li><code>Longs.concat(first, second)</code></li>\n<li><code>Floats.concat(first, second)</code></li>\n</ul>\n"
},
{
"answer_id": 5497557,
"author": "Adham",
"author_id": 671613,
"author_profile": "https://Stackoverflow.com/users/671613",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Object[] obj = {\"hi\",\"there\"};\nObject[] obj2 ={\"im\",\"fine\",\"what abt u\"};\nObject[] obj3 = new Object[obj.length+obj2.length];\n\nfor(int i =0;i<obj3.length;i++)\n obj3[i] = (i<obj.length)?obj[i]:obj2[i-obj.length];\n</code></pre>\n"
},
{
"answer_id": 6295624,
"author": "candrews",
"author_id": 791247,
"author_profile": "https://Stackoverflow.com/users/791247",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my slightly improved version of Joachim Sauer's concatAll. It can work on Java 5 or 6, using Java 6's System.arraycopy if it's available at runtime. This method (IMHO) is perfect for Android, as it work on Android <9 (which doesn't have System.arraycopy) but will use the faster method if possible.</p>\n\n<pre><code> public static <T> T[] concatAll(T[] first, T[]... rest) {\n int totalLength = first.length;\n for (T[] array : rest) {\n totalLength += array.length;\n }\n T[] result;\n try {\n Method arraysCopyOf = Arrays.class.getMethod(\"copyOf\", Object[].class, int.class);\n result = (T[]) arraysCopyOf.invoke(null, first, totalLength);\n } catch (Exception e){\n //Java 6 / Android >= 9 way didn't work, so use the \"traditional\" approach\n result = (T[]) java.lang.reflect.Array.newInstance(first.getClass().getComponentType(), totalLength);\n System.arraycopy(first, 0, result, 0, first.length);\n }\n int offset = first.length;\n for (T[] array : rest) {\n System.arraycopy(array, 0, result, offset, array.length);\n offset += array.length;\n }\n return result;\n }\n</code></pre>\n"
},
{
"answer_id": 6301908,
"author": "Muhammad Haris Altaf",
"author_id": 789261,
"author_profile": "https://Stackoverflow.com/users/789261",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way i could find is as following :</p>\n\n<pre>\n<code>\nList allFiltersList = Arrays.asList(regularFilters);\nallFiltersList.addAll(Arrays.asList(preFiltersArray));\nFilter[] mergedFilterArray = (Filter[]) allFiltersList.toArray();\n</code>\n</pre>\n"
},
{
"answer_id": 6318217,
"author": "Oritm",
"author_id": 574736,
"author_profile": "https://Stackoverflow.com/users/574736",
"pm_score": 3,
"selected": false,
"text": "<p>This is a converted function for a String array:</p>\n\n<pre><code>public String[] mergeArrays(String[] mainArray, String[] addArray) {\n String[] finalArray = new String[mainArray.length + addArray.length];\n System.arraycopy(mainArray, 0, finalArray, 0, mainArray.length);\n System.arraycopy(addArray, 0, finalArray, mainArray.length, addArray.length);\n\n return finalArray;\n}\n</code></pre>\n"
},
{
"answer_id": 6691787,
"author": "Jeroen",
"author_id": 844342,
"author_profile": "https://Stackoverflow.com/users/844342",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Import java.util.*;\n\nString array1[] = {\"bla\",\"bla\"};\nString array2[] = {\"bla\",\"bla\"};\n\nArrayList<String> tempArray = new ArrayList<String>(Arrays.asList(array1));\ntempArray.addAll(Arrays.asList(array2));\nString array3[] = films.toArray(new String[1]); // size will be overwritten if needed\n</code></pre>\n\n<p>You could replace String by a Type/Class of your liking</p>\n\n<p>Im sure this can be made shorter and better, but it works and im to lazy to sort it out further...</p>\n"
},
{
"answer_id": 6777237,
"author": "Sushim ",
"author_id": 856097,
"author_profile": "https://Stackoverflow.com/users/856097",
"pm_score": 0,
"selected": false,
"text": "<p><strong>You can try this</strong></p>\n\n<pre><code> public static Object[] addTwoArray(Object[] objArr1, Object[] objArr2){\n int arr1Length = objArr1!=null && objArr1.length>0?objArr1.length:0;\n int arr2Length = objArr2!=null && objArr2.length>0?objArr2.length:0;\n Object[] resutlentArray = new Object[arr1Length+arr2Length]; \n for(int i=0,j=0;i<resutlentArray.length;i++){\n if(i+1<=arr1Length){\n resutlentArray[i]=objArr1[i];\n }else{\n resutlentArray[i]=objArr2[j];\n j++;\n }\n }\n\n return resutlentArray;\n}\n</code></pre>\n\n<p>U can type cast your array !!!</p>\n"
},
{
"answer_id": 7724875,
"author": "francois",
"author_id": 989332,
"author_profile": "https://Stackoverflow.com/users/989332",
"pm_score": 5,
"selected": false,
"text": "<p>A solution <strong>100% old java</strong> and <strong>without</strong> <code>System.arraycopy</code> (not available in GWT client for example):</p>\n\n<pre><code>static String[] concat(String[]... arrays) {\n int length = 0;\n for (String[] array : arrays) {\n length += array.length;\n }\n String[] result = new String[length];\n int pos = 0;\n for (String[] array : arrays) {\n for (String element : array) {\n result[pos] = element;\n pos++;\n }\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 7733971,
"author": "Ephraim",
"author_id": 432499,
"author_profile": "https://Stackoverflow.com/users/432499",
"pm_score": 3,
"selected": false,
"text": "<p>How about simply </p>\n\n<pre><code>public static class Array {\n\n public static <T> T[] concat(T[]... arrays) {\n ArrayList<T> al = new ArrayList<T>();\n for (T[] one : arrays)\n Collections.addAll(al, one);\n return (T[]) al.toArray(arrays[0].clone());\n }\n}\n</code></pre>\n\n<p>And just do <code>Array.concat(arr1, arr2)</code>. As long as <code>arr1</code> and <code>arr2</code> are of the same type, this will give you another array of the same type containing both arrays. </p>\n"
},
{
"answer_id": 8728568,
"author": "hpgisler",
"author_id": 757684,
"author_profile": "https://Stackoverflow.com/users/757684",
"pm_score": 3,
"selected": false,
"text": "<p>Here a possible implementation in working code of the pseudo code solution written by silvertab. </p>\n\n<p>Thanks silvertab!</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Array {\n\n public static <T> T[] concat(T[] a, T[] b, ArrayBuilderI<T> builder) {\n T[] c = builder.build(a.length + b.length);\n System.arraycopy(a, 0, c, 0, a.length);\n System.arraycopy(b, 0, c, a.length, b.length);\n return c;\n }\n}\n</code></pre>\n\n<p>Following next is the builder interface. </p>\n\n<p>Note: A builder is necessary because in java it is not possible to do </p>\n\n<p><code>new T[size]</code> </p>\n\n<p>due to generic type erasure:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public interface ArrayBuilderI<T> {\n\n public T[] build(int size);\n}\n</code></pre>\n\n<p>Here a concrete builder implementing the interface, building a <code>Integer</code> array:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class IntegerArrayBuilder implements ArrayBuilderI<Integer> {\n\n @Override\n public Integer[] build(int size) {\n return new Integer[size];\n }\n}\n</code></pre>\n\n<p>And finally the application / test:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Test\npublic class ArrayTest {\n\n public void array_concatenation() {\n Integer a[] = new Integer[]{0,1};\n Integer b[] = new Integer[]{2,3};\n Integer c[] = Array.concat(a, b, new IntegerArrayBuilder());\n assertEquals(4, c.length);\n assertEquals(0, (int)c[0]);\n assertEquals(1, (int)c[1]);\n assertEquals(2, (int)c[2]);\n assertEquals(3, (int)c[3]);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 9512746,
"author": "Jerome",
"author_id": 811865,
"author_profile": "https://Stackoverflow.com/users/811865",
"pm_score": -1,
"selected": false,
"text": "<p>In Haskell you can do something like that <code>[a, b, c] ++ [d, e]</code> to get <code>[a, b, c, d, e]</code>. These are Haskell lists concatenated but that'd very nice to see a similar operator in Java for arrays. Don't you think so ? That's elegant, simple, generic and it's not that difficult to implement.</p>\n\n<p>If you want to, I suggest you to have a look at Alexander Hristov's work in his <a href=\"http://www.ahristov.com/tutoriales/java-compiler/duplicating-lexer.html\" rel=\"nofollow\">Hacking the OpenJDK compiler</a>. He explains how to modify javac source to create a new operator. His example consists in defining a '**' operator where <code>i ** j = Math.pow(i, j)</code>. One could take that example to implement an operator that concatenates two arrays of same type.<br></p>\n\n<p>Once you do that, you are bound to your customized javac to compile your code but the generated bytecode will be understood by any JVM. <br><br>Of course, you can implement your own array concatenatation method at your source level, there are many examples on how to do it in the other answers !<br>\n<br>\nThere are so many useful operators that could be added, this one would be one of them.</p>\n"
},
{
"answer_id": 10056834,
"author": "filosofem",
"author_id": 1319411,
"author_profile": "https://Stackoverflow.com/users/1319411",
"pm_score": -1,
"selected": false,
"text": "<p>Look at this elegant solution (if you need other type than char, change it):</p>\n\n<pre><code>private static void concatArrays(char[] destination, char[]... sources) {\n int currPos = 0;\n for (char[] source : sources) {\n int length = source.length;\n System.arraycopy(source, 0, destination, currPos, length);\n currPos += length;\n }\n}\n</code></pre>\n\n<p>You can concatenate a every count of arrays.</p>\n"
},
{
"answer_id": 10382513,
"author": "user462990",
"author_id": 462990,
"author_profile": "https://Stackoverflow.com/users/462990",
"pm_score": 2,
"selected": false,
"text": "<p>I found I had to deal with the case where the arrays can be null...</p>\n\n<pre><code>private double[] concat (double[]a,double[]b){\n if (a == null) return b;\n if (b == null) return a;\n double[] r = new double[a.length+b.length];\n System.arraycopy(a, 0, r, 0, a.length);\n System.arraycopy(b, 0, r, a.length, b.length);\n return r;\n\n}\nprivate double[] copyRest (double[]a, int start){\n if (a == null) return null;\n if (start > a.length)return null;\n double[]r = new double[a.length-start];\n System.arraycopy(a,start,r,0,a.length-start); \n return r;\n}\n</code></pre>\n"
},
{
"answer_id": 11470232,
"author": "Reto Höhener",
"author_id": 1124509,
"author_profile": "https://Stackoverflow.com/users/1124509",
"pm_score": 4,
"selected": false,
"text": "<p>Please forgive me for adding yet another version to this already long list. I looked at every answer and decided that I really wanted a version with just one parameter in the signature. I also added some argument checking to benefit from early failure with sensible info in case of unexpected input.</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\npublic static <T> T[] concat(T[]... inputArrays) {\n if(inputArrays.length < 2) {\n throw new IllegalArgumentException(\"inputArrays must contain at least 2 arrays\");\n }\n\n for(int i = 0; i < inputArrays.length; i++) {\n if(inputArrays[i] == null) {\n throw new IllegalArgumentException(\"inputArrays[\" + i + \"] is null\");\n }\n }\n\n int totalLength = 0;\n\n for(T[] array : inputArrays) {\n totalLength += array.length;\n }\n\n T[] result = (T[]) Array.newInstance(inputArrays[0].getClass().getComponentType(), totalLength);\n\n int offset = 0;\n\n for(T[] array : inputArrays) {\n System.arraycopy(array, 0, result, offset, array.length);\n\n offset += array.length;\n }\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 13112678,
"author": "doles",
"author_id": 1118233,
"author_profile": "https://Stackoverflow.com/users/1118233",
"pm_score": 3,
"selected": false,
"text": "<p>Wow! lot of complex answers here including some simple ones that depend on external dependencies. how about doing it like this:</p>\n\n<pre><code>String [] arg1 = new String{\"a\",\"b\",\"c\"};\nString [] arg2 = new String{\"x\",\"y\",\"z\"};\n\nArrayList<String> temp = new ArrayList<String>();\ntemp.addAll(Arrays.asList(arg1));\ntemp.addAll(Arrays.asList(arg2));\nString [] concatedArgs = temp.toArray(new String[arg1.length+arg2.length]);\n</code></pre>\n"
},
{
"answer_id": 15103456,
"author": "Earth Engine",
"author_id": 812034,
"author_profile": "https://Stackoverflow.com/users/812034",
"pm_score": 2,
"selected": false,
"text": "<p>Another way to think about the question. To concatenate two or more arrays, one have to do is to list all elements of each arrays, and then build a new array. This sounds like create a <code>List<T></code> and then calls <code>toArray</code> on it. Some other answers uses <code>ArrayList</code>, and that's fine. But how about implement our own? It is not hard:</p>\n\n<pre><code>private static <T> T[] addAll(final T[] f, final T...o){\n return new AbstractList<T>(){\n\n @Override\n public T get(int i) {\n return i>=f.length ? o[i - f.length] : f[i];\n }\n\n @Override\n public int size() {\n return f.length + o.length;\n }\n\n }.toArray(f);\n}\n</code></pre>\n\n<p>I believe the above is equivalent to solutions that uses <code>System.arraycopy</code>. However I think this one has its own beauty. </p>\n"
},
{
"answer_id": 17235840,
"author": "Frimousse",
"author_id": 2509077,
"author_profile": "https://Stackoverflow.com/users/2509077",
"pm_score": 2,
"selected": false,
"text": "<pre><code>String [] both = new ArrayList<String>(){{addAll(Arrays.asList(first)); addAll(Arrays.asList(second));}}.toArray(new String[0]);\n</code></pre>\n"
},
{
"answer_id": 18350255,
"author": "h-rai",
"author_id": 1109689,
"author_profile": "https://Stackoverflow.com/users/1109689",
"pm_score": 5,
"selected": false,
"text": "<pre><code>ArrayList<String> both = new ArrayList(Arrays.asList(first));\nboth.addAll(Arrays.asList(second));\n\nboth.toArray(new String[0]);\n</code></pre>\n"
},
{
"answer_id": 19666913,
"author": "SuperCamp",
"author_id": 2782483,
"author_profile": "https://Stackoverflow.com/users/2782483",
"pm_score": -1,
"selected": false,
"text": "<p>Should do the trick. This is assuming String[] first and String[] second</p>\n\n<pre><code>List<String> myList = new ArrayList<String>(Arrays.asList(first));\nmyList.addAll(new ArrayList<String>(Arrays.asList(second)));\nString[] both = myList.toArray(new String[myList.size()]);\n</code></pre>\n"
},
{
"answer_id": 20903551,
"author": "Ricardo Vallejo",
"author_id": 3144146,
"author_profile": "https://Stackoverflow.com/users/3144146",
"pm_score": 0,
"selected": false,
"text": "<p>This one works only with int but the idea is generic</p>\n\n<pre><code>public static int[] junta(int[] v, int[] w) {\n\nint[] junta = new int[v.length + w.length];\n\nfor (int i = 0; i < v.length; i++) { \n junta[i] = v[i];\n}\n\nfor (int j = v.length; j < junta.length; j++) {\n junta[j] = w[j - v.length];\n}\n</code></pre>\n"
},
{
"answer_id": 23188881,
"author": "Vitalii Fedorenko",
"author_id": 288671,
"author_profile": "https://Stackoverflow.com/users/288671",
"pm_score": 9,
"selected": false,
"text": "<p>Using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html\" rel=\"noreferrer\"><code>Stream</code></a> in Java 8:</p>\n\n<pre><code>String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))\n .toArray(String[]::new);\n</code></pre>\n\n<p>Or like this, using <code>flatMap</code>:</p>\n\n<pre><code>String[] both = Stream.of(a, b).flatMap(Stream::of)\n .toArray(String[]::new);\n</code></pre>\n\n<p>To do this for a generic type you have to use reflection:</p>\n\n<pre><code>@SuppressWarnings(\"unchecked\")\nT[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray(\n size -> (T[]) Array.newInstance(a.getClass().getComponentType(), size));\n</code></pre>\n"
},
{
"answer_id": 25026341,
"author": "spacebiker",
"author_id": 1114732,
"author_profile": "https://Stackoverflow.com/users/1114732",
"pm_score": 2,
"selected": false,
"text": "<p>I think the best solution with generics would be:</p>\n\n<pre><code>/* This for non primitive types */\npublic static <T> T[] concatenate (T[]... elements) {\n\n T[] C = null;\n for (T[] element: elements) {\n if (element==null) continue;\n if (C==null) C = (T[]) Array.newInstance(element.getClass().getComponentType(), element.length);\n else C = resizeArray(C, C.length+element.length);\n\n System.arraycopy(element, 0, C, C.length-element.length, element.length);\n }\n\n return C;\n}\n\n/**\n * as far as i know, primitive types do not accept generics \n * http://stackoverflow.com/questions/2721546/why-dont-java-generics-support-primitive-types\n * for primitive types we could do something like this:\n * */\npublic static int[] concatenate (int[]... elements){\n int[] C = null;\n for (int[] element: elements) {\n if (element==null) continue;\n if (C==null) C = new int[element.length];\n else C = resizeArray(C, C.length+element.length);\n\n System.arraycopy(element, 0, C, C.length-element.length, element.length);\n }\n return C;\n}\n\nprivate static <T> T resizeArray (T array, int newSize) {\n int oldSize =\n java.lang.reflect.Array.getLength(array);\n Class elementType =\n array.getClass().getComponentType();\n Object newArray =\n java.lang.reflect.Array.newInstance(\n elementType, newSize);\n int preserveLength = Math.min(oldSize, newSize);\n if (preserveLength > 0)\n System.arraycopy(array, 0,\n newArray, 0, preserveLength);\n return (T) newArray;\n}\n</code></pre>\n"
},
{
"answer_id": 28466684,
"author": "clément francomme",
"author_id": 4151755,
"author_profile": "https://Stackoverflow.com/users/4151755",
"pm_score": 2,
"selected": false,
"text": "<p>How about :</p>\n\n<pre><code>public String[] combineArray (String[] ... strings) {\n List<String> tmpList = new ArrayList<String>();\n for (int i = 0; i < strings.length; i++)\n tmpList.addAll(Arrays.asList(strings[i]));\n return tmpList.toArray(new String[tmpList.size()]);\n}\n</code></pre>\n"
},
{
"answer_id": 33018648,
"author": "George",
"author_id": 791195,
"author_profile": "https://Stackoverflow.com/users/791195",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public int[] mergeArrays(int [] a, int [] b) {\n int [] merged = new int[a.length + b.length];\n int i = 0, k = 0, l = a.length;\n int j = a.length > b.length ? a.length : b.length;\n while(i < j) {\n if(k < a.length) {\n merged[k] = a[k];\n k++;\n }\n if((l - a.length) < b.length) {\n merged[l] = b[l - a.length];\n l++;\n }\n i++;\n }\n return merged;\n}\n</code></pre>\n"
},
{
"answer_id": 33711992,
"author": "Paul",
"author_id": 4908555,
"author_profile": "https://Stackoverflow.com/users/4908555",
"pm_score": 4,
"selected": false,
"text": "<p>You could try converting it into a <code>ArrayList</code> and use the <code>addAll</code> method then convert back to an array.</p>\n<pre><code>List list = new ArrayList(Arrays.asList(first));\n list.addAll(Arrays.asList(second));\n String[] both = list.toArray();\n</code></pre>\n"
},
{
"answer_id": 35315750,
"author": "Vaseph",
"author_id": 1912860,
"author_profile": "https://Stackoverflow.com/users/1912860",
"pm_score": 4,
"selected": false,
"text": "<p>Another way with Java8 using Stream</p>\n\n<pre><code> public String[] concatString(String[] a, String[] b){ \n Stream<String> streamA = Arrays.stream(a);\n Stream<String> streamB = Arrays.stream(b);\n return Stream.concat(streamA, streamB).toArray(String[]::new); \n }\n</code></pre>\n"
},
{
"answer_id": 35644035,
"author": "Kamil Tomasz Jarmusik",
"author_id": 5642475,
"author_profile": "https://Stackoverflow.com/users/5642475",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public static String[] toArray(String[]... object){\n List<String> list=new ArrayList<>();\n for (String[] i : object) {\n list.addAll(Arrays.asList(i));\n }\n return list.toArray(new String[list.size()]);\n}\n</code></pre>\n"
},
{
"answer_id": 38448403,
"author": "obwan02",
"author_id": 6554496,
"author_profile": "https://Stackoverflow.com/users/6554496",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Object[] mixArray(String[] a, String[] b)\nString[] s1 = a;\nString[] s2 = b;\nObject[] result;\nList<String> input = new ArrayList<String>();\nfor (int i = 0; i < s1.length; i++)\n{\n input.add(s1[i]);\n}\nfor (int i = 0; i < s2.length; i++)\n{\n input.add(s2[i]);\n}\nresult = input.toArray();\nreturn result;\n</code></pre>\n"
},
{
"answer_id": 39322165,
"author": "Douglas Held",
"author_id": 399723,
"author_profile": "https://Stackoverflow.com/users/399723",
"pm_score": 2,
"selected": false,
"text": "<p>Every single answer is copying data and creating a new array. This is not strictly necessary and is definitely NOT what you want to do if your arrays are reasonably large. Java creators already knew that array copies are wasteful and that is why they provided us System.arrayCopy() to do those outside Java when we have to.</p>\n\n<p>Instead of copying your data around, consider leaving it in place and draw from it where it lies. Copying data locations just because the programmer would like to organize them is not always sensible.</p>\n\n<pre><code>// I have arrayA and arrayB; would like to treat them as concatenated\n// but leave my damn bytes where they are!\nObject accessElement ( int index ) {\n if ( index < 0 ) throw new ArrayIndexOutOfBoundsException(...);\n // is reading from the head part?\n if ( index < arrayA.length )\n return arrayA[ index ];\n // is reading from the tail part?\n if ( index < ( arrayA.length + arrayB.length ) )\n return arrayB[ index - arrayA.length ];\n throw new ArrayIndexOutOfBoundsException(...); // index too large\n}\n</code></pre>\n"
},
{
"answer_id": 40855217,
"author": "user_3380739",
"author_id": 3380739,
"author_profile": "https://Stackoverflow.com/users/3380739",
"pm_score": 2,
"selected": false,
"text": "<p>Here is the code by <a href=\"https://github.com/landawn/AbacusUtil\" rel=\"nofollow noreferrer\">AbacusUtil</a>.</p>\n\n<pre><code>String[] a = {\"a\", \"b\", \"c\"};\nString[] b = {\"1\", \"2\", \"3\"};\nString[] c = N.concat(a, b); // c = [\"a\", \"b\", \"c\", \"1\", \"2\", \"3\"]\n\n// N.concat(...) is null-safety.\na = null;\nc = N.concat(a, b); // c = [\"1\", \"2\", \"3\"]\n</code></pre>\n"
},
{
"answer_id": 40991067,
"author": "Yashovardhan99",
"author_id": 7252861,
"author_profile": "https://Stackoverflow.com/users/7252861",
"pm_score": -1,
"selected": false,
"text": "<pre><code> void f(String[] first, String[] second) {\n String[] both = new String[first.length+second.length];\n for(int i=0;i<first.length;i++)\n both[i] = first[i];\n for(int i=0;i<second.length;i++)\n both[first.length + i] = second[i];\n}\n</code></pre>\n\n<p>This one works without knowledge of any other classes/libraries etc.\nIt works for any data type. Just replace <code>String</code> with anything like <code>int</code>,<code>double</code> or <code>char</code>.\nIt works quite efficiently.</p>\n"
},
{
"answer_id": 42201601,
"author": "Raj S. Rusia",
"author_id": 7178104,
"author_profile": "https://Stackoverflow.com/users/7178104",
"pm_score": 4,
"selected": false,
"text": "<p>If you use this way so you no need to import any third party class.</p>\n\n<p>If you want concatenate <code>String</code></p>\n\n<p><strong>Sample code for concate two String Array</strong></p>\n\n<pre><code>public static String[] combineString(String[] first, String[] second){\n int length = first.length + second.length;\n String[] result = new String[length];\n System.arraycopy(first, 0, result, 0, first.length);\n System.arraycopy(second, 0, result, first.length, second.length);\n return result;\n }\n</code></pre>\n\n<p>If you want concatenate <code>Int</code></p>\n\n<p><strong>Sample code for concate two Integer Array</strong></p>\n\n<pre><code>public static int[] combineInt(int[] a, int[] b){\n int length = a.length + b.length;\n int[] result = new int[length];\n System.arraycopy(a, 0, result, 0, a.length);\n System.arraycopy(b, 0, result, a.length, b.length);\n return result;\n }\n</code></pre>\n\n<p><strong>Here is Main method</strong></p>\n\n<pre><code> public static void main(String[] args) {\n\n String [] first = {\"a\", \"b\", \"c\"};\n String [] second = {\"d\", \"e\"};\n\n String [] joined = combineString(first, second);\n System.out.println(\"concatenated String array : \" + Arrays.toString(joined));\n\n int[] array1 = {101,102,103,104};\n int[] array2 = {105,106,107,108};\n int[] concatenateInt = combineInt(array1, array2);\n\n System.out.println(\"concatenated Int array : \" + Arrays.toString(concatenateInt));\n\n }\n } \n</code></pre>\n\n<p>We can use this way also.</p>\n"
},
{
"answer_id": 46542530,
"author": "c-chavez",
"author_id": 1042409,
"author_profile": "https://Stackoverflow.com/users/1042409",
"pm_score": 0,
"selected": false,
"text": "<p>Yet another answer for algorithm lovers:</p>\n\n<pre><code>public static String[] mergeArrays(String[] array1, String[] array2) {\n int totalSize = array1.length + array2.length; // Get total size\n String[] merged = new String[totalSize]; // Create new array\n // Loop over the total size\n for (int i = 0; i < totalSize; i++) {\n if (i < array1.length) // If the current position is less than the length of the first array, take value from first array\n merged[i] = array1[i]; // Position in first array is the current position\n\n else // If current position is equal or greater than the first array, take value from second array.\n merged[i] = array2[i - array1.length]; // Position in second array is current position minus length of first array.\n }\n\n return merged;\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>String[] array1str = new String[]{\"a\", \"b\", \"c\", \"d\"}; \nString[] array2str = new String[]{\"e\", \"f\", \"g\", \"h\", \"i\"};\nString[] listTotalstr = mergeArrays(array1str, array2str);\nSystem.out.println(Arrays.toString(listTotalstr));\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>[a, b, c, d, e, f, g, h, i]\n</code></pre>\n"
},
{
"answer_id": 46972713,
"author": "Hakim",
"author_id": 4800139,
"author_profile": "https://Stackoverflow.com/users/4800139",
"pm_score": 0,
"selected": false,
"text": "<p>You can try this method which concatenates multiple arrays:</p>\n\n<pre><code>public static <T> T[] concatMultipleArrays(T[]... arrays)\n{\n int length = 0;\n for (T[] array : arrays)\n {\n length += array.length;\n }\n T[] result = (T[]) Array.newInstance(arrays.getClass().getComponentType(), length) ;\n\n length = 0;\n for (int i = 0; i < arrays.length; i++)\n {\n System.arraycopy(arrays[i], 0, result, length, arrays[i].length);\n length += arrays[i].length;\n }\n\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 49772469,
"author": "rghome",
"author_id": 3800782,
"author_profile": "https://Stackoverflow.com/users/3800782",
"pm_score": 7,
"selected": false,
"text": "<p>You can append the two arrays in two lines of code.</p>\n\n<pre><code>String[] both = Arrays.copyOf(first, first.length + second.length);\nSystem.arraycopy(second, 0, both, first.length, second.length);\n</code></pre>\n\n<p>This is a fast and efficient solution and will work for primitive types as well as the two methods involved are overloaded.</p>\n\n<p>You should avoid solutions involving ArrayLists, streams, etc as these will need to allocate temporary memory for no useful purpose.</p>\n\n<p>You should avoid <code>for</code> loops for large arrays as these are not efficient. The built in methods use block-copy functions that are extremely fast.</p>\n"
},
{
"answer_id": 49793485,
"author": "Basil Battikhi",
"author_id": 2901129,
"author_profile": "https://Stackoverflow.com/users/2901129",
"pm_score": 0,
"selected": false,
"text": "<p>In Java 8 </p>\n\n<pre><code>public String[] concat(String[] arr1, String[] arr2){\n Stream<String> stream1 = Stream.of(arr1);\n Stream<String> stream2 = Stream.of(arr2);\n Stream<String> stream = Stream.concat(stream1, stream2);\n return Arrays.toString(stream.toArray(String[]::new));\n}\n</code></pre>\n"
},
{
"answer_id": 52375659,
"author": "BrownRecluse",
"author_id": 5143356,
"author_profile": "https://Stackoverflow.com/users/5143356",
"pm_score": 1,
"selected": false,
"text": "<p>Non Java 8 solution:</p>\n\n<pre><code>public static int[] combineArrays(int[] a, int[] b) {\n int[] c = new int[a.length + b.length];\n\n for (int i = 0; i < a.length; i++) {\n c[i] = a[i];\n }\n\n for (int j = 0, k = a.length; j < b.length; j++, k++) {\n c[k] = b[j];\n }\n\n return c;\n }\n</code></pre>\n"
},
{
"answer_id": 52950353,
"author": "keisar",
"author_id": 1344070,
"author_profile": "https://Stackoverflow.com/users/1344070",
"pm_score": 4,
"selected": false,
"text": "<p>Using Java 8+ streams you can write the following function:</p>\n\n<pre><code>private static String[] concatArrays(final String[]... arrays) {\n return Arrays.stream(arrays)\n .flatMap(Arrays::stream)\n .toArray(String[]::new);\n}\n</code></pre>\n"
},
{
"answer_id": 53025243,
"author": "avigaild",
"author_id": 10567980,
"author_profile": "https://Stackoverflow.com/users/10567980",
"pm_score": 3,
"selected": false,
"text": "<p>This should be one-liner.</p>\n\n<pre><code>public String [] concatenate (final String array1[], final String array2[])\n{\n return Stream.concat(Stream.of(array1), Stream.of(array2)).toArray(String[]::new);\n}\n</code></pre>\n"
},
{
"answer_id": 53181401,
"author": "beaudet",
"author_id": 2730420,
"author_profile": "https://Stackoverflow.com/users/2730420",
"pm_score": 3,
"selected": false,
"text": "<p>A generic static version that uses the high performing System.arraycopy without requiring a @SuppressWarnings annotation:</p>\n\n<pre><code>public static <T> T[] arrayConcat(T[] a, T[] b) {\n T[] both = Arrays.copyOf(a, a.length + b.length);\n System.arraycopy(b, 0, both, a.length, b.length);\n return both;\n}\n</code></pre>\n"
},
{
"answer_id": 55320708,
"author": "ZhekaKozlov",
"author_id": 706317,
"author_profile": "https://Stackoverflow.com/users/706317",
"pm_score": 2,
"selected": false,
"text": "<p>This is probably the only generic and type-safe way:</p>\n\n<pre><code>public class ArrayConcatenator<T> {\n private final IntFunction<T[]> generator;\n\n private ArrayConcatenator(IntFunction<T[]> generator) {\n this.generator = generator;\n }\n\n public static <T> ArrayConcatenator<T> concat(IntFunction<T[]> generator) {\n return new ArrayConcatenator<>(generator);\n }\n\n public T[] apply(T[] array1, T[] array2) {\n T[] array = generator.apply(array1.length + array2.length);\n System.arraycopy(array1, 0, array, 0, array1.length);\n System.arraycopy(array2, 0, array, array1.length, array2.length);\n return array;\n }\n}\n</code></pre>\n\n<p>And the usage is quite concise:</p>\n\n<pre><code>Integer[] array1 = { 1, 2, 3 };\nDouble[] array2 = { 4.0, 5.0, 6.0 };\nNumber[] array = concat(Number[]::new).apply(array1, array2);\n</code></pre>\n\n<p>(requires static import)</p>\n\n<p>Invalid array types are rejected:</p>\n\n<pre><code>concat(String[]::new).apply(array1, array2); // error\nconcat(Integer[]::new).apply(array1, array2); // error\n</code></pre>\n"
},
{
"answer_id": 58587509,
"author": "Kaplan",
"author_id": 11199879,
"author_profile": "https://Stackoverflow.com/users/11199879",
"pm_score": 0,
"selected": false,
"text": "<p><em>concatenates a series of arrays compact, fast and type-safe with lambda</em></p>\n\n<pre><code>@SafeVarargs\npublic static <T> T[] concat( T[]... arrays ) {\n return( Stream.of( arrays ).reduce( ( arr1, arr2 ) -> {\n T[] rslt = Arrays.copyOf( arr1, arr1.length + arr2.length );\n System.arraycopy( arr2, 0, rslt, arr1.length, arr2.length );\n return( rslt );\n } ).orElse( null ) );\n};\n</code></pre>\n\n<p>returns <code>null</code> when called without argument<br /></p>\n\n<p>eg. example with 3 arrays:</p>\n\n<pre><code>String[] a = new String[] { \"a\", \"b\", \"c\", \"d\" };\nString[] b = new String[] { \"e\", \"f\", \"g\", \"h\" };\nString[] c = new String[] { \"i\", \"j\", \"k\", \"l\" };\n\nconcat( a, b, c ); // [a, b, c, d, e, f, g, h, i, j, k, l]\n</code></pre>\n\n<p><br /><em>\"…probably the only generic and type-safe way\"</em> – adapted:</p>\n\n<pre><code>Number[] array1 = { 1, 2, 3 };\nNumber[] array2 = { 4.0, 5.0, 6.0 };\nNumber[] array = concat( array1, array2 ); // [1, 2, 3, 4.0, 5.0, 6.0]\n</code></pre>\n"
},
{
"answer_id": 60017520,
"author": "JGFMK",
"author_id": 495157,
"author_profile": "https://Stackoverflow.com/users/495157",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to add, you can use <code>System.arraycopy</code> too:</p>\n\n<pre><code>import static java.lang.System.out;\nimport static java.lang.System.arraycopy;\nimport java.lang.reflect.Array;\nclass Playground {\n @SuppressWarnings(\"unchecked\")\n public static <T>T[] combineArrays(T[] a1, T[] a2) {\n T[] result = (T[]) Array.newInstance(a1.getClass().getComponentType(), a1.length+a2.length);\n arraycopy(a1,0,result,0,a1.length);\n arraycopy(a2,0,result,a1.length,a2.length);\n return result;\n }\n public static void main(String[ ] args) {\n String monthsString = \"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC\";\n String[] months = monthsString.split(\"(?<=\\\\G.{3})\");\n String daysString = \"SUNMONTUEWEDTHUFRISAT\";\n String[] days = daysString.split(\"(?<=\\\\G.{3})\");\n for (String m : months) {\n out.println(m);\n }\n out.println(\"===\");\n for (String d : days) {\n out.println(d);\n }\n out.println(\"===\");\n String[] results = combineArrays(months, days);\n for (String r : results) {\n out.println(r);\n }\n out.println(\"===\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 60188847,
"author": "Areeha",
"author_id": 6834039,
"author_profile": "https://Stackoverflow.com/users/6834039",
"pm_score": -1,
"selected": false,
"text": "<p>Here is what worked for me:</p>\n\n<pre><code>String[] data=null;\nString[] data2=null;\nArrayList<String> data1 = new ArrayList<String>();\nfor(int i=0; i<2;i++) {\n data2 = input.readLine().split(\",\");\n data1.addAll(Arrays.asList(data2));\n data= data1.toArray(new String[data1.size()]);\n }\n</code></pre>\n"
},
{
"answer_id": 65484015,
"author": "Oleksandr Tsurika",
"author_id": 1663094,
"author_profile": "https://Stackoverflow.com/users/1663094",
"pm_score": 0,
"selected": false,
"text": "<p>I use next method to concatenate any number of arrays of the same type using java 8:</p>\n<pre><code>public static <G> G[] concatenate(IntFunction<G[]> generator, G[] ... arrays) {\n int len = arrays.length;\n if (len == 0) {\n return generator.apply(0);\n } else if (len == 1) {\n return arrays[0];\n }\n int pos = 0;\n Stream<G> result = Stream.concat(Arrays.stream(arrays[pos]), Arrays.stream(arrays[++pos]));\n while (pos < len - 1) {\n result = Stream.concat(result, Arrays.stream(arrays[++pos]));\n }\n return result.toArray(generator);\n}\n</code></pre>\n<p>usage:</p>\n<pre><code> concatenate(String[]::new, new String[]{"one"}, new String[]{"two"}, new String[]{"three"}) \n</code></pre>\n<p>or</p>\n<pre><code> concatenate(Integer[]::new, new Integer[]{1}, new Integer[]{2}, new Integer[]{3})\n</code></pre>\n"
},
{
"answer_id": 65727399,
"author": "rizesky",
"author_id": 6324746,
"author_profile": "https://Stackoverflow.com/users/6324746",
"pm_score": 0,
"selected": false,
"text": "<p>I just discovered this question, sorry very late, and saw a lot of answers that were too far away,\nusing certain libraries, using the feature of converting data from an array to a stream and back to an array and so on. But,\nwe can just use a simple loop and the problem is done</p>\n<pre class=\"lang-java prettyprint-override\"><code>public String[] concat(String[] firstArr,String[] secondArr){\n //if both is empty just return\n if(firstArr.length==0 && secondArr.length==0)return new String[0];\n\n String[] res = new String[firstArr.length+secondArr.length];\n int idxFromFirst=0;\n\n //loop over firstArr, idxFromFirst will be used as starting offset for secondArr\n for(int i=0;i<firstArr.length;i++){\n res[i] = firstArr[i];\n idxFromFirst++;\n }\n\n //loop over secondArr, with starting offset idxFromFirst (the offset track from first array)\n for(int i=0;i<secondArr.length;i++){\n res[idxFromFirst+i]=secondArr[i];\n }\n\n return res;\n }\n</code></pre>\n<p>Thats it all, right? he didnt say he care about the order or anything.\nThis should be the easiest way of it.</p>\n"
},
{
"answer_id": 67960387,
"author": "Lakshitha Kanchana",
"author_id": 6696702,
"author_profile": "https://Stackoverflow.com/users/6696702",
"pm_score": 0,
"selected": false,
"text": "<p>I have a simple method. You don't want to waste your time to research complex java functions or libraries. But the return type should be String.</p>\n<pre><code>String[] f(String[] first, String[] second) {\n\n // Variable declaration part\n int len1 = first.length;\n int len2 = second.length;\n int lenNew = len1 + len2;\n String[] both = new String[len1+len2];\n\n // For loop to fill the array "both"\n for (int i=0 ; i<lenNew ; i++){\n if (i<len1) {\n both[i] = first[i];\n } else {\n both[i] = second[i-len1];\n }\n }\n\n return both;\n\n}\n</code></pre>\n<p>So simple...</p>\n"
},
{
"answer_id": 69157437,
"author": "Rajesh Patel",
"author_id": 7866838,
"author_profile": "https://Stackoverflow.com/users/7866838",
"pm_score": 0,
"selected": false,
"text": "<p>Using Java Collections</p>\n<p>Well, Java doesn't provide a helper method to concatenate arrays. However, since Java 5, the Collections utility class has introduced an addAll(Collection<? super T> c, T… elements) method.</p>\n<p>We can create a List object, then call this method twice to add the two arrays to the list. Finally, we convert the resulting List back to an array:</p>\n<pre><code>static <T> T[] concatWithCollection(T[] array1, T[] array2) {\n List<T> resultList = new ArrayList<>(array1.length + array2.length);\n Collections.addAll(resultList, array1);\n Collections.addAll(resultList, array2);\n\n @SuppressWarnings("unchecked")\n //the type cast is safe as the array1 has the type T[]\n T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0);\n return resultList.toArray(resultArray);\n}\n</code></pre>\n<p>Test</p>\n<pre><code>@Test\npublic void givenTwoStringArrays_whenConcatWithList_thenGetExpectedResult() {\n String[] result = ArrayConcatUtil.concatWithCollection(strArray1, strArray2);\n assertThat(result).isEqualTo(expectedStringArray);\n}\n\n</code></pre>\n"
},
{
"answer_id": 71449230,
"author": "mkemper",
"author_id": 14763038,
"author_profile": "https://Stackoverflow.com/users/14763038",
"pm_score": 0,
"selected": false,
"text": "<p>I see many generic answers with signatures such as public static T[] concat(T[] a, T[] b) {} but these only work on Object arrays, not on primitive arrays, as far as I can work out. The code below works both on Object and primitive arrays, making it more generic...</p>\n<pre><code>public static <T> T concat(T a, T b) {\n //Handles both arrays of Objects and primitives! E.g., int[] out = concat(new int[]{6,7,8}, new int[]{9,10});\n //You get a compile error if argument(s) not same type as output. (int[] in example above)\n //You get a runtime error if output type is not an array, i.e., when you do something like: int out = concat(6,7);\n if (a == null && b == null) return null;\n if (a == null) return b;\n if (b == null) return a;\n final int aLen = Array.getLength(a);\n final int bLen = Array.getLength(b);\n if (aLen == 0) return b;\n if (bLen == 0) return a;\n //From here on we really need to concatenate!\n\n Class componentType = a.getClass().getComponentType();\n final T result = (T)Array.newInstance(componentType, aLen + bLen);\n System.arraycopy(a, 0, result, 0, aLen);\n System.arraycopy(b, 0, result, aLen, bLen);\n return result;\n }\n\n public static void main(String[] args) {\n String[] out1 = concat(new String[]{"aap", "monkey"}, new String[]{"rat"});\n int[] out2 = concat(new int[]{6,7,8}, new int[]{9,10});\n }\n</code></pre>\n"
},
{
"answer_id": 72239759,
"author": "J.R",
"author_id": 3156682,
"author_profile": "https://Stackoverflow.com/users/3156682",
"pm_score": 1,
"selected": false,
"text": "<pre><code> /**\n * With Java Streams\n * @param first First Array\n * @param second Second Array\n * @return Merged Array\n */\n String[] mergeArrayOfStrings(String[] first, String[] second) {\n return Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(String[]::new);\n }\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2948/"
]
| I need to concatenate two `String` arrays in Java.
```
void f(String[] first, String[] second) {
String[] both = ???
}
```
Which is the easiest way to do this? | Here's a simple method that will concatenate two arrays and return the result:
```
public <T> T[] concatenate(T[] a, T[] b) {
int aLen = a.length;
int bLen = b.length;
@SuppressWarnings("unchecked")
T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen);
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
```
Note that it will not work with primitive data types, only with object types.
The following slightly more complicated version works with both object and primitive arrays. It does this by using `T` instead of `T[]` as the argument type.
It also makes it possible to concatenate arrays of two different types by picking the most general type as the component type of the result.
```
public static <T> T concatenate(T a, T b) {
if (!a.getClass().isArray() || !b.getClass().isArray()) {
throw new IllegalArgumentException();
}
Class<?> resCompType;
Class<?> aCompType = a.getClass().getComponentType();
Class<?> bCompType = b.getClass().getComponentType();
if (aCompType.isAssignableFrom(bCompType)) {
resCompType = aCompType;
} else if (bCompType.isAssignableFrom(aCompType)) {
resCompType = bCompType;
} else {
throw new IllegalArgumentException();
}
int aLen = Array.getLength(a);
int bLen = Array.getLength(b);
@SuppressWarnings("unchecked")
T result = (T) Array.newInstance(resCompType, aLen + bLen);
System.arraycopy(a, 0, result, 0, aLen);
System.arraycopy(b, 0, result, aLen, bLen);
return result;
}
```
Here is an example:
```
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, concatenate(new int[] { 1, 2 }, new int[] { 3 }));
Assert.assertArrayEquals(new Number[] { 1, 2, 3f }, concatenate(new Integer[] { 1, 2 }, new Number[] { 3f }));
``` |
80,486 | <p>I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file. </p>
<p>There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results.</p>
<p>I am running my tests using the *Tests.dll mask and NOT using Test Lists (.vsmdi).</p>
| [
{
"answer_id": 80600,
"author": "Martin Woodward",
"author_id": 6438,
"author_profile": "https://Stackoverflow.com/users/6438",
"pm_score": 5,
"selected": true,
"text": "<p>How are you running the tests? Are you using a .vsmdi file or just specifying that you run all tests in *Tests.dll assemblies?</p>\n\n<p>If it is the latter and you are using TFS 2008, then you need to add the following to the and of the first PropertyGroup in your TFSBuild.proj file for the build.</p>\n\n<pre><code><RunConfigFile>$(SolutionRoot)\\TestRunConfig.testrunconfig</RunConfigFile>\n</code></pre>\n\n<p>This points the build at your .testrunconfig so it can pick up the instructions to run code coverage.</p>\n"
},
{
"answer_id": 429561,
"author": "jlo",
"author_id": 48148,
"author_profile": "https://Stackoverflow.com/users/48148",
"pm_score": 1,
"selected": false,
"text": "<p>You'll need the RunConfigFile entry whether you use the .vsmdi file for Test Lists or just specify the assembly file pattern. In that .testrunconfig file you specify the assemblies you want to apply code coverage to.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
]
| I need to know how to turn on Code Coverage when running TFS builds on a solution with a .testrunconfig file.
There is an option in the testrunconfig file that is for code coverage, but when running a TFS build there is no code coverage results.
I am running my tests using the \*Tests.dll mask and NOT using Test Lists (.vsmdi). | How are you running the tests? Are you using a .vsmdi file or just specifying that you run all tests in \*Tests.dll assemblies?
If it is the latter and you are using TFS 2008, then you need to add the following to the and of the first PropertyGroup in your TFSBuild.proj file for the build.
```
<RunConfigFile>$(SolutionRoot)\TestRunConfig.testrunconfig</RunConfigFile>
```
This points the build at your .testrunconfig so it can pick up the instructions to run code coverage. |
80,493 | <p>In C, using the standard Windows API, what is the best way to read an unformatted disk? Specifically, I have an <a href="http://en.wikipedia.org/wiki/MultiMediaCard" rel="nofollow noreferrer">MMC</a> or <a href="http://en.wikipedia.org/wiki/Secure_Digital_card" rel="nofollow noreferrer">SD card</a> with data, but no file system (not FAT16, not FAT32, just raw data). If there was a simple way to open the entire card for byte by byte binary access, that would be great.</p>
<p>Thanks!</p>
| [
{
"answer_id": 80533,
"author": "Kasprzol",
"author_id": 5957,
"author_profile": "https://Stackoverflow.com/users/5957",
"pm_score": 1,
"selected": false,
"text": "<p>You have to open the device file with <a href=\"http://msdn.microsoft.com/en-us/library/aa363858(VS.85).aspx\" rel=\"nofollow noreferrer\">CreateFile</a> and then use <a href=\"http://msdn.microsoft.com/en-us/library/aa365467(VS.85).aspx\" rel=\"nofollow noreferrer\">ReadFile</a>/<a href=\"http://msdn.microsoft.com/en-us/library/aa365468(VS.85).aspx\" rel=\"nofollow noreferrer\">readFileEx</a>. Don't forget to close the file with <a href=\"http://msdn.microsoft.com/en-us/library/ms724211.aspx\" rel=\"nofollow noreferrer\">CloseHandle</a></p>\n"
},
{
"answer_id": 80542,
"author": "szevvy",
"author_id": 11437,
"author_profile": "https://Stackoverflow.com/users/11437",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa363858.aspx\" rel=\"nofollow noreferrer\">CreateFile function reference on MSDN</a></p>\n\n<p>Scroll down to \"Physical Disks and Volumes\" - note the security restrictions on Vista do not apply for voulmes without a filesystem, so you'll be fine even on Vista under the conditions you have given.</p>\n"
},
{
"answer_id": 81420,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 3,
"selected": true,
"text": "<p>I would go with</p>\n\n<pre><code>HANDLE drive = CreateFile(_T(\"\\\\.\\PhysicalDrive0\"), GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);\n// error handling\nDWORD br = 0;\nDISK_GEOMETRY dg;\nDeviceIOControl(drive, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0, &dg, sizeof(dg), &br, 0);\n//\nLARGE_INTEGER pos;\npos.QuadPart = static_cast<LONGLONG>(sectorToRead) * dg.BytesPerSector;\nSetFilePointerEx(drive, pos, 0, FILE_BEGIN);\nconst bool success = ReadFile(drive, sectorData, dg.BytesPerSector, &br) && br == dg.BytesPerSector;\n//\nCloseHandle(drive);\n</code></pre>\n\n<p>Please note that in order to verify that you've successfully read a sector you must verify that the read byte count corresponds to the number of bytes you wanted to read, i.e. in my experience ReadFile() on a physical disk can return TRUE even when no bytes are read (or maybe I just have a buggy driver).</p>\n\n<p>The problem that remains is to determine your drive number (0 as is used in my example refers to C: which is probably not what you want). I don't know how to do that, but if you only have one drive connected which is not formatted, it ought to be possible by calling opening each PhysicalDrive in order and calling DeviceIOControl() with <code>IOCTL_DISK_GET_DRIVE_LAYOUT_EX</code> as a command:</p>\n\n<pre><code>DRIVE_LAYOUT_INFORMATION_EX dl;\nDeviceIOControl(drive, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, 0, &dl, sizeof(dl), &br, 0);\nif(dl.PartitionStyle == PARTITION_STYLE_RAW)\n{\n // found correct disk\n}\n</code></pre>\n\n<p>But that's just a guess.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3175/"
]
| In C, using the standard Windows API, what is the best way to read an unformatted disk? Specifically, I have an [MMC](http://en.wikipedia.org/wiki/MultiMediaCard) or [SD card](http://en.wikipedia.org/wiki/Secure_Digital_card) with data, but no file system (not FAT16, not FAT32, just raw data). If there was a simple way to open the entire card for byte by byte binary access, that would be great.
Thanks! | I would go with
```
HANDLE drive = CreateFile(_T("\\.\PhysicalDrive0"), GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
// error handling
DWORD br = 0;
DISK_GEOMETRY dg;
DeviceIOControl(drive, IOCTL_DISK_GET_DRIVE_GEOMETRY, 0, 0, &dg, sizeof(dg), &br, 0);
//
LARGE_INTEGER pos;
pos.QuadPart = static_cast<LONGLONG>(sectorToRead) * dg.BytesPerSector;
SetFilePointerEx(drive, pos, 0, FILE_BEGIN);
const bool success = ReadFile(drive, sectorData, dg.BytesPerSector, &br) && br == dg.BytesPerSector;
//
CloseHandle(drive);
```
Please note that in order to verify that you've successfully read a sector you must verify that the read byte count corresponds to the number of bytes you wanted to read, i.e. in my experience ReadFile() on a physical disk can return TRUE even when no bytes are read (or maybe I just have a buggy driver).
The problem that remains is to determine your drive number (0 as is used in my example refers to C: which is probably not what you want). I don't know how to do that, but if you only have one drive connected which is not formatted, it ought to be possible by calling opening each PhysicalDrive in order and calling DeviceIOControl() with `IOCTL_DISK_GET_DRIVE_LAYOUT_EX` as a command:
```
DRIVE_LAYOUT_INFORMATION_EX dl;
DeviceIOControl(drive, IOCTL_DISK_GET_DRIVE_LAYOUT_EX, 0, 0, &dl, sizeof(dl), &br, 0);
if(dl.PartitionStyle == PARTITION_STYLE_RAW)
{
// found correct disk
}
```
But that's just a guess. |
80,541 | <p>The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.</p>
<p>For instance, how would I find out that there are 10 week days in between <code>31/08/2008</code> and <code>13/09/2008</code>?</p>
| [
{
"answer_id": 80553,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 0,
"selected": false,
"text": "<p>One way would be to convert the dates to unix timestamps using strtotime(...), subtracting the results and div'ing with 86400 (24*60*60):</p>\n\n<pre><code>$dif_in_seconds = abs(strtotime($a) - strtotime($b));\n$daysbetween = $dif_in_seconds / 86400;\n</code></pre>\n\n<p>ETA: Oh.. You meant weekdays as in Mon-Fri.. Didn't see that at first..</p>\n"
},
{
"answer_id": 80557,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 0,
"selected": false,
"text": "<p>The best way is to iterate through all dates in between the given date range, and get the day of week for each date. If it's a week day, increment a certain counter. At the end of the process you get the number of weekdays.</p>\n\n<p>The PHP functions mktime() and date() (for working with UNIX timestamps) are your friends here.</p>\n"
},
{
"answer_id": 80578,
"author": "kobusb",
"author_id": 1620,
"author_profile": "https://Stackoverflow.com/users/1620",
"pm_score": 3,
"selected": true,
"text": "<pre><code> $datefrom = strtotime($datefrom, 0);\n $dateto = strtotime($dateto, 0);\n\n $difference = $dateto - $datefrom;\n\n $days_difference = floor($difference / 86400);\n $weeks_difference = floor($days_difference / 7); // Complete weeks\n\n $first_day = date(\"w\", $datefrom);\n $days_remainder = floor($days_difference % 7);\n\n $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?\n if ($odd_days > 7) { // Sunday\n $days_remainder--;\n }\n if ($odd_days > 6) { // Saturday\n $days_remainder--;\n }\n\n $datediff = ($weeks_difference * 5) + $days_remainder;\n</code></pre>\n\n<p>From here: <a href=\"http://www.addedbytes.com/php/php-datediff-function/\" rel=\"nofollow noreferrer\">http://www.addedbytes.com/php/php-datediff-function/</a></p>\n"
},
{
"answer_id": 80627,
"author": "Matej",
"author_id": 11457,
"author_profile": "https://Stackoverflow.com/users/11457",
"pm_score": 2,
"selected": false,
"text": "<p>If you are creating an invoicing system, you have to think about the bank holidays, Easter, etc. It is not simple to compute it. </p>\n\n<p>The best solution I have ever seen is to pregenerate a table with days and its type to SQL database (row per day = 365 rows per year) and then perform simple count query with proper selection (WHERE clause). </p>\n\n<p>You can find this solution fully described in <em>Joe Celko's Thinking in Sets: Auxiliary, Temporal, and Virtual Tables in SQL</em></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/131/"
]
| The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday.
For instance, how would I find out that there are 10 week days in between `31/08/2008` and `13/09/2008`? | ```
$datefrom = strtotime($datefrom, 0);
$dateto = strtotime($dateto, 0);
$difference = $dateto - $datefrom;
$days_difference = floor($difference / 86400);
$weeks_difference = floor($days_difference / 7); // Complete weeks
$first_day = date("w", $datefrom);
$days_remainder = floor($days_difference % 7);
$odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?
if ($odd_days > 7) { // Sunday
$days_remainder--;
}
if ($odd_days > 6) { // Saturday
$days_remainder--;
}
$datediff = ($weeks_difference * 5) + $days_remainder;
```
From here: <http://www.addedbytes.com/php/php-datediff-function/> |
80,592 | <pre><code>public class Test {
public static void main(String[] args) {
}
}
class Outer {
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
}
}
</code></pre>
<p>Can someone tell me how to print the message from <code>bMethod</code>?</p>
| [
{
"answer_id": 80615,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>You can only instantiate <code>MethodLocalInner</code> within <code>aMethod</code>. So do </p>\n\n<pre><code>void aMethod() {\n\n class MethodLocalInner {\n\n void bMethod() {\n\n System.out.println(\"Inside method-local bMethod\");\n }\n }\n\n MethodLocalInner foo = new MethodLocalInner(); // Default Constructor\n foo.bMethod();\n\n}\n</code></pre>\n"
},
{
"answer_id": 80616,
"author": "Benno Richters",
"author_id": 3565,
"author_profile": "https://Stackoverflow.com/users/3565",
"pm_score": 1,
"selected": false,
"text": "<p>Within the method <em>aMethod</em> after the declaration of the class <em>MethodLocalInner</em> you could for instance do the following call:</p>\n\n<pre><code>new MethodLocalInner().bMethod();\n</code></pre>\n"
},
{
"answer_id": 80625,
"author": "Lior",
"author_id": 13321,
"author_profile": "https://Stackoverflow.com/users/13321",
"pm_score": 1,
"selected": false,
"text": "<p>Why don't you just create an instance of <code>MethodLocalInner</code>, in <code>aMethod</code>, and call <code>bMethod</code> on the new instance?</p>\n"
},
{
"answer_id": 19292897,
"author": "Fco Javier Perez",
"author_id": 2866485,
"author_profile": "https://Stackoverflow.com/users/2866485",
"pm_score": 0,
"selected": false,
"text": "<p>You need to call new Outer().aMethod() inside your main method. You also need to add a reference to MethodLocalInner().bMethod() inside your aMethod(), like this:</p>\n\n<pre><code>public class Test {\n public static void main(String[] args) {\n new Outer().aMethod();\n }\n}\n\n\nvoid aMethod() {\n class MethodLocalInner {\n void bMethod() {\n System.out.println(\"Inside method-local bMethod\");\n }\n }\n new MethodLocalInner().bMethod();\n}\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
]
| ```
public class Test {
public static void main(String[] args) {
}
}
class Outer {
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
}
}
```
Can someone tell me how to print the message from `bMethod`? | You can only instantiate `MethodLocalInner` within `aMethod`. So do
```
void aMethod() {
class MethodLocalInner {
void bMethod() {
System.out.println("Inside method-local bMethod");
}
}
MethodLocalInner foo = new MethodLocalInner(); // Default Constructor
foo.bMethod();
}
``` |
80,593 | <p>I have a FlowDocument in a standard WPF application window where I have some text, and in this text some hyperlinks and buttons.</p>
<p>The problem is, if I put this FlowDocument inside anything <strong>except</strong> a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentpageviewer.aspx" rel="nofollow noreferrer">FlowDocumentPageViewer</a> the hyperlinks and buttons are disabled ("grayed out").</p>
<pre><code><FlowDocumentScrollViewer>
<FlowDocument>
<Paragraph>
Hello, World!
<Hyperlink NavigateUri="some-uri">click me</Hyperlink>
<Button Click="myButton_Click" Content="Click me too!" />
</Paragraph>
</FlowDocument>
</FlowDocumentScrollViewer>
</code></pre>
<p>The above will work and the link will be clickable. However, I don't want the full pageviewer thing since it will show navigation buttons (back/forward) zoom and it also has a weird column behavior.</p>
<p>I want it in a simple <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentscrollviewer.aspx" rel="nofollow noreferrer">FlowDocumentScrollViewer</a> (or anything else that just displays the text without additional fuzz).</p>
<p><strong>EDIT:</strong>
It's not only hyperlinks that is the problem. <em>Any</em> control, like Button, ListBox, ComboBox - anything that the user can interact with - is "grayed out" regardless of the IsEnabled properties if the FlowDocument is inside a FlowDocumentScrollViewer.</p>
<p><strong>EDIT2:</strong>
Alright, it must have been a mistake or something from my end, because I ended up rewriting the control and now it works. I guess there was some sort if IsEnabled=False somewhere in the visual tree that caused this.</p>
| [
{
"answer_id": 80757,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 0,
"selected": false,
"text": "<p>I am wondering whether you expecing some thing like this?</p>\n\n<pre><code><TextBlock>\n<Hyperlink>\n <Run Text=\"Test link\"/>\n</Hyperlink >\n</code></pre>\n\n<p></p>\n\n<pre><code></TextBlock>\n</code></pre>\n"
},
{
"answer_id": 153713,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 3,
"selected": true,
"text": "<p>I'm using a FlowDocumentScrollViewer for my about box:</p>\n\n<pre><code><FlowDocumentScrollViewer VerticalScrollBarVisibility=\"Auto\">\n <FlowDocument>\n <Paragraph>\n <!-- ... -->\n</code></pre>\n\n<p>I don't have any of the controls or issues you mention.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8521/"
]
| I have a FlowDocument in a standard WPF application window where I have some text, and in this text some hyperlinks and buttons.
The problem is, if I put this FlowDocument inside anything **except** a [FlowDocumentPageViewer](http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentpageviewer.aspx) the hyperlinks and buttons are disabled ("grayed out").
```
<FlowDocumentScrollViewer>
<FlowDocument>
<Paragraph>
Hello, World!
<Hyperlink NavigateUri="some-uri">click me</Hyperlink>
<Button Click="myButton_Click" Content="Click me too!" />
</Paragraph>
</FlowDocument>
</FlowDocumentScrollViewer>
```
The above will work and the link will be clickable. However, I don't want the full pageviewer thing since it will show navigation buttons (back/forward) zoom and it also has a weird column behavior.
I want it in a simple [FlowDocumentScrollViewer](http://msdn.microsoft.com/en-us/library/system.windows.controls.flowdocumentscrollviewer.aspx) (or anything else that just displays the text without additional fuzz).
**EDIT:**
It's not only hyperlinks that is the problem. *Any* control, like Button, ListBox, ComboBox - anything that the user can interact with - is "grayed out" regardless of the IsEnabled properties if the FlowDocument is inside a FlowDocumentScrollViewer.
**EDIT2:**
Alright, it must have been a mistake or something from my end, because I ended up rewriting the control and now it works. I guess there was some sort if IsEnabled=False somewhere in the visual tree that caused this. | I'm using a FlowDocumentScrollViewer for my about box:
```
<FlowDocumentScrollViewer VerticalScrollBarVisibility="Auto">
<FlowDocument>
<Paragraph>
<!-- ... -->
```
I don't have any of the controls or issues you mention. |
80,609 | <p>I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have <strong>document1</strong>:</p>
<pre><code><mapping>
<key value="assigned">
<a/>
</key>
<whatever attribute="x">
<k/>
<j/>
</whatever>
</mapping>
</code></pre>
<p>and <strong>document2</strong>:</p>
<pre><code><mapping>
<key value="identity">
<a/>
<b/>
</key>
</mapping>
</code></pre>
<p>I want to merge the two like this:</p>
<pre><code><mapping>
<key value="identity">
<a/>
<b/>
</key>
<whatever attribute="x">
<k/>
<j/>
</whatever>
</mapping>
</code></pre>
<p>I prefer <strong>Java</strong> or <strong>XSLT</strong>-based solutions, <strong>ant</strong> will do fine, but if there's an easy way to do that in <strong>Rake</strong>, <strong>Ruby</strong> or <strong>Python</strong> please don't be shy :-)</p>
<p><strong>EDIT:</strong> actually I find I'd rather use an automated tool/script, even <a href="http://web.archive.org/web/20100818203850/http://stackoverflow.com:80/questions/58640/great-programming-quotes" rel="nofollow noreferrer">writing it by myself</a>, because manually merging some 30 XML files is a bit unwieldy... :-(</p>
| [
{
"answer_id": 80656,
"author": "moobaa",
"author_id": 3569,
"author_profile": "https://Stackoverflow.com/users/3569",
"pm_score": 1,
"selected": false,
"text": "<p>Unsure as to whether you want to do this programatically or not.</p>\n\n<p>Edit: Ah, I posted that before the Edit. Don't I look like an idiot now! ;)</p>\n\n<p>If you just want to merge two files together, IBM have an <a href=\"http://www.alphaworks.ibm.com/tech/xmldiffmerge\" rel=\"nofollow noreferrer\">XML Diff and Merge Tool</a>, and there's also Altova's <a href=\"http://www.altova.com/products/diffdog/diff_merge_tool.html\" rel=\"nofollow noreferrer\">DiffDog</a>.</p>\n"
},
{
"answer_id": 174071,
"author": "Craig.Nicol",
"author_id": 1404,
"author_profile": "https://Stackoverflow.com/users/1404",
"pm_score": 4,
"selected": true,
"text": "<p>If you like XSLT, there's a nice merge script I've used before at:\n<a href=\"http://web.archive.org/web/20160809092524/http://www2.informatik.hu-berlin.de/~obecker/XSLT/\" rel=\"nofollow noreferrer\">Oliver's XSLT page</a></p>\n"
},
{
"answer_id": 3537136,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I know this is an old thread, but <a href=\"http://www.projectmerge.com\" rel=\"nofollow noreferrer\">Project: Merge</a> can do this for you. It can merge two XML files together, and can be run from the command line, so you can batch everything up together, run it and just resolve any conflicts (such as the changing attribute value of 'key' in your above example) manually with a few clicks. (You can tell it to run silently providing there are no conflicts.)</p>\n\n<p>It can perform two-way and three-way comparisons of XML files and two-way and three-way merges. (Where a three-way operation assumes the two files being compared/merged have a common ancestor.)</p>\n"
},
{
"answer_id": 27258761,
"author": "Sławek",
"author_id": 1116153,
"author_profile": "https://Stackoverflow.com/users/1116153",
"pm_score": 2,
"selected": false,
"text": "<p>Check <a href=\"https://github.com/atteo/xml-combiner\" rel=\"nofollow noreferrer\">XmlCombiner</a> which is a Java library that implements XML merging in exactly this way. It is loosely based on a similar functionality offered by <a href=\"https://github.com/codehaus-plexus/plexus-utils/blob/master/src/main/java/org/codehaus/plexus/util/xml/Xpp3DomUtils.java\" rel=\"nofollow noreferrer\">plexus-utils</a> library.</p>\n\n<p>XmlCombiner default convention is to overwrite the overlapping attributes and elements. But the exact merging behavior can be altered using special <a href=\"https://github.com/atteo/xml-combiner#controlling-the-merging-behavior\" rel=\"nofollow noreferrer\">'combine.self' and 'combine.children'</a> attributes.</p>\n\n<p>Usage:</p>\n\n<pre><code>import org.atteo.xmlcombiner.XmlCombiner;\n\n// create combiner\nXmlCombiner combiner = new XmlCombiner();\n// combine files\ncombiner.combine(firstFile);\ncombiner.combine(secondFile);\n// store the result\ncombiner.buildDocument(resultFile);\n</code></pre>\n\n<p>Disclaimer: I am the author.</p>\n"
},
{
"answer_id": 43150501,
"author": "mwallner",
"author_id": 2279385,
"author_profile": "https://Stackoverflow.com/users/2279385",
"pm_score": 1,
"selected": false,
"text": "<p>(also using <a href=\"http://web.archive.org/web/20160809092524/http://www2.informatik.hu-berlin.de/~obecker/XSLT/\" rel=\"nofollow noreferrer\">Oliver's XSLT stlyesheets</a>)</p>\n\n<p>XSLT merge from PowerShell:</p>\n\n<pre><code>param(\n[Parameter(Mandatory = $True)][string]$file1,\n[Parameter(Mandatory = $True)][string]$file2,\n[Parameter(Mandatory = $True)][string]$path\n)\n\n# using only abs paths .. just to be safe\n$file1 = Join-Path $(Get-Location) $file1\n$file2 = Join-Path $(Get-Location) $file2\n$path = Join-Path $(Get-Location) $path\n\n# awesome xsl stylesheet from Oliver Becker\n# http://web.archive.org/web/20160502194427/http://www2.informatik.hu-berlin.de/~obecker/XSLT/merge/merge.xslt\n$xsltfile = Join-Path $(Get-Location) \"merge.xslt\"\n\n$XsltSettings = New-Object System.Xml.Xsl.XsltSettings\n$XsltSettings.EnableDocumentFunction = 1\n\n$xslt = New-Object System.Xml.Xsl.XslCompiledTransform;\n$xslt.Load($xsltfile , $XsltSettings, $(New-Object System.Xml.XmlUrlResolver))\n\n[System.Xml.Xsl.XsltArgumentList]$al = [System.Xml.Xsl.XsltArgumentList]::new()\n$al.AddParam(\"with\", \"\", $file2)\n$al.AddParam(\"replace\", \"\", \"true\")\n\n[System.Xml.XmlWriter]$xmlwriter = [System.Xml.XmlWriter]::Create($path)\n$xslt.Transform($file1, $al, $xmlwriter)\n</code></pre>\n\n<p>Using 'plain ol' Saxon:</p>\n\n<pre><code>java -jar saxon9he.jar .\\FileA.xml .\\merge.xslt with=FileB.xml replace=true\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
]
| I need to "merge" two XML documents, overwriting the overlapsed attributes and elements. For instance if I have **document1**:
```
<mapping>
<key value="assigned">
<a/>
</key>
<whatever attribute="x">
<k/>
<j/>
</whatever>
</mapping>
```
and **document2**:
```
<mapping>
<key value="identity">
<a/>
<b/>
</key>
</mapping>
```
I want to merge the two like this:
```
<mapping>
<key value="identity">
<a/>
<b/>
</key>
<whatever attribute="x">
<k/>
<j/>
</whatever>
</mapping>
```
I prefer **Java** or **XSLT**-based solutions, **ant** will do fine, but if there's an easy way to do that in **Rake**, **Ruby** or **Python** please don't be shy :-)
**EDIT:** actually I find I'd rather use an automated tool/script, even [writing it by myself](http://web.archive.org/web/20100818203850/http://stackoverflow.com:80/questions/58640/great-programming-quotes), because manually merging some 30 XML files is a bit unwieldy... :-( | If you like XSLT, there's a nice merge script I've used before at:
[Oliver's XSLT page](http://web.archive.org/web/20160809092524/http://www2.informatik.hu-berlin.de/~obecker/XSLT/) |
80,619 | <p>While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.</p>
<p>This led me to think about the best way to group 'helper' functions together. The Java/C# way would be to use a class of static functions with a private constructor, e.g.:</p>
<pre><code>class Helper
{
private:
Helper() { }
public:
static int HelperFunc1();
static int HelperFunc2();
};
</code></pre>
<p>However, being C++ you could also use a namespace:</p>
<pre><code>namespace Helper
{
int HelperFunc1();
int HelperFunc2();
}
</code></pre>
<p>In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are. If used the class approach for example, would there be any overheads?</p>
| [
{
"answer_id": 80636,
"author": "Don Neufeld",
"author_id": 13097,
"author_profile": "https://Stackoverflow.com/users/13097",
"pm_score": 2,
"selected": false,
"text": "<p>The main advantage to using a namespace is that you can reopen it and add more stuff later, you can't do that with a class. This makes this approach better for loosely coupled helpers (for example you could have a Helpers namespace for your entire library, much like all of STL is in ::std)</p>\n\n<p>The main advantage of a class is that you can nest it inside the class using it, you can't nest a namespace in a class. This makes this approach better for tightly coupled helpers.</p>\n\n<p>You won't have any extra overhead having them in a class vs a namespace.</p>\n"
},
{
"answer_id": 80651,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 6,
"selected": true,
"text": "<p>Overhead is not an issue, namespaces have some advantages though</p>\n\n<ul>\n<li>You can reopen a namespace in another header, grouping things more logically while\nkeeping compile dependencies low</li>\n<li><p>You can use namespace aliasing to your advantage \n(debug/release, platform specific helpers, ....)</p>\n\n<p>e.g. I've done stuff like</p>\n\n<pre><code>namespace LittleEndianHelper {\n void Function();\n}\nnamespace BigEndianHelper {\n void Function();\n}\n\n#if powerpc\n namespace Helper = BigEndianHelper;\n#elif intel\n namespace Helper = LittleEndianHelper;\n#endif\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 80804,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 3,
"selected": false,
"text": "<p>To add to Pieter's excellent response, another advantage of namespaces is that you can forward declare stuff that you put in a namespace somewhere else, especially structs...</p>\n<pre><code>//Header a.h\n// Lots of big header files, spreading throughout your code\nclass foo\n{\n struct bar {/* ... */);\n};\n\n//header b.h\n#include a.h // Required, no way around it, pulls in big headers\nclass b\n{\n //...\n DoSomething(foo::bar);\n};\n</code></pre>\n<p>And with namespaces...</p>\n<pre><code>//Header a.h\n// Big header files\nnamespace foo\n{\n struct bar {/* ... */);\n}\n\n//header b.h\n// Avoid include, instead forward declare \n// (can put forward declares in a _fwd.h file)\nnamespace foo\n{\n struct bar;\n}\n\nclass b\n{\n //...\n // note that foo:bar must be passed by reference or pointer\n void DoSomething(const foo::bar & o);\n};\n</code></pre>\n<p>Forward declares make a big difference to your compile times after small header changes once you end up with a project spanning hundreds of source files.</p>\n<h2>Edit from paercebal</h2>\n<p>The answer was too good to let it die because of an enum error (see comments). I replaced enums (which can be forward-declared only in C++0x, not in today C++) by structs.</p>\n"
},
{
"answer_id": 81316,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>Namespaces offer the additional advantage of Koenig lookup. Using helper classes may make your code more verbose - you usually need to include the helper class name in the call.</p>\n\n<p>Another benefit to namespaces is in readability later on. With classes, you need to include words like \"Helper\" to remind you later that the particular class isn't used to create objects</p>\n\n<p>In practice, there's no overhead in either. After compilation, only the name mangling used differs.</p>\n"
},
{
"answer_id": 88965,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 4,
"selected": false,
"text": "<p>A case where one might use <code>class</code> (or <code>struct</code>) over <code>namespace</code> is when one needs a type, for example:</p>\n\n<pre><code>struct C {\n static int f() { return 33; }\n};\n\nnamespace N {\n int f() { return 9; }\n}\n\ntemplate<typename T>\nint foo() {\n return T::f();\n}\n\nint main() {\n int ret = foo<C>();\n//ret += foo<N>(); // compile error: N is a namespace\n return ret;\n}\n</code></pre>\n"
},
{
"answer_id": 92517,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 2,
"selected": false,
"text": "<p>I tend to use anonymous namespaces when creating helper functions. Since they should (generally) only be seen by the module that cares about them, its a good way to control dependencies.</p>\n"
},
{
"answer_id": 383365,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "<p>Copied/trimmed/reworked part of my answer from <a href=\"https://stackoverflow.com/questions/41590/how-do-you-properly-use-namespaces-in-c#81602\">How do you properly use namespaces in C++?</a>.</p>\n\n<h2>Using \"using\"</h2>\n\n<p>You can use \"using\" to avoid repeating the \"prefixing\" of your helper function. for example:</p>\n\n<pre><code>struct AAA\n{\n void makeSomething() ;\n} ;\n\nnamespace BBB\n{\n void makeSomethingElse() ;\n}\n\nvoid willCompile()\n{\n AAA::makeSomething() ;\n BBB::makeSomethingElse() ;\n}\n\nvoid willCompileAgain()\n{\n using BBB ;\n\n makeSomethingElse() ; // This will call BBB::makeSomethingElse()\n}\n\nvoid WONT_COMPILE()\n{\n using AAA ; // ERROR : Won't compile\n\n makeSomething() ; // ERROR : Won't compile\n}\n</code></pre>\n\n<h2>Namespace Composition</h2>\n\n<p>Namespaces are more than packages. Another example can be found in Bjarne Stroustrup's \"The C++ Programming Language\".</p>\n\n<p>In the \"Special Edition\", at <strong>8.2.8 Namespace Composition</strong>, he describes how you can merge two namespaces AAA and BBB into another one called CCC. Thus CCC becomes an alias for both AAA and BBB:</p>\n\n<pre><code>namespace AAA\n{\n void doSomething() ;\n}\n\nnamespace BBB\n{\n void doSomethingElse() ;\n}\n\nnamespace CCC\n{\n using namespace AAA ;\n using namespace BBB ;\n}\n\nvoid doSomethingAgain()\n{\n CCC::doSomething() ;\n CCC::doSomethingElse() ;\n}\n</code></pre>\n\n<p>You could even import select symbols from different namespaces, to build your own custom namespace interface. I have yet to find a practical use of this, but in theory, it is cool.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80619",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
]
| While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere.
This led me to think about the best way to group 'helper' functions together. The Java/C# way would be to use a class of static functions with a private constructor, e.g.:
```
class Helper
{
private:
Helper() { }
public:
static int HelperFunc1();
static int HelperFunc2();
};
```
However, being C++ you could also use a namespace:
```
namespace Helper
{
int HelperFunc1();
int HelperFunc2();
}
```
In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are. If used the class approach for example, would there be any overheads? | Overhead is not an issue, namespaces have some advantages though
* You can reopen a namespace in another header, grouping things more logically while
keeping compile dependencies low
* You can use namespace aliasing to your advantage
(debug/release, platform specific helpers, ....)
e.g. I've done stuff like
```
namespace LittleEndianHelper {
void Function();
}
namespace BigEndianHelper {
void Function();
}
#if powerpc
namespace Helper = BigEndianHelper;
#elif intel
namespace Helper = LittleEndianHelper;
#endif
``` |
80,650 | <p>How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it?</p>
| [
{
"answer_id": 81954,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 5,
"selected": false,
"text": "<p>The MSDN link is nice, but the security information there isn't complete. The handler registration should contain \"%1\", not %1. This is a security measure, because some URL sources incorrectly decode %20 before invoking your custom protocol handler.</p>\n\n<p>PS. You'll get the entire URL, not just the URL parameters. But the URL might be subject to some mistreatment, besides the already mentioned %20->space conversion. It helps to be conservative in your URL syntax design. Don't throw in random // or you'll get into the mess that file:// is.</p>\n"
},
{
"answer_id": 38205984,
"author": "Matas Vaitkevicius",
"author_id": 1509764,
"author_profile": "https://Stackoverflow.com/users/1509764",
"pm_score": 7,
"selected": false,
"text": "<ol>\n<li><p>Go to <code>Start</code> then in <code>Find</code> type <code>regedit</code> -> it should open Registry editor</p>\n</li>\n<li><p>Click <kbd>Right Mouse</kbd> on <code>HKEY_CLASSES_ROOT</code> then <code>New</code> -> <code>Key</code></p>\n</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/9boI6.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/9boI6.png\" alt=\"enter image description here\" /></a></p>\n<ol start=\"3\">\n<li>In the Key give the lowercase name by which you want urls to be called (in my case it will be <code>testus://sdfsdfsdf</code>) then Click <kbd>Right Mouse</kbd> on <code>testus</code> -> then <code>New</code> -> <code>String Value</code> and add <code>URL Protocol</code> without value.</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/4wLev.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4wLev.png\" alt=\"enter image description here\" /></a></p>\n<ol start=\"4\">\n<li>Then add more entries like you did with protocol ( <kbd>Right Mouse</kbd> <code>New</code> -> <code>Key</code> ) and create hierarchy like <code>testus</code> -> <code>shell</code> -> <code>open</code> -> <code>command</code> and inside <code>command</code> change <code>(Default)</code> to the path where <code>.exe</code> you want to launch is, if you want to pass parameters to your exe then wrap path to exe in <code>""</code> and add <code> "%1"</code> to look like: <code>"c:\\testing\\test.exe" "%1"</code></li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/VbhsZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/VbhsZ.png\" alt=\"enter image description here\" /></a></p>\n<ol start=\"5\">\n<li>To test if it works go to Internet Explorer (not Chrome or Firefox) and enter <code>testus:have_you_seen_this_man</code> this should fire your <code>.exe</code> (give you some prompts that you want to do this - say Yes) and pass into args <code>testus://have_you_seen_this_man</code>.</li>\n</ol>\n<p>Here's sample console app to test:</p>\n<pre><code>using System;\n\nnamespace Testing\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (args!= null && args.Length > 0)\n Console.WriteLine(args[0]);\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n<p>Hope this saves you some time.</p>\n"
},
{
"answer_id": 67330359,
"author": "Shubham Kumar",
"author_id": 15748724,
"author_profile": "https://Stackoverflow.com/users/15748724",
"pm_score": 2,
"selected": false,
"text": "<p>There is an npm module for this purpose.</p>\n<p>link :<a href=\"https://www.npmjs.com/package/protocol-registry\" rel=\"nofollow noreferrer\">https://www.npmjs.com/package/protocol-registry</a></p>\n<p>So to do this in nodejs you just need to run the code below:</p>\n<p>First Install it</p>\n<pre><code>npm i protocol-registry\n</code></pre>\n<p>Then use the code below to register you entry file.</p>\n<pre class=\"lang-js prettyprint-override\"><code>const path = require('path');\n\nconst ProtocolRegistry = require('protocol-registry');\n\nconsole.log('Registering...');\n// Registers the Protocol\nProtocolRegistry.register({\n protocol: 'testproto', // sets protocol for your command , testproto://**\n command: `node ${path.join(__dirname, './index.js')} $_URL_`, // $_URL_ will the replaces by the url used to initiate it\n override: true, // Use this with caution as it will destroy all previous Registrations on this protocol\n terminal: true, // Use this to run your command inside a terminal\n script: false\n}).then(async () => {\n console.log('Successfully registered');\n});\n</code></pre>\n<p>Then suppose someone opens testproto://test\nthen a new terminal will be launched executing :</p>\n<pre><code>node yourapp/index.js testproto://test\n</code></pre>\n<p>It also supports all other operating system.</p>\n"
},
{
"answer_id": 73008905,
"author": "duck",
"author_id": 343311,
"author_profile": "https://Stackoverflow.com/users/343311",
"pm_score": 3,
"selected": false,
"text": "<p>If anyone wants a .reg file for creating the association, see below:</p>\n<pre><code>Windows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\duck]\n"URL Protocol"=""\n[HKEY_CLASSES_ROOT\\duck\\shell]\n[HKEY_CLASSES_ROOT\\duck\\shell\\open]\n[HKEY_CLASSES_ROOT\\duck\\shell\\open\\command] \n@="\\"C:\\\\Users\\\\duck\\\\source\\\\repos\\\\ConsoleApp1\\\\ConsoleApp1\\\\bin\\\\Debug\\\\net6.0\\\\ConsoleApp1.exe\\" \\"%1\\""\n</code></pre>\n<p>Pasted that into notepad, the file -> save as -> duck.reg, and then run it. After running it, when you type <code>duck://arg-here</code> into chrome, ConsoleApp1.exe will run with "arg-here" as an argument. Double slashes are required for the path to the exe and double quotes must be escaped.</p>\n<p>Tested and working on Windows 11 with Edge (the chrome version) and Chrome</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2189521/"
]
| How do I register a custom protocol with Windows so that when clicking a link in an email or on a web page my application is opened and the parameters from the URL are passed to it? | 1. Go to `Start` then in `Find` type `regedit` -> it should open Registry editor
2. Click `Right Mouse` on `HKEY_CLASSES_ROOT` then `New` -> `Key`
[](https://i.stack.imgur.com/9boI6.png)
3. In the Key give the lowercase name by which you want urls to be called (in my case it will be `testus://sdfsdfsdf`) then Click `Right Mouse` on `testus` -> then `New` -> `String Value` and add `URL Protocol` without value.
[](https://i.stack.imgur.com/4wLev.png)
4. Then add more entries like you did with protocol ( `Right Mouse` `New` -> `Key` ) and create hierarchy like `testus` -> `shell` -> `open` -> `command` and inside `command` change `(Default)` to the path where `.exe` you want to launch is, if you want to pass parameters to your exe then wrap path to exe in `""` and add `"%1"` to look like: `"c:\testing\test.exe" "%1"`
[](https://i.stack.imgur.com/VbhsZ.png)
5. To test if it works go to Internet Explorer (not Chrome or Firefox) and enter `testus:have_you_seen_this_man` this should fire your `.exe` (give you some prompts that you want to do this - say Yes) and pass into args `testus://have_you_seen_this_man`.
Here's sample console app to test:
```
using System;
namespace Testing
{
class Program
{
static void Main(string[] args)
{
if (args!= null && args.Length > 0)
Console.WriteLine(args[0]);
Console.ReadKey();
}
}
}
```
Hope this saves you some time. |
80,653 | <p>I may be wrong, but if you are working with SmtpClient.SendAsync in ASP.NET
2.0 and it throws an exception, the thread processing the request waits
indefinitely for the operation to complete.</p>
<p>To reproduce this problem, simply use an invalid SMTP address for the host
that could not be resolved when sending an email.</p>
<p>Note that you should set Page.Async = true to use SendAsync.</p>
<p>If Page.Async is set to false and Send throws an exception the thread
does not block, and the page is processed correctly.</p>
<p>TIA.</p>
| [
{
"answer_id": 80887,
"author": "bzlm",
"author_id": 7724,
"author_profile": "https://Stackoverflow.com/users/7724",
"pm_score": 2,
"selected": false,
"text": "<p><strike></p>\n\n<blockquote>\n <p>Note that you should set Page.Async = true to use SendAsync.</p>\n</blockquote>\n\n<p>Please explain the rationale behind this. Misunderstanding what Page.Async does may be the cause of your problems.</strike></p>\n\n<p>Sorry, I was unable to get an example working that reproduced the problem.</p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/magazine/cc163725.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/magazine/cc163725.aspx</a> (WICKED CODE: Asynchronous Pages in ASP.NET 2.0)</p>\n\n<p><strong>EDIT:</strong> Looking at your code example, I can see that you're not using <code>RegisterAsyncTask()</code> and the <code>PageAsyncTask</code> class. I think you must do this when executing asynchronous tasks on a Page where <code>@Async</code> is set to true. The example from MSDN Magazine looks like this:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n PageAsyncTask task = new PageAsyncTask(\n new BeginEventHandler(BeginAsyncOperation),\n new EndEventHandler(EndAsyncOperation),\n new EndEventHandler(TimeoutAsyncOperation),\n null\n );\n RegisterAsyncTask(task);\n}\n</code></pre>\n\n<p>Inside <code>BeginAsyncOperation</code>, then, should you send a mail asynchronously.</p>\n"
},
{
"answer_id": 83592,
"author": "Olivier MATROT",
"author_id": 15186,
"author_profile": "https://Stackoverflow.com/users/15186",
"pm_score": 0,
"selected": false,
"text": "<p>Here is mine. Give it a try.</p>\n\n<pre><code>public partial class _Default : System.Web.UI.Page\n{\n protected void Page_Load(object sender, EventArgs e)\n {\n // Using an incorrect SMTP server\n SmtpClient client = new SmtpClient(@\"smtp.nowhere.private\");\n // Specify the e-mail sender.\n // Create a mailing address that includes a UTF8 character\n // in the display name.\n MailAddress from = new MailAddress(\"[email protected]\",\n \"SOMEONE\" + (char)0xD8 + \" SOMEWHERE\",\n System.Text.Encoding.UTF8);\n // Set destinations for the e-mail message.\n MailAddress to = new MailAddress(\"[email protected]\");\n // Specify the message content.\n MailMessage message = new MailMessage(from, to);\n message.Body = \"This is a test e-mail message sent by an application. \";\n // Include some non-ASCII characters in body and subject.\n string someArrows = new string(new char[] { '\\u2190', '\\u2191', '\\u2192', '\\u2193' });\n message.Body += Environment.NewLine + someArrows;\n message.BodyEncoding = System.Text.Encoding.UTF8;\n message.Subject = \"test message 1\" + someArrows;\n message.SubjectEncoding = System.Text.Encoding.UTF8;\n // Set the method that is called back when the send operation ends.\n client.SendCompleted += new\n SendCompletedEventHandler(SendCompletedCallback);\n // The userState can be any object that allows your callback \n // method to identify this send operation.\n // For this example, the userToken is a string constant.\n string userState = \"test message1\";\n try\n {\n client.SendAsync(message, userState);\n }\n catch (System.Net.Mail.SmtpException ex)\n {\n Response.Write(string.Format(\"Send Error [{0}].\", ex.InnerException.Message));\n }\n finally\n {\n }\n }\n private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)\n {\n // Get the unique identifier for this asynchronous operation.\n String token = (string)e.UserState;\n\n if (e.Cancelled)\n {\n Response.Write(string.Format(\"[{0}] Send canceled.\", token));\n }\n if (e.Error != null)\n {\n Response.Write(string.Format(\"[{0}] {1}\", token, e.Error.ToString()));\n }\n else\n {\n Response.Write(\"Message sent.\");\n }\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 201596,
"author": "Olivier MATROT",
"author_id": 15186,
"author_profile": "https://Stackoverflow.com/users/15186",
"pm_score": 1,
"selected": false,
"text": "<p>RegisterAsyncTask could not be used.\nLook at the BeginEventHandler delegate:</p>\n\n<p>public delegate IAsyncResult BeginEventHandler(\n Object sender,\n EventArgs e,\n AsyncCallback cb,\n Object extraData\n)</p>\n\n<p>It should return an IAsyncResult.\nNow look at the SmtpClient.SendAsync function :</p>\n\n<p>public void SendAsync(\n MailMessage message,\n Object userToken\n)</p>\n\n<p>There is no return value.</p>\n\n<p>Anyway this is working fine, as long as SmtpClient.SendAsync does not throw an exception.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15186/"
]
| I may be wrong, but if you are working with SmtpClient.SendAsync in ASP.NET
2.0 and it throws an exception, the thread processing the request waits
indefinitely for the operation to complete.
To reproduce this problem, simply use an invalid SMTP address for the host
that could not be resolved when sending an email.
Note that you should set Page.Async = true to use SendAsync.
If Page.Async is set to false and Send throws an exception the thread
does not block, and the page is processed correctly.
TIA. | >
> Note that you should set Page.Async = true to use SendAsync.
>
>
>
Please explain the rationale behind this. Misunderstanding what Page.Async does may be the cause of your problems.
Sorry, I was unable to get an example working that reproduced the problem.
See <http://msdn.microsoft.com/en-us/magazine/cc163725.aspx> (WICKED CODE: Asynchronous Pages in ASP.NET 2.0)
**EDIT:** Looking at your code example, I can see that you're not using `RegisterAsyncTask()` and the `PageAsyncTask` class. I think you must do this when executing asynchronous tasks on a Page where `@Async` is set to true. The example from MSDN Magazine looks like this:
```
protected void Page_Load(object sender, EventArgs e)
{
PageAsyncTask task = new PageAsyncTask(
new BeginEventHandler(BeginAsyncOperation),
new EndEventHandler(EndAsyncOperation),
new EndEventHandler(TimeoutAsyncOperation),
null
);
RegisterAsyncTask(task);
}
```
Inside `BeginAsyncOperation`, then, should you send a mail asynchronously. |
80,657 | <p>In the process of learning <a href="https://en.wikipedia.org/wiki/TinyOS" rel="nofollow noreferrer">TinyOS</a> I have discovered that I am totally clueless about makefiles.</p>
<p>There are many optional compile time features that can be used by way of declaring preprocessor variables.</p>
<p>To use them you have to do things like:</p>
<p><code>CFLAGS="-DPACKET_LINK"</code> this enables a certain feature.</p>
<p>and</p>
<p><code>CFLAGS="-DPACKET_LINK" "-DLOW_POWER"</code> enables two features.</p>
<p>Can someone dissect these lines for me and tell me whats going on? Not in terms of TinyOS, but in terms of makefiles!</p>
| [
{
"answer_id": 80689,
"author": "Ilya",
"author_id": 6807,
"author_profile": "https://Stackoverflow.com/users/6807",
"pm_score": 3,
"selected": false,
"text": "<p>Somewhere in the makefile the CFLAG will be used in compilation line like this:<br>\n<code>$(CC) $(CFLAGS) $(C_INCLUDES) $<</code></p>\n\n<p>and eventually in the execution will be translated to : </p>\n\n<p><code>gcc -DPACKET_LINK -DLOW_POWER -c filename.c -o filename.o</code></p>\n\n<p>This define will be passed to the source code as it was define in the header file </p>\n"
},
{
"answer_id": 80698,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": 5,
"selected": false,
"text": "<p>CFLAGS is a variable that is most commonly used to add arguments to the compiler. In this case, it define macros. </p>\n\n<p>So the <code>-DPACKET_LINK</code> is the equivalent of putting <code>#define PACKET_LINK 1</code> at the top of all .c and .h files in your project. Most likely, you have code inside your project that looks if these macros are defined and does something depending on that:</p>\n\n<pre><code>#ifdef PACKET_LINK\n// This code will be ignored if PACKET_LINK is not defined\ndo_packet_link_stuff();\n#endif\n\n#ifdef LOW_POWER\n// This code will be ignored if LOW_POWER is not defined \nhandle_powersaving_functions();\n#endif\n</code></pre>\n\n<p>If you look further down in your makefile, you should see that <code>$(CFLAGS)</code> is probably used like:</p>\n\n<pre><code>$(CC) $(CFLAGS) ...some-more-arguments...\n</code></pre>\n"
},
{
"answer_id": 80710,
"author": "Flame",
"author_id": 5387,
"author_profile": "https://Stackoverflow.com/users/5387",
"pm_score": 1,
"selected": false,
"text": "<p>-D stands for <em>define</em> (in gcc) at least, which lets you #define on the command line instead of a file somewhere. A common thing to see would be -DDEBUG or -DNDEBUG which respectively activate or disable debugging code.</p>\n"
},
{
"answer_id": 80717,
"author": "Jonas Engström",
"author_id": 7634,
"author_profile": "https://Stackoverflow.com/users/7634",
"pm_score": 2,
"selected": false,
"text": "<p>The -D option set pre-processor variables, so in your case, all code that is in the specified \"#ifdef / #endif\" blocks will be compiled.</p>\n\n<p>I.e.</p>\n\n<pre><code>#ifdef PACKET_LINK\n/* whatever code here */\n#endif\n</code></pre>\n\n<p>The CFLAGS is a variable used in the makefile which will be expanded to it's contents when the compiler is invoked.</p>\n\n<p>E.g.</p>\n\n<pre><code>gcc $(CFLAGS) source.c\n</code></pre>\n"
},
{
"answer_id": 80880,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "<p>Just for completeness in this - if you're using Microsoft's nmake utility, you might not actually see the $(CFLAGS) macro used in the makefile because nmake has some defaults for things like compiling C/C++ files. Among others, the following are pre-defined in nmake (I'm not sure if GNU Make does anything like this), so you might not see it in a working makefile on Windows:</p>\n\n<pre><code>.c.exe:\n commands: $(CC) $(CFLAGS) $<\n\n.c.obj:\n commands: $(CC) $(CFLAGS) /c $<\n\n.cpp.exe:\n commands: $(CXX) $(CXXFLAGS) $<\n\n.cpp.obj:\n commands: $(CXX) $(CXXFLAGS) /c $<\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| In the process of learning [TinyOS](https://en.wikipedia.org/wiki/TinyOS) I have discovered that I am totally clueless about makefiles.
There are many optional compile time features that can be used by way of declaring preprocessor variables.
To use them you have to do things like:
`CFLAGS="-DPACKET_LINK"` this enables a certain feature.
and
`CFLAGS="-DPACKET_LINK" "-DLOW_POWER"` enables two features.
Can someone dissect these lines for me and tell me whats going on? Not in terms of TinyOS, but in terms of makefiles! | CFLAGS is a variable that is most commonly used to add arguments to the compiler. In this case, it define macros.
So the `-DPACKET_LINK` is the equivalent of putting `#define PACKET_LINK 1` at the top of all .c and .h files in your project. Most likely, you have code inside your project that looks if these macros are defined and does something depending on that:
```
#ifdef PACKET_LINK
// This code will be ignored if PACKET_LINK is not defined
do_packet_link_stuff();
#endif
#ifdef LOW_POWER
// This code will be ignored if LOW_POWER is not defined
handle_powersaving_functions();
#endif
```
If you look further down in your makefile, you should see that `$(CFLAGS)` is probably used like:
```
$(CC) $(CFLAGS) ...some-more-arguments...
``` |
80,677 | <p>One of the best tips for using vim that I have learned so far has been that one can press <kbd>Ctrl</kbd>+<kbd>C</kbd> or <kbd>Ctrl</kbd>+<kbd>[</kbd> instead of the <kbd>Esc</kbd> key. However I use a dvorak keyboard so <kbd>Ctrl</kbd>+<kbd>[</kbd> is a little out of reach for me as well so I mostly use <kbd>Ctrl</kbd>+<kbd>C</kbd>. Now I've read somewhere that these two key combinations don't actually have exactly the same behaviour and that it is better to use <kbd>Ctrl</kbd>+<kbd>[</kbd>. I haven't come across any problems so far though so I'd like to know what exactly is the difference between the two?</p>
| [
{
"answer_id": 80761,
"author": "jeannicolas",
"author_id": 14981,
"author_profile": "https://Stackoverflow.com/users/14981",
"pm_score": 4,
"selected": false,
"text": "<p>According to Vim's documentation, <kbd>Ctrl</kbd>+<kbd>C</kbd> does not check for abbreviations and does not trigger the <code>InsertLeave</code> autocommand event while <kbd>Ctrl</kbd>+<kbd>[</kbd> does.</p>\n\n<p>One option is to use the following to remap <kbd>Ctrl</kbd>+<kbd>C</kbd></p>\n\n<pre><code>inoremap <C-c> <Esc><Esc>\n</code></pre>\n"
},
{
"answer_id": 80826,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 1,
"selected": false,
"text": "<p>As it turns out, <code><C-[></code> is exactly identical to Esc, they are the same character. So no need to wonder about any difference there. :)</p>\n"
},
{
"answer_id": 11333911,
"author": "weronika",
"author_id": 456876,
"author_profile": "https://Stackoverflow.com/users/456876",
"pm_score": 2,
"selected": false,
"text": "<p>Extremely late answer, but I just had the same question and found one practical example which helps explain the difference, so why not. </p>\n\n<p>If you select a visual block and then change it with <code>c</code> or append something to the end of it with <code>A</code>, if you then exit with <code><Esc></code>, the same change will happen on all the lines of the visual block (which is really useful! See <code>:help v_b_A</code>); if you exit with <code><C-c></code>, this doesn't happen, only one line gets the change. There are probably other similar things I didn't realize I was missing with <code><C-c></code>...</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13060/"
]
| One of the best tips for using vim that I have learned so far has been that one can press `Ctrl`+`C` or `Ctrl`+`[` instead of the `Esc` key. However I use a dvorak keyboard so `Ctrl`+`[` is a little out of reach for me as well so I mostly use `Ctrl`+`C`. Now I've read somewhere that these two key combinations don't actually have exactly the same behaviour and that it is better to use `Ctrl`+`[`. I haven't come across any problems so far though so I'd like to know what exactly is the difference between the two? | According to Vim's documentation, `Ctrl`+`C` does not check for abbreviations and does not trigger the `InsertLeave` autocommand event while `Ctrl`+`[` does.
One option is to use the following to remap `Ctrl`+`C`
```
inoremap <C-c> <Esc><Esc>
``` |
80,691 | <p>I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that</p>
<pre><code>void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int x = x0; x < x1; x += step)
{
MoveToEx(dc, x, y0, NULL);
LineTo(dc, x, y1);
}
}
void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int y = y0; y < y1; y += step)
{
MoveToEx(dc, x0, y, NULL);
LineTo(dc, x1, y);
}
}
</code></pre>
<p>So if I decide to add some fancy stuff, like antialiasing or merely change drawing pencil or whatever I'll have to put the same code in both of them and it's code duplication and it's bad we all know why.</p>
<p>My question is how would you rewrite these two functions into a single one to avoid this problem?</p>
| [
{
"answer_id": 80722,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my own solution</p>\n\n<pre><code>\nclass CoordGenerator\n{\npublic:\n CoordGenerator(int _from, int _to, int _step)\n :from(_from), to(_to), step(_step), pos(_from){}\n virtual POINT GetPoint00() const = 0;\n virtual POINT GetPoint01() const = 0;\n bool Next()\n {\n if(pos > step) return false;\n pos += step;\n }\nprotected:\n int from;\n int to;\n int step;\n int pos;\n};\n\nclass GenX: public CoordGenerator\n{\npublic:\n GenX(int x0, int x1, int step, int _y0, int _y1)\n :CoordGenerator(x0, x1, step),y0(_y0), y1(_y1){}\n virtual POINT GetPoint00() const\n {\n const POINT p = {pos, y0};\n return p;\n }\n virtual POINT GetPoint01() const\n {\n const POINT p = {pos, y1};\n return p;\n }\nprivate:\n int y0;\n int y1;\n};\n\nclass GenY: public CoordGenerator\n{\npublic:\n GenY(int y0, int y1, int step, int _x0, int _x1)\n :CoordGenerator(y0, y1, step),x0(_x0), x1(_x1){}\n virtual POINT GetPoint00() const\n {\n const POINT p = {x0, pos};\n return p;\n }\n virtual POINT GetPoint01() const\n {\n const POINT p = {x1, pos};\n return p;\n }\nprivate:\n int x1;\n int x0;\n};\n\nvoid DrawScale(HDC dc, CoordGenerator* g)\n{\n do\n {\n POINT p = g->GetPoint00();\n MoveToEx(dc, p.x, p.y, 0);\n p = g->GetPoint01();\n LineTo(dc, p.x, p.y);\n }while(g->Next());\n}\n</code></pre>\n\n<p>But I it seems to me too complicated for such a tiny problem, so I'm looking forward to still see your solutions.</p>\n"
},
{
"answer_id": 80750,
"author": "Matej",
"author_id": 11457,
"author_profile": "https://Stackoverflow.com/users/11457",
"pm_score": 3,
"selected": false,
"text": "<p>Why you just do not extract the body of the for cycle into a separate function? Then you can do the funny stuff in the extracted function. </p>\n\n<pre><code>void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)\n{\n for(int x = x0; x < x1; x += step)\n {\n DrawScale(dc, x, y0, x, y1);\n }\n}\n\nvoid DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)\n{\n for(int y = y0; y < y1; y += step)\n {\n DrawScale(dc, x0, y, x1, y);\n }\n}\n\nprivate void DrawScale(HDC dc, int x0, int y0, int x1, int y1)\n{\n //Add funny stuff here\n\n MoveToEx(dc, x0, y0, NULL);\n LineTo(dc, x1, y1);\n\n //Add funny stuff here\n}\n</code></pre>\n"
},
{
"answer_id": 80755,
"author": "NeARAZ",
"author_id": 6799,
"author_profile": "https://Stackoverflow.com/users/6799",
"pm_score": 0,
"selected": false,
"text": "<p>Well, an obvious \"solution\" would be to make a single function and add one extra parameter (of enum-like type). And then do an if() or switch() inside, and perform the appropriate actions. Because hey, the <em>functionality</em> of the functions is different, so you have to do those different actions <em>somewhere</em>.</p>\n\n<p>However, this adds runtime complexity (check things at runtime) in a place that could be just better checked at compile time.</p>\n\n<p>I don't understand what's the problem in adding extra parameters in the future in both (or more functions). It goes like this:</p>\n\n<ol>\n<li>add more parameters to all functions</li>\n<li>compile your code, it won't compile in a bunch of places because it does not pass new parameters.</li>\n<li>fix all places that call those functions by passing new parameters.</li>\n<li>profit! :)</li>\n</ol>\n\n<p>If it's C++, of course you could make the function be a template, and instead adding an extra parameter, you add a template parameter, and then specialize template implementations to do different things. But this is just obfuscating the point, in my opinion. Code becomes harder to understand, and the process of extending it with more parameters is still <em>exactly</em> the same:</p>\n\n<ol>\n<li>add extra parameters</li>\n<li>compile code, it won't compile in a bunch of places</li>\n<li>fix all places that call that function</li>\n</ol>\n\n<p>So you've won nothing, but made code harder to understand. Not a worthy goal, IMO.</p>\n"
},
{
"answer_id": 80760,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "<p>I think I'd move:</p>\n\n<pre><code> MoveToEx(dc, x0, y, NULL);\n LineTo(dc, x1, y);\n</code></pre>\n\n<p>into their own function DrawLine(x0,y0,x0,y0), which you can call from each of the existing functions.</p>\n\n<p>Then there's one place to add extra drawing effects?</p>\n"
},
{
"answer_id": 80906,
"author": "Igor Semenov",
"author_id": 11401,
"author_profile": "https://Stackoverflow.com/users/11401",
"pm_score": 0,
"selected": false,
"text": "<p>A little templates... :)</p>\n\n<pre><code>void DrawLine(HDC dc, int x0, int y0, int x0, int x1)\n{\n // anti-aliasing stuff\n MoveToEx(dc, x0, y0, NULL);\n LineTo(dc, x1, y1);\n}\n\nstruct DrawBinderX\n{\n DrawBinderX(int y0, int y1) : y0_(y0), y1_(y1) {}\n\n void operator()(HDC dc, int i)\n {\n DrawLine(dc, i, y0_, i, y1_);\n }\n\nprivate:\n int y0_;\n int y1_;\n\n};\n\nstruct DrawBinderY\n{\n DrawBinderX(int x0, int x1) : x0_(x0), x1_(x1) {}\n\n void operator()(HDC dc, int i)\n {\n DrawLine(dc, x0_, i, x1_, i);\n }\n\nprivate:\n int x0_;\n int x1_;\n\n};\n\ntemplate< class Drawer >\nvoid DrawScale(Drawer drawer, HDC dc, int from, int to, int step)\n{\n for (int i = from; i < to; i += step)\n {\n drawer(dc, i);\n }\n}\n\nvoid DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)\n{\n DrawBindexX drawer(y0, y1);\n DrawScale(drawer, dc, x0, x1, step);\n}\n\nvoid DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)\n{\n DrawBindexY drawer( x0, x1 );\n DrawScale(drawer, dc, y0, y1, step);\n}\n</code></pre>\n"
},
{
"answer_id": 81827,
"author": "ppi",
"author_id": 2044155,
"author_profile": "https://Stackoverflow.com/users/2044155",
"pm_score": 3,
"selected": true,
"text": "<p>Drawing a line is simply joining two points, and drawing a scaling incrementing (x0,y0) and(x1,y1) in a particular direction, through X, and/or through Y.\nThis boils down to, in the scale case, which direction(s) stepping occurs (maybe both directions for fun).</p>\n\n<pre><code>template< int XIncrement, YIncrement >\nstruct DrawScale\n{\n void operator()(HDC dc, int step, int x0, int x1, int y0, int y1)\n {\n const int deltaX = XIncrement*step;\n const int deltaY = YIncrement*step;\n const int ymax = y1;\n const int xmax = x1;\n while( x0 < xmax && y0 < ymax )\n {\n MoveToEx(dc, x0, y0, NULL);\n LineTo(dc, x1, y1);\n x0 += deltaX;\n x1 += deltaX;\n y0 += deltaY;\n y1 += deltaY;\n }\n }\n};\ntypedef DrawScale< 1, 0 > DrawScaleX;\ntypedef DrawScale< 0, 1 > DrawScaleY;\n</code></pre>\n\n<p>The template will do its job: at compile time the compiler will remove all the null statements i.e. deltaX or deltaY is 0 regarding which function is called and half of the code goes away in each functor.</p>\n\n<p>You can add you anti-alias, pencil stuff inside this uniq function and get the code properly generated generated by the compiler.</p>\n\n<p>This is cut and paste on steroids ;-)</p>\n\n<p>-- ppi</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
]
| I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that
```
void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int x = x0; x < x1; x += step)
{
MoveToEx(dc, x, y0, NULL);
LineTo(dc, x, y1);
}
}
void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1)
{
for(int y = y0; y < y1; y += step)
{
MoveToEx(dc, x0, y, NULL);
LineTo(dc, x1, y);
}
}
```
So if I decide to add some fancy stuff, like antialiasing or merely change drawing pencil or whatever I'll have to put the same code in both of them and it's code duplication and it's bad we all know why.
My question is how would you rewrite these two functions into a single one to avoid this problem? | Drawing a line is simply joining two points, and drawing a scaling incrementing (x0,y0) and(x1,y1) in a particular direction, through X, and/or through Y.
This boils down to, in the scale case, which direction(s) stepping occurs (maybe both directions for fun).
```
template< int XIncrement, YIncrement >
struct DrawScale
{
void operator()(HDC dc, int step, int x0, int x1, int y0, int y1)
{
const int deltaX = XIncrement*step;
const int deltaY = YIncrement*step;
const int ymax = y1;
const int xmax = x1;
while( x0 < xmax && y0 < ymax )
{
MoveToEx(dc, x0, y0, NULL);
LineTo(dc, x1, y1);
x0 += deltaX;
x1 += deltaX;
y0 += deltaY;
y1 += deltaY;
}
}
};
typedef DrawScale< 1, 0 > DrawScaleX;
typedef DrawScale< 0, 1 > DrawScaleY;
```
The template will do its job: at compile time the compiler will remove all the null statements i.e. deltaX or deltaY is 0 regarding which function is called and half of the code goes away in each functor.
You can add you anti-alias, pencil stuff inside this uniq function and get the code properly generated generated by the compiler.
This is cut and paste on steroids ;-)
-- ppi |
80,692 | <pre><code>public static Logger getLogger() {
final Throwable t = new Throwable();
final StackTraceElement methodCaller = t.getStackTrace()[1];
final Logger logger = Logger.getLogger(methodCaller.getClassName());
logger.setLevel(ResourceManager.LOGLEVEL);
return logger;
}
</code></pre>
<p>This method would return a logger that knows the class it's logging for.
Any ideas against it?</p>
<p>Many years later: <a href="https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java" rel="noreferrer">https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java</a></p>
| [
{
"answer_id": 80754,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 2,
"selected": false,
"text": "<p>You could of course just use Log4J with the appropriate pattern layout:</p>\n\n<blockquote>\n <p>For example, for the class name \"org.apache.xyz.SomeClass\", the pattern %C{1} will output \"SomeClass\". </p>\n</blockquote>\n\n<p><a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html\" rel=\"nofollow noreferrer\">http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html</a></p>\n"
},
{
"answer_id": 80762,
"author": "Daan",
"author_id": 197,
"author_profile": "https://Stackoverflow.com/users/197",
"pm_score": 5,
"selected": true,
"text": "<p>I guess it adds a lot of overhead for every class. Every class has to be 'looked up'. You create new Throwable objects to do that... These throwables don't come for free.</p>\n"
},
{
"answer_id": 80851,
"author": "Mario Ortegón",
"author_id": 2309,
"author_profile": "https://Stackoverflow.com/users/2309",
"pm_score": 0,
"selected": false,
"text": "<p>Why not?</p>\n\n<pre><code>public static Logger getLogger(Object o) {\n final Logger logger = Logger.getLogger(o.getClass());\n logger.setLevel(ResourceManager.LOGLEVEL);\n return logger;\n}\n</code></pre>\n\n<p>And then when you need a logger for a class:</p>\n\n<pre><code>getLogger(this).debug(\"Some log message\")\n</code></pre>\n"
},
{
"answer_id": 80898,
"author": "Philip Helger",
"author_id": 15254,
"author_profile": "https://Stackoverflow.com/users/15254",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer creating a (static) Logger for each class (with it's explicit class name). I than use the logger as is.</p>\n"
},
{
"answer_id": 81494,
"author": "Bill Michell",
"author_id": 7938,
"author_profile": "https://Stackoverflow.com/users/7938",
"pm_score": 0,
"selected": false,
"text": "<p>This mechanism puts in a lot of extra effort at runtime.</p>\n\n<p>If you use Eclipse as your IDE, consider using <a href=\"http://log4e.jayefem.de/\" rel=\"nofollow noreferrer\">Log4e</a>. This handy plugin will generate logger declarations for you using your favourite logging framework. A fraction more effort at coding time, but <strong>much</strong> less work at runtime.</p>\n"
},
{
"answer_id": 83847,
"author": "18Rabbit",
"author_id": 12662,
"author_profile": "https://Stackoverflow.com/users/12662",
"pm_score": 3,
"selected": false,
"text": "<p>For every class that you use this with, you're going to have to look up the Logger anyway, so you might as well just use a static Logger in those classes.</p>\n\n<pre><code>private static final Logger logger = Logger.getLogger(MyClass.class.getName());\n</code></pre>\n\n<p>Then you just reference that logger when you need to do your log messages. Your method does the same thing that the static Log4J Logger does already so why reinvent the wheel?</p>\n"
},
{
"answer_id": 83866,
"author": "Asgeir S. Nilsen",
"author_id": 16023,
"author_profile": "https://Stackoverflow.com/users/16023",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you <em>really</em> need your Logger to be static, you could use</p>\n\n<pre><code>final Logger logger = LoggerFactory.getLogger(getClass());\n</code></pre>\n"
},
{
"answer_id": 104851,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 5,
"selected": false,
"text": "<p>Creating a stack trace is a relatively slow operation. Your caller already knows what class and method it is in, so the effort is wasted. This aspect of your solution is inefficient.</p>\n\n<p>Even if you use static class information, you should not fetch the Logger again for each message. <a href=\"http://www.qos.ch/logging/thinkAgain.jsp\" rel=\"noreferrer\">From the author</a> of Log4j,Ceki Gülcü: </p>\n\n<blockquote>\n <p>The most common error in wrapper classes is the invocation of the Logger.getLogger method on each log request. This is guaranteed to wreak havoc on your application's performance. Really!!! </p>\n</blockquote>\n\n<p>This is the conventional, efficient idiom for getting a Logger is during class initialization:</p>\n\n<pre><code>private static final Logger log = Logger.getLogger(MyClass.class);\n</code></pre>\n\n<p>Note that this gives you a separate Logger for each type in a hierarchy. If you come up with a method that invokes <code>getClass()</code> on an instance, you will see messages logged by a base type showing up under the subtype's logger. Maybe this is desirable in some cases, but I find it confusing (and I tend to favor composition over inheritance anyway). </p>\n\n<p>Obviously, using the dynamic type via <code>getClass()</code> will require you to obtain the logger at least once per instance, rather than once per class like the recommended idiom using static type information.</p>\n"
},
{
"answer_id": 303344,
"author": "ykaganovich",
"author_id": 10026,
"author_profile": "https://Stackoverflow.com/users/10026",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need to create a new Throwable object. You can just call \n<code>Thread.currentThread().getStackTrace()[1]</code></p>\n"
},
{
"answer_id": 1268633,
"author": "EGB",
"author_id": 155399,
"author_profile": "https://Stackoverflow.com/users/155399",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming you are keeping static refs to the loggers, here's a standalone static singleton:</p>\n\n<pre><code>public class LoggerUtils extends SecurityManager\n{\n public static Logger getLogger()\n {\n String className = new LoggerUtils().getClassName();\n Logger logger = Logger.getLogger(className);\n return logger;\n }\n\n private String getClassName()\n {\n return getClassContext()[2].getName();\n }\n}\n</code></pre>\n\n<p>Usage is nice and clean:</p>\n\n<pre><code>Logger logger = LoggerUtils.getLogger();\n</code></pre>\n"
},
{
"answer_id": 1705696,
"author": "Cowan",
"author_id": 17041,
"author_profile": "https://Stackoverflow.com/users/17041",
"pm_score": 4,
"selected": false,
"text": "<p>We actually have something quite similar in a LogUtils class. Yes, it's kind of icky, but the advantages are worth it as far as I'm concerned. We wanted to make sure we didn't have any overhead from it being repeatedly called though, so ours (somewhat hackily) ensures that it can ONLY be called from a static initializer context, a la:</p>\n\n<pre><code>private static final Logger LOG = LogUtils.loggerForThisClass();\n</code></pre>\n\n<p>It will fail if it's invoked from a normal method, or from an instance initializer (i.e. if the 'static' was left off above) to reduce the risk of performance overhead. The method is:</p>\n\n<pre><code>public static Logger loggerForThisClass() {\n // We use the third stack element; second is this method, first is .getStackTrace()\n StackTraceElement myCaller = Thread.currentThread().getStackTrace()[2];\n Assert.equal(\"<clinit>\", myCaller.getMethodName());\n return Logger.getLogger(myCaller.getClassName());\n}\n</code></pre>\n\n<p>Anyone who asks what advantage does this have over </p>\n\n<pre><code>= Logger.getLogger(MyClass.class);\n</code></pre>\n\n<p>has probably never had to deal with someone who copies and pastes that line from somewhere else and forgets to change the class name, leaving you dealing with a class which sends all its stuff to another logger.</p>\n"
},
{
"answer_id": 2400226,
"author": "Alaa Murad",
"author_id": 288624,
"author_profile": "https://Stackoverflow.com/users/288624",
"pm_score": 2,
"selected": false,
"text": "<p>Then the best thing is mix of two . </p>\n\n<pre><code>public class LoggerUtil {\n\n public static Level level=Level.ALL;\n\n public static java.util.logging.Logger getLogger() {\n final Throwable t = new Throwable();\n final StackTraceElement methodCaller = t.getStackTrace()[1];\n final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(methodCaller.getClassName());\n logger.setLevel(level);\n\n return logger;\n }\n}\n</code></pre>\n\n<p>And then in every class:</p>\n\n<pre><code>private static final Logger LOG = LoggerUtil.getLogger();\n</code></pre>\n\n<p>in code :</p>\n\n<pre><code>LOG.fine(\"debug that !...\");\n</code></pre>\n\n<p>You get static logger that you can just copy&paste in every class and with no overhead ...</p>\n\n<p>Alaa</p>\n"
},
{
"answer_id": 6459115,
"author": "Ed Sarrazin",
"author_id": 812881,
"author_profile": "https://Stackoverflow.com/users/812881",
"pm_score": 2,
"selected": false,
"text": "<p>From reading through all the other feedback on this site, I created the following for use with Log4j:</p>\n\n<pre><code>package com.edsdev.testapp.util;\n\nimport java.util.concurrent.ConcurrentHashMap;\n\nimport org.apache.log4j.Level;\nimport org.apache.log4j.Priority;\n\npublic class Logger extends SecurityManager {\n\nprivate static ConcurrentHashMap<String, org.apache.log4j.Logger> loggerMap = new ConcurrentHashMap<String, org.apache.log4j.Logger>();\n\npublic static org.apache.log4j.Logger getLog() {\n String className = new Logger().getClassName();\n if (!loggerMap.containsKey(className)) {\n loggerMap.put(className, org.apache.log4j.Logger.getLogger(className));\n }\n return loggerMap.get(className);\n}\npublic String getClassName() {\n return getClassContext()[3].getName();\n}\npublic static void trace(Object message) {\n getLog().trace(message);\n}\npublic static void trace(Object message, Throwable t) {\n getLog().trace(message, t);\n}\npublic static boolean isTraceEnabled() {\n return getLog().isTraceEnabled();\n}\npublic static void debug(Object message) {\n getLog().debug(message);\n}\npublic static void debug(Object message, Throwable t) {\n getLog().debug(message, t);\n}\npublic static void error(Object message) {\n getLog().error(message);\n}\npublic static void error(Object message, Throwable t) {\n getLog().error(message, t);\n}\npublic static void fatal(Object message) {\n getLog().fatal(message);\n}\npublic static void fatal(Object message, Throwable t) {\n getLog().fatal(message, t);\n}\npublic static void info(Object message) {\n getLog().info(message);\n}\npublic static void info(Object message, Throwable t) {\n getLog().info(message, t);\n}\npublic static boolean isDebugEnabled() {\n return getLog().isDebugEnabled();\n}\npublic static boolean isEnabledFor(Priority level) {\n return getLog().isEnabledFor(level);\n}\npublic static boolean isInfoEnabled() {\n return getLog().isInfoEnabled();\n}\npublic static void setLevel(Level level) {\n getLog().setLevel(level);\n}\npublic static void warn(Object message) {\n getLog().warn(message);\n}\npublic static void warn(Object message, Throwable t) {\n getLog().warn(message, t);\n}\n</code></pre>\n\n<p>}</p>\n\n<p>Now in your code all you need is</p>\n\n<pre><code>Logger.debug(\"This is a test\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Logger.error(\"Look what happened Ma!\", e);\n</code></pre>\n\n<p>If you need more exposure to log4j methods, just delegate them from the Logger class listed above.</p>\n"
},
{
"answer_id": 11937492,
"author": "joseaio",
"author_id": 1312464,
"author_profile": "https://Stackoverflow.com/users/1312464",
"pm_score": 0,
"selected": false,
"text": "<p>Please see my static getLogger() implementation (use same \"sun.*\" magic on JDK 7 as default java Logger doit)</p>\n\n<ul>\n<li><p>note static logging methods (with static import) without ugly log property...</p>\n\n<p>import static my.pakg.Logger.*;</p></li>\n</ul>\n\n<p>And their speed is equivalent to native Java implementation (checked with 1 million of log traces)</p>\n\n<pre><code>package my.pkg;\n\nimport java.text.MessageFormat;\nimport java.util.Arrays;\nimport java.util.IllegalFormatException;\nimport java.util.logging.Level;\nimport java.util.logging.LogRecord;\n\nimport sun.misc.JavaLangAccess;\nimport sun.misc.SharedSecrets;\n\n\npublic class Logger {\nstatic final int CLASS_NAME = 0;\nstatic final int METHOD_NAME = 1;\n\n// Private method to infer the caller's class and method names\nprotected static String[] getClassName() {\n JavaLangAccess access = SharedSecrets.getJavaLangAccess();\n Throwable throwable = new Throwable();\n int depth = access.getStackTraceDepth(throwable);\n\n boolean lookingForLogger = true;\n for (int i = 0; i < depth; i++) {\n // Calling getStackTraceElement directly prevents the VM\n // from paying the cost of building the entire stack frame.\n StackTraceElement frame = access.getStackTraceElement(throwable, i);\n String cname = frame.getClassName();\n boolean isLoggerImpl = isLoggerImplFrame(cname);\n if (lookingForLogger) {\n // Skip all frames until we have found the first logger frame.\n if (isLoggerImpl) {\n lookingForLogger = false;\n }\n } else {\n if (!isLoggerImpl) {\n // skip reflection call\n if (!cname.startsWith(\"java.lang.reflect.\") && !cname.startsWith(\"sun.reflect.\")) {\n // We've found the relevant frame.\n return new String[] {cname, frame.getMethodName()};\n }\n }\n }\n }\n return new String[] {};\n // We haven't found a suitable frame, so just punt. This is\n // OK as we are only committed to making a \"best effort\" here.\n}\n\nprotected static String[] getClassNameJDK5() {\n // Get the stack trace.\n StackTraceElement stack[] = (new Throwable()).getStackTrace();\n // First, search back to a method in the Logger class.\n int ix = 0;\n while (ix < stack.length) {\n StackTraceElement frame = stack[ix];\n String cname = frame.getClassName();\n if (isLoggerImplFrame(cname)) {\n break;\n }\n ix++;\n }\n // Now search for the first frame before the \"Logger\" class.\n while (ix < stack.length) {\n StackTraceElement frame = stack[ix];\n String cname = frame.getClassName();\n if (isLoggerImplFrame(cname)) {\n // We've found the relevant frame.\n return new String[] {cname, frame.getMethodName()};\n }\n ix++;\n }\n return new String[] {};\n // We haven't found a suitable frame, so just punt. This is\n // OK as we are only committed to making a \"best effort\" here.\n}\n\n\nprivate static boolean isLoggerImplFrame(String cname) {\n // the log record could be created for a platform logger\n return (\n cname.equals(\"my.package.Logger\") ||\n cname.equals(\"java.util.logging.Logger\") ||\n cname.startsWith(\"java.util.logging.LoggingProxyImpl\") ||\n cname.startsWith(\"sun.util.logging.\"));\n}\n\nprotected static java.util.logging.Logger getLogger(String name) {\n return java.util.logging.Logger.getLogger(name);\n}\n\nprotected static boolean log(Level level, String msg, Object... args) {\n return log(level, null, msg, args);\n}\n\nprotected static boolean log(Level level, Throwable thrown, String msg, Object... args) {\n String[] values = getClassName();\n java.util.logging.Logger log = getLogger(values[CLASS_NAME]);\n if (level != null && log.isLoggable(level)) {\n if (msg != null) {\n log.log(getRecord(level, thrown, values[CLASS_NAME], values[METHOD_NAME], msg, args));\n }\n return true;\n }\n return false;\n}\n\nprotected static LogRecord getRecord(Level level, Throwable thrown, String className, String methodName, String msg, Object... args) {\n LogRecord record = new LogRecord(level, format(msg, args));\n record.setSourceClassName(className);\n record.setSourceMethodName(methodName);\n if (thrown != null) {\n record.setThrown(thrown);\n }\n return record;\n}\n\nprivate static String format(String msg, Object... args) {\n if (msg == null || args == null || args.length == 0) {\n return msg;\n } else if (msg.indexOf('%') >= 0) {\n try {\n return String.format(msg, args);\n } catch (IllegalFormatException esc) {\n // none\n }\n } else if (msg.indexOf('{') >= 0) {\n try {\n return MessageFormat.format(msg, args);\n } catch (IllegalArgumentException exc) {\n // none\n }\n }\n if (args.length == 1) {\n Object param = args[0];\n if (param != null && param.getClass().isArray()) {\n return msg + Arrays.toString((Object[]) param);\n } else if (param instanceof Throwable){\n return msg;\n } else {\n return msg + param;\n }\n } else {\n return msg + Arrays.toString(args);\n }\n}\n\npublic static void severe(String msg, Object... args) {\n log(Level.SEVERE, msg, args);\n}\n\npublic static void warning(String msg, Object... args) {\n log(Level.WARNING, msg, args);\n}\n\npublic static void info(Throwable thrown, String format, Object... args) {\n log(Level.INFO, thrown, format, args);\n}\n\npublic static void warning(Throwable thrown, String format, Object... args) {\n log(Level.WARNING, thrown, format, args);\n}\n\npublic static void warning(Throwable thrown) {\n log(Level.WARNING, thrown, thrown.getMessage());\n}\n\npublic static void severe(Throwable thrown, String format, Object... args) {\n log(Level.SEVERE, thrown, format, args);\n}\n\npublic static void severe(Throwable thrown) {\n log(Level.SEVERE, thrown, thrown.getMessage());\n}\n\npublic static void info(String msg, Object... args) {\n log(Level.INFO, msg, args);\n}\n\npublic static void fine(String msg, Object... args) {\n log(Level.FINE, msg, args);\n}\n\npublic static void finer(String msg, Object... args) {\n log(Level.FINER, msg, args);\n}\n\npublic static void finest(String msg, Object... args) {\n log(Level.FINEST, msg, args);\n}\n\npublic static boolean isLoggableFinest() {\n return isLoggable(Level.FINEST);\n}\n\npublic static boolean isLoggableFiner() {\n return isLoggable(Level.FINER);\n}\n\npublic static boolean isLoggableFine() {\n return isLoggable(Level.FINE);\n}\n\npublic static boolean isLoggableInfo() {\n return isLoggable(Level.INFO);\n}\n\npublic static boolean isLoggableWarning() {\n return isLoggable(Level.WARNING);\n}\npublic static boolean isLoggableSevere() {\n return isLoggable(Level.SEVERE);\n}\n\nprivate static boolean isLoggable(Level level) {\n return log(level, null);\n}\n\n}\n</code></pre>\n"
},
{
"answer_id": 14670532,
"author": "yegor256",
"author_id": 187141,
"author_profile": "https://Stackoverflow.com/users/187141",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at <a href=\"http://www.jcabi.com/jcabi-log/apidocs-0.7.7/com/jcabi/log/Logger.html\" rel=\"nofollow\"><code>Logger</code></a> class from <a href=\"http://www.jcabi.com/jcabi-log/\" rel=\"nofollow\">jcabi-log</a>. It does exactly what you're looking for, providing a collection of static methods. You don't need to embed loggers into classes any more:</p>\n\n<pre><code>import com.jcabi.log.Logger;\nclass Foo {\n public void bar() {\n Logger.info(this, \"doing something...\");\n }\n}\n</code></pre>\n\n<p><code>Logger</code> sends all logs to SLF4J, which you can redirect to any other logging facility, in runtime.</p>\n"
},
{
"answer_id": 32010391,
"author": "muttonUp",
"author_id": 3696510,
"author_profile": "https://Stackoverflow.com/users/3696510",
"pm_score": 1,
"selected": false,
"text": "<p>I just have the following line at the beginning of most of my classes.</p>\n\n<pre><code> private static final Logger log = \n LoggerFactory.getLogger(new Throwable().getStackTrace()[0].getClassName());\n</code></pre>\n\n<p>yes there is some overhead the very first time an object of that class is created, but I work mostly in webapps, so adding microseconds onto a 20 second startup isn't really a problem.</p>\n"
},
{
"answer_id": 32132312,
"author": "Neeraj",
"author_id": 528757,
"author_profile": "https://Stackoverflow.com/users/528757",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.html\" rel=\"noreferrer\">MethodHandles</a> class (as of Java 7) includes a <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.Lookup.html\" rel=\"noreferrer\">Lookup</a> class that, from a static context, can find and return the name of the current class. Consider the following example:</p>\n\n<pre><code>import java.lang.invoke.MethodHandles;\n\npublic class Main {\n private static final Class clazz = MethodHandles.lookup().lookupClass();\n private static final String CLASSNAME = clazz.getSimpleName();\n\n public static void main( String args[] ) {\n System.out.println( CLASSNAME );\n }\n}\n</code></pre>\n\n<p>When run this produces:</p>\n\n<pre><code>Main\n</code></pre>\n\n<p>For a logger, you could use:</p>\n\n<pre><code>private static Logger LOGGER = \n Logger.getLogger(MethodHandles.lookup().lookupClass().getSimpleName());\n</code></pre>\n"
},
{
"answer_id": 39446629,
"author": "user2189998",
"author_id": 2189998,
"author_profile": "https://Stackoverflow.com/users/2189998",
"pm_score": 2,
"selected": false,
"text": "<p>A good alternative is to use (one of) the lombok logs annotations :\n<a href=\"https://projectlombok.org/features/Log.html\" rel=\"nofollow\">https://projectlombok.org/features/Log.html</a></p>\n\n<p>It generate the corresponding log statement with the current class.</p>\n"
},
{
"answer_id": 52744364,
"author": "James Mudd",
"author_id": 4653517,
"author_profile": "https://Stackoverflow.com/users/4653517",
"pm_score": 1,
"selected": false,
"text": "<p>Google Flogger logging API supports this e.g.</p>\n\n<pre><code>private static final FluentLogger logger = FluentLogger.forEnclosingClass();\n</code></pre>\n\n<p>See <a href=\"https://github.com/google/flogger\" rel=\"nofollow noreferrer\">https://github.com/google/flogger</a> for more details.</p>\n"
},
{
"answer_id": 54787201,
"author": "James Mudd",
"author_id": 4653517,
"author_profile": "https://Stackoverflow.com/users/4653517",
"pm_score": 1,
"selected": false,
"text": "<p>A nice way to do this from Java 7 onwards:</p>\n\n<pre><code>private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());\n</code></pre>\n\n<p>The logger can be <code>static</code> and that fine.\nHere its using the SLF4J API</p>\n\n<pre><code>import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\n</code></pre>\n\n<p>But in principal can be used with any logging framework. If the logger needs a string argument add <code>toString()</code></p>\n"
},
{
"answer_id": 56684047,
"author": "Choletski",
"author_id": 3595288,
"author_profile": "https://Stackoverflow.com/users/3595288",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Simple and trivial OLD SCHOOL:</strong></p>\n\n<p>Just create your own class and pass there class name, method name + comment (if class /method changed they're refactored automatically Shift+F6)</p>\n\n<pre><code>public class MyLogs { \n public static void LOG(String theClass, String theMethod, String theComment) {\n Log.d(\"MY_TAG\", \"class: \" + theClass + \" meth : \" + theMethod + \" comm : \" + theComment);\n }\n}\n</code></pre>\n\n<p>and just use it anywhere in the app (no context required, no initialzation, no extra libs and no look up) - can be used for any programing language!</p>\n\n<pre><code>MyLogs.LOG(\"MainActivity\", \"onCreate\", \"Hello world\");\n</code></pre>\n\n<p>this will print in your console:</p>\n\n<blockquote>\n <p>MY_TAG class: MainActivity meth: onCreate comm: Hello world</p>\n</blockquote>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15187/"
]
| ```
public static Logger getLogger() {
final Throwable t = new Throwable();
final StackTraceElement methodCaller = t.getStackTrace()[1];
final Logger logger = Logger.getLogger(methodCaller.getClassName());
logger.setLevel(ResourceManager.LOGLEVEL);
return logger;
}
```
This method would return a logger that knows the class it's logging for.
Any ideas against it?
Many years later: <https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java> | I guess it adds a lot of overhead for every class. Every class has to be 'looked up'. You create new Throwable objects to do that... These throwables don't come for free. |
80,706 | <p>I want to find 2<sup>nd</sup>, 3<sup>rd</sup>, ... n<sup>th</sup> maximum value of a column.</p>
| [
{
"answer_id": 80720,
"author": "TK.",
"author_id": 1816,
"author_profile": "https://Stackoverflow.com/users/1816",
"pm_score": 5,
"selected": true,
"text": "<p>You could sort the column into descending format and then just obtain the value from the nth row.</p>\n\n<p>EDIT::</p>\n\n<p>Updated as per comment request. <strong><em>WARNING</em></strong> completely untested!</p>\n\n<pre><code>SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6\n</code></pre>\n\n<p>Something like the above should work for Oracle ... you might have to get the syntax right first!</p>\n"
},
{
"answer_id": 80734,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 4,
"selected": false,
"text": "<p>You didn't specify which database, on MySQL you can do</p>\n\n<pre><code>SELECT column FROM table ORDER BY column DESC LIMIT 7,10;\n</code></pre>\n\n<p>Would skip the first 7, and then get you the next ten highest.</p>\n"
},
{
"answer_id": 80771,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 0,
"selected": false,
"text": "<p>In SQL Server, just do:</p>\n\n<pre><code>select distinct top n+1 column from table order by column desc\n</code></pre>\n\n<p>And then throw away the first value, if you don't need it.</p>\n"
},
{
"answer_id": 81088,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Again you may need to fix for your database, but if you want the top 2nd value in a dataset that potentially has the value duplicated, you'll want to do a group as well:</p>\n\n<pre><code>SELECT column \nFROM table \nWHERE column IS NOT NULL \nGROUP BY column \nORDER BY column DESC \nLIMIT 5 OFFSET 2;\n</code></pre>\n\n<p>Would skip the first two, and then will get you the next five highest. </p>\n"
},
{
"answer_id": 82609,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 3,
"selected": false,
"text": "<p>Pure SQL (note: I would recommend using SQL features specific to your DBMS since it will be likely more efficient). This will get you the n+1th largest value (to get smallest, flip the <). If you have duplicates, make it COUNT( DISTINCT VALUE )..</p>\n\n<pre><code>select id from table order by id desc limit 4 ;\n+------+\n| id |\n+------+\n| 2211 | \n| 2210 | \n| 2209 | \n| 2208 | \n+------+\n\n\nSELECT yourvalue\n FROM yourtable t1\n WHERE EXISTS( SELECT COUNT(*)\n FROM yourtable t2\n WHERE t1.id <> t2.id\n AND t1.yourvalue < t2.yourvalue\n HAVING COUNT(*) = 3 )\n\n\n+------+\n| id |\n+------+\n| 2208 | \n+------+\n</code></pre>\n"
},
{
"answer_id": 82829,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a method for Oracle. This example gets the 9th highest value. Simply replace the 9 with a bind variable containing the position you are looking for.</p>\n\n<pre><code> select created from (\n select created from (\n select created from user_objects\n order by created desc\n )\n where rownum <= 9\n order by created asc\n )\n where rownum = 1\n</code></pre>\n\n<p>If you wanted the nth unique value, you would add DISTINCT on the innermost query block.</p>\n"
},
{
"answer_id": 83170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>for SQL 2005:</p>\n\n<pre><code>SELECT col1 from \n (select col1, dense_rank(col1) over (order by col1 desc) ranking \n from t1) subq where ranking between 2 and @n\n</code></pre>\n"
},
{
"answer_id": 86447,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Another one for Oracle using analytic functions:</p>\n\n<pre><code>select distinct col1 --distinct is required to remove matching value of column\nfrom \n( select col1, dense_rank() over (order by col1 desc) rnk\n from tbl\n)\nwhere rnk = :b1\n</code></pre>\n"
},
{
"answer_id": 734650,
"author": "Phil H",
"author_id": 36537,
"author_profile": "https://Stackoverflow.com/users/36537",
"pm_score": 1,
"selected": false,
"text": "<p>Just dug out this question when looking for the answer myself, and this seems to work for SQL Server 2005 (derived from <a href=\"https://stackoverflow.com/questions/80706/query-to-find-nth-max-value-of-a-column/80771#80771\">Blorgbeard's solution</a>):</p>\n\n<pre><code>SELECT MIN(q.col1) FROM (\n SELECT\n DISTINCT TOP n col1\n FROM myTable\n ORDER BY col1 DESC\n) q;\n</code></pre>\n\n<p>Effectively, that is a <code>SELECT MIN(q.someCol) FROM someTable q</code>, with the top n of the table retrieved by the <code>SELECT DISTINCT...</code> query.</p>\n"
},
{
"answer_id": 750539,
"author": "dexter",
"author_id": 1385252,
"author_profile": "https://Stackoverflow.com/users/1385252",
"pm_score": 5,
"selected": false,
"text": "<p>Consider the following Employee table with a single column for salary.</p>\n\n<pre>\n+------+\n| Sal |\n+------+\n| 3500 | \n| 2500 | \n| 2500 | \n| 5500 |\n| 7500 |\n+------+\n</pre>\n\n<p>The following query will return the Nth Maximum element.</p>\n\n<pre><code>select SAL from EMPLOYEE E1 where \n (N - 1) = (select count(distinct(SAL)) \n from EMPLOYEE E2 \n where E2.SAL > E1.SAL )\n</code></pre>\n\n<p>For eg. when the second maximum value is required,</p>\n\n<pre><code> select SAL from EMPLOYEE E1 where \n (2 - 1) = (select count(distinct(SAL)) \n from EMPLOYEE E2 \n where E2.SAL > E1.SAL )\n</code></pre>\n\n<pre>\n+------+\n| Sal |\n+------+\n| 5500 |\n+------+\n</pre>\n"
},
{
"answer_id": 815171,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>select sal,ename from emp e where\n 2=(select count(distinct sal) from emp where e.sal<=emp.sal) or\n 3=(select count(distinct sal) from emp where e.sal<=emp.sal) or\n 4=(select count(distinct sal) from emp where e.sal<=emp.sal) order by sal desc;\n</code></pre>\n"
},
{
"answer_id": 1730110,
"author": "Piyush",
"author_id": 210562,
"author_profile": "https://Stackoverflow.com/users/210562",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Select max(sal) \nfrom table t1 \nwhere N (select max(sal) \n from table t2 \n where t2.sal > t1.sal)\n</code></pre>\n\n<p>To find the Nth max sal.</p>\n"
},
{
"answer_id": 4182477,
"author": "shankar",
"author_id": 507987,
"author_profile": "https://Stackoverflow.com/users/507987",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT * FROM tablename \nWHERE columnname<(select max(columnname) from tablename) \norder by columnname desc limit 1\n</code></pre>\n"
},
{
"answer_id": 4538635,
"author": "Ritesh",
"author_id": 554948,
"author_profile": "https://Stackoverflow.com/users/554948",
"pm_score": 0,
"selected": false,
"text": "<p>MySQL:</p>\n\n<pre><code>select distinct(salary) from employee order by salary desc limit (n-1), 1;\n</code></pre>\n"
},
{
"answer_id": 12241522,
"author": "Raman kumar",
"author_id": 1642680,
"author_profile": "https://Stackoverflow.com/users/1642680",
"pm_score": -1,
"selected": false,
"text": "<p>Table employee</p>\n\n<pre><code>salary \n1256\n1256\n2563\n8546\n5645\n</code></pre>\n\n<p>You find the second max value by this query</p>\n\n<pre><code>select salary \nfrom employee \nwhere salary=(select max(salary) \n from employee \n where salary <(select max(salary) from employee));\n</code></pre>\n\n<p>You find the third max value by this query</p>\n\n<pre><code>select salary \nfrom employee \nwhere salary=(select max(salary) \n from employee \n where salary <(select max(salary) \n from employee \n where salary <(select max(salary)from employee)));\n</code></pre>\n"
},
{
"answer_id": 12318458,
"author": "parveen",
"author_id": 1654762,
"author_profile": "https://Stackoverflow.com/users/1654762",
"pm_score": 0,
"selected": false,
"text": "<p>Answer :\ntop second:</p>\n\n<pre><code>select * from (select * from deletetable where rownum <=2 order by rownum desc) where rownum <=1\n</code></pre>\n"
},
{
"answer_id": 13466974,
"author": "German Alex",
"author_id": 1837741,
"author_profile": "https://Stackoverflow.com/users/1837741",
"pm_score": 2,
"selected": false,
"text": "<p>(Table Name=Student, Column Name= mark)</p>\n\n<pre><code>select * from(select row_number() over (order by mark desc) as t,mark from student group by mark) as td where t=4\n</code></pre>\n"
},
{
"answer_id": 13468939,
"author": "German Alex",
"author_id": 1837741,
"author_profile": "https://Stackoverflow.com/users/1837741",
"pm_score": 0,
"selected": false,
"text": "<p>(TableName=Student, ColumnName=Mark) :</p>\n\n<pre><code>select *\nfrom student \nwhere mark=(select mark \n from(select row_number() over (order by mark desc) as t,\n mark \n from student group by mark) as td \n where t=2)\n</code></pre>\n"
},
{
"answer_id": 14473660,
"author": "Abhishek B Patel",
"author_id": 2001168,
"author_profile": "https://Stackoverflow.com/users/2001168",
"pm_score": 2,
"selected": false,
"text": "<p>You can find the nth largest value of column by using the following query:</p>\n\n<pre><code>SELECT * FROM TableName a WHERE\n n = (SELECT count(DISTINCT(b.ColumnName)) \n FROM TableName b WHERE a.ColumnName <=b.ColumnName);\n</code></pre>\n"
},
{
"answer_id": 17875240,
"author": "ria",
"author_id": 2621681,
"author_profile": "https://Stackoverflow.com/users/2621681",
"pm_score": 0,
"selected": false,
"text": "<p>I think that the query below will work just perfect on oracle sql...I have tested it myself..</p>\n\n<p>Info related to this query : this query is using two tables named <code>employee</code> and <code>department</code> with columns in employee named: <code>name</code> (employee name), <code>dept_id</code> (common to employee and department), <code>salary</code></p>\n\n<p>And columns in department table: <code>dept_id</code> (common for employee table as well), <code>dept_name</code></p>\n\n<pre><code>SELECT\n tab.dept_name,MIN(tab.salary) AS Second_Max_Sal FROM (\n SELECT e.name, e.salary, d.dept_name, dense_rank() over (partition BY d.dept_name ORDER BY e.salary) AS rank FROM department d JOIN employee e USING (dept_id) ) tab\n WHERE\n rank BETWEEN 1 AND 2\n GROUP BY\n tab.dept_name\n</code></pre>\n\n<p>thanks</p>\n"
},
{
"answer_id": 20630590,
"author": "user3110552",
"author_id": 3110552,
"author_profile": "https://Stackoverflow.com/users/3110552",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Select min(fee) \nfrom fl_FLFee \nwhere fee in (Select top 4 Fee from fl_FLFee order by 1 desc)\n</code></pre>\n\n<p>Change Number four with N.</p>\n"
},
{
"answer_id": 24801342,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can simplify like this </p>\n\n<pre><code>SELECT MIN(Sal) FROM TableName\nWHERE Sal IN\n(SELECT TOP 4 Sal FROM TableName ORDER BY Sal DESC)\n</code></pre>\n\n<p>If the Sal contains duplicate values then use this</p>\n\n<pre><code>SELECT MIN(Sal) FROM TableName\nWHERE Sal IN\n(SELECT distinct TOP 4 Sal FROM TableName ORDER BY Sal DESC)\n</code></pre>\n\n<p>the 4 will be nth value it may any highest value such as 5 or 6 etc.</p>\n"
},
{
"answer_id": 27187656,
"author": "Prashant Maheshwari Andro",
"author_id": 2646705,
"author_profile": "https://Stackoverflow.com/users/2646705",
"pm_score": 1,
"selected": false,
"text": "<p>This is query for getting nth Highest from colomn put n=0 for second highest and n= 1 for 3rd highest and so on...</p>\n\n<pre><code> SELECT * FROM TableName\n WHERE ColomnName<(select max(ColomnName) from TableName)-n order by ColomnName desc limit 1;\n</code></pre>\n"
},
{
"answer_id": 46322804,
"author": "Rahul Raina",
"author_id": 2828087,
"author_profile": "https://Stackoverflow.com/users/2828087",
"pm_score": 1,
"selected": false,
"text": "<p><strong>Simple SQL Query to get the employee detail who has Nth MAX <code>Salary</code> in the table <code>Employee</code>.</strong></p>\n\n<pre><code>sql> select * from Employee order by salary desc LIMIT 1 OFFSET <N - 1>;\n</code></pre>\n\n<p><em>Consider table structure as:</em></p>\n\n<blockquote>\n <p>Employee ( \n id [int primary key auto_increment], \n name [varchar(30)], \n salary [int] );</p>\n</blockquote>\n\n<p><strong>Example:</strong></p>\n\n<p>If you need 3rd <code>MAX</code> salary in the above table then, query will be:</p>\n\n<pre><code>sql> select * from Employee order by salary desc LIMIT 1 OFFSET 2;\n</code></pre>\n\n<p><strong>Similarly:</strong></p>\n\n<p>If you need 8th <code>MAX</code> salary in the above table then, query will be:</p>\n\n<pre><code>sql> select * from Employee order by salary desc LIMIT 1 OFFSET 7;\n</code></pre>\n\n<blockquote>\n <p><strong>NOTE:</strong>\n When you have to get the <em>Nth</em> <code>MAX</code> value you should give the <code>OFFSET</code> as <em>(N - 1)</em>.</p>\n</blockquote>\n\n<p><em>Like this you can do same kind of operation in case of salary in ascending order.</em></p>\n"
},
{
"answer_id": 46408544,
"author": "rashedcs",
"author_id": 6714430,
"author_profile": "https://Stackoverflow.com/users/6714430",
"pm_score": 2,
"selected": false,
"text": "<pre><code>select column_name from table_name \norder by column_name desc limit n-1,1;\n</code></pre>\n\n<p>where n = 1, 2, 3,....nth max value.</p>\n"
},
{
"answer_id": 48053324,
"author": "Trung Lê Hoàng",
"author_id": 4902809,
"author_profile": "https://Stackoverflow.com/users/4902809",
"pm_score": 0,
"selected": false,
"text": "<p>In PostgreSQL, to find N-th largest salary from Employee table.</p>\n\n<pre><code>SELECT * FROM Employee WHERE salary in \n(SELECT salary FROM Employee ORDER BY salary DESC LIMIT N) \nORDER BY salary ASC LIMIT 1;\n</code></pre>\n"
},
{
"answer_id": 51723878,
"author": "mjp",
"author_id": 9253770,
"author_profile": "https://Stackoverflow.com/users/9253770",
"pm_score": 1,
"selected": false,
"text": "<p><strong>mysql query</strong>:\n<em>suppose i want to find out nth max salary form employee table</em></p>\n\n<pre><code>select salary \nform employee\norder by salary desc\nlimit n-1,1 ;\n</code></pre>\n"
},
{
"answer_id": 52591150,
"author": "ARSHAD M",
"author_id": 9196559,
"author_profile": "https://Stackoverflow.com/users/9196559",
"pm_score": 0,
"selected": false,
"text": "<p>Solution to find Nth Maximum value of a particular column in SQL Server:</p>\n\n<p>Employee table:</p>\n\n<p><img src=\"https://i.stack.imgur.com/nMqUu.jpg\" alt=\"Employee Table\"></p>\n\n<p>Sales table:</p>\n\n<p><img src=\"https://i.stack.imgur.com/SqdMi.jpg\" alt=\"Sales Table\"></p>\n\n<p>Employee table data:</p>\n\n<pre><code>==========\nId name\n=========\n6 ARSHAD M\n7 Manu\n8 Shaji\n</code></pre>\n\n<p>Sales table data:</p>\n\n<pre><code>=================\nid emp_id amount\n=================\n1 6 500\n2 7 100\n3 8 100\n4 6 150\n5 7 130\n6 7 130\n7 7 330\n</code></pre>\n\n<p>Query to Find out details of an employee who have highest sale/ <strong>N</strong>th highest salesperson</p>\n\n<pre><code>select * from (select E.Id,E.name,SUM(S.amount) AS 'total_amount' from employee E INNER JOIN Sale S on E.Id=S.emp_id group by S.emp_id,E.Id,E.name ) AS T1 WHERE(0)=( select COUNT(DISTINCT(total_amount)) from(select E.Id,E.name,SUM(S.amount) AS 'total_amount' from employee E INNER JOIN Sale S on E.Id=S.emp_id group by S.emp_id,E.Id,E.name )AS T2 WHERE(T1.total_amount<T2.total_amount) );\n</code></pre>\n\n<p>In the <strong>WHERE(0)</strong> replace 0 by n-1</p>\n\n<p>Result:</p>\n\n<pre><code>========================\nid name total_amount\n========================\n7 Manu 690\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15181/"
]
| I want to find 2nd, 3rd, ... nth maximum value of a column. | You could sort the column into descending format and then just obtain the value from the nth row.
EDIT::
Updated as per comment request. ***WARNING*** completely untested!
```
SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6
```
Something like the above should work for Oracle ... you might have to get the syntax right first! |
80,726 | <pre><code>> jruby -S gem install warbler
JRuby limited openssl loaded. gem install jruby-openssl for full support.
Successfully installed warbler-0.9.11
1 gem installed
Installing ri documentation for warbler-0.9.11...
Installing RDoc documentation for warbler-0.9.11...
> jruby -S warble
<snip>/jruby-1.1.4/bin/warble:1: undefined method `warble' for JRuby::Commands:Class (NoMethodError)
</code></pre>
<p>Any ideas why I don't get a warbler command in my jruby bin directory?</p>
<p>Thanks,</p>
| [
{
"answer_id": 92779,
"author": "Andrew Burgess",
"author_id": 12096,
"author_profile": "https://Stackoverflow.com/users/12096",
"pm_score": 1,
"selected": false,
"text": "<p>The only thing that I can really think of is to ensure that your instance of JRuby is using gems by default. I ran into that problem a few times when using gems where I would forget to either set the environmental variable or pass in the switch to Ruby. I don't know if things are different for JRuby though.</p>\n"
},
{
"answer_id": 1548574,
"author": "Vinod Singh",
"author_id": 47704,
"author_profile": "https://Stackoverflow.com/users/47704",
"pm_score": 0,
"selected": false,
"text": "<p>Did you tried <code>gem install warbler</code> ? It worked like charm for me-</p>\n\n<pre><code>C:\\>gem install warbler\nJRuby limited openssl loaded. gem install jruby-openssl for full support.\nhttp://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL\nSuccessfully installed jruby-jars-1.3.1\nSuccessfully installed warbler-0.9.14\n2 gems installed\nInstalling ri documentation for jruby-jars-1.3.1...\nInstalling ri documentation for warbler-0.9.14...\nInstalling RDoc documentation for jruby-jars-1.3.1...\nInstalling RDoc documentation for warbler-0.9.14...\n</code></pre>\n"
},
{
"answer_id": 3043799,
"author": "Ggmon",
"author_id": 327907,
"author_profile": "https://Stackoverflow.com/users/327907",
"pm_score": 0,
"selected": false,
"text": "<p>You should have the warble in you path, the warble binary is in the bin directory in your gems home directory.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14952/"
]
| ```
> jruby -S gem install warbler
JRuby limited openssl loaded. gem install jruby-openssl for full support.
Successfully installed warbler-0.9.11
1 gem installed
Installing ri documentation for warbler-0.9.11...
Installing RDoc documentation for warbler-0.9.11...
> jruby -S warble
<snip>/jruby-1.1.4/bin/warble:1: undefined method `warble' for JRuby::Commands:Class (NoMethodError)
```
Any ideas why I don't get a warbler command in my jruby bin directory?
Thanks, | The only thing that I can really think of is to ensure that your instance of JRuby is using gems by default. I ran into that problem a few times when using gems where I would forget to either set the environmental variable or pass in the switch to Ruby. I don't know if things are different for JRuby though. |
80,766 | <p>I got a typed (not connected) dataset, and many records (binary seriliazed) created with this dataset.
I've added a property to one of the types, and I want to convert the old records with the new data set.
I know how to load them: providing custom binder for the BinaryFormatter with the old schema dll.
The question is how can I convert objects of the old type to objects of the new type - both types has the same name but the new one has one more property.</p>
| [
{
"answer_id": 81192,
"author": "paulwhit",
"author_id": 7301,
"author_profile": "https://Stackoverflow.com/users/7301",
"pm_score": 0,
"selected": false,
"text": "<p>Can you make the new class inherit from the old one? If so, maybe you can simply deserialize into the new one through casting.</p>\n\n<p>If not, another possible solution is to implement a batch operation where you include a reference to the old class and new class in different namespaces, hydrate the old object, perform a deep copy into an object of the new class, and serialize the new object.</p>\n"
},
{
"answer_id": 81230,
"author": "Brownie",
"author_id": 6600,
"author_profile": "https://Stackoverflow.com/users/6600",
"pm_score": 2,
"selected": false,
"text": "<p>If the only difference between the existing dataset and the new one is an added field then you can \"upgrade\" them by writing out the old ones to XML and then reading that into the new ones. The value of the added field will be DBNull.</p>\n\n<pre><code>MyDataSet myDS = new MyDataSet();\nMyDataSet.MyTableRow row1 = myDS.MyTable.NewMyTableRow();\nrow1.Name = \"Brownie\";\nmyDS.MyTable.Rows.Add(row1);\n\nMyNewDataSet myNewDS = new MyNewDataSet();\n\nusing(MemoryStream ms = new MemoryStream()){\n myDS.WriteXml(ms);\n ms.Position = 0;\n myNewDS.ReadXml(ms);\n}\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I got a typed (not connected) dataset, and many records (binary seriliazed) created with this dataset.
I've added a property to one of the types, and I want to convert the old records with the new data set.
I know how to load them: providing custom binder for the BinaryFormatter with the old schema dll.
The question is how can I convert objects of the old type to objects of the new type - both types has the same name but the new one has one more property. | If the only difference between the existing dataset and the new one is an added field then you can "upgrade" them by writing out the old ones to XML and then reading that into the new ones. The value of the added field will be DBNull.
```
MyDataSet myDS = new MyDataSet();
MyDataSet.MyTableRow row1 = myDS.MyTable.NewMyTableRow();
row1.Name = "Brownie";
myDS.MyTable.Rows.Add(row1);
MyNewDataSet myNewDS = new MyNewDataSet();
using(MemoryStream ms = new MemoryStream()){
myDS.WriteXml(ms);
ms.Position = 0;
myNewDS.ReadXml(ms);
}
``` |
80,770 | <p>I have been reading a lot of XQuery tutorials on the website. Almost all of them are teaching me XQuery syntax. Let's say I have understood the XQuery syntax, how am I going to actually implement XQuery on my website?</p>
<p>For example, I have <strong>book.xml</strong>:</p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" ?>
<books>
<book>
<title>Doraemon</title>
<authorid>1</authorid>
</book>
<book>
<title>Ultraman</title>
<authorid>2</authorid>
</book>
</books>
</code></pre>
<p>Then, I have <strong>author.xml</strong></p>
<pre><code><?xml version="1.0" encoding="iso-8859-1" ?>
<authors>
<author id="1">Mr A</author>
<author id="2">Mr B</author>
</authors>
</code></pre>
<p>I want to generate HTML which looks like following:</p>
<pre><code><table>
<tr> <td>Title</td> <td>Author</td> </tr>
<tr> <td>Doraemon</td> <td>Mr A</td> </tr>
<tr> <td>Ultraman</td> <td>Mr B</td> </tr>
</table>
</code></pre>
<p>Please show me some examples. Or any website that I can do reference. Thanks very much.</p>
| [
{
"answer_id": 82980,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code><table>\n<tr><td>Title<td><td>Author<td></tr>\n{\n let $authordoc := fn:doc(\"author.xml\")\n for $book in fn:doc(\"book.xml\")/books/book\n return\n <tr>\n <td>{ $book/title }</td>\n <td>{ $authordoc/authors/author/[@id eq $book/authorid] }</td>\n </tr>\n}\n</table>\n</code></pre>\n\n<p>ps: haven't tested/executed it, but this is how one solution could look like</p>\n"
},
{
"answer_id": 89704,
"author": "frglps",
"author_id": 6015,
"author_profile": "https://Stackoverflow.com/users/6015",
"pm_score": 3,
"selected": false,
"text": "<pre><code>(: file: titles.xqy :)\n<table>\n<tr><th>title</th><th>author</th></tr>\n{\nlet $books-doc := doc(\"books.xml\")\nlet $authors-doc := doc(\"authors.xml\")\nfor $b in $books-doc//book,\n $a in $authors-doc//author\nwhere $a/@id = $b/authorid\nreturn \n<tr>\n <td>{$b/title/text()}</td>\n <td>{$a/text()}</td>\n</tr>\n}\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 108507,
"author": "Mattio",
"author_id": 19626,
"author_profile": "https://Stackoverflow.com/users/19626",
"pm_score": 2,
"selected": false,
"text": "<p>To be completely honest, maybe you don't need to use XQuery at all. </p>\n\n<p>If you need to transform moderately complex XML documents from XML to HTML, I would recommend using XSL. Personally, I found XSL easier to learn than XQuery. There are also a larger number of examples and tutorials available online because XSL has been around longer.</p>\n\n<p>We're currently using XQuery only because it's required as part of a piece of specialized XML software we've licensed. XQuery is a fantastic tool for selecting pieces of XML from a large repository, but we still use XSL to transform our documents.</p>\n"
},
{
"answer_id": 109605,
"author": "Sixty4Bit",
"author_id": 1681,
"author_profile": "https://Stackoverflow.com/users/1681",
"pm_score": 2,
"selected": false,
"text": "<p>XQuery is similar to SQL in that it allows you to retrieve specific portions of data from a large data repository. SQL is used for relational databases (MS SQL Server, Oracle, Sybase, MySQL, PostreSQL, SQLite, etc...) and XQuery is used for XML databases (MARKLogic, Sedena, Qexo, Qizx/db, etc...).</p>\n\n<p>MARKLogic gives you XDB servers and HTTP servers. You can have a typical web server and connect to MARKLogic through XDB or you can use their HTTP server and mix your XQuery with your HTML directly.</p>\n\n<p>I suggest downloading MARKLogic's developer server (allows for 100MB of documents) and giving it a try.</p>\n"
},
{
"answer_id": 144305,
"author": "MattMcKnight",
"author_id": 8136,
"author_profile": "https://Stackoverflow.com/users/8136",
"pm_score": 2,
"selected": false,
"text": "<p>You need a server or a library to process the xml into html. In my opinion, XQuery is much better than XSLT at this sort of thing when you are dealing with anything slightly complex. It is a much cleaner language as well. This website has <a href=\"http://www.sqlsummit.com/XQueryProv.htm\" rel=\"nofollow noreferrer\">a nice list of XQuery processors</a>.</p>\n"
},
{
"answer_id": 7137531,
"author": "masoud ramezani",
"author_id": 191997,
"author_profile": "https://Stackoverflow.com/users/191997",
"pm_score": 1,
"selected": false,
"text": "<p>please see the below link :</p>\n\n<p><a href=\"http://beyondrelational.com/blogs/jacob/archive/2009/08/19/xquery-lab-47-generating-html-table-from-xml-data.aspx\" rel=\"nofollow\">http://beyondrelational.com/blogs/jacob/archive/2009/08/19/xquery-lab-47-generating-html-table-from-xml-data.aspx</a></p>\n"
},
{
"answer_id": 7285610,
"author": "Basel Shishani",
"author_id": 804138,
"author_profile": "https://Stackoverflow.com/users/804138",
"pm_score": 1,
"selected": false,
"text": "<p>There can be many scenarios for using XQuery in a website development setting:</p>\n\n<p><strong>Generating pages dynamically:</strong></p>\n\n<p>You would need a library that provides an API that you can call from your server-side code, this would be the case if your XML data is stored say in a conventional database or on the file system. For example: Zorba provides such an API for PHP, and there is the XQuery API for Java etc.</p>\n\n<p>If your XML data is stored in an XML database server that supports XQuery, then you would issue your XQuery queries to the server and get the results back. There are many open source and commercial products in this category. BaseX is an open source example.</p>\n\n<p><strong>Generating pages statically:</strong></p>\n\n<p>You might wish to generate some of the HTML pages statically from XML data. In this case you can run a command line XQuery utility, for example Zorba, Saxon, BaseX and many others provide such CLI tools. Or you can also do it from your own scripts using an API.</p>\n\n<p>Then you would define rules in your build system to execute these commands or scripts whenever your XML data changes.</p>\n\n<p>In both the static and dynamic approaches, you can set your environment so that XQuery plays along with your templating system, for example, instead of generating whole HTML pages by XQuery, you can generate HTML segments based on XML, and then plug them into your templates.</p>\n\n<p><strong>Uses other than transformations:</strong></p>\n\n<p>The above cases are about transforming XML to HTML, but XQuery can be used in other ways in the web development process. One way I find it useful is to modify XML documents. Say you have a long XML document and you would like to modify field values or add fields or attributes - you can use the XQuery Update Facility extension to achieve that.</p>\n\n<p>Hope this helps. I didn't discuss your example because I assume it's just for clarification.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have been reading a lot of XQuery tutorials on the website. Almost all of them are teaching me XQuery syntax. Let's say I have understood the XQuery syntax, how am I going to actually implement XQuery on my website?
For example, I have **book.xml**:
```
<?xml version="1.0" encoding="iso-8859-1" ?>
<books>
<book>
<title>Doraemon</title>
<authorid>1</authorid>
</book>
<book>
<title>Ultraman</title>
<authorid>2</authorid>
</book>
</books>
```
Then, I have **author.xml**
```
<?xml version="1.0" encoding="iso-8859-1" ?>
<authors>
<author id="1">Mr A</author>
<author id="2">Mr B</author>
</authors>
```
I want to generate HTML which looks like following:
```
<table>
<tr> <td>Title</td> <td>Author</td> </tr>
<tr> <td>Doraemon</td> <td>Mr A</td> </tr>
<tr> <td>Ultraman</td> <td>Mr B</td> </tr>
</table>
```
Please show me some examples. Or any website that I can do reference. Thanks very much. | ```
(: file: titles.xqy :)
<table>
<tr><th>title</th><th>author</th></tr>
{
let $books-doc := doc("books.xml")
let $authors-doc := doc("authors.xml")
for $b in $books-doc//book,
$a in $authors-doc//author
where $a/@id = $b/authorid
return
<tr>
<td>{$b/title/text()}</td>
<td>{$a/text()}</td>
</tr>
}
``` |
80,787 | <p>Any ideas how to determine the number of active threads currently running in an <a href="https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html" rel="noreferrer"><code>ExecutorService</code></a>?</p>
| [
{
"answer_id": 80809,
"author": "Daan",
"author_id": 197,
"author_profile": "https://Stackoverflow.com/users/197",
"pm_score": 7,
"selected": true,
"text": "<p>Use a <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html\" rel=\"noreferrer\">ThreadPoolExecutor</a> implementation and call <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getActiveCount()\" rel=\"noreferrer\">getActiveCount()</a> on it:</p>\n\n<pre><code>int getActiveCount() \n// Returns the approximate number of threads that are actively executing tasks.\n</code></pre>\n\n<p>The ExecutorService interface does not provide a method for that, it depends on the implementation.</p>\n"
},
{
"answer_id": 80814,
"author": "Javaxpert",
"author_id": 15241,
"author_profile": "https://Stackoverflow.com/users/15241",
"pm_score": -1,
"selected": false,
"text": "<p>Place a static volatile counter on the thread which is updated whenever the thread is activated and deactivated.\nAlso, see the API.</p>\n"
},
{
"answer_id": 80828,
"author": "Arno",
"author_id": 13685,
"author_profile": "https://Stackoverflow.com/users/13685",
"pm_score": 5,
"selected": false,
"text": "<p>Check the sourcecode for <code>Executors.newFixedThreadPool()</code>:</p>\n\n<pre><code>return new ThreadPoolExecutor(nThreads, nThreads,\n 0L, TimeUnit.MILLISECONDS,\n new LinkedBlockingQueue<Runnable>());\n</code></pre>\n\n<p>ThreadPoolExecutor has a getActiveCount() method. So you might either cast the ExecutorService to ThreadPoolExecutor, or use the above code directly to obtain one. You can then invoke <code>getActiveCount()</code>.</p>\n"
},
{
"answer_id": 80874,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 3,
"selected": false,
"text": "<p>The ExecutorService interface does not define a method to examine the number of worker threads in the pool, as this is an implementation detail</p>\n\n<pre><code>public int getPoolSize()\nReturns the current number of threads in the pool.\n</code></pre>\n\n<p>Is available on the ThreadPoolExecutor class</p>\n\n<pre>\nimport java.util.concurrent.LinkedBlockingQueue;\nimport java.util.concurrent.ThreadPoolExecutor;\nimport java.util.concurrent.TimeUnit;\n\n\npublic class PoolSize {\n\n public static void main(String[] args) {\n ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 20, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue());\n System.out.println(executor.getPoolSize());\n }\n}\n</pre>\n\n<p>But this requires you to explicitly create the ThreadPoolExecutor, rather than using the Executors factory which returns ExecutorService objects. You could always create your own factory that returned ThreadPoolExecutors, but you would still be left with the bad form of using the concrete type, not its interface.</p>\n\n<p>One possibility would be to provide your own ThreadFactory which creates threads in a known thread group, which you can then count</p>\n\n<pre>\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\nimport java.util.concurrent.ThreadFactory;\n\n\npublic class PoolSize2 {\n\n public static void main(String[] args) {\n final ThreadGroup threadGroup = new ThreadGroup(\"workers\");\n\n ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {\n public Thread newThread(Runnable r) {\n return new Thread(threadGroup, r);\n }\n });\n\n System.out.println(threadGroup.activeCount());\n }\n}\n</pre>\n"
},
{
"answer_id": 18563922,
"author": "andyroid",
"author_id": 1546403,
"author_profile": "https://Stackoverflow.com/users/1546403",
"pm_score": 5,
"selected": false,
"text": "<p>Assuming <code>pool</code> is the name of the ExecutorService instance:</p>\n\n<pre><code>if (pool instanceof ThreadPoolExecutor) {\n System.out.println(\n \"Pool size is now \" +\n ((ThreadPoolExecutor) pool).getActiveCount()\n );\n}\n</code></pre>\n"
},
{
"answer_id": 38182852,
"author": "Ankit Katiyar",
"author_id": 3373597,
"author_profile": "https://Stackoverflow.com/users/3373597",
"pm_score": 2,
"selected": false,
"text": "<p>I had same issue so created a simple Runnable to trace a ExecutorService instance. </p>\n\n<pre><code>import java.util.concurrent.ExecutorService;\nimport java.util.concurrent.ThreadPoolExecutor;\n\npublic class ExecutorServiceAnalyzer implements Runnable\n{\n private final ThreadPoolExecutor threadPoolExecutor;\n private final int timeDiff;\n\n public ExecutorServiceAnalyzer(ExecutorService executorService, int timeDiff)\n {\n this.timeDiff = timeDiff;\n if (executorService instanceof ThreadPoolExecutor)\n {\n threadPoolExecutor = (ThreadPoolExecutor) executorService;\n }\n else\n {\n threadPoolExecutor = null;\n System.out.println(\"This executor doesn't support ThreadPoolExecutor \");\n }\n\n }\n\n @Override\n public void run()\n {\n if (threadPoolExecutor != null)\n {\n do\n {\n System.out.println(\"#### Thread Report:: Active:\" + threadPoolExecutor.getActiveCount() + \" Pool: \"\n + threadPoolExecutor.getPoolSize() + \" MaxPool: \" + threadPoolExecutor.getMaximumPoolSize()\n + \" ####\");\n try\n {\n Thread.sleep(timeDiff);\n }\n catch (Exception e)\n {\n }\n } while (threadPoolExecutor.getActiveCount() > 1);\n System.out.println(\"##### Terminating as only 1 thread is active ######\");\n }\n\n }\n}\n</code></pre>\n\n<p>You can simply use this with your executor to get states of ThreadPool </p>\n\n<p>Ex </p>\n\n<pre><code>ExecutorService executorService = Executors.newFixedThreadPool(4);\n executorService.execute(new ExecutorServiceAnalyzer(executorService, 1000));\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8441/"
]
| Any ideas how to determine the number of active threads currently running in an [`ExecutorService`](https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html)? | Use a [ThreadPoolExecutor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html) implementation and call [getActiveCount()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getActiveCount()) on it:
```
int getActiveCount()
// Returns the approximate number of threads that are actively executing tasks.
```
The ExecutorService interface does not provide a method for that, it depends on the implementation. |
80,788 | <p>I'm trying to get IKVM to build (see <a href="https://stackoverflow.com/questions/71599/how-to-get-ikvm-to-build-in-visual-studio-2008">this question</a>) but now have encountered a problem not having to do with IKVM so I'm opening up a new question:</p>
<p>When running nant on the IKVM directory with the Visual Studio 2008 Command Prompt (from the Start Menu), I get the following error:</p>
<blockquote>
<pre><code> ikvm-native-win32:
[cl] Compiling 2 files to C:\ikvm-0.36.0.11\native\Release'.
[cl] jni.c
[cl] os.c
[cl] C:\ikvm-0.36.0.11\native\os.c(25) : fatal error C1083: Cannot open include file: 'windows.h': No such
file or directory
[cl] Generating Code...
BUILD FAILED
C:\ikvm-0.36.0.11\native\native.build(17,10):
External Program Failed: cl (return code was 2)
</code></pre>
</blockquote>
<p>I have the Platform SDK installed. What am I missing? I'm sure it's something simple...</p>
<p><strong>Edit #1</strong> I just checked - I do have the directory containing windows.h on the Path.
<strong>Edit #2</strong> Found the answer (see my answer below): The directory containing windows.h needed to be in the "Include" path variable.</p>
| [
{
"answer_id": 81226,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 4,
"selected": true,
"text": "<p>OK here is the answer I ended up finding: rather than being on the Path, the directory with windows.h (in my case, C:\\Program Files\\Microsoft SDKs\\Windows\\v6.0A\\Include) needed to be set in the Include environment variable.</p>\n"
},
{
"answer_id": 446658,
"author": "abatishchev",
"author_id": 41956,
"author_profile": "https://Stackoverflow.com/users/41956",
"pm_score": 1,
"selected": false,
"text": "<p>By the way, create environment variable %LIB%, meaning the same - path to all SDKs lib directories</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
]
| I'm trying to get IKVM to build (see [this question](https://stackoverflow.com/questions/71599/how-to-get-ikvm-to-build-in-visual-studio-2008)) but now have encountered a problem not having to do with IKVM so I'm opening up a new question:
When running nant on the IKVM directory with the Visual Studio 2008 Command Prompt (from the Start Menu), I get the following error:
>
>
> ```
> ikvm-native-win32:
>
> [cl] Compiling 2 files to C:\ikvm-0.36.0.11\native\Release'.
>
> [cl] jni.c
> [cl] os.c
> [cl] C:\ikvm-0.36.0.11\native\os.c(25) : fatal error C1083: Cannot open include file: 'windows.h': No such
> file or directory
> [cl] Generating Code...
>
> BUILD FAILED
>
> C:\ikvm-0.36.0.11\native\native.build(17,10):
> External Program Failed: cl (return code was 2)
>
> ```
>
>
I have the Platform SDK installed. What am I missing? I'm sure it's something simple...
**Edit #1** I just checked - I do have the directory containing windows.h on the Path.
**Edit #2** Found the answer (see my answer below): The directory containing windows.h needed to be in the "Include" path variable. | OK here is the answer I ended up finding: rather than being on the Path, the directory with windows.h (in my case, C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include) needed to be set in the Include environment variable. |
80,801 | <p>If I have a large number of SQLite databases, all with the same schema, what is the best way to merge them together in order to perform a query on all databases? </p>
<p>I know it is possible to use <a href="http://www.sqlite.org/lang_attach.html" rel="noreferrer">ATTACH</a> to do this but it has <a href="http://www.sqlite.org/limits.html#max_attached" rel="noreferrer">a limit</a> of 32 and 64 databases depending on the memory system on the machine.</p>
| [
{
"answer_id": 80812,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>If you only need to do this merge operation once (to create a new bigger database), you could create a script/program that will loop all your sqlite databases and then insert the data into your main (big) database.</p>\n"
},
{
"answer_id": 81488,
"author": "Robert Gould",
"author_id": 15124,
"author_profile": "https://Stackoverflow.com/users/15124",
"pm_score": -1,
"selected": false,
"text": "<p>With no offense, just as one developer to another, I'm afraid that your idea seems terribly inefficient.\nIt seems to me that instead of uniting SQLite databases you should probably be storing several tables within the same Database file.</p>\n\n<p>However if I'm mistaken I guess you could ATTACH the databases and then use a VIEW to simplify your queries. Or make an in-memory table and copy over all the data (but that's even worse performance wise, especially if you have large databases)</p>\n"
},
{
"answer_id": 11089277,
"author": "dfrankow",
"author_id": 34935,
"author_profile": "https://Stackoverflow.com/users/34935",
"pm_score": 7,
"selected": false,
"text": "<p>To summarize from the <a href=\"https://web.archive.org/web/20120615034014/http://sqlite.1065341.n5.nabble.com/Attempting-to-merge-large-databases-td39548.html\" rel=\"noreferrer\">Nabble post</a> in DavidM's answer:</p>\n<pre><code>attach 'c:\\test\\b.db3' as toMerge; \nBEGIN; \ninsert into AuditRecords select * from toMerge.AuditRecords; \nCOMMIT; \ndetach toMerge;\n</code></pre>\n<p>Repeat as needed.</p>\n<p><em>Note: added <code>detach toMerge;</code> as per mike's comment.</em></p>\n"
},
{
"answer_id": 53313528,
"author": "Damilola Olowookere",
"author_id": 1823554,
"author_profile": "https://Stackoverflow.com/users/1823554",
"pm_score": 3,
"selected": false,
"text": "<p>Although a very old thread, this is still a relevant question in today's programming needs. I am posting this here because none of the answers provided yet is concise, easy, and straight-to-point. This is for sake of Googlers that end up on this page. GUI we go:</p>\n\n<ol>\n<li>Download <a href=\"https://sqlitestudio.pl/index.rvt?act=download\" rel=\"noreferrer\">Sqlitestudio</a> </li>\n<li>Add all your database files by using the <code>Ctrl + O</code> keyboard shortcut</li>\n<li>Double-click each now-loaded db file to open/activate/expand them all</li>\n<li>Fun part: simply right-click on each of the tables and click on <code>Copy</code>, and then go to the target database in the list of the loaded database files (or create new one if required) and right-click on the target db and click on <code>Paste</code></li>\n</ol>\n\n<p>I was wowed to realize that such a daunting task can be solved using the ancient programming skill called: copy-and-paste :)</p>\n"
},
{
"answer_id": 61954182,
"author": "Pedro Lobito",
"author_id": 797495,
"author_profile": "https://Stackoverflow.com/users/797495",
"pm_score": 2,
"selected": false,
"text": "<p>Late answer, but you can use:</p>\n\n<pre><code>#!/usr/bin/python\n\nimport sys, sqlite3\n\nclass sqlMerge(object):\n \"\"\"Basic python script to merge data of 2 !!!IDENTICAL!!!! SQL tables\"\"\"\n\n def __init__(self, parent=None):\n super(sqlMerge, self).__init__()\n\n self.db_a = None\n self.db_b = None\n\n def loadTables(self, file_a, file_b):\n self.db_a = sqlite3.connect(file_a)\n self.db_b = sqlite3.connect(file_b)\n\n cursor_a = self.db_a.cursor()\n cursor_a.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")\n\n table_counter = 0\n print(\"SQL Tables available: \\n===================================================\\n\")\n for table_item in cursor_a.fetchall():\n current_table = table_item[0]\n table_counter += 1\n print(\"-> \" + current_table)\n print(\"\\n===================================================\\n\")\n\n if table_counter == 1:\n table_to_merge = current_table\n else:\n table_to_merge = input(\"Table to Merge: \")\n\n return table_to_merge\n\n def merge(self, table_name):\n cursor_a = self.db_a.cursor()\n cursor_b = self.db_b.cursor()\n\n new_table_name = table_name + \"_new\"\n\n try:\n cursor_a.execute(\"CREATE TABLE IF NOT EXISTS \" + new_table_name + \" AS SELECT * FROM \" + table_name)\n for row in cursor_b.execute(\"SELECT * FROM \" + table_name):\n print(row)\n cursor_a.execute(\"INSERT INTO \" + new_table_name + \" VALUES\" + str(row) +\";\")\n\n cursor_a.execute(\"DROP TABLE IF EXISTS \" + table_name);\n cursor_a.execute(\"ALTER TABLE \" + new_table_name + \" RENAME TO \" + table_name);\n self.db_a.commit()\n\n print(\"\\n\\nMerge Successful!\\n\")\n\n except sqlite3.OperationalError:\n print(\"ERROR!: Merge Failed\")\n cursor_a.execute(\"DROP TABLE IF EXISTS \" + new_table_name);\n\n finally:\n self.db_a.close()\n self.db_b.close()\n\n return\n\n def main(self):\n print(\"Please enter name of db file\")\n file_name_a = input(\"File Name A:\")\n file_name_b = input(\"File Name B:\")\n\n table_name = self.loadTables(file_name_a, file_name_b)\n self.merge(table_name)\n\n return\n\nif __name__ == '__main__':\n app = sqlMerge()\n app.main()\n</code></pre>\n\n<hr>\n\n<p>SRC : <a href=\"https://github.com/kd8bny/sqlMerge\" rel=\"nofollow noreferrer\">Tool to merge identical SQLite3 databases</a> </p>\n"
},
{
"answer_id": 62630929,
"author": "Taba",
"author_id": 8346770,
"author_profile": "https://Stackoverflow.com/users/8346770",
"pm_score": -1,
"selected": false,
"text": "<p>If you have reached the bottom of this feed and yet didn't find your solution, here is also a way to merge the tables of 2 or more sqlite databases.</p>\n<p>First try to download and install <a href=\"https://sqlitebrowser.org/\" rel=\"nofollow noreferrer\">DB browser for sqlite database</a>. Then try to open your databases in 2 windows and try merging them by simply <strong>drag and drop</strong> tables from one to another. But the problem is that you can just drag and drop only <strong>one</strong> table at a time and therefore its not really a solution for this answer specifically but yet it can used to save some time from further searches if your database is small.</p>\n"
},
{
"answer_id": 68526717,
"author": "Mohammadsadegh",
"author_id": 11586886,
"author_profile": "https://Stackoverflow.com/users/11586886",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a simple python code to either merge two database files or scan a directory to find all database files and merge them all together (by simply inserting all data in other files to the first database file found).Note that this code just attaches the databases with the same schema.</p>\n<pre><code>import sqlite3\nimport os\n\n\ndef merge_databases(db1, db2):\n con3 = sqlite3.connect(db1)\n\n con3.execute("ATTACH '" + db2 + "' as dba")\n\n con3.execute("BEGIN")\n for row in con3.execute("SELECT * FROM dba.sqlite_master WHERE type='table'"):\n combine = "INSERT OR IGNORE INTO "+ row[1] + " SELECT * FROM dba." + row[1]\n print(combine)\n con3.execute(combine)\n con3.commit()\n con3.execute("detach database dba")\n\n\ndef read_files(directory):\n fname = []\n for root,d_names,f_names in os.walk(directory):\n for f in f_names:\n c_name = os.path.join(root, f)\n filename, file_extension = os.path.splitext(c_name)\n if (file_extension == '.sqlitedb'):\n fname.append(c_name)\n\n return fname\n\ndef batch_merge(directory):\n db_files = read_files(directory)\n for db_file in db_files[1:]:\n merge_databases(db_files[0], db_file)\n\nif __name__ == '__main__':\n batch_merge('/directory/to/database/files')\n</code></pre>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
]
| If I have a large number of SQLite databases, all with the same schema, what is the best way to merge them together in order to perform a query on all databases?
I know it is possible to use [ATTACH](http://www.sqlite.org/lang_attach.html) to do this but it has [a limit](http://www.sqlite.org/limits.html#max_attached) of 32 and 64 databases depending on the memory system on the machine. | To summarize from the [Nabble post](https://web.archive.org/web/20120615034014/http://sqlite.1065341.n5.nabble.com/Attempting-to-merge-large-databases-td39548.html) in DavidM's answer:
```
attach 'c:\test\b.db3' as toMerge;
BEGIN;
insert into AuditRecords select * from toMerge.AuditRecords;
COMMIT;
detach toMerge;
```
Repeat as needed.
*Note: added `detach toMerge;` as per mike's comment.* |
80,802 | <p>I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript? </p>
<pre><code>for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = function() {
// do something
};
}
</code></pre>
<p>vs</p>
<pre><code>function myEventHandler() {
// do something
}
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = myEventHandler;
}
</code></pre>
<p>The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times?</p>
| [
{
"answer_id": 80823,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 2,
"selected": false,
"text": "<p>As a general design principle, you should avoid implimenting the same code multiple times. Instead you should lift common code out into a function and execute that (general, well tested, easy to modify) function from multiple places.</p>\n\n<p>If (unlike what you infer from your question) you are declaring the internal function once and using that code once (and have nothing else identical in your program) then an anonomous function <em>probably</em> (thats a guess folks) gets treated the same way by the compiler as a normal named function.</p>\n\n<p>Its a very useful feature in specific instances, but shouldn't be used in many situations.</p>\n"
},
{
"answer_id": 80840,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 1,
"selected": false,
"text": "<p>I wouldn't expect much difference but if there is one it will likely vary by scripting engine or browser. </p>\n\n<p>If you find the code easier to grok, performance is a non-issue unless you expect to call the function millions of times.</p>\n"
},
{
"answer_id": 80882,
"author": "Sarhanis",
"author_id": 7966,
"author_profile": "https://Stackoverflow.com/users/7966",
"pm_score": 0,
"selected": false,
"text": "<p>What will definitely make your loop faster across a variety of browsers, especially IE browsers, is looping as follows:</p>\n\n<pre><code>for (var i = 0, iLength = imgs.length; i < iLength; i++)\n{\n // do something\n}\n</code></pre>\n\n<p>You've put in an arbitrary 1000 into the loop condition, but you get my drift if you wanted to go through all the items in the array.</p>\n"
},
{
"answer_id": 80927,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": false,
"text": "<p>Here's my test code:</p>\n\n<pre><code>var dummyVar;\nfunction test1() {\n for (var i = 0; i < 1000000; ++i) {\n dummyVar = myFunc;\n }\n}\n\nfunction test2() {\n for (var i = 0; i < 1000000; ++i) {\n dummyVar = function() {\n var x = 0;\n x++;\n };\n }\n}\n\nfunction myFunc() {\n var x = 0;\n x++;\n}\n\ndocument.onclick = function() {\n var start = new Date();\n test1();\n var mid = new Date();\n test2();\n var end = new Date();\n alert (\"Test 1: \" + (mid - start) + \"\\n Test 2: \" + (end - mid));\n}\n</code></pre>\n\n<p>The results:<br>\nTest 1: 142ms\nTest 2: 1983ms</p>\n\n<p>It appears that the JS engine doesn't recognise that it's the same function in Test2 and compiles it each time.</p>\n"
},
{
"answer_id": 81185,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 0,
"selected": false,
"text": "<p>@nickf</p>\n\n<p>That's a rather fatuous test though, you're comparing the execution <em>and compilation</em> time there which is obviously going to cost method 1 (compiles N times, JS engine depending) with method 2 (compiles once). I can't imagine a JS developer who would pass their probation writing code in such a manner.</p>\n\n<p>A far more realistic approach is the anonymous assignment, as in fact you're using for your document.onclick method is more like the following, which in fact mildly favours the anon method.</p>\n\n<p>Using a similar test framework to yours:</p>\n\n<hr>\n\n<pre><code>function test(m)\n{\n for (var i = 0; i < 1000000; ++i) \n {\n m();\n }\n}\n\nfunction named() {var x = 0; x++;}\n\nvar test1 = named;\n\nvar test2 = function() {var x = 0; x++;}\n\ndocument.onclick = function() {\n var start = new Date();\n test(test1);\n var mid = new Date();\n test(test2);\n var end = new Date();\n alert (\"Test 1: \" + (mid - start) + \"ms\\n Test 2: \" + (end - mid) + \"ms\");\n}\n</code></pre>\n"
},
{
"answer_id": 81329,
"author": "Atif Aziz",
"author_id": 6682,
"author_profile": "https://Stackoverflow.com/users/6682",
"pm_score": 8,
"selected": true,
"text": "<p>The performance problem here is the cost of creating a new function object at each iteration of the loop and not the fact that you use an anonymous function:</p>\n\n<pre><code>for (var i = 0; i < 1000; ++i) { \n myObjects[i].onMyEvent = function() {\n // do something \n };\n}\n</code></pre>\n\n<p>You are creating a thousand distinct function objects even though they have the same body of code and no binding to the lexical scope (<a href=\"http://www.google.com/search?q=javascript+closure\" rel=\"noreferrer\">closure</a>). The following seems faster, on the other hand, because it simply assigns the <em>same</em> function reference to the array elements throughout the loop:</p>\n\n<pre><code>function myEventHandler() {\n // do something\n}\n\nfor (var i = 0; i < 1000; ++i) {\n myObjects[i].onMyEvent = myEventHandler;\n}\n</code></pre>\n\n<p>If you were to create the anonymous function before entering the loop, then only assign references to it to the array elements while inside the loop, you will find that there is no performance or semantic difference whatsoever when compared to the named function version:</p>\n\n<pre><code>var handler = function() {\n // do something \n};\nfor (var i = 0; i < 1000; ++i) { \n myObjects[i].onMyEvent = handler;\n}\n</code></pre>\n\n<p>In short, there is no observable performance cost to using anonymous over named functions.</p>\n\n<p>As an aside, it may appear from above that there is no difference between:</p>\n\n<pre><code>function myEventHandler() { /* ... */ }\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>var myEventHandler = function() { /* ... */ }\n</code></pre>\n\n<p>The former is a <em>function declaration</em> whereas the latter is a variable assignment to an anonymous function. Although they may appear to have the same effect, JavaScript does treat them slightly differently. To understand the difference, I recommend reading, “<a href=\"http://www.dustindiaz.com/javascript-function-declaration-ambiguity/\" rel=\"noreferrer\">JavaScript function declaration ambiguity</a>”.</p>\n\n<p>The actual execution time for any approach is largely going to be dictated by the browser's implementation of the compiler and runtime. For a complete comparison of modern browser performance, visit <a href=\"http://jsperf.com/named-or-anonymous-functions/12\" rel=\"noreferrer\">the JS Perf site</a></p>\n"
},
{
"answer_id": 81354,
"author": "matt lohkamp",
"author_id": 14026,
"author_profile": "https://Stackoverflow.com/users/14026",
"pm_score": 0,
"selected": false,
"text": "<p>a reference is nearly always going to be slower then the thing it's refering to. Think of it this way - let's say you want to print the result of adding 1 + 1. Which makes more sense:</p>\n\n<pre><code>alert(1 + 1);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>a = 1;\nb = 1;\nalert(a + b);\n</code></pre>\n\n<p>I realize that's a really simplistic way to look at it, but it's illustrative, right? Use a reference only if it's going to be used multiple times - for instance, which of these examples makes more sense:</p>\n\n<pre><code>$(a.button1).click(function(){alert('you clicked ' + this);});\n$(a.button2).click(function(){alert('you clicked ' + this);});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>function buttonClickHandler(){alert('you clicked ' + this);}\n$(a.button1).click(buttonClickHandler);\n$(a.button2).click(buttonClickHandler);\n</code></pre>\n\n<p>The second one is better practice, even if it's got more lines. Hopefully all this is helpful. (and the jquery syntax didn't throw anyone off)</p>\n"
},
{
"answer_id": 81481,
"author": "Christopher Tokar",
"author_id": 315650,
"author_profile": "https://Stackoverflow.com/users/315650",
"pm_score": 0,
"selected": false,
"text": "<p>YES! Anonymous functions are faster than regular functions. Perhaps if speed is of the utmost importance... more important than code re-use then consider using anonymous functions.</p>\n\n<p>There is a really good article about optimizing javascript and anonymous functions here:</p>\n\n<p><a href=\"http://dev.opera.com/articles/view/efficient-javascript/?page=2\" rel=\"nofollow noreferrer\">http://dev.opera.com/articles/view/efficient-javascript/?page=2</a></p>\n"
},
{
"answer_id": 81726,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 0,
"selected": false,
"text": "<p>@nickf</p>\n\n<p>(wish I had the rep to just comment, but I've only just found this site)</p>\n\n<p>My point is that there is confusion here between named/anonymous functions and the use case of executing + compiling in an iteration. As I illustrated, the difference between anon+named is negligible in itself - I'm saying it's the use case which is faulty.</p>\n\n<p>It seems obvious to me, but if not I think the best advice is \"don't do dumb things\" (of which the constant block shifting + object creation of this use case is one) and if you aren't sure, test!</p>\n"
},
{
"answer_id": 83689,
"author": "pcorcoran",
"author_id": 15992,
"author_profile": "https://Stackoverflow.com/users/15992",
"pm_score": -1,
"selected": false,
"text": "<p>Anonymous objects are faster than named objects. But calling more functions is more expensive, and to a degree which eclipses any savings you might get from using anonymous functions. Each function called adds to the call stack, which introduces a small but non-trivial amount of overhead.</p>\n\n<p>But unless you're writing encryption/decryption routines or something similarly sensitive to performance, as many others have noted it's always better to optimize for elegant, easy-to-read code over fast code.</p>\n\n<p>Assuming you are writing well-architected code, then issues of speed should be the responsibility of those writing the interpreters/compilers.</p>\n"
},
{
"answer_id": 33904169,
"author": "Pablo Estornut",
"author_id": 4433714,
"author_profile": "https://Stackoverflow.com/users/4433714",
"pm_score": 1,
"selected": false,
"text": "<p>Where we can have a performance impact is in the operation of declaring functions. Here is a benchmark of declaring functions inside the context of another function or outside:</p>\n\n<p><a href=\"http://jsperf.com/function-context-benchmark\" rel=\"nofollow\">http://jsperf.com/function-context-benchmark</a></p>\n\n<p>In Chrome the operation is faster if we declare the function outside, but in Firefox it's the opposite.</p>\n\n<p>In other example we see that if the inner function is not a pure function, it will have a lack of performance also in Firefox:\n<a href=\"http://jsperf.com/function-context-benchmark-3\" rel=\"nofollow\">http://jsperf.com/function-context-benchmark-3</a></p>\n"
},
{
"answer_id": 44602865,
"author": "bluenote10",
"author_id": 1804173,
"author_profile": "https://Stackoverflow.com/users/1804173",
"pm_score": 0,
"selected": false,
"text": "<p>As pointed out in the comments to @nickf answer: The answer to </p>\n\n<blockquote>\n <p>Is creating a function once faster than creating it a million times</p>\n</blockquote>\n\n<p>is simply yes. But as his JS perf shows, it is not slower by a factor of a million, showing that it actually gets faster over time.</p>\n\n<p>The more interesting question to me is:</p>\n\n<blockquote>\n <p>How does a repeated <strong>create + run</strong> compare to create once + repeated <strong>run</strong>.</p>\n</blockquote>\n\n<p>If a function performs a complex computation the time to create the function object is most likely negligible. But what about the over head of <strong>create</strong> in cases where <strong>run</strong> is fast? For instance:</p>\n\n\n\n<pre><code>// Variant 1: create once\nfunction adder(a, b) {\n return a + b;\n}\nfor (var i = 0; i < 100000; ++i) {\n var x = adder(412, 123);\n}\n\n// Variant 2: repeated creation via function statement\nfor (var i = 0; i < 100000; ++i) {\n function adder(a, b) {\n return a + b;\n }\n var x = adder(412, 123);\n}\n\n// Variant 3: repeated creation via function expression\nfor (var i = 0; i < 100000; ++i) {\n var x = (function(a, b) { return a + b; })(412, 123);\n}\n</code></pre>\n\n<p>This <a href=\"https://jsperf.com/function-creation-performance-overhead/1\" rel=\"nofollow noreferrer\">JS Perf</a> shows that creating the function just once is faster as expected. However, even with a very quick operation like a simple add, the overhead of creating the function repeatedly is only a few percent.</p>\n\n<p>The difference probably only becomes significant in cases where creating the function object is complex, while maintaining a negligible run time, e.g., if the entire function body is wrapped into an <code>if (unlikelyCondition) { ... }</code>.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
]
| I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript?
```
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = function() {
// do something
};
}
```
vs
```
function myEventHandler() {
// do something
}
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = myEventHandler;
}
```
The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times? | The performance problem here is the cost of creating a new function object at each iteration of the loop and not the fact that you use an anonymous function:
```
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = function() {
// do something
};
}
```
You are creating a thousand distinct function objects even though they have the same body of code and no binding to the lexical scope ([closure](http://www.google.com/search?q=javascript+closure)). The following seems faster, on the other hand, because it simply assigns the *same* function reference to the array elements throughout the loop:
```
function myEventHandler() {
// do something
}
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = myEventHandler;
}
```
If you were to create the anonymous function before entering the loop, then only assign references to it to the array elements while inside the loop, you will find that there is no performance or semantic difference whatsoever when compared to the named function version:
```
var handler = function() {
// do something
};
for (var i = 0; i < 1000; ++i) {
myObjects[i].onMyEvent = handler;
}
```
In short, there is no observable performance cost to using anonymous over named functions.
As an aside, it may appear from above that there is no difference between:
```
function myEventHandler() { /* ... */ }
```
and:
```
var myEventHandler = function() { /* ... */ }
```
The former is a *function declaration* whereas the latter is a variable assignment to an anonymous function. Although they may appear to have the same effect, JavaScript does treat them slightly differently. To understand the difference, I recommend reading, “[JavaScript function declaration ambiguity](http://www.dustindiaz.com/javascript-function-declaration-ambiguity/)”.
The actual execution time for any approach is largely going to be dictated by the browser's implementation of the compiler and runtime. For a complete comparison of modern browser performance, visit [the JS Perf site](http://jsperf.com/named-or-anonymous-functions/12) |
80,820 | <p>On a file path field, I want to capture the directory path like:</p>
<pre><code>textbox1.Text = directory path
</code></pre>
<p>Anyone?</p>
| [
{
"answer_id": 80824,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p>There is a FolderBrowserDialog class that you can use if you want the user to select a folder.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx</a></p>\n\n<pre><code>DialogResult result = folderBrowserDialog1.ShowDialog();\nif (result.Equals(get_DialogResult().OK)) {\n textbox1.Text = folderBrowserDialog1.get_SelectedPath();\n}\n</code></pre>\n\n<p>If all you want is to get the direcotory from a full path, you can do this:</p>\n\n<pre><code>textbox1.Text = Path.GetDirectoryName(@\"c:\\windows\\temp\\myfile.txt\");\n</code></pre>\n\n<p>This will set the Text-property to \"c:\\windows\\temp\\\"</p>\n"
},
{
"answer_id": 81047,
"author": "MarlonRibunal",
"author_id": 10385,
"author_profile": "https://Stackoverflow.com/users/10385",
"pm_score": 3,
"selected": true,
"text": "<p>Well I am using VS 2008 SP1. This all I need:</p>\n\n<pre><code>private void button1_Click(object sender, EventArgs e)\n{\n FolderBrowserDialog profilePath = new FolderBrowserDialog();\n\n if (profilePath.ShowDialog() == DialogResult.OK) \n {\n profilePathTextBox.Text = profilePath.SelectedPath;\n }\n else\n {\n profilePathTextBox.Text = \"Please Specify The Profile Path\";\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6281800,
"author": "Pat",
"author_id": 116891,
"author_profile": "https://Stackoverflow.com/users/116891",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want a terrible, non-user friendly dialog*, try <a href=\"http://www.ookii.org/software/dialogs/\" rel=\"nofollow noreferrer\">Ookii.Dialogs</a> or see other answers to <a href=\"https://stackoverflow.com/questions/31059/how-do-you-configure-an-openfiledialog-to-select-folders\">How do you configure an OpenFileDialog to select folders?</a>. The only downside I see to Ookii is that it requires .NET 4 Full, not just Client Profile. But the source is included in the download, so I'm going to work on that. Too bad the license isn't LGPL or similar...</p>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/4342895/winforms-message-box-with-textual-buttons\">WinForms message box with textual buttons</a></p>\n\n<p>*This is what FolderBrowserDialog looks like:</p>\n\n<p><img src=\"https://i.stack.imgur.com/NvD6F.png\" alt=\"Ugly, unfriendly folder browser dialog\"></p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10385/"
]
| On a file path field, I want to capture the directory path like:
```
textbox1.Text = directory path
```
Anyone? | Well I am using VS 2008 SP1. This all I need:
```
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog profilePath = new FolderBrowserDialog();
if (profilePath.ShowDialog() == DialogResult.OK)
{
profilePathTextBox.Text = profilePath.SelectedPath;
}
else
{
profilePathTextBox.Text = "Please Specify The Profile Path";
}
}
``` |
80,831 | <p>There is a <a href="http://support.microsoft.com/?scid=194627" rel="nofollow noreferrer">Microsoft knowledge base article</a> with sample code to open all mailboxes in a given information store. It works so far (requires a bit of <a href="http://blogs.msdn.com/jasonjoh/archive/2004/08/01/204585.aspx" rel="nofollow noreferrer">copy & pasting</a> on compilers newer than VC++ 6.0).</p>
<p>At one point it calls IExchangeManageStore::GetMailboxTable with the distinguished name of the information store. For the Exchange 2007 Trial Virtual Server image it has to look like this: </p>
<pre><code>"/o=Litware Inc/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=servers/cn=DC1".
</code></pre>
<p>Using <a href="http://www.dimastr.com/outspy/" rel="nofollow noreferrer">OutlookSpy</a> and clicking on IMsgStore and IExchangeManageStore reveals the desired string next to "Server DN:".</p>
<p>I want to avoid forcing the user to put this into a config file. So if OutlookSpy can do it, how can my application find out the distinguished name of the information store where the currently open mailbox is on?</p>
| [
{
"answer_id": 82342,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 0,
"selected": false,
"text": "<p>It'll be in Active Directory, so you'd use ADSI/LDAP to look at CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=<em>example</em>,DC=<em>com</em>. Use Sysinternals' ADExplorer to have a dig around in there to find the value you're looking for.</p>\n"
},
{
"answer_id": 90972,
"author": "Sebastian Kirsche",
"author_id": 4097,
"author_profile": "https://Stackoverflow.com/users/4097",
"pm_score": 3,
"selected": true,
"text": "<p>Thinking there must be a pure MAPI solution, I believe I've figured out how OutlookSpy does it.\n<br><br><br>\nThe following code snippet, inserted after </p>\n\n<pre><code>printf(\"Created MAPI session\\n\");\n</code></pre>\n\n<p>in the example from <a href=\"http://support.microsoft.com/kb/194627\" rel=\"nofollow noreferrer\">KB194627</a>, will show the <em>Server DN</em>.</p>\n\n<pre><code>LPPROFSECT lpProfSect;\nhr = lpSess->OpenProfileSection((LPMAPIUID)pbGlobalProfileSectionGuid, NULL, 0, &lpProfSect);\nif(SUCCEEDED(hr))\n{\n LPSPropValue lpPropValue;\n hr = HrGetOneProp(lpProfSect, PR_PROFILE_HOME_SERVER_DN, &lpPropValue);\n if(SUCCEEDED(hr))\n {\n printf(\"Server DN: %s\\n\", lpPropValue->Value.lpszA);\n MAPIFreeBuffer(lpPropValue);\n }\n lpProfSect->Release();\n}\n</code></pre>\n\n<p><br><br>\n<strong>Update:</strong><br>\nThere is the function <em>HrGetServerDN</em> in the <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=36a309c3-8c55-4476-8785-cafc59a2d075&DisplayLang=en\" rel=\"nofollow noreferrer\">EDK 5.5 source code</a>, it extracts the <em>Server DN</em> from a given session's <em>PR_EMS_AB_HOME_MTA</em>. I'll try it if the other way turns out to be unreliable.</p>\n"
},
{
"answer_id": 400448,
"author": "Cain T. S. Random",
"author_id": 45341,
"author_profile": "https://Stackoverflow.com/users/45341",
"pm_score": 0,
"selected": false,
"text": "<p>I'd download the source for MFCMapi and see how they do this.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4097/"
]
| There is a [Microsoft knowledge base article](http://support.microsoft.com/?scid=194627) with sample code to open all mailboxes in a given information store. It works so far (requires a bit of [copy & pasting](http://blogs.msdn.com/jasonjoh/archive/2004/08/01/204585.aspx) on compilers newer than VC++ 6.0).
At one point it calls IExchangeManageStore::GetMailboxTable with the distinguished name of the information store. For the Exchange 2007 Trial Virtual Server image it has to look like this:
```
"/o=Litware Inc/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=servers/cn=DC1".
```
Using [OutlookSpy](http://www.dimastr.com/outspy/) and clicking on IMsgStore and IExchangeManageStore reveals the desired string next to "Server DN:".
I want to avoid forcing the user to put this into a config file. So if OutlookSpy can do it, how can my application find out the distinguished name of the information store where the currently open mailbox is on? | Thinking there must be a pure MAPI solution, I believe I've figured out how OutlookSpy does it.
The following code snippet, inserted after
```
printf("Created MAPI session\n");
```
in the example from [KB194627](http://support.microsoft.com/kb/194627), will show the *Server DN*.
```
LPPROFSECT lpProfSect;
hr = lpSess->OpenProfileSection((LPMAPIUID)pbGlobalProfileSectionGuid, NULL, 0, &lpProfSect);
if(SUCCEEDED(hr))
{
LPSPropValue lpPropValue;
hr = HrGetOneProp(lpProfSect, PR_PROFILE_HOME_SERVER_DN, &lpPropValue);
if(SUCCEEDED(hr))
{
printf("Server DN: %s\n", lpPropValue->Value.lpszA);
MAPIFreeBuffer(lpPropValue);
}
lpProfSect->Release();
}
```
**Update:**
There is the function *HrGetServerDN* in the [EDK 5.5 source code](http://www.microsoft.com/downloads/details.aspx?FamilyID=36a309c3-8c55-4476-8785-cafc59a2d075&DisplayLang=en), it extracts the *Server DN* from a given session's *PR\_EMS\_AB\_HOME\_MTA*. I'll try it if the other way turns out to be unreliable. |
80,846 | <p>I am trying to use Zend_Db_Select to write a select query that looks somewhat like this:</p>
<pre><code>SELECT * FROM bar WHERE a = 1 AND (b = 2 OR b = 3)
</code></pre>
<p>However, when using a combination of where() and orWhere(), it seems impossible to use condition grouping like the above.</p>
<p>Are there any native ways in Zend Framework to achieve the above (without writing the actual query?)</p>
| [
{
"answer_id": 80871,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>From <a href=\"http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.where\" rel=\"nofollow noreferrer\">the manual</a> (Example 11.61. Example of parenthesizing Boolean expressions)</p>\n\n<pre><code>\n// Build this query:\n// SELECT product_id, product_name, price\n// FROM \"products\"\n// WHERE (price < 100.00 OR price > 500.00)\n// AND (product_name = 'Apple')\n\n$minimumPrice = 100;\n$maximumPrice = 500;\n$prod = 'Apple';\n\n$select = $db->select()\n ->from('products',\n array('product_id', 'product_name', 'price'))\n ->where(\"price < $minimumPrice OR price > $maximumPrice\")\n ->where('product_name = ?', $prod);\n\n</code></pre>\n"
},
{
"answer_id": 727266,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The above reference is great, but what if you are playing with strings?</p>\n\n<p>Here would is the above example with strings...</p>\n\n<pre><code>// Build this query:\n// SELECT product_id, product_name, price\n// FROM \"products\"\n// WHERE (product_name = 'Bananas' OR product_name = 'Apples')\n// AND (price = 100)\n\n$name1 = 'Bananas';\n\n$name2 = 'Apples';\n\n$price = 100;\n\n$select = $db->select()\n\n->from('products',\n array('product_id', 'product_name', 'price'))\n\n->where(\"product_name = '\" . $name1 . \"' OR product_name = '\" . $name2 . \"'\")\n\n->where(\"price=?\", $price);\n</code></pre>\n\n<p>I hope that helps. Took me some fooling around to get the strings to work correctly.</p>\n\n<p>Cheers.</p>\n"
}
]
| 2008/09/17 | [
"https://Stackoverflow.com/questions/80846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11568/"
]
| I am trying to use Zend\_Db\_Select to write a select query that looks somewhat like this:
```
SELECT * FROM bar WHERE a = 1 AND (b = 2 OR b = 3)
```
However, when using a combination of where() and orWhere(), it seems impossible to use condition grouping like the above.
Are there any native ways in Zend Framework to achieve the above (without writing the actual query?) | From [the manual](http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.where) (Example 11.61. Example of parenthesizing Boolean expressions)
```
// Build this query:
// SELECT product_id, product_name, price
// FROM "products"
// WHERE (price < 100.00 OR price > 500.00)
// AND (product_name = 'Apple')
$minimumPrice = 100;
$maximumPrice = 500;
$prod = 'Apple';
$select = $db->select()
->from('products',
array('product_id', 'product_name', 'price'))
->where("price < $minimumPrice OR price > $maximumPrice")
->where('product_name = ?', $prod);
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.