qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
4
<p>I want to assign the decimal variable &quot;trans&quot; to the double variable &quot;this.Opacity&quot;.</p> <pre class="lang-cs prettyprint-override"><code>decimal trans = trackBar1.Value / 5000; this.Opacity = trans; </code></pre> <p>When I build the app it gives the following error:</p> <blockquote> <p>Cannot implicitly convert type decimal to double</p> </blockquote>
[ { "answer_id": 7, "author": "Kevin Dente", "author_id": 9, "author_profile": "https://Stackoverflow.com/users/9", "pm_score": 10, "selected": true, "text": "double double trans = (double) trackBar1.Value / 5000.0;\n 5000.0 5000d double trans = trackBar1.Value / 5000.0;\ndouble trans = trackBar1.Value / 5000d;\n" }, { "answer_id": 78, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 6, "selected": false, "text": "this.Opacity" }, { "answer_id": 2791, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 6, "selected": false, "text": ".0 decimal.ToDouble() // Example 1\ndouble transparency = trackBar1.Value/5000;\nthis.Opacity = decimal.ToDouble(transparency);\n\n// Example 2 - with inline temp\nthis.Opacity = decimal.ToDouble(trackBar1.Value/5000);\n" }, { "answer_id": 7263, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 7, "selected": false, "text": "decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = (double) trans;\n (double)" }, { "answer_id": 110198, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 7, "selected": false, "text": "private void Form1_Load(object sender, System.EventArgs e)\n{\n TrackBar1.Minimum = 20;\n TrackBar1.Maximum = 100;\n\n TrackBar1.LargeChange = 10;\n TrackBar1.SmallChange = 1;\n TrackBar1.TickFrequency = 5;\n}\n\nprivate void TrackBar1_Scroll(object sender, System.EventArgs e)\n{\n this.Opacity = TrackBar1.Value / 100;\n}\n" }, { "answer_id": 305467, "author": "Dinah", "author_id": 356, "author_profile": "https://Stackoverflow.com/users/356", "pm_score": 6, "selected": false, "text": "5000.0 5000" }, { "answer_id": 594436, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": false, "text": "Opacity TrackBar.Value trackBar.Value trackBar.Value trackBar.Opacity = (double)trackBar.Value / 5000.0;\n" }, { "answer_id": 7262112, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 6, "selected": false, "text": "double trans = trackBar1.Value / 5000.0;\nthis.Opacity = trans;\n this.Opacity = trackBar1.Value / 5000.0;\n this.Opacity = trackBar1.Value / 5000d;\n 5000.0 5000d trackBar1.Value" }, { "answer_id": 7262131, "author": "ChrisF", "author_id": 59303, "author_profile": "https://Stackoverflow.com/users/59303", "pm_score": 6, "selected": false, "text": "Form.Opacity double double trans = trackBar1.Value / 5000.0;\nthis.Opacity = trans;\n this.Opacity = trackBar1.Value / 5000.0;\n double trans = trackbar1.Value / 5000;\n 5000 trackbar1.Value trans .0" }, { "answer_id": 9579950, "author": "Danny Fox", "author_id": 1091828, "author_profile": "https://Stackoverflow.com/users/1091828", "pm_score": 6, "selected": false, "text": "this.Opacity = decimal.ToDouble(trackBar1.Value/5000);\n" }, { "answer_id": 10568821, "author": "Darryl", "author_id": 1391700, "author_profile": "https://Stackoverflow.com/users/1391700", "pm_score": 6, "selected": false, "text": "Opacity Opacity = trackBar1.Value / 5000.0;\n" }, { "answer_id": 71840515, "author": "Arnold Brown", "author_id": 5049244, "author_profile": "https://Stackoverflow.com/users/5049244", "pm_score": 1, "selected": false, "text": "decimal d1 = 3234.3434m;\n double r1 = Decimal.ToDouble(d1);\n" }, { "answer_id": 72996737, "author": "David Rodrigues", "author_id": 5768360, "author_profile": "https://Stackoverflow.com/users/5768360", "pm_score": 1, "selected": false, "text": "Double Decimal decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = (double) trans;\n decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = decimal.ToDouble(trans);\n 5000d 5000.0 decimal 1.0 1d" } ]
2008/07/31
[ "https://Stackoverflow.com/questions/4", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8/" ]
6
<p>I have an absolutely positioned <code>div</code> containing several children, one of which is a relatively positioned <code>div</code>. When I use a <code>percentage-based width</code> on the child <code>div</code>, it collapses to <code>0 width</code> on IE7, but not on Firefox or Safari.</p> <p>If I use <code>pixel width</code>, it works. If the parent is relatively positioned, the percentage width on the child works.</p> <ol> <li>Is there something I'm missing here?</li> <li>Is there an easy fix for this besides the <code>pixel-based width</code> on the child?</li> <li>Is there an area of the CSS specification that covers this?</li> </ol>
[ { "answer_id": 31, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "div width div width div" }, { "answer_id": 1948, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 6, "selected": false, "text": "#absdiv {\n position: absolute; \n left: 100px; \n top: 100px; \n width: 80%; \n height: 60%; \n background: #999;\n}\n\n#pctchild {\n width: 60%; \n height: 40%; \n background: #CCC;\n}\n\n#reldiv {\n position: relative;\n left: 20px;\n top: 20px;\n height: 25px;\n width: 40%;\n background: red;\n} <div id=\"absdiv\">\n <div id=\"reldiv\"></div>\n <div id=\"pctchild\"></div>\n</div>" }, { "answer_id": 43377, "author": "Evil Andy", "author_id": 4431, "author_profile": "https://Stackoverflow.com/users/4431", "pm_score": 5, "selected": false, "text": "div div" }, { "answer_id": 856615, "author": "lock", "author_id": 24744, "author_profile": "https://Stackoverflow.com/users/24744", "pm_score": 5, "selected": false, "text": "em em" }, { "answer_id": 3998843, "author": "Mike", "author_id": 484413, "author_profile": "https://Stackoverflow.com/users/484413", "pm_score": 5, "selected": false, "text": "hasLayout" }, { "answer_id": 52225050, "author": "Mohamed El Mrabet", "author_id": 1314885, "author_profile": "https://Stackoverflow.com/users/1314885", "pm_score": 3, "selected": false, "text": "div <div id=\"parent\" style=\"width:230px;\">\n <div id=\"child1\"></div>\n <div id=\"child2\"></div>\n</div>\n" }, { "answer_id": 64219066, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<div> <div> <div id=\"MainDiv\" style=\"width:60%;\">\n <div id=\"Div1\">\n ...\n </div>\n <div id=\"Div2\">\n ...\n </div>\n ...\n</div>\n" } ]
2008/07/31
[ "https://Stackoverflow.com/questions/6", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9/" ]
9
<p>Given a <code>DateTime</code> representing a person's birthday, how do I calculate their age in years?</p>
[ { "answer_id": 22, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 6, "selected": false, "text": "DateTime birthDate = new DateTime(2000,3,1);\nint age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);\n" }, { "answer_id": 229, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 7, "selected": false, "text": "public static int GetAge(DateTime birthDate)\n{\n DateTime n = DateTime.Now; // To avoid a race condition around midnight\n int age = n.Year - birthDate.Year;\n\n if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))\n age--;\n\n return age;\n}\n" }, { "answer_id": 1404, "author": "Mike Polen", "author_id": 212, "author_profile": "https://Stackoverflow.com/users/212", "pm_score": 12, "selected": true, "text": "// Save today's date.\nvar today = DateTime.Today;\n\n// Calculate the age.\nvar age = today.Year - birthdate.Year;\n\n// Go back to the year in which the person was born in case of a leap year\nif (birthdate.Date > today.AddYears(-age)) age--;\n" }, { "answer_id": 3261, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 6, "selected": false, "text": "public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)\n{\n return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1);\n}\n DateTime DateTime.Now" }, { "answer_id": 11942, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 10, "selected": false, "text": "yyyymmdd 20080814 - 19800703 = 280111 \n 28 int now = int.Parse(DateTime.Now.ToString(\"yyyyMMdd\"));\nint dob = int.Parse(dateOfBirth.ToString(\"yyyyMMdd\"));\nint age = (now - dob) / 10000;\n public static Int32 GetAge(this DateTime dateOfBirth)\n{\n var today = DateTime.Today;\n\n var a = (today.Year * 100 + today.Month) * 100 + today.Day;\n var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;\n\n return (a - b) / 10000;\n}\n" }, { "answer_id": 24242, "author": "user2601", "author_id": 2601, "author_profile": "https://Stackoverflow.com/users/2601", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Data;\nusing System.Data.Sql;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\npublic partial class UserDefinedFunctions\n{\n [SqlFunction(DataAccess = DataAccessKind.Read)]\n public static SqlInt32 CalculateAge(string strBirthDate)\n {\n DateTime dtBirthDate = new DateTime();\n dtBirthDate = Convert.ToDateTime(strBirthDate);\n DateTime dtToday = DateTime.Now;\n\n // get the difference in years\n int years = dtToday.Year - dtBirthDate.Year;\n\n // subtract another year if we're before the\n // birth day in the current year\n if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))\n years=years-1;\n\n int intCustomerAge = years;\n return intCustomerAge;\n }\n};\n" }, { "answer_id": 141644, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "DateTime myBD = new DateTime(1980, 10, 10);\nTimeSpan difference = DateTime.Now.Subtract(myBD);\n\ntextBox1.Text = difference.Years + \" years \" + difference.Months + \" Months \" + difference.Days + \" days\";\n" }, { "answer_id": 168703, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 7, "selected": false, "text": "int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);\n" }, { "answer_id": 877247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "public void LoopAge(DateTime myDOB, DateTime FutureDate)\n{\n int years = 0;\n int months = 0;\n int days = 0;\n\n DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);\n\n DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);\n\n while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)\n {\n months++;\n\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (FutureDate.Day >= myDOB.Day)\n {\n days = days + FutureDate.Day - myDOB.Day;\n }\n else\n {\n months--;\n\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n\n days +=\n DateTime.DaysInMonth(\n FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month\n ) + FutureDate.Day - myDOB.Day;\n\n }\n\n //add an extra day if the dob is a leap day\n if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)\n {\n //but only if the future date is less than 1st March\n if (FutureDate >= new DateTime(FutureDate.Year, 3, 1))\n days++;\n }\n\n}\n" }, { "answer_id": 877516, "author": "SillyMonkey", "author_id": 88600, "author_profile": "https://Stackoverflow.com/users/88600", "pm_score": 6, "selected": false, "text": "int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;\n" }, { "answer_id": 1011981, "author": "Rajeshwaran S P", "author_id": 21995, "author_profile": "https://Stackoverflow.com/users/21995", "pm_score": 4, "selected": false, "text": "DateTime dateOfBirth = new DateTime(2000, 4, 18);\nDateTime currentDate = DateTime.Now;\n\nint ageInYears = 0;\nint ageInMonths = 0;\nint ageInDays = 0;\n\nageInDays = currentDate.Day - dateOfBirth.Day;\nageInMonths = currentDate.Month - dateOfBirth.Month;\nageInYears = currentDate.Year - dateOfBirth.Year;\n\nif (ageInDays < 0)\n{\n ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);\n ageInMonths = ageInMonths--;\n\n if (ageInMonths < 0)\n {\n ageInMonths += 12;\n ageInYears--;\n }\n}\n\nif (ageInMonths < 0)\n{\n ageInMonths += 12;\n ageInYears--;\n}\n\nConsole.WriteLine(\"{0}, {1}, {2}\", ageInYears, ageInMonths, ageInDays);\n" }, { "answer_id": 1595311, "author": "RMA", "author_id": 193184, "author_profile": "https://Stackoverflow.com/users/193184", "pm_score": 9, "selected": false, "text": "DateTime bDay = new DateTime(2000, 2, 29);\nDateTime now = new DateTime(2009, 2, 28);\nMessageBox.Show(string.Format(\"Test {0} {1} {2}\",\n CalculateAgeWrong1(bDay, now), // outputs 9\n CalculateAgeWrong2(bDay, now), // outputs 9\n CalculateAgeCorrect(bDay, now), // outputs 8\n CalculateAgeCorrect2(bDay, now))); // outputs 8\n public int CalculateAgeWrong1(DateTime birthDate, DateTime now)\n{\n return new DateTime(now.Subtract(birthDate).Ticks).Year - 1;\n}\n\npublic int CalculateAgeWrong2(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n if (now < birthDate.AddYears(age))\n age--;\n\n return age;\n}\n\npublic int CalculateAgeCorrect(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))\n age--;\n\n return age;\n}\n\npublic int CalculateAgeCorrect2(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n // For leap years we need this\n if (birthDate > now.AddYears(-age)) \n age--;\n // Don't use:\n // if (birthDate.AddYears(age) > now) \n // age--;\n\n return age;\n}\n" }, { "answer_id": 1811311, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 2, "selected": false, "text": "public override bool IsValid(DateTime value)\n{\n _dateOfBirth = value;\n var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);\n if (yearsOld > 18)\n return true;\n return false;\n}\n" }, { "answer_id": 1913553, "author": "Frederik Gheysels", "author_id": 55774, "author_profile": "https://Stackoverflow.com/users/55774", "pm_score": 2, "selected": false, "text": "public struct Age : IEquatable<Age>, IComparable<Age>\n{\n private readonly int _years;\n private readonly int _months;\n private readonly int _days;\n\n public int Years { get { return _years; } }\n public int Months { get { return _months; } }\n public int Days { get { return _days; } }\n\n public Age( int years, int months, int days ) : this()\n {\n _years = years;\n _months = months;\n _days = days;\n }\n\n public static Age CalculateAge( DateTime dateOfBirth, DateTime date )\n {\n // Here is some logic that ressembles Mike's solution, although it\n // also takes into account months & days.\n // Ommitted for brevity.\n return new Age (years, months, days);\n }\n\n // Ommited Equality, Comparable, GetHashCode, functionality for brevity.\n}\n" }, { "answer_id": 1928680, "author": "Jon", "author_id": 234611, "author_profile": "https://Stackoverflow.com/users/234611", "pm_score": 2, "selected": false, "text": "public string LoopAge(DateTime myDOB, DateTime FutureDate)\n{\n int years = 0;\n int months = 0;\n int days = 0;\n\n DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);\n\n DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);\n\n while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)\n {\n months++;\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (FutureDate.Day >= myDOB.Day)\n {\n days = days + FutureDate.Day - myDOB.Day;\n }\n else\n {\n months--;\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n days = days + (DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day) - myDOB.Day;\n\n }\n\n //add an extra day if the dob is a leap day\n if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)\n {\n //but only if the future date is less than 1st March\n if(FutureDate >= new DateTime(FutureDate.Year, 3,1))\n days++;\n }\n\n return \"Years: \" + years + \" Months: \" + months + \" Days: \" + days;\n}\n" }, { "answer_id": 2280982, "author": "Elmer", "author_id": 173109, "author_profile": "https://Stackoverflow.com/users/173109", "pm_score": 5, "selected": false, "text": "public static class DateTimeExtensions\n{\n public static int Age(this DateTime birthDate)\n {\n return Age(birthDate, DateTime.Now);\n }\n\n public static int Age(this DateTime birthDate, DateTime offsetDate)\n {\n int result=0;\n result = offsetDate.Year - birthDate.Year;\n\n if (offsetDate.DayOfYear < birthDate.DayOfYear)\n {\n result--;\n }\n\n return result;\n }\n}\n" }, { "answer_id": 3513146, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "DateTime birth = new DateTime(1975, 09, 27, 01, 00, 00, 00);\nTimeSpan ts = DateTime.Now - birth;\nConsole.WriteLine(\"You are approximately \" + ts.TotalSeconds.ToString() + \" seconds old.\");\n" }, { "answer_id": 3652116, "author": "AEMLoviji", "author_id": 440670, "author_profile": "https://Stackoverflow.com/users/440670", "pm_score": 4, "selected": false, "text": "private int GetAge(int _year, int _month, int _day\n{\n DateTime yourBirthDate= new DateTime(_year, _month, _day);\n\n DateTime todaysDateTime = DateTime.Today;\n int noOfYears = todaysDateTime.Year - yourBirthDate.Year;\n\n if (DateTime.Now.Month < yourBirthDate.Month ||\n (DateTime.Now.Month == yourBirthDate.Month && DateTime.Now.Day < yourBirthDate.Day))\n {\n noOfYears--;\n }\n\n return noOfYears;\n}\n" }, { "answer_id": 3869003, "author": "Nicholas Carey", "author_id": 467473, "author_profile": "https://Stackoverflow.com/users/467473", "pm_score": 4, "selected": false, "text": "public int AgeInYears(DateTime birthDate, DateTime referenceDate)\n{\n Debug.Assert(referenceDate >= birthDate, \n \"birth date must be on or prior to the reference date\");\n\n DateTime birth = birthDate.Date;\n DateTime reference = referenceDate.Date;\n int years = (reference.Year - birth.Year);\n\n //\n // an offset of -1 is applied if the birth date has \n // not yet occurred in the current year.\n //\n if (reference.Month > birth.Month);\n else if (reference.Month < birth.Month) \n --years;\n else // in birth month\n {\n if (reference.Day < birth.Day)\n --years;\n }\n\n return years ;\n}\n public enum LeapDayRule\n{\n OrdinalDay = 1 ,\n LastDayOfMonth = 2 ,\n}\n\nstatic int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect)\n{\n bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day);\n DateTime cutoff;\n\n if (isLeapYearBirthday && !DateTime.IsLeapYear(reference.Year))\n {\n switch (ruleInEffect)\n {\n case LeapDayRule.OrdinalDay:\n cutoff = new DateTime(reference.Year, 1, 1)\n .AddDays(birth.DayOfYear - 1);\n break;\n\n case LeapDayRule.LastDayOfMonth:\n cutoff = new DateTime(reference.Year, birth.Month, 1)\n .AddMonths(1)\n .AddDays(-1);\n break;\n\n default:\n throw new InvalidOperationException();\n }\n }\n else\n {\n cutoff = new DateTime(reference.Year, birth.Month, birth.Day);\n }\n\n int age = (reference.Year - birth.Year) + (reference >= cutoff ? 0 : -1);\n return age < 0 ? 0 : age;\n}\n" }, { "answer_id": 5054317, "author": "camelCasus", "author_id": 624612, "author_profile": "https://Stackoverflow.com/users/624612", "pm_score": 7, "selected": false, "text": "AddYears DateTime public static class DateTimeExtensions\n{\n /// <summary>\n /// Calculates the age in years of the current System.DateTime object today.\n /// </summary>\n /// <param name=\"birthDate\">The date of birth</param>\n /// <returns>Age in years today. 0 is returned for a future date of birth.</returns>\n public static int Age(this DateTime birthDate)\n {\n return Age(birthDate, DateTime.Today);\n }\n\n /// <summary>\n /// Calculates the age in years of the current System.DateTime object on a later date.\n /// </summary>\n /// <param name=\"birthDate\">The date of birth</param>\n /// <param name=\"laterDate\">The date on which to calculate the age.</param>\n /// <returns>Age in years on a later day. 0 is returned as minimum.</returns>\n public static int Age(this DateTime birthDate, DateTime laterDate)\n {\n int age;\n age = laterDate.Year - birthDate.Year;\n\n if (age > 0)\n {\n age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age));\n }\n else\n {\n age = 0;\n }\n\n return age;\n }\n}\n class Program\n{\n static void Main(string[] args)\n {\n RunTest();\n }\n\n private static void RunTest()\n {\n DateTime birthDate = new DateTime(2000, 2, 28);\n DateTime laterDate = new DateTime(2011, 2, 27);\n string iso = \"yyyy-MM-dd\";\n\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n Console.WriteLine(\"Birth date: \" + birthDate.AddDays(i).ToString(iso) + \" Later date: \" + laterDate.AddDays(j).ToString(iso) + \" Age: \" + birthDate.AddDays(i).Age(laterDate.AddDays(j)).ToString());\n }\n }\n\n Console.ReadKey();\n }\n}\n {\n Birth date: 2000-02-28 Later date: 2011-02-27 Age: 10\n Birth date: 2000-02-28 Later date: 2011-02-28 Age: 11\n Birth date: 2000-02-28 Later date: 2011-03-01 Age: 11\n Birth date: 2000-02-29 Later date: 2011-02-27 Age: 10\n Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11\n Birth date: 2000-02-29 Later date: 2011-03-01 Age: 11\n Birth date: 2000-03-01 Later date: 2011-02-27 Age: 10\n Birth date: 2000-03-01 Later date: 2011-02-28 Age: 10\n Birth date: 2000-03-01 Later date: 2011-03-01 Age: 11\n}\n {\n Birth date: 2000-02-28 Later date: 2012-02-28 Age: 12\n Birth date: 2000-02-28 Later date: 2012-02-29 Age: 12\n Birth date: 2000-02-28 Later date: 2012-03-01 Age: 12\n Birth date: 2000-02-29 Later date: 2012-02-28 Age: 11\n Birth date: 2000-02-29 Later date: 2012-02-29 Age: 12\n Birth date: 2000-02-29 Later date: 2012-03-01 Age: 12\n Birth date: 2000-03-01 Later date: 2012-02-28 Age: 11\n Birth date: 2000-03-01 Later date: 2012-02-29 Age: 11\n Birth date: 2000-03-01 Later date: 2012-03-01 Age: 12\n}\n" }, { "answer_id": 5229568, "author": "Doron", "author_id": 649407, "author_profile": "https://Stackoverflow.com/users/649407", "pm_score": 4, "selected": false, "text": "static string CalcAge(DateTime birthDay)\n{\n DateTime currentDate = DateTime.Now; \n int approximateAge = currentDate.Year - birthDay.Year;\n int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) - \n (currentDate.Month * 30 + currentDate.Day) ;\n\n if (approximateAge == 0 || approximateAge == 1)\n { \n int month = Math.Abs(daysToNextBirthDay / 30);\n int days = Math.Abs(daysToNextBirthDay % 30);\n\n if (month == 0)\n return \"Your age is: \" + daysToNextBirthDay + \" days\";\n\n return \"Your age is: \" + month + \" months and \" + days + \" days\"; ;\n }\n\n if (daysToNextBirthDay > 0)\n return \"Your age is: \" + --approximateAge + \" Years\";\n\n return \"Your age is: \" + approximateAge + \" Years\"; ;\n}\n" }, { "answer_id": 5623077, "author": "Marcel Toth", "author_id": 702199, "author_profile": "https://Stackoverflow.com/users/702199", "pm_score": 6, "selected": false, "text": "DateTime birth = DateTime.Parse(\"1.1.2000\");\nDateTime today = DateTime.Today; //we usually don't care about birth time\nTimeSpan age = today - birth; //.NET FCL should guarantee this as precise\ndouble ageInDays = age.TotalDays; //total number of days ... also precise\ndouble daysInYear = 365.2425; //statistical value for 400 years\ndouble ageInYears = ageInDays / daysInYear; //can be shifted ... not so precise\n DateTime birth = DateTime.Parse(\"1.1.2000\");\nDateTime today = DateTime.Today;\nint age = today.Year - birth.Year; //people perceive their age in years\n\nif (today.Month < birth.Month ||\n ((today.Month == birth.Month) && (today.Day < birth.Day)))\n{\n age--; //birthday in current year not yet reached, we are 1 year younger ;)\n //+ no birthday for 29.2. guys ... sorry, just wrong date for birth\n}\n public static int GetAge(DateTime bithDay, DateTime today) \n{ \n //chosen solution method body\n}\n\npublic static int GetAge(DateTime birthDay) \n{ \n return GetAge(birthDay, DateTime.Now);\n}\n" }, { "answer_id": 5989087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "// ----------------------------------------------------------------------\nprivate static int YearDiff( DateTime date1, DateTime date2 )\n{\n return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );\n} // YearDiff\n\n// ----------------------------------------------------------------------\nprivate static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )\n{\n if ( date1.Equals( date2 ) )\n {\n return 0;\n }\n\n int year1 = calendar.GetYear( date1 );\n int month1 = calendar.GetMonth( date1 );\n int year2 = calendar.GetYear( date2 );\n int month2 = calendar.GetMonth( date2 );\n\n // find the the day to compare\n int compareDay = date2.Day;\n int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );\n if ( compareDay > compareDaysPerMonth )\n {\n compareDay = compareDaysPerMonth;\n }\n\n // build the compare date\n DateTime compareDate = new DateTime( year1, month2, compareDay,\n date2.Hour, date2.Minute, date2.Second, date2.Millisecond );\n if ( date2 > date1 )\n {\n if ( compareDate < date1 )\n {\n compareDate = compareDate.AddYears( 1 );\n }\n }\n else\n {\n if ( compareDate > date1 )\n {\n compareDate = compareDate.AddYears( -1 );\n }\n }\n return year2 - calendar.GetYear( compareDate );\n} // YearDiff\n // ----------------------------------------------------------------------\npublic void CalculateAgeSamples()\n{\n PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );\n // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years\n PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );\n // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years\n} // CalculateAgeSamples\n\n// ----------------------------------------------------------------------\npublic void PrintAge( DateTime birthDate, DateTime moment )\n{\n Console.WriteLine( \"Birthdate={0:d}, Age at {1:d} is {2} years\", birthDate, moment, YearDiff( birthDate, moment ) );\n} // PrintAge\n" }, { "answer_id": 6075141, "author": "B2K", "author_id": 763112, "author_profile": "https://Stackoverflow.com/users/763112", "pm_score": 2, "selected": false, "text": "public static class AgeExtender\n{\n public static int GetAge(this DateTime dt)\n {\n int d = int.Parse(dt.ToString(\"yyyyMMdd\"));\n int t = int.Parse(DateTime.Today.ToString(\"yyyyMMdd\"));\n return (t-d)/10000;\n }\n}\n" }, { "answer_id": 6719204, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 3, "selected": false, "text": "public int AgeInYears(DateTime bday)\n{\n DateTime now = DateTime.Today;\n int age = now.Year - bday.Year; \n if (bday.AddYears(age) > now) \n age--;\n return age;\n}\n" }, { "answer_id": 7046204, "author": "Dylan Hayes", "author_id": 892460, "author_profile": "https://Stackoverflow.com/users/892460", "pm_score": 3, "selected": false, "text": " public static Dictionary<string,int> CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate)\n {\n //----------------------------------------------------------------------\n // Can't determine age if we don't have a dates.\n //----------------------------------------------------------------------\n if (ndtBirthDate == null) return null;\n if (ndtReferralDate == null) return null;\n\n DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate);\n DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate);\n\n //----------------------------------------------------------------------\n // Create our Variables\n //----------------------------------------------------------------------\n Dictionary<string, int> dYMD = new Dictionary<string,int>();\n int iNowDate, iBirthDate, iYears, iMonths, iDays;\n string sDif = \"\";\n\n //----------------------------------------------------------------------\n // Store off current date/time and DOB into local variables\n //---------------------------------------------------------------------- \n iNowDate = int.Parse(dtReferralDate.ToString(\"yyyyMMdd\"));\n iBirthDate = int.Parse(dtBirthDate.ToString(\"yyyyMMdd\"));\n\n //----------------------------------------------------------------------\n // Calculate Years\n //----------------------------------------------------------------------\n sDif = (iNowDate - iBirthDate).ToString();\n iYears = int.Parse(sDif.Substring(0, sDif.Length - 4));\n\n //----------------------------------------------------------------------\n // Store Years in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Years\", iYears);\n\n //----------------------------------------------------------------------\n // Calculate Months\n //----------------------------------------------------------------------\n if (dtBirthDate.Month > dtReferralDate.Month)\n iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1;\n else\n iMonths = dtBirthDate.Month - dtReferralDate.Month;\n\n //----------------------------------------------------------------------\n // Store Months in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Months\", iMonths);\n\n //----------------------------------------------------------------------\n // Calculate Remaining Days\n //----------------------------------------------------------------------\n if (dtBirthDate.Day > dtReferralDate.Day)\n //Logic: Figure out the days in month previous to the current month, or the admitted month.\n // Subtract the birthday from the total days which will give us how many days the person has lived since their birthdate day the previous month.\n // then take the referral date and simply add the number of days the person has lived this month.\n\n //If referral date is january, we need to go back to the following year's December to get the days in that month.\n if (dtReferralDate.Month == 1)\n iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day; \n else\n iDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day; \n else\n iDays = dtReferralDate.Day - dtBirthDate.Day; \n\n //----------------------------------------------------------------------\n // Store Days in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Days\", iDays);\n\n return dYMD;\n}\n" }, { "answer_id": 8816564, "author": "Moshe L", "author_id": 1056259, "author_profile": "https://Stackoverflow.com/users/1056259", "pm_score": 2, "selected": false, "text": "Public Shared Function CalculateAge(BirthDate As DateTime) As Integer\n Dim HebCal As New System.Globalization.HebrewCalendar ()\n Dim now = DateTime.Now()\n Dim iAge = HebCal.GetYear(now) - HebCal.GetYear(BirthDate)\n Dim iNowMonth = HebCal.GetMonth(now), iBirthMonth = HebCal.GetMonth(BirthDate)\n If iNowMonth < iBirthMonth Or (iNowMonth = iBirthMonth AndAlso HebCal.GetDayOfMonth(now) < HebCal.GetDayOfMonth(BirthDate)) Then iAge -= 1\n Return iAge\nEnd Function\n" }, { "answer_id": 9431192, "author": "musefan", "author_id": 838807, "author_profile": "https://Stackoverflow.com/users/838807", "pm_score": 3, "selected": false, "text": "DateTime now = DateTime.Today;\nDateTime birthday = new DateTime(1991, 02, 03);//3rd feb\n\nint age = now.Year - birthday.Year;\n\nif (now.Month < birthday.Month || (now.Month == birthday.Month && now.Day < birthday.Day))//not had bday this year yet\n age--;\n\nreturn age;\n" }, { "answer_id": 11328202, "author": "Narasimha", "author_id": 254790, "author_profile": "https://Stackoverflow.com/users/254790", "pm_score": 2, "selected": false, "text": "int age = (Int32.Parse(DateTime.Today.ToString(\"yyyyMMdd\")) - \n Int32.Parse(birthday.ToString(\"yyyyMMdd rawrrr\"))) / 10000;\n" }, { "answer_id": 13531544, "author": "flindeberg", "author_id": 691294, "author_profile": "https://Stackoverflow.com/users/691294", "pm_score": 4, "selected": false, "text": "second DateTime var lifeInSeconds = (DateTime.Now.Ticks - then.Ticks)/TickFactor;\n var then = ... // Then, in this case the birthday\nvar now = DateTime.UtcNow;\nint age = now.Year - then.Year;\nif (now.AddYears(-age) < then) age--;\n DateTime start, end = .... // Whatever, assume start is before end\n\ndouble startYearContribution = 1 - (double) start.DayOfYear / (double) (DateTime.IsLeapYear(start.Year) ? 366 : 365);\ndouble endYearContribution = (double)end.DayOfYear / (double)(DateTime.IsLeapYear(end.Year) ? 366 : 365);\ndouble middleContribution = (double) (end.Year - start.Year - 1);\n\ndouble DCF = startYearContribution + endYearContribution + middleContribution;\n DateTime start, end = .... // Whatever, assume start is before end\nint days = (end - start).Days;\n" }, { "answer_id": 13645039, "author": "rockXrock", "author_id": 1254006, "author_profile": "https://Stackoverflow.com/users/1254006", "pm_score": 4, "selected": false, "text": "public static string HowOld(DateTime birthday, DateTime now)\n{\n if (now < birthday)\n throw new ArgumentOutOfRangeException(\"birthday must be less than now.\");\n\n TimeSpan diff = now - birthday;\n int diffDays = (int)diff.TotalDays;\n\n if (diffDays > 7)//year, month and week\n {\n int age = now.Year - birthday.Year;\n\n if (birthday > now.AddYears(-age))\n age--;\n\n if (age > 0)\n {\n return age + (age > 1 ? \" years\" : \" year\");\n }\n else\n {// month and week\n DateTime d = birthday;\n int diffMonth = 1;\n\n while (d.AddMonths(diffMonth) <= now)\n {\n diffMonth++;\n }\n\n age = diffMonth-1;\n\n if (age == 1 && d.Day > now.Day)\n age--;\n\n if (age > 0)\n {\n return age + (age > 1 ? \" months\" : \" month\");\n }\n else\n {\n age = diffDays / 7;\n return age + (age > 1 ? \" weeks\" : \" week\");\n }\n }\n }\n else if (diffDays > 0)\n {\n int age = diffDays;\n return age + (age > 1 ? \" days\" : \" day\");\n }\n else\n {\n int age = diffDays;\n return \"just born\";\n }\n}\n [TestMethod]\npublic void TestAge()\n{\n string age = HowOld(new DateTime(2011, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2011, 11, 30), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2001, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"11 years\", age);\n\n age = HowOld(new DateTime(2012, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"10 months\", age);\n\n age = HowOld(new DateTime(2011, 12, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"11 months\", age);\n\n age = HowOld(new DateTime(2012, 10, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2008, 2, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"11 months\", age);\n\n age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 3, 28));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2009, 1, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"1 month\", age);\n\n // NOTE.\n // new DateTime(2008, 1, 31).AddMonths(1) == new DateTime(2009, 2, 28);\n // new DateTime(2008, 1, 28).AddMonths(1) == new DateTime(2009, 2, 28);\n age = HowOld(new DateTime(2009, 1, 31), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"4 weeks\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"3 weeks\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2012, 11, 5), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"3 weeks\", age);\n\n age = HowOld(new DateTime(2012, 11, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"4 weeks\", age);\n\n age = HowOld(new DateTime(2012, 11, 20), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 week\", age);\n\n age = HowOld(new DateTime(2012, 11, 25), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"5 days\", age);\n\n age = HowOld(new DateTime(2012, 11, 29), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 day\", age);\n\n age = HowOld(new DateTime(2012, 11, 30), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"just born\", age);\n\n age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"8 years\", age);\n\n age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"9 years\", age);\n\n Exception e = null;\n\n try\n {\n age = HowOld(new DateTime(2012, 12, 1), new DateTime(2012, 11, 30));\n }\n catch (ArgumentOutOfRangeException ex)\n {\n e = ex;\n }\n\n Assert.IsTrue(e != null);\n}\n" }, { "answer_id": 14125249, "author": "Stranger", "author_id": 1462452, "author_profile": "https://Stackoverflow.com/users/1462452", "pm_score": 2, "selected": false, "text": "private int CalculateAge()\n{\n//get birthdate\n DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);\n int byear = dtBirth.Year;\n int bmonth = dtBirth.Month;\n int bday = dtBirth.Day;\n DateTime dtToday = DateTime.Now;\n int tYear = dtToday.Year;\n int tmonth = dtToday.Month;\n int tday = dtToday.Day;\n int age = tYear - byear;\n if (bmonth < tmonth)\n age--;\n else if (bmonth == tmonth && bday>tday)\n {\n age--;\n }\nreturn age;\n}\n" }, { "answer_id": 16142434, "author": "Matthew Watson", "author_id": 106159, "author_profile": "https://Stackoverflow.com/users/106159", "pm_score": 5, "selected": false, "text": "public static int AgeInYears(DateTime birthday, DateTime today)\n{\n return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;\n}\n Yn = DateTime.Now.Year, Yb = birthday.Year, Mn = DateTime.Now.Month, Mb = birthday.Month, Dn = DateTime.Now.Day, Db = birthday.Day age = Yn - Yb + (31*(Mn - Mb) + (Dn - Db)) / 372 Yn-Yb Yn-Yb-1 Mn<Mb -341 <= 31*(Mn-Mb) <= -31 and -30 <= Dn-Db <= 30 -371 <= 31*(Mn - Mb) + (Dn - Db) <= -1 (31*(Mn - Mb) + (Dn - Db)) / 372 = -1 Mn=Mb Dn<Db 31*(Mn - Mb) = 0 and -30 <= Dn-Db <= -1 (31*(Mn - Mb) + (Dn - Db)) / 372 = -1 Mn>Mb 31 <= 31*(Mn-Mb) <= 341 and -30 <= Dn-Db <= 30 1 <= 31*(Mn - Mb) + (Dn - Db) <= 371 (31*(Mn - Mb) + (Dn - Db)) / 372 = 0 Mn=Mb Dn>Db 31*(Mn - Mb) = 0 and 1 <= Dn-Db <= 3 (31*(Mn - Mb) + (Dn - Db)) / 372 = 0 Mn=Mb Dn=Db 31*(Mn - Mb) + Dn-Db = 0 (31*(Mn - Mb) + (Dn - Db)) / 372 = 0" }, { "answer_id": 18682920, "author": "vulcan raven", "author_id": 863980, "author_profile": "https://Stackoverflow.com/users/863980", "pm_score": 2, "selected": false, "text": "public int GetAge(DateTime DateOfBirth)\n{\n var Now = DateTime.UtcNow;\n return Now.Year - DateOfBirth.Year -\n (\n (\n Now.Month > DateOfBirth.Month ||\n (Now.Month == DateOfBirth.Month && Now.Day >= DateOfBirth.Day)\n ) ? 0 : 1\n );\n}\n" }, { "answer_id": 18895699, "author": "Archit", "author_id": 2435287, "author_profile": "https://Stackoverflow.com/users/2435287", "pm_score": 1, "selected": false, "text": "System.DateTime birthTime = AskTheUser(myUser); // :-)\nSystem.DateTime now = System.DateTime.Now;\nSystem.TimeSpan age = now - birthTime; // As simple as that\ndouble ageInDays = age.TotalDays; // Will you convert to whatever you want yourself?\n" }, { "answer_id": 18898663, "author": "Dakotah Hicock", "author_id": 1226335, "author_profile": "https://Stackoverflow.com/users/1226335", "pm_score": 4, "selected": false, "text": "TimeSpan diff = DateTime.Now - birthdayDateTime;\nstring age = String.Format(\"{0:%y} years, {0:%M} months, {0:%d}, days old\", diff);\n" }, { "answer_id": 18924226, "author": "Jacqueline Loriault", "author_id": 2778315, "author_profile": "https://Stackoverflow.com/users/2778315", "pm_score": 5, "selected": false, "text": "DateTime birth = new DateTime(1974, 8, 29);\nDateTime today = DateTime.Now;\nTimeSpan span = today - birth;\nDateTime age = DateTime.MinValue + span;\n\n// Make adjustment due to MinValue equalling 1/1/1\nint years = age.Year - 1;\nint months = age.Month - 1;\nint days = age.Day - 1;\n\n// Print out not only how many years old they are but give months and days as well\nConsole.Write(\"{0} years, {1} months, {2} days\", years, months, days);\n" }, { "answer_id": 20348258, "author": "Dhaval Panchal", "author_id": 2368967, "author_profile": "https://Stackoverflow.com/users/2368967", "pm_score": -1, "selected": false, "text": "var ts = DateTime.Now - new DateTime(1988, 3, 19);\nvar age = Math.Round(ts.Days / 365.0);\n" }, { "answer_id": 20715576, "author": "Matt Johnson-Pint", "author_id": 634824, "author_profile": "https://Stackoverflow.com/users/634824", "pm_score": 4, "selected": false, "text": "static int GetAge(LocalDate dateOfBirth)\n{\n Instant now = SystemClock.Instance.Now;\n\n // The target time zone is important.\n // It should align with the *current physical location* of the person\n // you are talking about. When the whereabouts of that person are unknown,\n // then you use the time zone of the person who is *asking* for the age.\n // The time zone of birth is irrelevant!\n\n DateTimeZone zone = DateTimeZoneProviders.Tzdb[\"America/New_York\"];\n\n LocalDate today = now.InZone(zone).Date;\n\n Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);\n\n return (int) period.Years;\n}\n LocalDate dateOfBirth = new LocalDate(1976, 8, 27);\nint age = GetAge(dateOfBirth);\n IClock SystemClock.Instance DateTimeZone" }, { "answer_id": 21276626, "author": "DareDevil", "author_id": 1147352, "author_profile": "https://Stackoverflow.com/users/1147352", "pm_score": 4, "selected": false, "text": "public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days)\n{\n years = 0;\n months = 0;\n days = 0;\n\n DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1);\n DateTime tmpnow = new DateTime(now.Year, now.Month, 1);\n\n while (tmpdob.AddYears(years).AddMonths(months) < tmpnow)\n {\n months++;\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (now.Day >= dob.Day)\n days = days + now.Day - dob.Day;\n else\n {\n months--;\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day;\n }\n\n if (DateTime.IsLeapYear(dob.Year) && dob.Month == 2 && dob.Day == 29 && now >= new DateTime(now.Year, 3, 1))\n days++;\n\n} \n\nprivate string ValidateDate(DateTime dob) //This method will validate the date\n{\n int Years = 0; int Months = 0; int Days = 0;\n\n GetAge(dob, DateTime.Now, out Years, out Months, out Days);\n\n if (Years < 18)\n message = Years + \" is too young. Please try again on your 18th birthday.\";\n else if (Years >= 65)\n message = Years + \" is too old. Date of Birth must not be 65 or older.\";\n else\n return null; //Denotes validation passed\n}\n DateTime dob = DateTime.Parse(\"03/10/1982\"); \n\nstring message = ValidateDate(dob);\n\nlbldatemessage.Visible = !StringIsNullOrWhitespace(message);\nlbldatemessage.Text = message ?? \"\"; //Ternary if message is null then default to empty string\n" }, { "answer_id": 25014539, "author": "Pratik Bhoir", "author_id": 2772550, "author_profile": "https://Stackoverflow.com/users/2772550", "pm_score": -1, "selected": false, "text": "DateTime dateOfBirth = Convert.ToDateTime(\"01/16/1990\");\nvar age = ((DateTime.Now - dateOfBirth).Days) / 365;\n" }, { "answer_id": 26529035, "author": "mjb", "author_id": 520848, "author_profile": "https://Stackoverflow.com/users/520848", "pm_score": 4, "selected": false, "text": "public int GetAge(DateTime birthDate)\n{\n int age = DateTime.Now.Year - birthDate.Year;\n\n if (birthDate.DayOfYear > DateTime.Now.DayOfYear)\n age--;\n\n return age;\n}\n\n\n\n\n" }, { "answer_id": 28567336, "author": "dav_i", "author_id": 1185053, "author_profile": "https://Stackoverflow.com/users/1185053", "pm_score": 2, "selected": false, "text": "public static int GetAgeByLoop(DateTime birthday)\n{\n var age = -1;\n\n for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))\n {\n age++;\n }\n\n return age;\n}\n" }, { "answer_id": 30145502, "author": "mind_overflow", "author_id": 3889784, "author_profile": "https://Stackoverflow.com/users/3889784", "pm_score": -1, "selected": false, "text": "TimeSpan ts = DateTime.Now.Subtract(Birthdate);\nage = (byte)(ts.TotalDays / 365.25);\n" }, { "answer_id": 31025282, "author": "user1210708", "author_id": 1210708, "author_profile": "https://Stackoverflow.com/users/1210708", "pm_score": 2, "selected": false, "text": " public static string ToAge(this DateTime dob, DateTime? toDate = null)\n {\n if (!toDate.HasValue)\n toDate = DateTime.Now;\n var now = toDate.Value;\n\n if (now.CompareTo(dob) < 0)\n return \"Future date\";\n\n int years = now.Year - dob.Year;\n int months = now.Month - dob.Month;\n int days = now.Day - dob.Day;\n\n if (days < 0)\n {\n months--;\n days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;\n }\n\n if (months < 0)\n {\n years--;\n months = 12 + months;\n }\n\n\n return string.Format(\"{0} year(s), {1} month(s), {2} days(s)\",\n years,\n months,\n days);\n }\n [Test]\n public void ToAgeTests()\n {\n var date = new DateTime(2000, 1, 1);\n Assert.AreEqual(\"0 year(s), 0 month(s), 1 days(s)\", new DateTime(1999, 12, 31).ToAge(date));\n Assert.AreEqual(\"0 year(s), 0 month(s), 0 days(s)\", new DateTime(2000, 1, 1).ToAge(date));\n Assert.AreEqual(\"1 year(s), 0 month(s), 0 days(s)\", new DateTime(1999, 1, 1).ToAge(date));\n Assert.AreEqual(\"0 year(s), 11 month(s), 0 days(s)\", new DateTime(1999, 2, 1).ToAge(date));\n Assert.AreEqual(\"0 year(s), 10 month(s), 25 days(s)\", new DateTime(1999, 2, 4).ToAge(date));\n Assert.AreEqual(\"0 year(s), 10 month(s), 1 days(s)\", new DateTime(1999, 2, 28).ToAge(date));\n\n date = new DateTime(2000, 2, 15);\n Assert.AreEqual(\"0 year(s), 0 month(s), 28 days(s)\", new DateTime(2000, 1, 18).ToAge(date));\n }\n" }, { "answer_id": 31077562, "author": "Lukas", "author_id": 593388, "author_profile": "https://Stackoverflow.com/users/593388", "pm_score": 3, "selected": false, "text": "int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;\n" }, { "answer_id": 31178328, "author": "BrunoVT", "author_id": 4090831, "author_profile": "https://Stackoverflow.com/users/4090831", "pm_score": 2, "selected": false, "text": "DateTime birthDay = new DateTime(1990, 05, 23);\nDateTime age = DateTime.Now - birthDay;\n" }, { "answer_id": 32954095, "author": "VhsPiceros", "author_id": 581783, "author_profile": "https://Stackoverflow.com/users/581783", "pm_score": 2, "selected": false, "text": "DateTime zeroTime = new DateTime(1, 1, 1);\nvar date1 = new DateTime(1983, 03, 04);\nvar date2 = DateTime.Now;\nvar dif = date2 - date1;\nint years = (zeroTime + dif).Year - 1;\nLog.DebugFormat(\"Years -->{0}\", years);\n" }, { "answer_id": 33082044, "author": "Ahmed Sabry", "author_id": 4707576, "author_profile": "https://Stackoverflow.com/users/4707576", "pm_score": 2, "selected": false, "text": "public string GetAge(this DateTime birthdate, string ageStrinFormat = null)\n{\n var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day);\n return string.Format(ageStrinFormat ?? \"{0}/{1}/{2}\",\n (date.Year - birthdate.Year), date.Month, date.Day);\n}\n" }, { "answer_id": 36893577, "author": "CathalMF", "author_id": 1680271, "author_profile": "https://Stackoverflow.com/users/1680271", "pm_score": 3, "selected": false, "text": "DateTime Dob = DateTime.Parse(\"1985-04-24\");\n \nint Age = DateTime.MinValue.AddDays(DateTime.Now.Subtract(Dob).TotalHours/24 - 1).Year - 1;\n" }, { "answer_id": 37022367, "author": "John Jang", "author_id": 3634867, "author_profile": "https://Stackoverflow.com/users/3634867", "pm_score": 3, "selected": false, "text": "DateTime today = DateTime.Today;\nDateTime bday = DateTime.Parse(\"2016-2-14\");\nint age = today.Year - bday.Year;\nvar unit = \"\";\n\nif (bday > today.AddYears(-age))\n{\n age--;\n}\nif (age == 0) // Under one year old\n{\n age = today.Month - bday.Month;\n\n age = age <= 0 ? (12 + age) : age; // The next year before birthday\n\n age = today.Day - bday.Day >= 0 ? age : --age; // Before the birthday.day\n\n unit = \"month\";\n}\nelse {\n unit = \"year\";\n}\n\nif (age > 1)\n{\n unit = unit + \"s\";\n}\n The birthday: 2016-2-14\n\n2016-2-15 => age=0, unit=month;\n2016-5-13 => age=2, unit=months;\n2016-5-14 => age=3, unit=months; \n2016-6-13 => age=3, unit=months; \n2016-6-15 => age=4, unit=months; \n2017-1-13 => age=10, unit=months; \n2017-1-14 => age=11, unit=months; \n2017-2-13 => age=11, unit=months; \n2017-2-14 => age=1, unit=year; \n2017-2-15 => age=1, unit=year; \n2017-3-13 => age=1, unit=year;\n2018-1-13 => age=1, unit=year; \n2018-1-14 => age=1, unit=year; \n2018-2-13 => age=1, unit=year; \n2018-2-14 => age=2, unit=years; \n" }, { "answer_id": 38121726, "author": "xenedia", "author_id": 836565, "author_profile": "https://Stackoverflow.com/users/836565", "pm_score": 3, "selected": false, "text": "declare @dd smalldatetime = '1980-04-01'\ndeclare @age int = YEAR(GETDATE())-YEAR(@dd)\nif (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1\n\nprint @age \n" }, { "answer_id": 39779195, "author": "André Sobreiro", "author_id": 3177959, "author_profile": "https://Stackoverflow.com/users/3177959", "pm_score": 3, "selected": false, "text": "private int CalcularIdade(DateTime dtNascimento)\n {\n var nHoje = Convert.ToInt32(DateTime.Today.ToString(\"yyyyMMdd\"));\n var nAniversario = Convert.ToInt32(dtNascimento.ToString(\"yyyyMMdd\"));\n\n double diff = (nHoje - nAniversario) / 10000;\n\n var ret = Convert.ToInt32(Math.Truncate(diff));\n\n return ret;\n }\n" }, { "answer_id": 40196001, "author": "K1laba", "author_id": 1591350, "author_profile": "https://Stackoverflow.com/users/1591350", "pm_score": 3, "selected": false, "text": "private int GetYearDiff(DateTime start, DateTime end)\n{\n int diff = end.Year - start.Year;\n if (end.DayOfYear < start.DayOfYear) { diff -= 1; }\n return diff;\n}\n[Fact]\npublic void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff()\n{\n //arrange\n var now = DateTime.Now;\n //act\n //assert\n Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed\n Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed\n Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed\n}\n" }, { "answer_id": 45127603, "author": "Sean Kearon", "author_id": 2608, "author_profile": "https://Stackoverflow.com/users/2608", "pm_score": 2, "selected": false, "text": "int AgeNow(DateTime birthday)\n{\n return AgeAt(DateTime.Now, birthday);\n}\n\nint AgeAt(DateTime now, DateTime birthday)\n{\n return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);\n}\n\nint AgeAt(DateTime now, DateTime birthday, Calendar calendar)\n{\n // My age has increased on the morning of my\n // birthday even though I was born in the evening.\n now = now.Date;\n birthday = birthday.Date;\n\n var age = 0;\n if (now <= birthday) return age; // I am zero now if I am to be born tomorrow.\n\n while (calendar.AddYears(birthday, age + 1) <= now)\n {\n age++;\n }\n return age;\n}\n PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968\nPASSED: someone born on 29 February 1964 is age 3 on 28 February 1968\nPASSED: someone born on 31 December 2016 is age 0 on 01 January 2017\n" }, { "answer_id": 46968983, "author": "Sunny Jangid", "author_id": 6803066, "author_profile": "https://Stackoverflow.com/users/6803066", "pm_score": 2, "selected": false, "text": " var birthYear=1993;\n var age = DateTime.Now.AddYears(-birthYear).Year;\n" }, { "answer_id": 47035067, "author": "Kaval Patel", "author_id": 6629154, "author_profile": "https://Stackoverflow.com/users/6629154", "pm_score": 0, "selected": false, "text": "DateTime dateOfBirth;\n\nint ageInYears = DateTime.Now.Year - dateOfBirth.Year;\n\nif (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --;\n" }, { "answer_id": 47837162, "author": "Moises Conejo", "author_id": 4155324, "author_profile": "https://Stackoverflow.com/users/4155324", "pm_score": 2, "selected": false, "text": "(DateTime.Now - myDate).TotalHours / 8766.0\n myDate = TimeSpan" }, { "answer_id": 48688691, "author": "wild coder", "author_id": 9106094, "author_profile": "https://Stackoverflow.com/users/9106094", "pm_score": 2, "selected": false, "text": " C#\n // get the difference in years\n int years = DateTime.Now.Year - BirthDate.Year; \n // subtract another year if we're before the\n // birth day in the current year\n if (DateTime.Now.Month < BirthDate.Month || \n (DateTime.Now.Month == BirthDate.Month && \n DateTime.Now.Day < BirthDate.Day)) \n years--;\n VB.NET\n ' get the difference in years\n Dim years As Integer = DateTime.Now.Year - BirthDate.Year\n ' subtract another year if we're before the\n ' birth day in the current year\n If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then \n years = years - 1\n End If\n" }, { "answer_id": 48805951, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var birthDate = ... // DOB\nvar resultDate = DateTime.Now - birthDate;\n resultDate TimeSpan" }, { "answer_id": 60541141, "author": "Alexander", "author_id": 11841521, "author_profile": "https://Stackoverflow.com/users/11841521", "pm_score": 0, "selected": false, "text": " DateTime dob = new DateTime(1991, 3, 4); \n DateTime now = DateTime.Now; \n int dobDay = dob.Day, dobMonth = dob.Month; \n int add = -1; \n if (dobMonth < now.Month)\n {\n add = 0;\n }\n else if (dobMonth == now.Month)\n {\n if(dobDay <= now.Day)\n {\n add = 0;\n }\n else\n {\n add = -1;\n }\n }\n else\n {\n add = -1;\n } \n int age = now.Year - dob.Year + add;\n" }, { "answer_id": 64085367, "author": "Alexander Díaz", "author_id": 11120141, "author_profile": "https://Stackoverflow.com/users/11120141", "pm_score": 0, "selected": false, "text": "int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;\nConsole.WriteLine(\"Age {0}\", Age);\n" }, { "answer_id": 64135345, "author": "Abrar Jahin", "author_id": 2193439, "author_profile": "https://Stackoverflow.com/users/2193439", "pm_score": -1, "selected": false, "text": "using System;\n\nnamespace TSA\n{\n class BirthDay\n {\n double ageDay;\n public BirthDay(int day, int month, int year)\n {\n DateTime birthDate = new DateTime(year, month, day);\n ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow\n }\n\n internal int GetAgeYear()\n {\n return (int)Math.Truncate(ageDay / 365);\n }\n\n internal int GetAgeMonth()\n {\n return (int)Math.Truncate((ageDay % 365) / 30);\n }\n }\n}\n BirthDay b = new BirthDay(1,12,1990);\nint year = b.GetAgeYear();\nint month = b.GetAgeMonth();\n" }, { "answer_id": 64220001, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "DateTime using System;\n \npublic class Program\n{\n public static int getAge(int month, int day, int year) {\n DateTime today = DateTime.Today;\n int currentDay = today.Day;\n int currentYear = today.Year;\n int currentMonth = today.Month;\n int age = 0;\n if (currentMonth < month) {\n age -= 1;\n } else if (currentMonth == month) {\n if (currentDay < day) {\n age -= 1;\n }\n }\n currentYear -= year;\n age += currentYear;\n return age;\n }\n public static void Main()\n {\n int ageInYears = getAge(8, 10, 2007);\n Console.WriteLine(ageInYears);\n }\n}\n" }, { "answer_id": 68783776, "author": "Wylan Osorio", "author_id": 2249897, "author_profile": "https://Stackoverflow.com/users/2249897", "pm_score": 0, "selected": false, "text": "var startDate = new DateTime(2015, 04, 05);//your start date\nvar endDate = DateTime.Now;\nvar years = 0;\nwhile(startDate < endDate) \n{\n startDate = startDate.AddYears(1);\n if(startDate < endDate) \n {\n years++;\n }\n}\n" }, { "answer_id": 69123059, "author": "Rob", "author_id": 3178666, "author_profile": "https://Stackoverflow.com/users/3178666", "pm_score": 0, "selected": false, "text": "public static int AgeInYears(this System.DateTime source, System.DateTime target)\n => target.Year - source.Year is int age && age > 0 && source.AddYears(age) > target ? age - 1 : age < 0 && source.AddYears(age) < target ? age + 1 : age;\n public static double AgeInTotalYears(this System.DateTime source, System.DateTime target)\n{\n var sign = (source <= target ? 1 : -1);\n\n var ageInYears = AgeInYears(source, target); // The method above.\n\n var last = source.AddYears(ageInYears);\n var next = source.AddYears(ageInYears + sign);\n\n var fractionalAge = (double)(target - last).Ticks / (double)(next - last).Ticks * sign;\n\n return ageInYears + fractionalAge;\n}\n" }, { "answer_id": 69981159, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;\n" }, { "answer_id": 70659202, "author": "Wouter", "author_id": 4491768, "author_profile": "https://Stackoverflow.com/users/4491768", "pm_score": 0, "selected": false, "text": "public int GetAge(DateOnly birthDate, DateOnly today)\n{\n return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);\n}\n" }, { "answer_id": 71185870, "author": "subcoder", "author_id": 8227155, "author_profile": "https://Stackoverflow.com/users/8227155", "pm_score": 1, "selected": false, "text": "public static int getAge(DateTime birthDate)\n{\n var today = DateTime.Today;\n var age = today.Year - birthDate.Year;\n var monthDiff = today.Month - birthDate.Month;\n var dayDiff = today.Day - birthDate.Day;\n\n if (dayDiff < 0)\n {\n monthDiff--;\n }\n if (monthDiff < 0)\n {\n age--;\n }\n return age;\n}\n" }, { "answer_id": 73211429, "author": "Ruchir Gupta", "author_id": 3832403, "author_profile": "https://Stackoverflow.com/users/3832403", "pm_score": 0, "selected": false, "text": " ushort age = (ushort)DateAndTime.DateDiff(DateInterval.Year, DateTime.Now.Date, birthdate);\n using Microsoft.VisualBasic;" } ]
2008/07/31
[ "https://Stackoverflow.com/questions/9", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
11
<p>Given a specific <code>DateTime</code> value, how do I display relative time, like:</p> <ul> <li><code>2 hours ago</code></li> <li><code>3 days ago</code></li> <li><code>a month ago</code></li> </ul>
[ { "answer_id": 12, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 8, "selected": false, "text": "var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);\ndouble delta = Math.Abs(ts.TotalSeconds);\n\nif (delta < 60)\n{\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n}\nif (delta < 60 * 2)\n{\n return \"a minute ago\";\n}\nif (delta < 45 * 60)\n{\n return ts.Minutes + \" minutes ago\";\n}\nif (delta < 90 * 60)\n{\n return \"an hour ago\";\n}\nif (delta < 24 * 60 * 60)\n{\n return ts.Hours + \" hours ago\";\n}\nif (delta < 48 * 60 * 60)\n{\n return \"yesterday\";\n}\nif (delta < 30 * 24 * 60 * 60)\n{\n return ts.Days + \" days ago\";\n}\nif (delta < 12 * 30 * 24 * 60 * 60)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nint years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\nreturn years <= 1 ? \"one year ago\" : years + \" years ago\";\n" }, { "answer_id": 27, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 5, "selected": false, "text": "public static string ToLongString(this TimeSpan time)\n{\n string output = String.Empty;\n\n if (time.Days > 0)\n output += time.Days + \" days \";\n\n if ((time.Days == 0 || time.Days == 1) && time.Hours > 0)\n output += time.Hours + \" hr \";\n\n if (time.Days == 0 && time.Minutes > 0)\n output += time.Minutes + \" min \";\n\n if (output.Length == 0)\n output += time.Seconds + \" sec\";\n\n return output.Trim();\n}\n" }, { "answer_id": 1248, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 11, "selected": true, "text": "const int SECOND = 1;\nconst int MINUTE = 60 * SECOND;\nconst int HOUR = 60 * MINUTE;\nconst int DAY = 24 * HOUR;\nconst int MONTH = 30 * DAY;\n\nvar ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);\ndouble delta = Math.Abs(ts.TotalSeconds);\n\nif (delta < 1 * MINUTE)\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n\nif (delta < 2 * MINUTE)\n return \"a minute ago\";\n\nif (delta < 45 * MINUTE)\n return ts.Minutes + \" minutes ago\";\n\nif (delta < 90 * MINUTE)\n return \"an hour ago\";\n\nif (delta < 24 * HOUR)\n return ts.Hours + \" hours ago\";\n\nif (delta < 48 * HOUR)\n return \"yesterday\";\n\nif (delta < 30 * DAY)\n return ts.Days + \" days ago\";\n\nif (delta < 12 * MONTH)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nelse\n{\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n}\n" }, { "answer_id": 1752, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 4, "selected": false, "text": "public class RelativeTimeRange : IComparable\n{\n public TimeSpan UpperBound { get; set; }\n\n public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta);\n\n public RelativeTimeTextDelegate MessageCreator { get; set; }\n\n public int CompareTo(object obj)\n {\n if (!(obj is RelativeTimeRange))\n {\n return 1;\n }\n // note that this sorts in reverse order to the way you'd expect, \n // this saves having to reverse a list later\n return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound);\n }\n}\n\npublic class PrintRelativeTime\n{\n private static List<RelativeTimeRange> timeRanges;\n\n static PrintRelativeTime()\n {\n timeRanges = new List<RelativeTimeRange>{\n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromSeconds(1),\n MessageCreator = (delta) => \n { return \"one second ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromSeconds(60),\n MessageCreator = (delta) => \n { return delta.Seconds + \" seconds ago\"; }\n\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromMinutes(2),\n MessageCreator = (delta) => \n { return \"one minute ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromMinutes(60),\n MessageCreator = (delta) => \n { return delta.Minutes + \" minutes ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromHours(2),\n MessageCreator = (delta) => \n { return \"one hour ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromHours(24),\n MessageCreator = (delta) => \n { return delta.Hours + \" hours ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromDays(2),\n MessageCreator = (delta) => \n { return \"yesterday\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)),\n MessageCreator = (delta) => \n { return delta.Days + \" days ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)),\n MessageCreator = (delta) => \n { return \"one month ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)),\n MessageCreator = (delta) => \n { return (int)Math.Floor(delta.TotalDays / 30) + \" months ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)),\n MessageCreator = (delta) => \n { return \"one year ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.MaxValue,\n MessageCreator = (delta) => \n { return (int)Math.Floor(delta.TotalDays / 365.24D) + \" years ago\"; }\n }\n };\n\n timeRanges.Sort();\n }\n\n public static string GetRelativeTimeMessage(TimeSpan ago)\n {\n RelativeTimeRange postRelativeDateRange = timeRanges[0];\n\n foreach (var timeRange in timeRanges)\n {\n if (ago.CompareTo(timeRange.UpperBound) <= 0)\n {\n postRelativeDateRange = timeRange;\n }\n }\n\n return postRelativeDateRange.MessageCreator(ago);\n }\n}\n" }, { "answer_id": 10705, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 7, "selected": false, "text": "public static string RelativeDate(DateTime theDate)\n{\n Dictionary<long, string> thresholds = new Dictionary<long, string>();\n int minute = 60;\n int hour = 60 * minute;\n int day = 24 * hour;\n thresholds.Add(60, \"{0} seconds ago\");\n thresholds.Add(minute * 2, \"a minute ago\");\n thresholds.Add(45 * minute, \"{0} minutes ago\");\n thresholds.Add(120 * minute, \"an hour ago\");\n thresholds.Add(day, \"{0} hours ago\");\n thresholds.Add(day * 2, \"yesterday\");\n thresholds.Add(day * 30, \"{0} days ago\");\n thresholds.Add(day * 365, \"{0} months ago\");\n thresholds.Add(long.MaxValue, \"{0} years ago\");\n long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000;\n foreach (long threshold in thresholds.Keys) \n {\n if (since < threshold) \n {\n TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks));\n return string.Format(thresholds[threshold], (t.Days > 365 ? t.Days / 365 : (t.Days > 0 ? t.Days : (t.Hours > 0 ? t.Hours : (t.Minutes > 0 ? t.Minutes : (t.Seconds > 0 ? t.Seconds : 0))))).ToString());\n }\n }\n return \"\";\n}\n Latest()" }, { "answer_id": 12279, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 4, "selected": false, "text": "var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);\n DateTime TimeSpan (DateTime.UtcNow - dt).TotalSeconds\n" }, { "answer_id": 13690, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "public string GetRelativeTime(DateTime timeStamp)\n{\n return string.Format(\"<script>printdate({0});</script>\", timeStamp.ToFileTimeUtc());\n}\n" }, { "answer_id": 18393, "author": "icco", "author_id": 1063, "author_profile": "https://Stackoverflow.com/users/1063", "pm_score": 4, "selected": false, "text": "<?php\nfunction timesince($original) {\n // array of time period chunks\n $chunks = array(\n array(60 * 60 * 24 * 365 , 'year'),\n array(60 * 60 * 24 * 30 , 'month'),\n array(60 * 60 * 24 * 7, 'week'),\n array(60 * 60 * 24 , 'day'),\n array(60 * 60 , 'hour'),\n array(60 , 'minute'),\n );\n\n $today = time(); /* Current unix time */\n $since = $today - $original;\n\n if($since > 604800) {\n $print = date(\"M jS\", $original);\n\n if($since > 31536000) {\n $print .= \", \" . date(\"Y\", $original);\n }\n\n return $print;\n}\n\n// $j saves performing the count function each time around the loop\nfor ($i = 0, $j = count($chunks); $i < $j; $i++) {\n\n $seconds = $chunks[$i][0];\n $name = $chunks[$i][1];\n\n // finding the biggest chunk (if the chunk fits, break)\n if (($count = floor($since / $seconds)) != 0) {\n break;\n }\n}\n\n$print = ($count == 1) ? '1 '.$name : \"$count {$name}s\";\n\nreturn $print . \" ago\";\n\n} ?>\n" }, { "answer_id": 25709, "author": "Cebjyre", "author_id": 1612, "author_profile": "https://Stackoverflow.com/users/1612", "pm_score": 2, "selected": false, "text": "if (delta < 5400) // 90 * 60\n{\n return \"an hour ago\";\n}\n if (delta < 7200) // 120 * 60\n{\n return \"an hour ago\";\n}\n" }, { "answer_id": 79601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "public static string ToRelativeDate(DateTime input)\n{\n TimeSpan oSpan = DateTime.Now.Subtract(input);\n double TotalMinutes = oSpan.TotalMinutes;\n string Suffix = \" ago\";\n\n if (TotalMinutes < 0.0)\n {\n TotalMinutes = Math.Abs(TotalMinutes);\n Suffix = \" from now\";\n }\n\n var aValue = new SortedList<double, Func<string>>();\n aValue.Add(0.75, () => \"less than a minute\");\n aValue.Add(1.5, () => \"about a minute\");\n aValue.Add(45, () => string.Format(\"{0} minutes\", Math.Round(TotalMinutes)));\n aValue.Add(90, () => \"about an hour\");\n aValue.Add(1440, () => string.Format(\"about {0} hours\", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24\n aValue.Add(2880, () => \"a day\"); // 60 * 48\n aValue.Add(43200, () => string.Format(\"{0} days\", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30\n aValue.Add(86400, () => \"about a month\"); // 60 * 24 * 60\n aValue.Add(525600, () => string.Format(\"{0} months\", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365 \n aValue.Add(1051200, () => \"about a year\"); // 60 * 24 * 365 * 2\n aValue.Add(double.MaxValue, () => string.Format(\"{0} years\", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));\n\n return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix;\n}\n static readonly SortedList<double, Func<TimeSpan, string>> offsets = \n new SortedList<double, Func<TimeSpan, string>>\n{\n { 0.75, _ => \"less than a minute\"},\n { 1.5, _ => \"about a minute\"},\n { 45, x => $\"{x.TotalMinutes:F0} minutes\"},\n { 90, x => \"about an hour\"},\n { 1440, x => $\"about {x.TotalHours:F0} hours\"},\n { 2880, x => \"a day\"},\n { 43200, x => $\"{x.TotalDays:F0} days\"},\n { 86400, x => \"about a month\"},\n { 525600, x => $\"{x.TotalDays / 30:F0} months\"},\n { 1051200, x => \"about a year\"},\n { double.MaxValue, x => $\"{x.TotalDays / 365:F0} years\"}\n};\n\npublic static string ToRelativeDate(this DateTime input)\n{\n TimeSpan x = DateTime.Now - input;\n string Suffix = x.TotalMinutes > 0 ? \" ago\" : \" from now\";\n x = new TimeSpan(Math.Abs(x.Ticks));\n return offsets.First(n => x.TotalMinutes < n.Key).Value(x) + Suffix;\n}\n" }, { "answer_id": 111303, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 9, "selected": false, "text": "jQuery(document).ready(function() {\n jQuery('abbr.timeago').timeago();\n});\n abbr <abbr class=\"timeago\" title=\"2008-07-17T09:24:17Z\">July 17, 2008</abbr>\n <abbr class=\"timeago\" title=\"July 17, 2008\">4 months ago</abbr>\n" }, { "answer_id": 118569, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 3, "selected": false, "text": "agoify($delta)\n local($y, $mo, $d, $h, $m, $s);\n $s = floor($delta);\n if($s<=1) return \"a second ago\";\n if($s<60) return \"$s seconds ago\";\n $m = floor($s/60);\n if($m==1) return \"a minute ago\";\n if($m<45) return \"$m minutes ago\";\n $h = floor($m/60);\n if($h==1) return \"an hour ago\";\n if($h<24) return \"$h hours ago\";\n $d = floor($h/24);\n if($d<2) return \"yesterday\";\n if($d<30) return \"$d days ago\";\n $mo = floor($d/30);\n if($mo<=1) return \"a month ago\";\n $y = floor($mo/12);\n if($y<1) return \"$mo months ago\";\n if($y==1) return \"a year ago\";\n return \"$y years ago\";\n" }, { "answer_id": 229285, "author": "Jauder Ho", "author_id": 26366, "author_profile": "https://Stackoverflow.com/users/26366", "pm_score": 5, "selected": false, "text": "/*\n * Javascript Humane Dates\n * Copyright (c) 2008 Dean Landolt (deanlandolt.com)\n * Re-write by Zach Leatherman (zachleat.com)\n * \n * Adopted from the John Resig's pretty.js\n * at http://ejohn.org/blog/javascript-pretty-date\n * and henrah's proposed modification \n * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458\n * \n * Licensed under the MIT license.\n */\n\nfunction humane_date(date_str){\n var time_formats = [\n [60, 'just now'],\n [90, '1 minute'], // 60*1.5\n [3600, 'minutes', 60], // 60*60, 60\n [5400, '1 hour'], // 60*60*1.5\n [86400, 'hours', 3600], // 60*60*24, 60*60\n [129600, '1 day'], // 60*60*24*1.5\n [604800, 'days', 86400], // 60*60*24*7, 60*60*24\n [907200, '1 week'], // 60*60*24*7*1.5\n [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7\n [3942000, '1 month'], // 60*60*24*(365/12)*1.5\n [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)\n [47304000, '1 year'], // 60*60*24*365*1.5\n [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365\n [4730400000, '1 century'] // 60*60*24*365*100*1.5\n ];\n\n var time = ('' + date_str).replace(/-/g,\"/\").replace(/[TZ]/g,\" \"),\n dt = new Date,\n seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),\n token = ' ago',\n i = 0,\n format;\n\n if (seconds < 0) {\n seconds = Math.abs(seconds);\n token = '';\n }\n\n while (format = time_formats[i++]) {\n if (seconds < format[0]) {\n if (format.length == 2) {\n return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago\n } else {\n return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');\n }\n }\n }\n\n // overflow for centuries\n if(seconds > 4730400000)\n return Math.round(seconds / 4730400000) + ' centuries' + token;\n\n return date_str;\n};\n\nif(typeof jQuery != 'undefined') {\n jQuery.fn.humane_dates = function(){\n return this.each(function(){\n var date = humane_date(this.title);\n if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to\n jQuery(this).text(date);\n });\n };\n}\n" }, { "answer_id": 501415, "author": "Thomaschaaf", "author_id": 19929, "author_profile": "https://Stackoverflow.com/users/19929", "pm_score": 6, "selected": false, "text": "define(\"SECOND\", 1);\ndefine(\"MINUTE\", 60 * SECOND);\ndefine(\"HOUR\", 60 * MINUTE);\ndefine(\"DAY\", 24 * HOUR);\ndefine(\"MONTH\", 30 * DAY);\nfunction relativeTime($time)\n{ \n $delta = time() - $time;\n\n if ($delta < 1 * MINUTE)\n {\n return $delta == 1 ? \"one second ago\" : $delta . \" seconds ago\";\n }\n if ($delta < 2 * MINUTE)\n {\n return \"a minute ago\";\n }\n if ($delta < 45 * MINUTE)\n {\n return floor($delta / MINUTE) . \" minutes ago\";\n }\n if ($delta < 90 * MINUTE)\n {\n return \"an hour ago\";\n }\n if ($delta < 24 * HOUR)\n {\n return floor($delta / HOUR) . \" hours ago\";\n }\n if ($delta < 48 * HOUR)\n {\n return \"yesterday\";\n }\n if ($delta < 30 * DAY)\n {\n return floor($delta / DAY) . \" days ago\";\n }\n if ($delta < 12 * MONTH)\n {\n $months = floor($delta / DAY / 30);\n return $months <= 1 ? \"one month ago\" : $months . \" months ago\";\n }\n else\n {\n $years = floor($delta / DAY / 365);\n return $years <= 1 ? \"one year ago\" : $years . \" years ago\";\n }\n} \n" }, { "answer_id": 569913, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "java.util.Date import java.util.Date;\nimport javax.management.timer.Timer;\n\nString getRelativeDate(Date date) { \n long delta = new Date().getTime() - date.getTime();\n if (delta < 1L * Timer.ONE_MINUTE) {\n return toSeconds(delta) == 1 ? \"one second ago\" : toSeconds(delta) + \" seconds ago\";\n }\n if (delta < 2L * Timer.ONE_MINUTE) {\n return \"a minute ago\";\n }\n if (delta < 45L * Timer.ONE_MINUTE) {\n return toMinutes(delta) + \" minutes ago\";\n }\n if (delta < 90L * Timer.ONE_MINUTE) {\n return \"an hour ago\";\n }\n if (delta < 24L * Timer.ONE_HOUR) {\n return toHours(delta) + \" hours ago\";\n }\n if (delta < 48L * Timer.ONE_HOUR) {\n return \"yesterday\";\n }\n if (delta < 30L * Timer.ONE_DAY) {\n return toDays(delta) + \" days ago\";\n }\n if (delta < 12L * 4L * Timer.ONE_WEEK) { // a month\n long months = toMonths(delta); \n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n }\n else {\n long years = toYears(delta);\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n}\n\nprivate long toSeconds(long date) {\n return date / 1000L;\n}\n\nprivate long toMinutes(long date) {\n return toSeconds(date) / 60L;\n}\n\nprivate long toHours(long date) {\n return toMinutes(date) / 60L;\n}\n\nprivate long toDays(long date) {\n return toHours(date) / 24L;\n}\n\nprivate long toMonths(long date) {\n return toDays(date) / 30L;\n}\n\nprivate long toYears(long date) {\n return toMonths(date) / 365L;\n}\n" }, { "answer_id": 628203, "author": "neuracnu", "author_id": 19277, "author_profile": "https://Stackoverflow.com/users/19277", "pm_score": 6, "selected": false, "text": "using System.Text;\n\n/// <summary>\n/// Compares a supplied date to the current date and generates a friendly English \n/// comparison (\"5 days ago\", \"5 days from now\")\n/// </summary>\n/// <param name=\"date\">The date to convert</param>\n/// <param name=\"approximate\">When off, calculate timespan down to the second.\n/// When on, approximate to the largest round unit of time.</param>\n/// <returns></returns>\npublic static string ToRelativeDateString(this DateTime value, bool approximate)\n{\n StringBuilder sb = new StringBuilder();\n\n string suffix = (value > DateTime.Now) ? \" from now\" : \" ago\";\n\n TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks));\n\n if (timeSpan.Days > 0)\n {\n sb.AppendFormat(\"{0} {1}\", timeSpan.Days,\n (timeSpan.Days > 1) ? \"days\" : \"day\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Hours > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty,\n timeSpan.Hours, (timeSpan.Hours > 1) ? \"hours\" : \"hour\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Minutes > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty, \n timeSpan.Minutes, (timeSpan.Minutes > 1) ? \"minutes\" : \"minute\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Seconds > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty, \n timeSpan.Seconds, (timeSpan.Seconds > 1) ? \"seconds\" : \"second\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (sb.Length == 0) return \"right now\";\n\n sb.Append(suffix);\n return sb.ToString();\n}\n" }, { "answer_id": 1141237, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class RelativeDateHelper\n{\n private static Dictionary<double, Func<double, string>> sm_Dict = null;\n\n private static Dictionary<double, Func<double, string>> DictionarySetup()\n {\n var dict = new Dictionary<double, Func<double, string>>();\n dict.Add(0.75, (mins) => \"less than a minute\");\n dict.Add(1.5, (mins) => \"about a minute\");\n dict.Add(45, (mins) => string.Format(\"{0} minutes\", Math.Round(mins)));\n dict.Add(90, (mins) => \"about an hour\");\n dict.Add(1440, (mins) => string.Format(\"about {0} hours\", Math.Round(Math.Abs(mins / 60)))); // 60 * 24\n dict.Add(2880, (mins) => \"a day\"); // 60 * 48\n dict.Add(43200, (mins) => string.Format(\"{0} days\", Math.Floor(Math.Abs(mins / 1440)))); // 60 * 24 * 30\n dict.Add(86400, (mins) => \"about a month\"); // 60 * 24 * 60\n dict.Add(525600, (mins) => string.Format(\"{0} months\", Math.Floor(Math.Abs(mins / 43200)))); // 60 * 24 * 365 \n dict.Add(1051200, (mins) => \"about a year\"); // 60 * 24 * 365 * 2\n dict.Add(double.MaxValue, (mins) => string.Format(\"{0} years\", Math.Floor(Math.Abs(mins / 525600))));\n\n return dict;\n }\n\n public static string ToRelativeDate(this DateTime input)\n {\n TimeSpan oSpan = DateTime.Now.Subtract(input);\n double TotalMinutes = oSpan.TotalMinutes;\n string Suffix = \" ago\";\n\n if (TotalMinutes < 0.0)\n {\n TotalMinutes = Math.Abs(TotalMinutes);\n Suffix = \" from now\";\n }\n\n if (null == sm_Dict)\n sm_Dict = DictionarySetup();\n\n return sm_Dict.First(n => TotalMinutes < n.Key).Value.Invoke(TotalMinutes) + Suffix;\n }\n}\n" }, { "answer_id": 1379178, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 4, "selected": false, "text": "var dateTime1 = 2.Hours().Ago();\nvar dateTime2 = 3.Days().Ago();\nvar dateTime3 = 1.Months().Ago();\nvar dateTime4 = 5.Hours().FromNow();\nvar dateTime5 = 2.Weeks().FromNow();\nvar dateTime6 = 40.Seconds().FromNow();\n" }, { "answer_id": 1735172, "author": "antony.trupe", "author_id": 5849, "author_profile": "https://Stackoverflow.com/users/5849", "pm_score": 3, "selected": false, "text": "import java.util.Date;\n\npublic class RelativeDateFormat {\n\n private static final long ONE_MINUTE = 60000L;\n private static final long ONE_HOUR = 3600000L;\n private static final long ONE_DAY = 86400000L;\n private static final long ONE_WEEK = 604800000L;\n\n public static String format(Date date) {\n\n long delta = new Date().getTime() - date.getTime();\n if (delta < 1L * ONE_MINUTE) {\n return toSeconds(delta) == 1 ? \"one second ago\" : toSeconds(delta)\n + \" seconds ago\";\n }\n if (delta < 2L * ONE_MINUTE) {\n return \"one minute ago\";\n }\n if (delta < 45L * ONE_MINUTE) {\n return toMinutes(delta) + \" minutes ago\";\n }\n if (delta < 90L * ONE_MINUTE) {\n return \"one hour ago\";\n }\n if (delta < 24L * ONE_HOUR) {\n return toHours(delta) + \" hours ago\";\n }\n if (delta < 48L * ONE_HOUR) {\n return \"yesterday\";\n }\n if (delta < 30L * ONE_DAY) {\n return toDays(delta) + \" days ago\";\n }\n if (delta < 12L * 4L * ONE_WEEK) {\n long months = toMonths(delta);\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n } else {\n long years = toYears(delta);\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n }\n\n private static long toSeconds(long date) {\n return date / 1000L;\n }\n\n private static long toMinutes(long date) {\n return toSeconds(date) / 60L;\n }\n\n private static long toHours(long date) {\n return toMinutes(date) / 60L;\n }\n\n private static long toDays(long date) {\n return toHours(date) / 24L;\n }\n\n private static long toMonths(long date) {\n return toDays(date) / 30L;\n }\n\n private static long toYears(long date) {\n return toMonths(date) / 365L;\n }\n\n}\n" }, { "answer_id": 2179589, "author": "Buhake Sindi", "author_id": 251173, "author_profile": "https://Stackoverflow.com/users/251173", "pm_score": 3, "selected": false, "text": "function posted(t) {\n var now = new Date();\n var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);\n if (diff < 60) { return 'less than a minute ago'; }\n else if (diff < 120) { return 'about a minute ago'; }\n else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }\n else if (diff < (5400)) { return 'about an hour ago'; }\n else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }\n else if (diff < (172800)) { return '1 day ago'; } \n else {return (parseInt(diff / 86400)).toString() + ' days ago'; }\n}\n" }, { "answer_id": 2244324, "author": "0llie", "author_id": 229906, "author_profile": "https://Stackoverflow.com/users/229906", "pm_score": 4, "selected": false, "text": "+ (NSString *)timeAgoString:(NSDate *)date {\n int delta = -(int)[date timeIntervalSinceNow];\n\n if (delta < 60)\n {\n return delta == 1 ? @\"one second ago\" : [NSString stringWithFormat:@\"%i seconds ago\", delta];\n }\n if (delta < 120)\n {\n return @\"a minute ago\";\n }\n if (delta < 2700)\n {\n return [NSString stringWithFormat:@\"%i minutes ago\", delta/60];\n }\n if (delta < 5400)\n {\n return @\"an hour ago\";\n }\n if (delta < 24 * 3600)\n {\n return [NSString stringWithFormat:@\"%i hours ago\", delta/3600];\n }\n if (delta < 48 * 3600)\n {\n return @\"yesterday\";\n }\n if (delta < 30 * 24 * 3600)\n {\n return [NSString stringWithFormat:@\"%i days ago\", delta/(24*3600)];\n }\n if (delta < 12 * 30 * 24 * 3600)\n {\n int months = delta/(30*24*3600);\n return months <= 1 ? @\"one month ago\" : [NSString stringWithFormat:@\"%i months ago\", months];\n }\n else\n {\n int years = delta/(12*30*24*3600);\n return years <= 1 ? @\"one year ago\" : [NSString stringWithFormat:@\"%i years ago\", years];\n }\n}\n" }, { "answer_id": 5427203, "author": "Town", "author_id": 54975, "author_profile": "https://Stackoverflow.com/users/54975", "pm_score": 5, "selected": false, "text": "public static class DateTimeHelper\n {\n private const int SECOND = 1;\n private const int MINUTE = 60 * SECOND;\n private const int HOUR = 60 * MINUTE;\n private const int DAY = 24 * HOUR;\n private const int MONTH = 30 * DAY;\n\n /// <summary>\n /// Returns a friendly version of the provided DateTime, relative to now. E.g.: \"2 days ago\", or \"in 6 months\".\n /// </summary>\n /// <param name=\"dateTime\">The DateTime to compare to Now</param>\n /// <returns>A friendly string</returns>\n public static string GetFriendlyRelativeTime(DateTime dateTime)\n {\n if (DateTime.UtcNow.Ticks == dateTime.Ticks)\n {\n return \"Right now!\";\n }\n\n bool isFuture = (DateTime.UtcNow.Ticks < dateTime.Ticks);\n var ts = DateTime.UtcNow.Ticks < dateTime.Ticks ? new TimeSpan(dateTime.Ticks - DateTime.UtcNow.Ticks) : new TimeSpan(DateTime.UtcNow.Ticks - dateTime.Ticks);\n\n double delta = ts.TotalSeconds;\n\n if (delta < 1 * MINUTE)\n {\n return isFuture ? \"in \" + (ts.Seconds == 1 ? \"one second\" : ts.Seconds + \" seconds\") : ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n }\n if (delta < 2 * MINUTE)\n {\n return isFuture ? \"in a minute\" : \"a minute ago\";\n }\n if (delta < 45 * MINUTE)\n {\n return isFuture ? \"in \" + ts.Minutes + \" minutes\" : ts.Minutes + \" minutes ago\";\n }\n if (delta < 90 * MINUTE)\n {\n return isFuture ? \"in an hour\" : \"an hour ago\";\n }\n if (delta < 24 * HOUR)\n {\n return isFuture ? \"in \" + ts.Hours + \" hours\" : ts.Hours + \" hours ago\";\n }\n if (delta < 48 * HOUR)\n {\n return isFuture ? \"tomorrow\" : \"yesterday\";\n }\n if (delta < 30 * DAY)\n {\n return isFuture ? \"in \" + ts.Days + \" days\" : ts.Days + \" days ago\";\n }\n if (delta < 12 * MONTH)\n {\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return isFuture ? \"in \" + (months <= 1 ? \"one month\" : months + \" months\") : months <= 1 ? \"one month ago\" : months + \" months ago\";\n }\n else\n {\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return isFuture ? \"in \" + (years <= 1 ? \"one year\" : years + \" years\") : years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n }\n }\n" }, { "answer_id": 5835905, "author": "Owen Blacker", "author_id": 205245, "author_profile": "https://Stackoverflow.com/users/205245", "pm_score": 4, "selected": false, "text": "Grammar FuzzyDateExtensions public class Grammar\n{\n /// <summary> Gets or sets the term for \"just now\". </summary>\n public string JustNow { get; set; }\n /// <summary> Gets or sets the term for \"X minutes ago\". </summary>\n /// <remarks>\n /// This is a <see cref=\"String.Format\"/> pattern, where <c>{0}</c>\n /// is the number of minutes.\n /// </remarks>\n public string MinutesAgo { get; set; }\n public string OneHourAgo { get; set; }\n public string HoursAgo { get; set; }\n public string Yesterday { get; set; }\n public string DaysAgo { get; set; }\n public string LastMonth { get; set; }\n public string MonthsAgo { get; set; }\n public string LastYear { get; set; }\n public string YearsAgo { get; set; }\n /// <summary> Gets or sets the term for \"ages ago\". </summary>\n public string AgesAgo { get; set; }\n\n /// <summary>\n /// Gets or sets the threshold beyond which the fuzzy date should be\n /// considered \"ages ago\".\n /// </summary>\n public TimeSpan AgesAgoThreshold { get; set; }\n\n /// <summary>\n /// Initialises a new <see cref=\"Grammar\"/> instance with the\n /// specified properties.\n /// </summary>\n private void Initialise(string justNow, string minutesAgo,\n string oneHourAgo, string hoursAgo, string yesterday, string daysAgo,\n string lastMonth, string monthsAgo, string lastYear, string yearsAgo,\n string agesAgo, TimeSpan agesAgoThreshold)\n { ... }\n}\n FuzzyDateString public static class FuzzyDateExtensions\n{\n public static string ToFuzzyDateString(this TimeSpan timespan)\n {\n return timespan.ToFuzzyDateString(new Grammar());\n }\n\n public static string ToFuzzyDateString(this TimeSpan timespan,\n Grammar grammar)\n {\n return GetFuzzyDateString(timespan, grammar);\n }\n\n public static string ToFuzzyDateString(this DateTime datetime)\n {\n return (DateTime.Now - datetime).ToFuzzyDateString();\n }\n\n public static string ToFuzzyDateString(this DateTime datetime,\n Grammar grammar)\n {\n return (DateTime.Now - datetime).ToFuzzyDateString(grammar);\n }\n\n\n private static string GetFuzzyDateString(TimeSpan timespan,\n Grammar grammar)\n {\n timespan = timespan.Duration();\n\n if (timespan >= grammar.AgesAgoThreshold)\n {\n return grammar.AgesAgo;\n }\n\n if (timespan < new TimeSpan(0, 2, 0)) // 2 minutes\n {\n return grammar.JustNow;\n }\n\n if (timespan < new TimeSpan(1, 0, 0)) // 1 hour\n {\n return String.Format(grammar.MinutesAgo, timespan.Minutes);\n }\n\n if (timespan < new TimeSpan(1, 55, 0)) // 1 hour 55 minutes\n {\n return grammar.OneHourAgo;\n }\n\n if (timespan < new TimeSpan(12, 0, 0) // 12 hours\n && (DateTime.Now - timespan).IsToday())\n {\n return String.Format(grammar.HoursAgo, timespan.RoundedHours());\n }\n\n if ((DateTime.Now.AddDays(1) - timespan).IsToday())\n {\n return grammar.Yesterday;\n }\n\n if (timespan < new TimeSpan(32, 0, 0, 0) // 32 days\n && (DateTime.Now - timespan).IsThisMonth())\n {\n return String.Format(grammar.DaysAgo, timespan.RoundedDays());\n }\n\n if ((DateTime.Now.AddMonths(1) - timespan).IsThisMonth())\n {\n return grammar.LastMonth;\n }\n\n if (timespan < new TimeSpan(365, 0, 0, 0, 0) // 365 days\n && (DateTime.Now - timespan).IsThisYear())\n {\n return String.Format(grammar.MonthsAgo, timespan.RoundedMonths());\n }\n\n if ((DateTime.Now - timespan).AddYears(1).IsThisYear())\n {\n return grammar.LastYear;\n }\n\n return String.Format(grammar.YearsAgo, timespan.RoundedYears());\n }\n}\n IsToday IsThisMonth IsThisYear public static bool IsToday(this DateTime date)\n{\n return date.DayOfYear == DateTime.Now.DayOfYear && date.IsThisYear();\n}\n RoundedMonths public static int RoundedDays(this TimeSpan timespan)\n{\n return (timespan.Hours > 12) ? timespan.Days + 1 : timespan.Days;\n}\n\npublic static int RoundedMonths(this TimeSpan timespan)\n{\n DateTime then = DateTime.Now - timespan;\n\n // Number of partial months elapsed since 1 Jan, AD 1 (DateTime.MinValue)\n int nowMonthYears = DateTime.Now.Year * 12 + DateTime.Now.Month;\n int thenMonthYears = then.Year * 12 + then.Month; \n\n return nowMonthYears - thenMonthYears;\n}\n" }, { "answer_id": 10775917, "author": "JoeyFur62", "author_id": 1420406, "author_profile": "https://Stackoverflow.com/users/1420406", "pm_score": 3, "selected": false, "text": "var ts = new TimeSpan(DateTime.Now.Ticks - dt.Ticks);\n" }, { "answer_id": 12406029, "author": "tugberk", "author_id": 463785, "author_profile": "https://Stackoverflow.com/users/463785", "pm_score": 3, "selected": false, "text": "Int32 public static class TimeSpanExtensions {\n\n public static TimeSpan Days(this int value) {\n\n return new TimeSpan(value, 0, 0, 0);\n }\n\n public static TimeSpan Hours(this int value) {\n\n return new TimeSpan(0, value, 0, 0);\n }\n\n public static TimeSpan Minutes(this int value) {\n\n return new TimeSpan(0, 0, value, 0);\n }\n\n public static TimeSpan Seconds(this int value) {\n\n return new TimeSpan(0, 0, 0, value);\n }\n\n public static TimeSpan Milliseconds(this int value) {\n\n return new TimeSpan(0, 0, 0, 0, value);\n }\n\n public static DateTime Ago(this TimeSpan value) {\n\n return DateTime.Now - value;\n }\n}\n DateTime public static class DateTimeExtensions {\n\n public static DateTime Ago(this DateTime dateTime, TimeSpan delta) {\n\n return dateTime - delta;\n }\n}\n var date = DateTime.Now;\ndate.Ago(2.Days()); // 2 days ago\ndate.Ago(7.Hours()); // 7 hours ago\ndate.Ago(567.Milliseconds()); // 567 milliseconds ago\n" }, { "answer_id": 15446338, "author": "Prashant Gupta", "author_id": 985335, "author_profile": "https://Stackoverflow.com/users/985335", "pm_score": 3, "selected": false, "text": "public string RelativeDateTimeCount(DateTime inputDateTime)\n{\n string outputDateTime = string.Empty;\n TimeSpan ts = DateTime.Now - inputDateTime;\n\n if (ts.Days > 7)\n { outputDateTime = inputDateTime.ToString(\"MMMM d, yyyy\"); }\n\n else if (ts.Days > 0)\n {\n outputDateTime = ts.Days == 1 ? (\"about 1 Day ago\") : (\"about \" + ts.Days.ToString() + \" Days ago\");\n }\n else if (ts.Hours > 0)\n {\n outputDateTime = ts.Hours == 1 ? (\"an hour ago\") : (ts.Hours.ToString() + \" hours ago\");\n }\n else if (ts.Minutes > 0)\n {\n outputDateTime = ts.Minutes == 1 ? (\"1 minute ago\") : (ts.Minutes.ToString() + \" minutes ago\");\n }\n else outputDateTime = \"few seconds ago\";\n\n return outputDateTime;\n}\n" }, { "answer_id": 18074585, "author": "string.Empty", "author_id": 2027232, "author_profile": "https://Stackoverflow.com/users/2027232", "pm_score": 2, "selected": false, "text": "public string getRelativeDateTime(DateTime date)\n{\n TimeSpan ts = DateTime.Now - date;\n if (ts.TotalMinutes < 1)//seconds ago\n return \"just now\";\n if (ts.TotalHours < 1)//min ago\n return (int)ts.TotalMinutes == 1 ? \"1 Minute ago\" : (int)ts.TotalMinutes + \" Minutes ago\";\n if (ts.TotalDays < 1)//hours ago\n return (int)ts.TotalHours == 1 ? \"1 Hour ago\" : (int)ts.TotalHours + \" Hours ago\";\n if (ts.TotalDays < 7)//days ago\n return (int)ts.TotalDays == 1 ? \"1 Day ago\" : (int)ts.TotalDays + \" Days ago\";\n if (ts.TotalDays < 30.4368)//weeks ago\n return (int)(ts.TotalDays / 7) == 1 ? \"1 Week ago\" : (int)(ts.TotalDays / 7) + \" Weeks ago\";\n if (ts.TotalDays < 365.242)//months ago\n return (int)(ts.TotalDays / 30.4368) == 1 ? \"1 Month ago\" : (int)(ts.TotalDays / 30.4368) + \" Months ago\";\n //years ago\n return (int)(ts.TotalDays / 365.242) == 1 ? \"1 Year ago\" : (int)(ts.TotalDays / 365.242) + \" Years ago\";\n}\n" }, { "answer_id": 19377828, "author": "Premdeep Mohanty", "author_id": 2749766, "author_profile": "https://Stackoverflow.com/users/2749766", "pm_score": 4, "selected": false, "text": "long delta = new Date().getTime() - date.getTime();\nconst int SECOND = 1;\nconst int MINUTE = 60 * SECOND;\nconst int HOUR = 60 * MINUTE;\nconst int DAY = 24 * HOUR;\nconst int MONTH = 30 * DAY;\n\nif (delta < 0L)\n{\n return \"not yet\";\n}\nif (delta < 1L * MINUTE)\n{\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n}\nif (delta < 2L * MINUTE)\n{\n return \"a minute ago\";\n}\nif (delta < 45L * MINUTE)\n{\n return ts.Minutes + \" minutes ago\";\n}\nif (delta < 90L * MINUTE)\n{\n return \"an hour ago\";\n}\nif (delta < 24L * HOUR)\n{\n return ts.Hours + \" hours ago\";\n}\nif (delta < 48L * HOUR)\n{\n return \"yesterday\";\n}\nif (delta < 30L * DAY)\n{\n return ts.Days + \" days ago\";\n}\nif (delta < 12L * MONTH)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nelse\n{\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n}\n" }, { "answer_id": 22961626, "author": "Karl-Henrik", "author_id": 1770846, "author_profile": "https://Stackoverflow.com/users/1770846", "pm_score": 6, "selected": false, "text": "DateTime.UtcNow.AddHours(-30).Humanize() => \"yesterday\"\nDateTime.UtcNow.AddHours(-2).Humanize() => \"2 hours ago\"\n\nDateTime.UtcNow.AddHours(30).Humanize() => \"tomorrow\"\nDateTime.UtcNow.AddHours(2).Humanize() => \"2 hours from now\"\n\nTimeSpan.FromMilliseconds(1299630020).Humanize() => \"2 weeks\"\nTimeSpan.FromMilliseconds(1299630020).Humanize(3) => \"2 weeks, 1 day, 1 hour\"\n" }, { "answer_id": 25677278, "author": "Wai Ho Leung", "author_id": 1418148, "author_profile": "https://Stackoverflow.com/users/1418148", "pm_score": 2, "selected": false, "text": "/** \n * {@code date1} has to be earlier than {@code date2}.\n */\npublic static String relativize(Date date1, Date date2) {\n assert date2.getTime() >= date1.getTime();\n\n long duration = date2.getTime() - date1.getTime();\n long converted;\n\n if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"day\" : \"days\");\n } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"hour\" : \"hours\");\n } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"minute\" : \"minutes\");\n } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"second\" : \"seconds\");\n } else {\n return \"just now\";\n }\n}\n" }, { "answer_id": 32459883, "author": "Bgl86", "author_id": 5293002, "author_profile": "https://Stackoverflow.com/users/5293002", "pm_score": 3, "selected": false, "text": "\"2 days, 4 hours and 12 minutes ago\" TimeSpan timeDiff = DateTime.Now-CreatedDate;\n timeDiff.Days\ntimeDiff.Hours\n" }, { "answer_id": 32459892, "author": "Piotr Stapp", "author_id": 1749895, "author_profile": "https://Stackoverflow.com/users/1749895", "pm_score": 4, "selected": false, "text": "public static string TimeAgo(this DateTime dateTime)\n{\n string result = string.Empty;\n var timeSpan = DateTime.Now.Subtract(dateTime);\n \n if (timeSpan <= TimeSpan.FromSeconds(60))\n {\n result = string.Format(\"{0} seconds ago\", timeSpan.Seconds);\n }\n else if (timeSpan <= TimeSpan.FromMinutes(60))\n {\n result = timeSpan.Minutes > 1 ? \n String.Format(\"about {0} minutes ago\", timeSpan.Minutes) :\n \"about a minute ago\";\n }\n else if (timeSpan <= TimeSpan.FromHours(24))\n {\n result = timeSpan.Hours > 1 ? \n String.Format(\"about {0} hours ago\", timeSpan.Hours) : \n \"about an hour ago\";\n }\n else if (timeSpan <= TimeSpan.FromDays(30))\n {\n result = timeSpan.Days > 1 ? \n String.Format(\"about {0} days ago\", timeSpan.Days) : \n \"yesterday\";\n }\n else if (timeSpan <= TimeSpan.FromDays(365))\n {\n result = timeSpan.Days > 30 ? \n String.Format(\"about {0} months ago\", timeSpan.Days / 30) : \n \"about a month ago\";\n }\n else\n {\n result = timeSpan.Days > 365 ? \n String.Format(\"about {0} years ago\", timeSpan.Days / 365) : \n \"about a year ago\";\n }\n \n return result;\n}\n" }, { "answer_id": 46029235, "author": "VnDevil", "author_id": 1326699, "author_profile": "https://Stackoverflow.com/users/1326699", "pm_score": 1, "selected": false, "text": "public static string RelativeDate(DateTime theDate)\n{\n var span = DateTime.Now - theDate;\n if (span.Days > 365)\n {\n var years = (span.Days / 365);\n if (span.Days % 365 != 0)\n years += 1;\n return $\"about {years} {(years == 1 ? \"year\" : \"years\")} ago\";\n }\n if (span.Days > 30)\n {\n var months = (span.Days / 30);\n if (span.Days % 31 != 0)\n months += 1;\n return $\"about {months} {(months == 1 ? \"month\" : \"months\")} ago\";\n }\n if (span.Days > 0)\n return $\"about {span.Days} {(span.Days == 1 ? \"day\" : \"days\")} ago\";\n if (span.Hours > 0)\n return $\"about {span.Hours} {(span.Hours == 1 ? \"hour\" : \"hours\")} ago\";\n if (span.Minutes > 0)\n return $\"about {span.Minutes} {(span.Minutes == 1 ? \"minute\" : \"minutes\")} ago\";\n if (span.Seconds > 5)\n return $\"about {span.Seconds} seconds ago\";\n\n return span.Seconds <= 5 ? \"about 5 seconds ago\" : string.Empty;\n}\n" }, { "answer_id": 49300196, "author": "Beingnin", "author_id": 7441056, "author_profile": "https://Stackoverflow.com/users/7441056", "pm_score": -1, "selected": false, "text": " public static string TimeLeft(DateTime utcDate)\n {\n TimeSpan timeLeft = DateTime.UtcNow - utcDate;\n string timeLeftString = \"\";\n if (timeLeft.Days > 0)\n {\n timeLeftString += timeLeft.Days == 1 ? timeLeft.Days + \" day\" : timeLeft.Days + \" days\";\n }\n else if (timeLeft.Hours > 0)\n {\n timeLeftString += timeLeft.Hours == 1 ? timeLeft.Hours + \" hour\" : timeLeft.Hours + \" hours\";\n }\n else\n {\n timeLeftString += timeLeft.Minutes == 1 ? timeLeft.Minutes+\" minute\" : timeLeft.Minutes + \" minutes\";\n }\n return timeLeftString;\n }\n" }, { "answer_id": 54018412, "author": "boyukbas", "author_id": 1051784, "author_profile": "https://Stackoverflow.com/users/1051784", "pm_score": 2, "selected": false, "text": " const int SECOND = 1;\n const int MINUTE = 60 * SECOND;\n const int HOUR = 60 * MINUTE;\n const int DAY = 24 * HOUR;\n const int MONTH = 30 * DAY;\n\n var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);\n double delta = Math.Abs(ts.TotalSeconds);\n\n if (delta < 1 * MINUTE)\n return ts.Seconds + \" saniye önce\";\n\n if (delta < 45 * MINUTE)\n return ts.Minutes + \" dakika önce\";\n\n if (delta < 24 * HOUR)\n return ts.Hours + \" saat önce\";\n\n if (delta < 48 * HOUR)\n return \"dün\";\n\n if (delta < 30 * DAY)\n return ts.Days + \" gün önce\";\n\n if (delta < 12 * MONTH)\n {\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months + \" ay önce\";\n }\n else\n {\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years + \" yıl önce\";\n }\n" }, { "answer_id": 56310196, "author": "Ahmed Osama", "author_id": 5514131, "author_profile": "https://Stackoverflow.com/users/5514131", "pm_score": 2, "selected": false, "text": "// Calculate total days in current year\nint daysInYear;\n\nfor (var i = 1; i <= 12; i++)\n daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i);\n\n// Past date\nDateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582));\n\n// Calculate difference between current date and past date\ndouble diff = (DateTime.Now - dateToCompare).TotalMilliseconds;\n\nTimeSpan ts = TimeSpan.FromMilliseconds(diff);\n\nvar years = ts.TotalDays / daysInYear; // Years\nvar months = ts.TotalDays / (daysInYear / (double)12); // Months\nvar weeks = ts.TotalDays / 7; // Weeks\nvar days = ts.TotalDays; // Days\nvar hours = ts.TotalHours; // Hours\nvar minutes = ts.TotalMinutes; // Minutes\nvar seconds = ts.TotalSeconds; // Seconds\n\nif (years >= 1)\n Console.WriteLine(Math.Round(years, 0) + \" year(s) ago\");\nelse if (months >= 1)\n Console.WriteLine(Math.Round(months, 0) + \" month(s) ago\");\nelse if (weeks >= 1)\n Console.WriteLine(Math.Round(weeks, 0) + \" week(s) ago\");\nelse if (days >= 1)\n Console.WriteLine(Math.Round(days, 0) + \" days(s) ago\");\nelse if (hours >= 1)\n Console.WriteLine(Math.Round(hours, 0) + \" hour(s) ago\");\nelse if (minutes >= 1)\n Console.WriteLine(Math.Round(minutes, 0) + \" minute(s) ago\");\nelse if (seconds >= 1)\n Console.WriteLine(Math.Round(seconds, 0) + \" second(s) ago\");\n\nConsole.ReadLine();\n" }, { "answer_id": 64329743, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "DateTime using System;\n\npublic class Program {\n public static string getRelativeTime(DateTime past) {\n DateTime now = DateTime.Today;\n string rt = \"\";\n int time;\n string statement = \"\";\n if (past.Second >= now.Second) {\n if (past.Second - now.Second == 1) {\n rt = \"second ago\";\n }\n rt = \"seconds ago\";\n time = past.Second - now.Second;\n statement = \"\" + time;\n return (statement + rt);\n }\n if (past.Minute >= now.Minute) {\n if (past.Second - now.Second == 1) {\n rt = \"second ago\";\n } else {\n rt = \"minutes ago\";\n }\n time = past.Minute - now.Minute;\n statement = \"\" + time;\n return (statement + rt);\n }\n // This process will go on until years\n }\n public static void Main() {\n DateTime before = new DateTime(1995, 8, 24);\n string date = getRelativeTime(before);\n Console.WriteLine(\"Windows 95 was {0}.\", date);\n }\n}\n" }, { "answer_id": 65238004, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "TimeSpan timeSpan = DateTime.Now - new DateTime(1234, 5, 6, 7, 8, 9);\n\n(string unit, int value) = new Dictionary<string, int>\n{\n {\"year(s)\", (int)(timeSpan.TotalDays / 365.25)}, //https://en.wikipedia.org/wiki/Year#Intercalation\n {\"month(s)\", (int)(timeSpan.TotalDays / 29.53)}, //https://en.wikipedia.org/wiki/Month\n {\"day(s)\", (int)timeSpan.TotalDays},\n {\"hour(s)\", (int)timeSpan.TotalHours},\n {\"minute(s)\", (int)timeSpan.TotalMinutes},\n {\"second(s)\", (int)timeSpan.TotalSeconds},\n {\"millisecond(s)\", (int)timeSpan.TotalMilliseconds}\n}.First(kvp => kvp.Value > 0);\n\nConsole.WriteLine($\"{value} {unit} ago\");\n 786 year(s) ago TimeSpan timeSpan = DateTime.Now - new DateTime(2020, 12, 6, 7, 8, 9);\n 4 day(s) ago TimeSpan timeSpan = DateTime.Now - DateTime.Now.Date;\n 9 hour(s) ago" }, { "answer_id": 69020909, "author": "Shujat Munawar", "author_id": 7849868, "author_profile": "https://Stackoverflow.com/users/7849868", "pm_score": -1, "selected": false, "text": " public string GetTimeSince(DateTime postDate)\n {\n string message = \"\";\n DateTime currentDate = DateTime.Now;\n TimeSpan timegap = currentDate - postDate;\n\n \n if (timegap.Days > 365)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Years\"), (((timegap.Days) / 30) / 12)); \n }\n else if (timegap.Days > 30)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Months\"), timegap.Days/30); \n }\n else if (timegap.Days > 0)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Days\"), timegap.Days);\n } \n else if (timegap.Hours > 0)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Hours\"), timegap.Hours);\n } \n else if (timegap.Minutes > 0)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Minutes\"), timegap.Minutes);\n }\n else if (timegap.Seconds > 0)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Seconds\"), timegap.Seconds);\n }\n\n // let's handle future times..just in case \n else if (timegap.Days < -365)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Years\"), (((Math.Abs(timegap.Days)) / 30) / 12)); \n }\n else if (timegap.Days < -30)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Months\"), ((Math.Abs(timegap.Days)) / 30)); \n }\n else if (timegap.Days < 0)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Days\"), Math.Abs(timegap.Days)); \n } \n \n else if (timegap.Hours < 0)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Hours\"), Math.Abs(timegap.Hours)); \n }\n else if (timegap.Minutes < 0)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Minutes\"), Math.Abs(timegap.Minutes)); \n }\n else if (timegap.Seconds < 0)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Seconds\"), Math.Abs(timegap.Seconds)); \n }\n\n\n else\n {\n message = \"a bit\";\n }\n\n return message;\n }\n" }, { "answer_id": 73608368, "author": "StudioLE", "author_id": 247218, "author_profile": "https://Stackoverflow.com/users/247218", "pm_score": 0, "selected": false, "text": "TimeSpan.TicksPerSecond /// <summary>\n/// Convert a <see cref=\"TimeSpan\"/> to a natural language representation.\n/// </summary>\n/// <example>\n/// <code>\n/// TimeSpan.FromSeconds(10).ToNaturalLanguage();\n/// // 10 seconds\n/// </code>\n/// </example>\npublic static string ToNaturalLanguage(this TimeSpan @this)\n{\n const int daysInWeek = 7;\n const int daysInMonth = 30;\n const int daysInYear = 365;\n const long threshold = 100 * TimeSpan.TicksPerMillisecond;\n @this = @this.TotalSeconds < 0\n ? TimeSpan.FromSeconds(@this.TotalSeconds * -1)\n : @this;\n return (@this.Ticks + threshold) switch\n {\n < 2 * TimeSpan.TicksPerSecond => \"a second\",\n < 1 * TimeSpan.TicksPerMinute => @this.Seconds + \" seconds\",\n < 2 * TimeSpan.TicksPerMinute => \"a minute\",\n < 1 * TimeSpan.TicksPerHour => @this.Minutes + \" minutes\",\n < 2 * TimeSpan.TicksPerHour => \"an hour\",\n < 1 * TimeSpan.TicksPerDay => @this.Hours + \" hours\",\n < 2 * TimeSpan.TicksPerDay => \"a day\",\n < 1 * daysInWeek * TimeSpan.TicksPerDay => @this.Days + \" days\",\n < 2 * daysInWeek * TimeSpan.TicksPerDay => \"a week\",\n < 1 * daysInMonth * TimeSpan.TicksPerDay => (@this.Days / daysInWeek).ToString(\"F0\") + \" weeks\",\n < 2 * daysInMonth * TimeSpan.TicksPerDay => \"a month\",\n < 1 * daysInYear * TimeSpan.TicksPerDay => (@this.Days / daysInMonth).ToString(\"F0\") + \" months\",\n < 2 * daysInYear * TimeSpan.TicksPerDay => \"a year\",\n _ => (@this.Days / daysInYear).ToString(\"F0\") + \" years\"\n };\n}\n\n/// <summary>\n/// Convert a <see cref=\"DateTime\"/> to a natural language representation.\n/// </summary>\n/// <example>\n/// <code>\n/// (DateTime.Now - TimeSpan.FromSeconds(10)).ToNaturalLanguage()\n/// // 10 seconds ago\n/// </code>\n/// </example>\npublic static string ToNaturalLanguage(this DateTime @this)\n{\n TimeSpan timeSpan = @this - DateTime.Now;\n return timeSpan.TotalSeconds switch\n {\n >= 1 => timeSpan.ToNaturalLanguage() + \" until\",\n <= -1 => timeSpan.ToNaturalLanguage() + \" ago\",\n _ => \"now\",\n };\n}\n [TestCase(\"a second\", 0)]\n[TestCase(\"a second\", 1)]\n[TestCase(\"2 seconds\", 2)]\n[TestCase(\"a minute\", 0, 1)]\n[TestCase(\"5 minutes\", 0, 5)]\n[TestCase(\"an hour\", 0, 0, 1)]\n[TestCase(\"2 hours\", 0, 0, 2)]\n[TestCase(\"a day\", 0, 0, 24)]\n[TestCase(\"a day\", 0, 0, 0, 1)]\n[TestCase(\"6 days\", 0, 0, 0, 6)]\n[TestCase(\"a week\", 0, 0, 0, 7)]\n[TestCase(\"4 weeks\", 0, 0, 0, 29)]\n[TestCase(\"a month\", 0, 0, 0, 30)]\n[TestCase(\"6 months\", 0, 0, 0, 6 * 30)]\n[TestCase(\"a year\", 0, 0, 0, 365)]\n[TestCase(\"68 years\", int.MaxValue)]\npublic void NaturalLanguageHelpers_TimeSpan(\n string expected,\n int seconds,\n int minutes = 0,\n int hours = 0,\n int days = 0\n)\n{\n // Arrange\n TimeSpan timeSpan = new(days, hours, minutes, seconds);\n\n // Act\n string result = timeSpan.ToNaturalLanguage();\n\n // Assert\n Assert.That(result, Is.EqualTo(expected));\n}\n\n[TestCase(\"now\", 0)]\n[TestCase(\"10 minutes ago\", 0, -10)]\n[TestCase(\"10 minutes until\", 10, 10)]\n[TestCase(\"68 years until\", int.MaxValue)]\n[TestCase(\"68 years ago\", int.MinValue)]\npublic void NaturalLanguageHelpers_DateTime(\n string expected,\n int seconds,\n int minutes = 0,\n int hours = 0,\n int days = 0\n)\n{\n // Arrange\n TimeSpan timeSpan = new(days, hours, minutes, seconds);\n DateTime now = DateTime.Now;\n DateTime dateTime = now + timeSpan;\n\n // Act\n string result = dateTime.ToNaturalLanguage();\n\n // Assert\n Assert.That(result, Is.EqualTo(expected));\n}\n" } ]
2008/07/31
[ "https://Stackoverflow.com/questions/11", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
13
<p>Is there a standard way for a web server to be able to determine a user's timezone within a web page? </p> <p>Perhaps from an HTTP header or part of the <code>user-agent</code> string?</p>
[ { "answer_id": 817, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": false, "text": "visitortime.getTimezoneOffset()\n maxmind" }, { "answer_id": 1809974, "author": "JD Isaacks", "author_id": 46011, "author_profile": "https://Stackoverflow.com/users/46011", "pm_score": 8, "selected": false, "text": "-new Date().getTimezoneOffset()/60;\n getTimezoneOffset()" }, { "answer_id": 2901216, "author": "Alek Davis", "author_id": 52545, "author_profile": "https://Stackoverflow.com/users/52545", "pm_score": 4, "selected": false, "text": "getTimezoneOffset" }, { "answer_id": 3724089, "author": "Sanjay Khatri", "author_id": 1026244, "author_profile": "https://Stackoverflow.com/users/1026244", "pm_score": 5, "selected": false, "text": "date date_default_timezone_set <?php\n #http://www.php.net/manual/en/timezones.php List of Time Zones\n function showclienttime()\n {\n if(!isset($_COOKIE['GMT_bias']))\n {\n?>\n\n <script type=\"text/javascript\">\n var Cookies = {};\n Cookies.create = function (name, value, days) {\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n var expires = \"; expires=\" + date.toGMTString();\n }\n else {\n var expires = \"\";\n }\n document.cookie = name + \"=\" + value + expires + \"; path=/\";\n this[name] = value;\n }\n\n var now = new Date();\n Cookies.create(\"GMT_bias\",now.getTimezoneOffset(),1);\n window.location = \"<?php echo $_SERVER['PHP_SELF'];?>\";\n </script>\n\n <?php\n\n }\n else {\n $fct_clientbias = $_COOKIE['GMT_bias'];\n }\n\n $fct_servertimedata = gettimeofday();\n $fct_servertime = $fct_servertimedata['sec'];\n $fct_serverbias = $fct_servertimedata['minuteswest'];\n $fct_totalbias = $fct_serverbias – $fct_clientbias;\n $fct_totalbias = $fct_totalbias * 60;\n $fct_clienttimestamp = $fct_servertime + $fct_totalbias;\n $fct_time = time();\n $fct_year = strftime(\"%Y\", $fct_clienttimestamp);\n $fct_month = strftime(\"%B\", $fct_clienttimestamp);\n $fct_day = strftime(\"%d\", $fct_clienttimestamp);\n $fct_hour = strftime(\"%I\", $fct_clienttimestamp);\n $fct_minute = strftime(\"%M\", $fct_clienttimestamp);\n $fct_second = strftime(\"%S\", $fct_clienttimestamp);\n $fct_am_pm = strftime(\"%p\", $fct_clienttimestamp);\n echo $fct_day.\", \".$fct_month.\" \".$fct_year.\" ( \".$fct_hour.\":\".$fct_minute.\":\".$fct_second.\" \".$fct_am_pm.\" )\";\n }\n\n showclienttime();\n?>\n" }, { "answer_id": 5492192, "author": "Joseph Lust", "author_id": 564157, "author_profile": "https://Stackoverflow.com/users/564157", "pm_score": 6, "selected": false, "text": "function TimezoneDetect(){\n var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());\n var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt\n var intMonth;\n var intHoursUtc;\n var intHours;\n var intDaysMultiplyBy;\n\n // Go through each month to find the lowest offset to account for DST\n for (intMonth=0;intMonth < 12;intMonth++){\n //go to the next month\n dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);\n\n // To ignore daylight saving time look for the lowest offset.\n // Since, during DST, the clock moves forward, it'll be a bigger number.\n if (intOffset > (dtDate.getTimezoneOffset() * (-1))){\n intOffset = (dtDate.getTimezoneOffset() * (-1));\n }\n }\n\n return intOffset;\n}\n" }, { "answer_id": 5607229, "author": "Westy92", "author_id": 453314, "author_profile": "https://Stackoverflow.com/users/453314", "pm_score": 5, "selected": false, "text": "<?php\n session_start();\n $timezone = $_SESSION['time'];\n?>\n <script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-latest.min.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function() {\n if(\"<?php echo $timezone; ?>\".length==0){\n var visitortime = new Date();\n var visitortimezone = \"GMT \" + -visitortime.getTimezoneOffset()/60;\n $.ajax({\n type: \"GET\",\n url: \"http://example.org/timezone.php\",\n data: 'time='+ visitortimezone,\n success: function(){\n location.reload();\n }\n });\n }\n });\n</script>\n <?php\n session_start();\n $_SESSION['time'] = $_GET['time'];\n?>\n" }, { "answer_id": 7217925, "author": "Envis", "author_id": 915954, "author_profile": "https://Stackoverflow.com/users/915954", "pm_score": 5, "selected": false, "text": "function maketimus(timestampz)\n{\n var linktime = new Date(timestampz * 1000);\n var linkday = linktime.getDate();\n var freakingmonths = new Array();\n\n freakingmonths[0] = \"jan\";\n freakingmonths[1] = \"feb\";\n freakingmonths[2] = \"mar\";\n freakingmonths[3] = \"apr\";\n freakingmonths[4] = \"may\";\n freakingmonths[5] = \"jun\";\n freakingmonths[6] = \"jul\";\n freakingmonths[7] = \"aug\";\n freakingmonths[8] = \"sep\";\n freakingmonths[9] = \"oct\";\n freakingmonths[10] = \"nov\";\n freakingmonths[11] = \"dec\";\n\n var linkmonthnum = linktime.getMonth();\n var linkmonth = freakingmonths[linkmonthnum];\n var linkyear = linktime.getFullYear();\n var linkhour = linktime.getHours();\n var linkminute = linktime.getMinutes();\n\n if (linkminute < 10)\n {\n linkminute = \"0\" + linkminute;\n }\n\n var fomratedtime = linkday + linkmonth + linkyear + \" \" +\n linkhour + \":\" + linkminute + \"h\";\n return fomratedtime;\n}\n echo '<script type=\"text/javascript\">\nvar eltimio = maketimus('.$unix_timestamp_ofshiz.');\ndocument.write(eltimio);\n</script><noscript>pls enable javascript</noscript>';\n" }, { "answer_id": 8340357, "author": "Naeem Ul Wahhab", "author_id": 1067051, "author_profile": "https://Stackoverflow.com/users/1067051", "pm_score": 4, "selected": false, "text": "new Date().getTimezoneOffset();\n" }, { "answer_id": 9043904, "author": "Dane Iracleous", "author_id": 644337, "author_profile": "https://Stackoverflow.com/users/644337", "pm_score": 3, "selected": false, "text": "<?php\nsession_start();\n\nif(!isset($_SESSION['timezone']))\n{\n if(!isset($_REQUEST['offset']))\n {\n ?>\n <script>\n var d = new Date()\n var offset= -d.getTimezoneOffset()/60;\n location.href = \"<?php echo $_SERVER['PHP_SELF']; ?>?offset=\"+offset;\n </script>\n <?php \n }\n else\n {\n $zonelist = array('Kwajalein' => -12.00, 'Pacific/Midway' => -11.00, 'Pacific/Honolulu' => -10.00, 'America/Anchorage' => -9.00, 'America/Los_Angeles' => -8.00, 'America/Denver' => -7.00, 'America/Tegucigalpa' => -6.00, 'America/New_York' => -5.00, 'America/Caracas' => -4.30, 'America/Halifax' => -4.00, 'America/St_Johns' => -3.30, 'America/Argentina/Buenos_Aires' => -3.00, 'America/Sao_Paulo' => -3.00, 'Atlantic/South_Georgia' => -2.00, 'Atlantic/Azores' => -1.00, 'Europe/Dublin' => 0, 'Europe/Belgrade' => 1.00, 'Europe/Minsk' => 2.00, 'Asia/Kuwait' => 3.00, 'Asia/Tehran' => 3.30, 'Asia/Muscat' => 4.00, 'Asia/Yekaterinburg' => 5.00, 'Asia/Kolkata' => 5.30, 'Asia/Katmandu' => 5.45, 'Asia/Dhaka' => 6.00, 'Asia/Rangoon' => 6.30, 'Asia/Krasnoyarsk' => 7.00, 'Asia/Brunei' => 8.00, 'Asia/Seoul' => 9.00, 'Australia/Darwin' => 9.30, 'Australia/Canberra' => 10.00, 'Asia/Magadan' => 11.00, 'Pacific/Fiji' => 12.00, 'Pacific/Tongatapu' => 13.00);\n $index = array_keys($zonelist, $_REQUEST['offset']);\n $_SESSION['timezone'] = $index[0];\n }\n}\n\ndate_default_timezone_set($_SESSION['timezone']);\n\n//rest of your code goes here\n?>\n" }, { "answer_id": 10775887, "author": "JoeyFur62", "author_id": 1420406, "author_profile": "https://Stackoverflow.com/users/1420406", "pm_score": 5, "selected": false, "text": "getTimezoneOffset -new Date().getTimezoneOffset()/60;\n" }, { "answer_id": 11717580, "author": "pckabeer", "author_id": 1298003, "author_profile": "https://Stackoverflow.com/users/1298003", "pm_score": 4, "selected": false, "text": "<?php\n $ip = $_SERVER['REMOTE_ADDR'];\n $json = file_get_contents(\"http://api.easyjquery.com/ips/?ip=\" . $ip . \"&full=true\");\n $json = json_decode($json,true);\n $timezone = $json['LocalTimeZone'];\n?>\n" }, { "answer_id": 11836123, "author": "Adam", "author_id": 226513, "author_profile": "https://Stackoverflow.com/users/226513", "pm_score": 6, "selected": false, "text": ">>> var timezone = jstz.determine();\n>>> timezone.name(); \n\"Europe/London\"\n" }, { "answer_id": 12190240, "author": "Benbob", "author_id": 181637, "author_profile": "https://Stackoverflow.com/users/181637", "pm_score": 5, "selected": false, "text": ">> new Date().toTimeString();\n\"15:46:04 GMT+1200 (New Zealand Standard Time)\"\n//Use some regular expression to extract the time.\n" }, { "answer_id": 12398468, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 5, "selected": false, "text": "$.ajaxSetup({\n beforeSend: function(xhr, settings) {\n xhr.setRequestHeader(\"X-TZ-Offset\", -new Date().getTimezoneOffset()/60);\n }\n});\n moment.tz.guess();" }, { "answer_id": 22625076, "author": "Matt Johnson-Pint", "author_id": 634824, "author_profile": "https://Stackoverflow.com/users/634824", "pm_score": 7, "selected": false, "text": "getTimezoneOffset Date America/Los_Angeles const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;\nconsole.log(tzid); DateTimeFormat resolvedOptions().timeZone defaults to the host environment luxon.Settings.defaultZoneName Intl getTimezoneOffset Date // using jsTimeZoneDetect\n var tzid = jstz.determine().name();\n\n // using moment-timezone\n var tzid = moment.tz.guess();\n" }, { "answer_id": 25734579, "author": "Berislav Lopac", "author_id": 122033, "author_profile": "https://Stackoverflow.com/users/122033", "pm_score": 3, "selected": false, "text": "Date" }, { "answer_id": 25839604, "author": "man", "author_id": 1881655, "author_profile": "https://Stackoverflow.com/users/1881655", "pm_score": 4, "selected": false, "text": "new Date().getTimezoneOffset(); users date_created int(13) creates a new account post insert/update date_created column var off = (-new Date().getTimezoneOffset()/60).toString();//note the '-' in front which makes it return positive for negative offsets and negative for positive offsets\nvar tzo = off == '0' ? 'GMT' : off.indexOf('-') > -1 ? 'GMT'+off : 'GMT+'+off;\n tzo $_POST['tzo'] $ts = new DateTime('now', new DateTimeZone($_POST['tzo']);\n$user_time = $ts->format(\"F j, Y, g:i a\");//will return the users current time in readable format, regardless of whether date_default_timezone() is set or not.\n$user_timestamp = strtotime($user_time);\n date_created=$user_timestamp $date_created = // Get from the database\n$created = date(\"F j, Y, g:i a\",$date_created); // Return it to the user or whatever\n first" }, { "answer_id": 39463380, "author": "Tomas Tomecek", "author_id": 909579, "author_profile": "https://Stackoverflow.com/users/909579", "pm_score": 4, "selected": false, "text": "> moment.tz.guess()\n\"America/Asuncion\"\n" }, { "answer_id": 41568276, "author": "Useful Angle", "author_id": 7191417, "author_profile": "https://Stackoverflow.com/users/7191417", "pm_score": 4, "selected": false, "text": "getTimezoneOffset var timezone_offset_minutes = new Date().getTimezoneOffset();\ntimezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;\n // Just an example.\n$timezone_offset_minutes = -360; // $_GET['timezone_offset_minutes']\n\n// Convert minutes to seconds\n$timezone_name = timezone_name_from_abbr(\"\", $timezone_offset_minutes*60, false);\n\n// America/Chicago\necho $timezone_name;</code></pre>\n" }, { "answer_id": 64329945, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "user-agent getTzimezoneOffset() Date new Date().getTimezoneOffset();" }, { "answer_id": 67072466, "author": "Antony", "author_id": 3897214, "author_profile": "https://Stackoverflow.com/users/3897214", "pm_score": 1, "selected": false, "text": "@Matt Johnson-Pints @Mads Kristiansen" }, { "answer_id": 70495118, "author": "Atul Lohiya", "author_id": 9942276, "author_profile": "https://Stackoverflow.com/users/9942276", "pm_score": 2, "selected": false, "text": "Intl.DateTimeFormat().resolvedOptions().timeZone let dateObj = new Date(2021, 11, 25, 09, 30, 00);\n\n//then \n\ndateObj.toString() \n\n//yields\n\nSat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time) //I am located in India (IST) let longZoneRegex = /\\((.+)\\)/;\ndateObj.toString().match(longZoneRegex);\n\n//yields\n\n['(India Standard Time)', 'India Standard Time', index: 34, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined]\n\n//Note that output is an array so use output[1] to get the timezone name. let shortZoneRegex = /GMT[+-]\\d{1,4}/;\ndateObj.toString().match(shortZoneRegex);\n\n//yields\n\n['GMT+0530', index: 25, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined]\n\n//Note that output is an array so use output[0] to get the timezone name." } ]
2008/08/01
[ "https://Stackoverflow.com/questions/13", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9/" ]
14
<p>What is the difference between <a href="http://msdn.microsoft.com/en-us/library/9a6a2sxy.aspx" rel="noreferrer"><code>Math.Floor()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.math.truncate.aspx" rel="noreferrer"><code>Math.Truncate()</code></a> in .NET?</p>
[ { "answer_id": 33, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 9, "selected": false, "text": "Math.Floor Math.Ceiling Math.Truncate Math.Truncate Math.Floor Math.Ceiling Math.Round" }, { "answer_id": 2086, "author": "Marek Grzenkowicz", "author_id": 95, "author_profile": "https://Stackoverflow.com/users/95", "pm_score": 6, "selected": false, "text": "Round(1.5) = 2\nRound(2.5) = 2\nRound(1.5, MidpointRounding.AwayFromZero) = 2\nRound(2.5, MidpointRounding.AwayFromZero) = 3\nRound(1.55, 1) = 1.6\nRound(1.65, 1) = 1.6\nRound(1.55, 1, MidpointRounding.AwayFromZero) = 1.6\nRound(1.65, 1, MidpointRounding.AwayFromZero) = 1.7\n\nTruncate(2.10) = 2\nTruncate(2.00) = 2\nTruncate(1.90) = 1\nTruncate(1.80) = 1\n" }, { "answer_id": 580252, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 9, "selected": false, "text": "Math.Floor Math.Ceiling Math.Truncate Math.Round Round(2.5,MidpointRounding.ToEven) Round(2.5,MidpointRounding.AwayFromZero) -3 -2 -1 0 1 2 3\n +--|------+---------+----|----+--|------+----|----+-------|-+\n a b c d e\n\n a=-2.7 b=-0.5 c=0.3 d=1.5 e=2.8\n ====== ====== ===== ===== =====\nFloor -3 -1 0 1 2\nCeiling -2 0 1 2 3\nTruncate -2 0 0 1 2\nRound (ToEven) -3 0 0 2 3\nRound (AwayFromZero) -3 -1 0 2 3\n Round n = 3.145;\na = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14\nb = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15\n c = System.Math.Truncate (n * 100) / 100; // 3.14\nd = System.Math.Ceiling (n * 100) / 100; // 3.15\n" }, { "answer_id": 6742125, "author": "Azhar", "author_id": 228755, "author_profile": "https://Stackoverflow.com/users/228755", "pm_score": 6, "selected": false, "text": "Math.Floor() Math.Truncate Math.Floor(-3.4) = -4\nMath.Truncate(-3.4) = -3\n Math.Floor(3.4) = 3\nMath.Truncate(3.4) = 3\n" }, { "answer_id": 10937469, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "Math.Floor() Math.Truncate()" }, { "answer_id": 18893721, "author": "Pinky", "author_id": 2699939, "author_profile": "https://Stackoverflow.com/users/2699939", "pm_score": 4, "selected": false, "text": "Math.Floor() Math.Round()" }, { "answer_id": 27742779, "author": "Sandesh", "author_id": 1018966, "author_profile": "https://Stackoverflow.com/users/1018966", "pm_score": 5, "selected": false, "text": "Math.Floor(2.5) = 2\nMath.Truncate(2.5) = 2\n\nMath.Floor(-2.5) = -3\nMath.Truncate(-2.5) = -2\n float myFloat = 4.5;\nConsole.WriteLine( Math.Round(myFloat) ); // writes 4\nConsole.WriteLine( Math.Round(myFloat, 0, MidpointRounding.AwayFromZero) ) //writes 5\nConsole.WriteLine( myFloat.ToString(\"F0\") ); // writes 5\n" }, { "answer_id": 35358670, "author": "safin chacko", "author_id": 5815959, "author_profile": "https://Stackoverflow.com/users/5815959", "pm_score": 5, "selected": false, "text": "Math.Floor(2.56) = 2\nMath.Floor(3.22) = 3\nMath.Floor(-2.56) = -3\nMath.Floor(-3.26) = -4\n\nMath.Truncate(2.56) = 2\nMath.Truncate(2.00) = 2\nMath.Truncate(1.20) = 1\nMath.Truncate(-3.26) = -3\nMath.Truncate(-3.96) = -3\n Math.Round(1.6) = 2\n Math.Round(-8.56) = -9\n Math.Round(8.16) = 8\n Math.Round(8.50) = 8\n Math.Round(8.51) = 9\n math.floor() math.truncate()" }, { "answer_id": 48732884, "author": "Puddle", "author_id": 9312988, "author_profile": "https://Stackoverflow.com/users/9312988", "pm_score": 6, "selected": false, "text": "Math.floor Math.ceil Math.truncate Math.round Math.floor -- -=2 floor if (this == \"wrong\")\n return \"i don't wanna be right\";\n Math.truncate(x) int(x)" }, { "answer_id": 51375320, "author": "vidy", "author_id": 9993935, "author_profile": "https://Stackoverflow.com/users/9993935", "pm_score": 3, "selected": false, "text": "Math.floor() round()" }, { "answer_id": 62551075, "author": "Anonymous", "author_id": 13127212, "author_profile": "https://Stackoverflow.com/users/13127212", "pm_score": 2, "selected": false, "text": " Math.Floor(3.45) =3\n Math.Floor(-3.45) =-4\n Math.Truncate(3.45)=3\n Math.Truncate(-3.45)=-3\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/14", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11/" ]
16
<p>How do you expose a LINQ query as an ASMX web service? <br> Usually, from the business tier, I can return a typed <code>DataSet</code> or a <code>DataTable</code> which can be serialized for transport over ASMX.</p> <p>How can I do the same for a LINQ query? <br> Is there a way to populate a typed <code>DataSet</code> or a <code>DataTable</code> via a LINQ query?</p> <pre><code>public static MyDataTable CallMySproc() { string conn = &quot;...&quot;; MyDatabaseDataContext db = new MyDatabaseDataContext(conn); MyDataTable dt = new MyDataTable(); // execute a sproc via LINQ var query = from dr in db.MySproc().AsEnumerable select dr; // copy LINQ query resultset into a DataTable -this does not work ! dt = query.CopyToDataTable(); return dt; } </code></pre> <p>How could I put the result set of a LINQ query into a <code>DataSet</code> or a <code>DataTable</code>? <br> Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service?</p>
[ { "answer_id": 84, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 4, "selected": false, "text": "IEnumerable" }, { "answer_id": 5830, "author": "Brian Childress", "author_id": 721, "author_profile": "https://Stackoverflow.com/users/721", "pm_score": 4, "selected": false, "text": "list(T)" }, { "answer_id": 12446, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 8, "selected": true, "text": "IEnumerable CopyToDataTable IEnumerable<DataRow> query =\n from order in orders.AsEnumerable()\n where order.Field<DateTime>(\"OrderDate\") > new DateTime(2001, 8, 1)\n select order;\n\n// Create a table from the query.\nDataTable boundTable = query.CopyToDataTable<DataRow>();\n" }, { "answer_id": 544169, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "DataContext MyDataContext db = new MyDataContext();\nIEnumerable<DataRow> query = \n (from order in db.Orders.AsEnumerable()\n select new\n {\n order.Property,\n order.Property2\n })\n as IEnumerable<DataRow>;\nreturn query.CopyToDataTable<DataRow>();\n as IEnumerable<DataRow>;" }, { "answer_id": 49774484, "author": "Vijay S", "author_id": 7204125, "author_profile": "https://Stackoverflow.com/users/7204125", "pm_score": 3, "selected": false, "text": "IEnumerable MyDataContext db = new MyDataContext();\nIEnumerable<DataRow> query = \n (from order in db.Orders.AsEnumerable()\n select new\n {\n order.Property,\n order.Property2\n })\n as IEnumerable<DataRow>;\nreturn query.CopyToDataTable<DataRow>();\n" }, { "answer_id": 56693278, "author": "Gabriel Magana", "author_id": 99455, "author_profile": "https://Stackoverflow.com/users/99455", "pm_score": 2, "selected": false, "text": "IEnumerable<DataRow>" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/16", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2/" ]
17
<p>How do I store binary data in <a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>?</p>
[ { "answer_id": 18, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "CREATE TABLE binary_data (\n id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,\n description CHAR(50),\n bin_data LONGBLOB,\n filename CHAR(50),\n filesize CHAR(50),\n filetype CHAR(50)\n);\n <?php\n // store.php3 - by Florian Dittmer <[email protected]>\n // Example php script to demonstrate the storing of binary files into\n // an sql database. More information can be found at http://www.phpbuilder.com/\n?>\n\n<html>\n <head><title>Store binary data into SQL Database</title></head>\n\n <body>\n <?php\n // Code that will be executed if the form has been submitted:\n\n if ($submit) {\n // Connect to the database (you may have to adjust\n // the hostname, username or password).\n\n mysql_connect(\"localhost\", \"root\", \"password\");\n mysql_select_db(\"binary_data\");\n\n $data = mysql_real_escape_string(fread(fopen($form_data, \"r\"), filesize($form_data)));\n\n $result = mysql_query(\"INSERT INTO binary_data (description, bin_data, filename, filesize, filetype) \".\n \"VALUES ('$form_description', '$data', '$form_data_name', '$form_data_size', '$form_data_type')\");\n\n $id= mysql_insert_id();\n print \"<p>This file has the following Database ID: <b>$id</b>\";\n\n mysql_close();\n } else {\n\n // else show the form to submit new data:\n ?>\n <form method=\"post\" action=\"<?php echo $PHP_SELF; ?>\" enctype=\"multipart/form-data\">\n File Description:<br>\n <input type=\"text\" name=\"form_description\" size=\"40\">\n <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"1000000\">\n <br>File to upload/store in database:<br>\n <input type=\"file\" name=\"form_data\" size=\"40\">\n <p><input type=\"submit\" name=\"submit\" value=\"submit\">\n </form>\n\n <?php\n }\n ?>\n </body>\n</html>\n" }, { "answer_id": 26, "author": "Mat", "author_id": 48, "author_profile": "https://Stackoverflow.com/users/48", "pm_score": 8, "selected": true, "text": "BLOB" }, { "answer_id": 69311, "author": "user10117", "author_id": 10117, "author_profile": "https://Stackoverflow.com/users/10117", "pm_score": 4, "selected": false, "text": "base64" }, { "answer_id": 4567420, "author": "d0nut", "author_id": 499257, "author_profile": "https://Stackoverflow.com/users/499257", "pm_score": 4, "selected": false, "text": "LONGBLOB TINYBLOB/BLOB/MEDIUMBLOB/LONGBLOB VARBINARY BINARY BINARY VARBINARY" }, { "answer_id": 18763725, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "mysql_query(\"UPDATE table SET field=X'\".bin2hex($bin_data).\"' WHERE id=$id\");\n" }, { "answer_id": 23405248, "author": "zeppaman", "author_id": 3559251, "author_profile": "https://Stackoverflow.com/users/3559251", "pm_score": 4, "selected": false, "text": "VARBINARY" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/17", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2/" ]
19
<p>I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using <code>#define</code> constants like <code>M_PI</code>, or hard-coding the number in.</p> <p>The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the <code>4 * atan(1)</code> version is fastest on GCC 4.2, because it auto-folds the <code>atan(1)</code> into a constant. With <code>-fno-builtin</code> specified, the <code>atan2(0, -1)</code> version is fastest.</p> <p>Here's the main testing program (<code>pitimes.c</code>):</p> <pre class="lang-c prettyprint-override"><code>#include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; #define ITERS 10000000 #define TESTWITH(x) { \ diff = 0.0; \ time1 = clock(); \ for (i = 0; i &lt; ITERS; ++i) \ diff += (x) - M_PI; \ time2 = clock(); \ printf("%s\t=&gt; %e, time =&gt; %f\n", #x, diff, diffclock(time2, time1)); \ } static inline double diffclock(clock_t time1, clock_t time0) { return (double) (time1 - time0) / CLOCKS_PER_SEC; } int main() { int i; clock_t time1, time2; double diff; /* Warmup. The atan2 case catches GCC's atan folding (which would * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin * is not used. */ TESTWITH(4 * atan(1)) TESTWITH(4 * atan2(1, 1)) #if defined(__GNUC__) &amp;&amp; (defined(__i386__) || defined(__amd64__)) extern double fldpi(); TESTWITH(fldpi()) #endif /* Actual tests start here. */ TESTWITH(atan2(0, -1)) TESTWITH(acos(-1)) TESTWITH(2 * asin(1)) TESTWITH(4 * atan2(1, 1)) TESTWITH(4 * atan(1)) return 0; } </code></pre> <p>And the inline assembly stuff (<code>fldpi.c</code>) that will only work for x86 and x64 systems:</p> <pre class="lang-c prettyprint-override"><code>double fldpi() { double pi; asm("fldpi" : "=t" (pi)); return pi; } </code></pre> <p>And a build script that builds all the configurations I'm testing (<code>build.sh</code>):</p> <pre><code>#!/bin/sh gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm </code></pre> <p>Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the <code>atan2(0, -1)</code> version still comes out on top every time.</p>
[ { "answer_id": 531, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 9, "selected": true, "text": "let pi_2 iters =\n let rec loop_ a b t p i =\n if i = 0 then a,b,t,p\n else\n let a_n = (a +. b) /. 2.0 \n and b_n = sqrt (a*.b)\n and p_n = 2.0 *. p in\n let t_n = t -. (p *. (a -. a_n) *. (a -. a_n)) in\n loop_ a_n b_n t_n p_n (i - 1)\n in \n let a,b,t,p = loop_ (1.0) (1.0 /. (sqrt 2.0)) (1.0/.4.0) (1.0) iters in\n (a +. b) *. (a +. b) /. (4.0 *. t)\n int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,printf(\"%.4d\",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);}\n" }, { "answer_id": 4089, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 4, "selected": false, "text": ";''6666,-2%{2+.2/@*\\/10.3??2*+}*`1000<~\\;\n" }, { "answer_id": 39512, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 7, "selected": false, "text": "#define _ -F<00||--F-OO--;\nint F=00,OO=00;main(){F_OO();printf(\"%1.3f\\n\",4.*-F/OO/OO);}F_OO()\n{\n _-_-_-_\n _-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_\n _-_-_-_\n}\n" }, { "answer_id": 85798, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 4, "selected": false, "text": "/** Calculate pi at compile time\n *\n * Compile with dmd -c pi.d\n */\nmodule calcpi;\n\nimport meta.math;\nimport meta.conv;\n\n/** real evaluateSeries!(real x, real metafunction!(real y, int n) term)\n *\n * Evaluate a power series at compile time.\n *\n * Given a metafunction of the form\n * real term!(real y, int n),\n * which gives the nth term of a convergent series at the point y\n * (where the first term is n==1), and a real number x,\n * this metafunction calculates the infinite sum at the point x\n * by adding terms until the sum doesn't change any more.\n */\ntemplate evaluateSeries(real x, alias term, int n=1, real sumsofar=0.0)\n{\n static if (n>1 && sumsofar == sumsofar + term!(x, n+1)) {\n const real evaluateSeries = sumsofar;\n } else {\n const real evaluateSeries = evaluateSeries!(x, term, n+1, sumsofar + term!(x, n));\n }\n}\n\n/*** Calculate atan(x) at compile time.\n *\n * Uses the Maclaurin formula\n * atan(z) = z - z^3/3 + Z^5/5 - Z^7/7 + ...\n */\ntemplate atan(real z)\n{\n const real atan = evaluateSeries!(z, atanTerm);\n}\n\ntemplate atanTerm(real x, int n)\n{\n const real atanTerm = (n & 1 ? 1 : -1) * pow!(x, 2*n-1)/(2*n-1);\n}\n\n/// Machin's formula for pi\n/// pi/4 = 4 atan(1/5) - atan(1/239).\npragma(msg, \"PI = \" ~ fcvt!(4.0 * (4*atan!(1/5.0) - atan!(1/239.0))) );\n" }, { "answer_id": 164687, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 5, "selected": false, "text": "from math import pi\nfrom time import time\n\n\nprecision = 10**6 # higher value -> higher precision\n # lower value -> higher speed\n\nt = time()\n\ncalc = 0\nfor k in xrange(0, precision):\n calc += ((-1)**k) / (2*k+1.)\ncalc *= 4. # this is just a little optimization\n\nt = time()-t\n\nprint \"Calculated: %.40f\" % calc\nprint \"Constant pi: %.40f\" % pi\nprint \"Difference: %.40f\" % abs(calc-pi)\nprint \"Time elapsed: %s\" % repr(t)\n from gmpy import pi\nprint pi(3000) # the rule is the same as \n # the precision on the previous code\n static char doc_pi[]=\"\\\npi(n): returns pi with n bits of precision in an mpf object\\n\\\n\";\n\n/* This function was originally from netlib, package bmp, by\n * Richard P. Brent. Paulo Cesar Pereira de Andrade converted\n * it to C and used it in his LISP interpreter.\n *\n * Original comments:\n * \n * sets mp pi = 3.14159... to the available precision.\n * uses the gauss-legendre algorithm.\n * this method requires time o(ln(t)m(t)), so it is slower\n * than mppi if m(t) = o(t**2), but would be faster for\n * large t if a faster multiplication algorithm were used\n * (see comments in mpmul).\n * for a description of the method, see - multiple-precision\n * zero-finding and the complexity of elementary function\n * evaluation (by r. p. brent), in analytic computational\n * complexity (edited by j. f. traub), academic press, 1976, 151-176.\n * rounding options not implemented, no guard digits used.\n*/\nstatic PyObject *\nPygmpy_pi(PyObject *self, PyObject *args)\n{\n PympfObject *pi;\n int precision;\n mpf_t r_i2, r_i3, r_i4;\n mpf_t ix;\n\n ONE_ARG(\"pi\", \"i\", &precision);\n if(!(pi = Pympf_new(precision))) {\n return NULL;\n }\n\n mpf_set_si(pi->f, 1);\n\n mpf_init(ix);\n mpf_set_ui(ix, 1);\n\n mpf_init2(r_i2, precision);\n\n mpf_init2(r_i3, precision);\n mpf_set_d(r_i3, 0.25);\n\n mpf_init2(r_i4, precision);\n mpf_set_d(r_i4, 0.5);\n mpf_sqrt(r_i4, r_i4);\n\n for (;;) {\n mpf_set(r_i2, pi->f);\n mpf_add(pi->f, pi->f, r_i4);\n mpf_div_ui(pi->f, pi->f, 2);\n mpf_mul(r_i4, r_i2, r_i4);\n mpf_sub(r_i2, pi->f, r_i2);\n mpf_mul(r_i2, r_i2, r_i2);\n mpf_mul(r_i2, r_i2, ix);\n mpf_sub(r_i3, r_i3, r_i2);\n mpf_sqrt(r_i4, r_i4);\n mpf_mul_ui(ix, ix, 2);\n /* Check for convergence */\n if (!(mpf_cmp_si(r_i2, 0) && \n mpf_get_prec(r_i2) >= (unsigned)precision)) {\n mpf_mul(pi->f, pi->f, r_i4);\n mpf_div(pi->f, pi->f, r_i3);\n break;\n }\n }\n\n mpf_clear(ix);\n mpf_clear(r_i2);\n mpf_clear(r_i3);\n mpf_clear(r_i4);\n\n return (PyObject*)pi;\n}\n" }, { "answer_id": 436447, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 4, "selected": false, "text": "program calcpi;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\n\nvar\n start, finish: TDateTime;\n\nfunction CalculatePi(iterations: integer): double;\nvar\n numerator, denominator, i: integer;\n sum: double;\nbegin\n {\n PI may be approximated with this formula:\n 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 .......)\n //}\n numerator := 1;\n denominator := 1;\n sum := 0;\n for i := 1 to iterations do begin\n sum := sum + (numerator/denominator);\n denominator := denominator + 2;\n numerator := -numerator;\n end;\n Result := 4 * sum;\nend;\n\nbegin\n try\n start := Now;\n WriteLn(FloatToStr(CalculatePi(StrToInt(ParamStr(1)))));\n finish := Now;\n WriteLn('Seconds:' + FormatDateTime('hh:mm:ss.zz',finish-start));\n except\n on E:Exception do\n Writeln(E.Classname, ': ', E.Message);\n end;\nend.\n" }, { "answer_id": 571276, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 4, "selected": false, "text": "/* Return approximation of n * PI; n is integer */\n#define pi_times(n) (((n) * 22) / 7)\n" }, { "answer_id": 592025, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Text;\n\nclass Program {\n static void Main(string[] args) {\n int Digits = 100;\n\n BigNumber x = new BigNumber(Digits);\n BigNumber y = new BigNumber(Digits);\n x.ArcTan(16, 5);\n y.ArcTan(4, 239);\n x.Subtract(y);\n string pi = x.ToString();\n Console.WriteLine(pi);\n }\n}\n\npublic class BigNumber {\n private UInt32[] number;\n private int size;\n private int maxDigits;\n\n public BigNumber(int maxDigits) {\n this.maxDigits = maxDigits;\n this.size = (int)Math.Ceiling((float)maxDigits * 0.104) + 2;\n number = new UInt32[size];\n }\n public BigNumber(int maxDigits, UInt32 intPart)\n : this(maxDigits) {\n number[0] = intPart;\n for (int i = 1; i < size; i++) {\n number[i] = 0;\n }\n }\n private void VerifySameSize(BigNumber value) {\n if (Object.ReferenceEquals(this, value))\n throw new Exception(\"BigNumbers cannot operate on themselves\");\n if (value.size != this.size)\n throw new Exception(\"BigNumbers must have the same size\");\n }\n\n public void Add(BigNumber value) {\n VerifySameSize(value);\n\n int index = size - 1;\n while (index >= 0 && value.number[index] == 0)\n index--;\n\n UInt32 carry = 0;\n while (index >= 0) {\n UInt64 result = (UInt64)number[index] +\n value.number[index] + carry;\n number[index] = (UInt32)result;\n if (result >= 0x100000000U)\n carry = 1;\n else\n carry = 0;\n index--;\n }\n }\n public void Subtract(BigNumber value) {\n VerifySameSize(value);\n\n int index = size - 1;\n while (index >= 0 && value.number[index] == 0)\n index--;\n\n UInt32 borrow = 0;\n while (index >= 0) {\n UInt64 result = 0x100000000U + (UInt64)number[index] -\n value.number[index] - borrow;\n number[index] = (UInt32)result;\n if (result >= 0x100000000U)\n borrow = 0;\n else\n borrow = 1;\n index--;\n }\n }\n public void Multiply(UInt32 value) {\n int index = size - 1;\n while (index >= 0 && number[index] == 0)\n index--;\n\n UInt32 carry = 0;\n while (index >= 0) {\n UInt64 result = (UInt64)number[index] * value + carry;\n number[index] = (UInt32)result;\n carry = (UInt32)(result >> 32);\n index--;\n }\n }\n public void Divide(UInt32 value) {\n int index = 0;\n while (index < size && number[index] == 0)\n index++;\n\n UInt32 carry = 0;\n while (index < size) {\n UInt64 result = number[index] + ((UInt64)carry << 32);\n number[index] = (UInt32)(result / (UInt64)value);\n carry = (UInt32)(result % (UInt64)value);\n index++;\n }\n }\n public void Assign(BigNumber value) {\n VerifySameSize(value);\n for (int i = 0; i < size; i++) {\n number[i] = value.number[i];\n }\n }\n\n public override string ToString() {\n BigNumber temp = new BigNumber(maxDigits);\n temp.Assign(this);\n\n StringBuilder sb = new StringBuilder();\n sb.Append(temp.number[0]);\n sb.Append(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);\n\n int digitCount = 0;\n while (digitCount < maxDigits) {\n temp.number[0] = 0;\n temp.Multiply(100000);\n sb.AppendFormat(\"{0:D5}\", temp.number[0]);\n digitCount += 5;\n }\n\n return sb.ToString();\n }\n public bool IsZero() {\n foreach (UInt32 item in number) {\n if (item != 0)\n return false;\n }\n return true;\n }\n\n public void ArcTan(UInt32 multiplicand, UInt32 reciprocal) {\n BigNumber X = new BigNumber(maxDigits, multiplicand);\n X.Divide(reciprocal);\n reciprocal *= reciprocal;\n\n this.Assign(X);\n\n BigNumber term = new BigNumber(maxDigits);\n UInt32 divisor = 1;\n bool subtractTerm = true;\n while (true) {\n X.Divide(reciprocal);\n term.Assign(X);\n divisor += 2;\n term.Divide(divisor);\n if (term.IsZero())\n break;\n\n if (subtractTerm)\n this.Subtract(term);\n else\n this.Add(term);\n subtractTerm = !subtractTerm;\n }\n }\n}\n" }, { "answer_id": 622950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "acos(-1)" }, { "answer_id": 1439914, "author": "Daniel C. Sobral", "author_id": 53013, "author_profile": "https://Stackoverflow.com/users/53013", "pm_score": 4, "selected": false, "text": "355 / 113" }, { "answer_id": 1947163, "author": "jon-hanson", "author_id": 84538, "author_profile": "https://Stackoverflow.com/users/84538", "pm_score": 6, "selected": false, "text": "#include <iostream>\n\ntemplate<int I>\nstruct sign\n{\n enum {value = (I % 2) == 0 ? 1 : -1};\n};\n\ntemplate<int I, int J>\nstruct pi_calc\n{\n inline static double value ()\n {\n return (pi_calc<I-1, J>::value () + pi_calc<I-1, J+1>::value ()) / 2.0;\n }\n};\n\ntemplate<int J>\nstruct pi_calc<0, J>\n{\n inline static double value ()\n {\n return (sign<J>::value * 4.0) / (2.0 * J + 1.0) + pi_calc<0, J-1>::value ();\n }\n};\n\n\ntemplate<>\nstruct pi_calc<0, 0>\n{\n inline static double value ()\n {\n return 4.0;\n }\n};\n\ntemplate<int I>\nstruct pi\n{\n inline static double value ()\n {\n return pi_calc<I, I>::value ();\n }\n};\n\nint main ()\n{\n std::cout.precision (12);\n\n const double pi_value = pi<10>::value ();\n\n std::cout << \"pi ~ \" << pi_value << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 1949194, "author": "Seth", "author_id": 65295, "author_profile": "https://Stackoverflow.com/users/65295", "pm_score": 4, "selected": false, "text": "PI = 3.141592654\n" }, { "answer_id": 2350024, "author": "qwerty01", "author_id": 282776, "author_profile": "https://Stackoverflow.com/users/282776", "pm_score": 4, "selected": false, "text": "4.0 * (4.0 * Math.Atan(0.2) - Math.Atan(1.0 / 239.0))\n" }, { "answer_id": 4905303, "author": "NihilistDandy", "author_id": 604108, "author_profile": "https://Stackoverflow.com/users/604108", "pm_score": 4, "selected": false, "text": "176 * arctan (1/57) + 28 * arctan (1/239) - 48 * arctan (1/682) + 96 * arctan(1/12943) \n\n[; \\left( 176 \\arctan \\frac{1}{57} + 28 \\arctan \\frac{1}{239} - 48 \\arctan \\frac{1}{682} + 96 \\arctan \\frac{1}{12943}\\right) ;], for you TeX the World people.\n (+ (- (+ (* 176 (atan (/ 1 57))) (* 28 (atan (/ 1 239)))) (* 48 (atan (/ 1 682)))) (* 96 (atan (/ 1 12943))))" }, { "answer_id": 44346598, "author": "Agnius Vasiliauskas", "author_id": 380331, "author_profile": "https://Stackoverflow.com/users/380331", "pm_score": 1, "selected": false, "text": "<input id=\"range\" type=\"range\" min=\"10\" max=\"960\" value=\"10\" step=\"50\" oninput=\"calcPi()\">\n<br>\n<div id=\"cont\"></div>\n\n<script>\nfunction generateCircle(width) {\n var c = width/2;\n var delta = 1.0;\n var str = \"\";\n var xCount = 0;\n for (var x=0; x <= width; x++) {\n for (var y = 0; y <= width; y++) {\n var d = Math.sqrt((x-c)*(x-c) + (y-c)*(y-c));\n if (d > (width-1)/2) {\n str += '.';\n }\n else {\n xCount++;\n str += 'o';\n }\n str += \"&nbsp;\" \n }\n str += \"\\n\";\n }\n var pi = (xCount * 4) / (width * width);\n return [str, pi];\n}\n\nfunction calcPi() {\n var e = document.getElementById(\"cont\");\n var width = document.getElementById(\"range\").value;\n e.innerHTML = \"<h4>Generating circle...</h4>\";\n setTimeout(function() {\n var circ = generateCircle(width);\n e.innerHTML = \"<pre>\" + \"π = \" + circ[1].toFixed(2) + \"\\n\" + circ[0] +\"</pre>\";\n }, 200);\n}\ncalcPi();\n</script>" }, { "answer_id": 50907044, "author": "Anand Tripathi", "author_id": 5230702, "author_profile": "https://Stackoverflow.com/users/5230702", "pm_score": 0, "selected": false, "text": "import math\nprint math.pi\n /usr/bin/time -v python math_pi.py Command being timed: \"python math_pi.py\"\nUser time (seconds): 0.01\nSystem time (seconds): 0.01\nPercent of CPU this job got: 91%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03\n import math\nprint math.acos(-1)\n /usr/bin/time -v python acos_pi.py Command being timed: \"python acos_pi.py\"\nUser time (seconds): 0.02\nSystem time (seconds): 0.01\nPercent of CPU this job got: 94%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03\n from decimal import Decimal, getcontext\ngetcontext().prec=100\nprint sum(1/Decimal(16)**k * \n (Decimal(4)/(8*k+1) - \n Decimal(2)/(8*k+4) - \n Decimal(1)/(8*k+5) -\n Decimal(1)/(8*k+6)) for k in range(100))\n /usr/bin/time -v python bbp_pi.py Command being timed: \"python c.py\"\nUser time (seconds): 0.05\nSystem time (seconds): 0.01\nPercent of CPU this job got: 98%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.06\n" }, { "answer_id": 61670212, "author": "paperclip optimizer", "author_id": 11147804, "author_profile": "https://Stackoverflow.com/users/11147804", "pm_score": 1, "selected": false, "text": "/*\n Chudnovsky algorithm for computing PI\n*/\n\n#include <iostream>\n#include <cmath>\nusing namespace std;\n\ndouble calc_PI(int K=2) {\n\n static const int A = 545140134;\n static const int B = 13591409;\n static const int D = 640320;\n\n const double ID3 = 1./ (double(D)*double(D)*double(D));\n\n double sum = 0.;\n double b = sqrt(ID3);\n long long int p = 1;\n long long int a = B;\n\n sum += double(p) * double(a)* b;\n\n // 2 iterations enough for double convergence\n for (int k=1; k<K; ++k) {\n // A*k + B\n a += A;\n // update denominator\n b *= ID3;\n // p = (-1)^k 6k! / 3k! k!^3\n p *= (6*k)*(6*k-1)*(6*k-2)*(6*k-3)*(6*k-4)*(6*k-5);\n p /= (3*k)*(3*k-1)*(3*k-2) * k*k*k;\n p = -p;\n\n sum += double(p) * double(a)* b;\n }\n\n return 1./(12*sum);\n}\n\nint main() {\n\n cout.precision(16);\n cout.setf(ios::fixed);\n\n for (int k=1; k<=5; ++k) cout << \"k = \" << k << \" PI = \" << calc_PI(k) << endl;\n\n return 0;\n}\n k = 1 PI = 3.1415926535897341\nk = 2 PI = 3.1415926535897931\nk = 3 PI = 3.1415926535897931\nk = 4 PI = 3.1415926535897931\nk = 5 PI = 3.1415926535897931\n" }, { "answer_id": 64410809, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <math.h>\n\ndouble calc_PI(int K) {\n static const int A = 545140134;\n static const int B = 13591409;\n static const int D = 640320;\n const double ID3 = 1.0 / ((double) D * (double) D * (double) D);\n double sum = 0.0;\n double b = sqrt(ID3);\n long long int p = 1;\n long long int a = B;\n sum += (double) p * (double) a * b;\n for (int k = 1; k < K; ++k) {\n a += A;\n b *= ID3;\n p *= (6 * k) * (6 * k - 1) * (6 * k - 2) * (6 * k - 3) * (6 * k - 4) * (6 * k - 5);\n p /= (3 * k) * (3 * k - 1) * (3 * k - 2) * k * k * k;\n p = -p;\n sum += (double) p * (double) a * b;\n }\n return 1.0 / (12 * sum);\n}\n\nint main() {\n for (int k = 1; k <= 5; ++k) {\n printf(\"k = %i, PI = %.16f\\n\", k, calc_PI(k));\n }\n}\n double double double double double" }, { "answer_id": 73777598, "author": "Andy Richter", "author_id": 6262481, "author_profile": "https://Stackoverflow.com/users/6262481", "pm_score": 0, "selected": false, "text": "class PiChudnovsky:\n \"\"\"Version of Chudnovsky Bros using Binary Splitting \n So far this is the winner for fastest time to a million digits on my older intel i7\n \"\"\"\n A = mpz(13591409)\n B = mpz(545140134)\n C = mpz(640320)\n D = mpz(426880)\n E = mpz(10005)\n C3_24 = pow(C, mpz(3)) // mpz(24)\n #DIGITS_PER_TERM = math.log(53360 ** 3) / math.log(10) #=> 14.181647462725476\n DIGITS_PER_TERM = 14.181647462725476\n MMILL = mpz(1000000)\n\n def __init__(self,ndigits):\n \"\"\" Initialization\n :param int ndigits: digits of PI computation\n \"\"\"\n self.ndigits = ndigits\n self.n = mpz(self.ndigits // self.DIGITS_PER_TERM + 1)\n self.prec = mpz((self.ndigits + 1) * LOG2_10)\n self.one_sq = pow(mpz(10),mpz(2 * ndigits))\n self.sqrt_c = isqrt(self.E * self.one_sq)\n self.iters = mpz(0)\n self.start_time = 0\n\n def compute(self):\n \"\"\" Computation \"\"\"\n try:\n self.start_time = time.time()\n logging.debug(\"Starting {} formula to {:,} decimal places\"\n .format(name,ndigits) )\n __, q, t = self.__bs(mpz(0), self.n) # p is just for recursion\n pi = (q * self.D * self.sqrt_c) // t\n logging.debug('{} calulation Done! {:,} iterations and {:.2f} seconds.'\n .format( name, int(self.iters),time.time() - self.start_time))\n get_context().precision= int((self.ndigits+10) * LOG2_10)\n pi_s = pi.digits() # digits() gmpy2 creates a string \n pi_o = pi_s[:1] + \".\" + pi_s[1:]\n return pi_o,int(self.iters),time.time() - self.start_time\n except Exception as e:\n print (e.message, e.args)\n raise\n\n def __bs(self, a, b):\n \"\"\" PQT computation by BSA(= Binary Splitting Algorithm)\n :param int a: positive integer\n :param int b: positive integer\n :return list [int p_ab, int q_ab, int t_ab]\n \"\"\"\n try:\n self.iters += mpz(1)\n if self.iters % self.MMILL == mpz(0):\n logging.debug('Chudnovsky ... {:,} iterations and {:.2f} seconds.'\n .format( int(self.iters),time.time() - self.start_time))\n if a + mpz(1) == b:\n if a == mpz(0):\n p_ab = q_ab = mpz(1)\n else:\n p_ab = mpz((mpz(6) * a - mpz(5)) * (mpz(2) * a - mpz(1)) * (mpz(6) * a - mpz(1)))\n q_ab = pow(a,mpz(3)) * self.C3_24\n t_ab = p_ab * (self.A + self.B * a)\n if a & 1:\n t_ab *= mpz(-1)\n else:\n m = (a + b) // mpz(2)\n p_am, q_am, t_am = self.__bs(a, m)\n p_mb, q_mb, t_mb = self.__bs(m, b)\n p_ab = p_am * p_mb\n q_ab = q_am * q_mb\n t_ab = q_mb * t_am + p_am * t_mb\n return [p_ab, q_ab, t_ab]\n except Exception as e:\n print (e.message, e.args)\n raise\n python pi-pourri.py -v -d 1,000,000,000 -a 10 \n\n[INFO] 2022-10-03 09:22:51,860 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-03 09:25:00,543 compute: MainProcess Starting Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-03 09:25:04,995 __bs: MainProcess Chudnovsky ... 1,000,000 iterations and 4.45 seconds.\n[DEBUG] 2022-10-03 09:25:10,836 __bs: MainProcess Chudnovsky ... 2,000,000 iterations and 10.29 seconds.\n[DEBUG] 2022-10-03 09:25:18,227 __bs: MainProcess Chudnovsky ... 3,000,000 iterations and 17.68 seconds.\n[DEBUG] 2022-10-03 09:25:24,512 __bs: MainProcess Chudnovsky ... 4,000,000 iterations and 23.97 seconds.\n[DEBUG] 2022-10-03 09:25:35,670 __bs: MainProcess Chudnovsky ... 5,000,000 iterations and 35.13 seconds.\n[DEBUG] 2022-10-03 09:25:41,376 __bs: MainProcess Chudnovsky ... 6,000,000 iterations and 40.83 seconds.\n[DEBUG] 2022-10-03 09:25:49,238 __bs: MainProcess Chudnovsky ... 7,000,000 iterations and 48.69 seconds.\n[DEBUG] 2022-10-03 09:25:55,646 __bs: MainProcess Chudnovsky ... 8,000,000 iterations and 55.10 seconds.\n[DEBUG] 2022-10-03 09:26:15,043 __bs: MainProcess Chudnovsky ... 9,000,000 iterations and 74.50 seconds.\n[DEBUG] 2022-10-03 09:26:21,437 __bs: MainProcess Chudnovsky ... 10,000,000 iterations and 80.89 seconds.\n[DEBUG] 2022-10-03 09:26:26,587 __bs: MainProcess Chudnovsky ... 11,000,000 iterations and 86.04 seconds.\n[DEBUG] 2022-10-03 09:26:34,777 __bs: MainProcess Chudnovsky ... 12,000,000 iterations and 94.23 seconds.\n[DEBUG] 2022-10-03 09:26:41,231 __bs: MainProcess Chudnovsky ... 13,000,000 iterations and 100.69 seconds.\n[DEBUG] 2022-10-03 09:26:52,972 __bs: MainProcess Chudnovsky ... 14,000,000 iterations and 112.43 seconds.\n[DEBUG] 2022-10-03 09:26:59,517 __bs: MainProcess Chudnovsky ... 15,000,000 iterations and 118.97 seconds.\n[DEBUG] 2022-10-03 09:27:07,932 __bs: MainProcess Chudnovsky ... 16,000,000 iterations and 127.39 seconds.\n[DEBUG] 2022-10-03 09:27:14,036 __bs: MainProcess Chudnovsky ... 17,000,000 iterations and 133.49 seconds.\n[DEBUG] 2022-10-03 09:27:51,629 __bs: MainProcess Chudnovsky ... 18,000,000 iterations and 171.09 seconds.\n[DEBUG] 2022-10-03 09:27:58,176 __bs: MainProcess Chudnovsky ... 19,000,000 iterations and 177.63 seconds.\n[DEBUG] 2022-10-03 09:28:06,704 __bs: MainProcess Chudnovsky ... 20,000,000 iterations and 186.16 seconds.\n[DEBUG] 2022-10-03 09:28:13,376 __bs: MainProcess Chudnovsky ... 21,000,000 iterations and 192.83 seconds.\n[DEBUG] 2022-10-03 09:28:18,737 __bs: MainProcess Chudnovsky ... 22,000,000 iterations and 198.19 seconds.\n[DEBUG] 2022-10-03 09:28:31,095 __bs: MainProcess Chudnovsky ... 23,000,000 iterations and 210.55 seconds.\n[DEBUG] 2022-10-03 09:28:37,789 __bs: MainProcess Chudnovsky ... 24,000,000 iterations and 217.25 seconds.\n[DEBUG] 2022-10-03 09:28:46,171 __bs: MainProcess Chudnovsky ... 25,000,000 iterations and 225.63 seconds.\n[DEBUG] 2022-10-03 09:28:52,933 __bs: MainProcess Chudnovsky ... 26,000,000 iterations and 232.39 seconds.\n[DEBUG] 2022-10-03 09:29:13,524 __bs: MainProcess Chudnovsky ... 27,000,000 iterations and 252.98 seconds.\n[DEBUG] 2022-10-03 09:29:19,676 __bs: MainProcess Chudnovsky ... 28,000,000 iterations and 259.13 seconds.\n[DEBUG] 2022-10-03 09:29:28,196 __bs: MainProcess Chudnovsky ... 29,000,000 iterations and 267.65 seconds.\n[DEBUG] 2022-10-03 09:29:34,720 __bs: MainProcess Chudnovsky ... 30,000,000 iterations and 274.18 seconds.\n[DEBUG] 2022-10-03 09:29:47,075 __bs: MainProcess Chudnovsky ... 31,000,000 iterations and 286.53 seconds.\n[DEBUG] 2022-10-03 09:29:53,746 __bs: MainProcess Chudnovsky ... 32,000,000 iterations and 293.20 seconds.\n[DEBUG] 2022-10-03 09:29:59,099 __bs: MainProcess Chudnovsky ... 33,000,000 iterations and 298.56 seconds.\n[DEBUG] 2022-10-03 09:30:07,511 __bs: MainProcess Chudnovsky ... 34,000,000 iterations and 306.97 seconds.\n[DEBUG] 2022-10-03 09:30:14,279 __bs: MainProcess Chudnovsky ... 35,000,000 iterations and 313.74 seconds.\n[DEBUG] 2022-10-03 09:31:31,710 __bs: MainProcess Chudnovsky ... 36,000,000 iterations and 391.17 seconds.\n[DEBUG] 2022-10-03 09:31:38,454 __bs: MainProcess Chudnovsky ... 37,000,000 iterations and 397.91 seconds.\n[DEBUG] 2022-10-03 09:31:46,437 __bs: MainProcess Chudnovsky ... 38,000,000 iterations and 405.89 seconds.\n[DEBUG] 2022-10-03 09:31:53,285 __bs: MainProcess Chudnovsky ... 39,000,000 iterations and 412.74 seconds.\n[DEBUG] 2022-10-03 09:32:05,602 __bs: MainProcess Chudnovsky ... 40,000,000 iterations and 425.06 seconds.\n[DEBUG] 2022-10-03 09:32:12,220 __bs: MainProcess Chudnovsky ... 41,000,000 iterations and 431.68 seconds.\n[DEBUG] 2022-10-03 09:32:20,708 __bs: MainProcess Chudnovsky ... 42,000,000 iterations and 440.17 seconds.\n[DEBUG] 2022-10-03 09:32:27,552 __bs: MainProcess Chudnovsky ... 43,000,000 iterations and 447.01 seconds.\n[DEBUG] 2022-10-03 09:32:32,986 __bs: MainProcess Chudnovsky ... 44,000,000 iterations and 452.44 seconds.\n[DEBUG] 2022-10-03 09:32:53,904 __bs: MainProcess Chudnovsky ... 45,000,000 iterations and 473.36 seconds.\n[DEBUG] 2022-10-03 09:33:00,832 __bs: MainProcess Chudnovsky ... 46,000,000 iterations and 480.29 seconds.\n[DEBUG] 2022-10-03 09:33:09,198 __bs: MainProcess Chudnovsky ... 47,000,000 iterations and 488.66 seconds.\n[DEBUG] 2022-10-03 09:33:16,000 __bs: MainProcess Chudnovsky ... 48,000,000 iterations and 495.46 seconds.\n[DEBUG] 2022-10-03 09:33:27,921 __bs: MainProcess Chudnovsky ... 49,000,000 iterations and 507.38 seconds.\n[DEBUG] 2022-10-03 09:33:34,778 __bs: MainProcess Chudnovsky ... 50,000,000 iterations and 514.24 seconds.\n[DEBUG] 2022-10-03 09:33:43,298 __bs: MainProcess Chudnovsky ... 51,000,000 iterations and 522.76 seconds.\n[DEBUG] 2022-10-03 09:33:49,959 __bs: MainProcess Chudnovsky ... 52,000,000 iterations and 529.42 seconds.\n[DEBUG] 2022-10-03 09:34:29,294 __bs: MainProcess Chudnovsky ... 53,000,000 iterations and 568.75 seconds.\n[DEBUG] 2022-10-03 09:34:36,176 __bs: MainProcess Chudnovsky ... 54,000,000 iterations and 575.63 seconds.\n[DEBUG] 2022-10-03 09:34:41,576 __bs: MainProcess Chudnovsky ... 55,000,000 iterations and 581.03 seconds.\n[DEBUG] 2022-10-03 09:34:50,161 __bs: MainProcess Chudnovsky ... 56,000,000 iterations and 589.62 seconds.\n[DEBUG] 2022-10-03 09:34:56,811 __bs: MainProcess Chudnovsky ... 57,000,000 iterations and 596.27 seconds.\n[DEBUG] 2022-10-03 09:35:09,382 __bs: MainProcess Chudnovsky ... 58,000,000 iterations and 608.84 seconds.\n[DEBUG] 2022-10-03 09:35:16,206 __bs: MainProcess Chudnovsky ... 59,000,000 iterations and 615.66 seconds.\n[DEBUG] 2022-10-03 09:35:24,295 __bs: MainProcess Chudnovsky ... 60,000,000 iterations and 623.75 seconds.\n[DEBUG] 2022-10-03 09:35:31,095 __bs: MainProcess Chudnovsky ... 61,000,000 iterations and 630.55 seconds.\n[DEBUG] 2022-10-03 09:35:52,139 __bs: MainProcess Chudnovsky ... 62,000,000 iterations and 651.60 seconds.\n[DEBUG] 2022-10-03 09:35:58,781 __bs: MainProcess Chudnovsky ... 63,000,000 iterations and 658.24 seconds.\n[DEBUG] 2022-10-03 09:36:07,399 __bs: MainProcess Chudnovsky ... 64,000,000 iterations and 666.86 seconds.\n[DEBUG] 2022-10-03 09:36:12,847 __bs: MainProcess Chudnovsky ... 65,000,000 iterations and 672.30 seconds.\n[DEBUG] 2022-10-03 09:36:19,763 __bs: MainProcess Chudnovsky ... 66,000,000 iterations and 679.22 seconds.\n[DEBUG] 2022-10-03 09:36:32,351 __bs: MainProcess Chudnovsky ... 67,000,000 iterations and 691.81 seconds.\n[DEBUG] 2022-10-03 09:36:39,078 __bs: MainProcess Chudnovsky ... 68,000,000 iterations and 698.53 seconds.\n[DEBUG] 2022-10-03 09:36:47,830 __bs: MainProcess Chudnovsky ... 69,000,000 iterations and 707.29 seconds.\n[DEBUG] 2022-10-03 09:36:54,701 __bs: MainProcess Chudnovsky ... 70,000,000 iterations and 714.16 seconds.\n[DEBUG] 2022-10-03 09:39:39,357 __bs: MainProcess Chudnovsky ... 71,000,000 iterations and 878.81 seconds.\n[DEBUG] 2022-10-03 09:39:46,199 __bs: MainProcess Chudnovsky ... 72,000,000 iterations and 885.66 seconds.\n[DEBUG] 2022-10-03 09:39:54,956 __bs: MainProcess Chudnovsky ... 73,000,000 iterations and 894.41 seconds.\n[DEBUG] 2022-10-03 09:40:01,639 __bs: MainProcess Chudnovsky ... 74,000,000 iterations and 901.10 seconds.\n[DEBUG] 2022-10-03 09:40:14,219 __bs: MainProcess Chudnovsky ... 75,000,000 iterations and 913.68 seconds.\n[DEBUG] 2022-10-03 09:40:19,680 __bs: MainProcess Chudnovsky ... 76,000,000 iterations and 919.14 seconds.\n[DEBUG] 2022-10-03 09:40:26,625 __bs: MainProcess Chudnovsky ... 77,000,000 iterations and 926.08 seconds.\n[DEBUG] 2022-10-03 09:40:35,212 __bs: MainProcess Chudnovsky ... 78,000,000 iterations and 934.67 seconds.\n[DEBUG] 2022-10-03 09:40:41,914 __bs: MainProcess Chudnovsky ... 79,000,000 iterations and 941.37 seconds.\n[DEBUG] 2022-10-03 09:41:03,218 __bs: MainProcess Chudnovsky ... 80,000,000 iterations and 962.68 seconds.\n[DEBUG] 2022-10-03 09:41:10,213 __bs: MainProcess Chudnovsky ... 81,000,000 iterations and 969.67 seconds.\n[DEBUG] 2022-10-03 09:41:18,344 __bs: MainProcess Chudnovsky ... 82,000,000 iterations and 977.80 seconds.\n[DEBUG] 2022-10-03 09:41:25,261 __bs: MainProcess Chudnovsky ... 83,000,000 iterations and 984.72 seconds.\n[DEBUG] 2022-10-03 09:41:37,663 __bs: MainProcess Chudnovsky ... 84,000,000 iterations and 997.12 seconds.\n[DEBUG] 2022-10-03 09:41:44,680 __bs: MainProcess Chudnovsky ... 85,000,000 iterations and 1004.14 seconds.\n[DEBUG] 2022-10-03 09:41:53,411 __bs: MainProcess Chudnovsky ... 86,000,000 iterations and 1012.87 seconds.\n[DEBUG] 2022-10-03 09:41:58,926 __bs: MainProcess Chudnovsky ... 87,000,000 iterations and 1018.38 seconds.\n[DEBUG] 2022-10-03 09:42:05,858 __bs: MainProcess Chudnovsky ... 88,000,000 iterations and 1025.32 seconds.\n[DEBUG] 2022-10-03 09:42:46,163 __bs: MainProcess Chudnovsky ... 89,000,000 iterations and 1065.62 seconds.\n[DEBUG] 2022-10-03 09:42:53,054 __bs: MainProcess Chudnovsky ... 90,000,000 iterations and 1072.51 seconds.\n[DEBUG] 2022-10-03 09:43:02,030 __bs: MainProcess Chudnovsky ... 91,000,000 iterations and 1081.49 seconds.\n[DEBUG] 2022-10-03 09:43:09,192 __bs: MainProcess Chudnovsky ... 92,000,000 iterations and 1088.65 seconds.\n[DEBUG] 2022-10-03 09:43:21,533 __bs: MainProcess Chudnovsky ... 93,000,000 iterations and 1100.99 seconds.\n[DEBUG] 2022-10-03 09:43:28,643 __bs: MainProcess Chudnovsky ... 94,000,000 iterations and 1108.10 seconds.\n[DEBUG] 2022-10-03 09:43:37,372 __bs: MainProcess Chudnovsky ... 95,000,000 iterations and 1116.83 seconds.\n[DEBUG] 2022-10-03 09:43:44,558 __bs: MainProcess Chudnovsky ... 96,000,000 iterations and 1124.02 seconds.\n[DEBUG] 2022-10-03 09:44:06,555 __bs: MainProcess Chudnovsky ... 97,000,000 iterations and 1146.01 seconds.\n[DEBUG] 2022-10-03 09:44:12,220 __bs: MainProcess Chudnovsky ... 98,000,000 iterations and 1151.68 seconds.\n[DEBUG] 2022-10-03 09:44:19,278 __bs: MainProcess Chudnovsky ... 99,000,000 iterations and 1158.74 seconds.\n[DEBUG] 2022-10-03 09:44:28,323 __bs: MainProcess Chudnovsky ... 100,000,000 iterations and 1167.78 seconds.\n[DEBUG] 2022-10-03 09:44:35,211 __bs: MainProcess Chudnovsky ... 101,000,000 iterations and 1174.67 seconds.\n[DEBUG] 2022-10-03 09:44:48,331 __bs: MainProcess Chudnovsky ... 102,000,000 iterations and 1187.79 seconds.\n[DEBUG] 2022-10-03 09:44:54,835 __bs: MainProcess Chudnovsky ... 103,000,000 iterations and 1194.29 seconds.\n[DEBUG] 2022-10-03 09:45:03,869 __bs: MainProcess Chudnovsky ... 104,000,000 iterations and 1203.33 seconds.\n[DEBUG] 2022-10-03 09:45:10,967 __bs: MainProcess Chudnovsky ... 105,000,000 iterations and 1210.42 seconds.\n[DEBUG] 2022-10-03 09:46:32,760 __bs: MainProcess Chudnovsky ... 106,000,000 iterations and 1292.22 seconds.\n[DEBUG] 2022-10-03 09:46:39,872 __bs: MainProcess Chudnovsky ... 107,000,000 iterations and 1299.33 seconds.\n[DEBUG] 2022-10-03 09:46:48,948 __bs: MainProcess Chudnovsky ... 108,000,000 iterations and 1308.41 seconds.\n[DEBUG] 2022-10-03 09:46:54,611 __bs: MainProcess Chudnovsky ... 109,000,000 iterations and 1314.07 seconds.\n[DEBUG] 2022-10-03 09:47:01,727 __bs: MainProcess Chudnovsky ... 110,000,000 iterations and 1321.18 seconds.\n[DEBUG] 2022-10-03 09:47:14,525 __bs: MainProcess Chudnovsky ... 111,000,000 iterations and 1333.98 seconds.\n[DEBUG] 2022-10-03 09:47:21,682 __bs: MainProcess Chudnovsky ... 112,000,000 iterations and 1341.14 seconds.\n[DEBUG] 2022-10-03 09:47:30,610 __bs: MainProcess Chudnovsky ... 113,000,000 iterations and 1350.07 seconds.\n[DEBUG] 2022-10-03 09:47:37,176 __bs: MainProcess Chudnovsky ... 114,000,000 iterations and 1356.63 seconds.\n[DEBUG] 2022-10-03 09:47:59,642 __bs: MainProcess Chudnovsky ... 115,000,000 iterations and 1379.10 seconds.\n[DEBUG] 2022-10-03 09:48:06,702 __bs: MainProcess Chudnovsky ... 116,000,000 iterations and 1386.16 seconds.\n[DEBUG] 2022-10-03 09:48:15,483 __bs: MainProcess Chudnovsky ... 117,000,000 iterations and 1394.94 seconds.\n[DEBUG] 2022-10-03 09:48:22,537 __bs: MainProcess Chudnovsky ... 118,000,000 iterations and 1401.99 seconds.\n[DEBUG] 2022-10-03 09:48:35,714 __bs: MainProcess Chudnovsky ... 119,000,000 iterations and 1415.17 seconds.\n[DEBUG] 2022-10-03 09:48:41,321 __bs: MainProcess Chudnovsky ... 120,000,000 iterations and 1420.78 seconds.\n[DEBUG] 2022-10-03 09:48:48,408 __bs: MainProcess Chudnovsky ... 121,000,000 iterations and 1427.87 seconds.\n[DEBUG] 2022-10-03 09:48:57,138 __bs: MainProcess Chudnovsky ... 122,000,000 iterations and 1436.60 seconds.\n[DEBUG] 2022-10-03 09:49:04,328 __bs: MainProcess Chudnovsky ... 123,000,000 iterations and 1443.79 seconds.\n[DEBUG] 2022-10-03 09:49:46,274 __bs: MainProcess Chudnovsky ... 124,000,000 iterations and 1485.73 seconds.\n[DEBUG] 2022-10-03 09:49:52,833 __bs: MainProcess Chudnovsky ... 125,000,000 iterations and 1492.29 seconds.\n[DEBUG] 2022-10-03 09:50:01,786 __bs: MainProcess Chudnovsky ... 126,000,000 iterations and 1501.24 seconds.\n[DEBUG] 2022-10-03 09:50:08,975 __bs: MainProcess Chudnovsky ... 127,000,000 iterations and 1508.43 seconds.\n[DEBUG] 2022-10-03 09:50:21,850 __bs: MainProcess Chudnovsky ... 128,000,000 iterations and 1521.31 seconds.\n[DEBUG] 2022-10-03 09:50:28,962 __bs: MainProcess Chudnovsky ... 129,000,000 iterations and 1528.42 seconds.\n[DEBUG] 2022-10-03 09:50:34,594 __bs: MainProcess Chudnovsky ... 130,000,000 iterations and 1534.05 seconds.\n[DEBUG] 2022-10-03 09:50:43,647 __bs: MainProcess Chudnovsky ... 131,000,000 iterations and 1543.10 seconds.\n[DEBUG] 2022-10-03 09:50:50,724 __bs: MainProcess Chudnovsky ... 132,000,000 iterations and 1550.18 seconds.\n[DEBUG] 2022-10-03 09:51:12,742 __bs: MainProcess Chudnovsky ... 133,000,000 iterations and 1572.20 seconds.\n[DEBUG] 2022-10-03 09:51:19,799 __bs: MainProcess Chudnovsky ... 134,000,000 iterations and 1579.26 seconds.\n[DEBUG] 2022-10-03 09:51:28,824 __bs: MainProcess Chudnovsky ... 135,000,000 iterations and 1588.28 seconds.\n[DEBUG] 2022-10-03 09:51:35,324 __bs: MainProcess Chudnovsky ... 136,000,000 iterations and 1594.78 seconds.\n[DEBUG] 2022-10-03 09:51:48,419 __bs: MainProcess Chudnovsky ... 137,000,000 iterations and 1607.88 seconds.\n[DEBUG] 2022-10-03 09:51:55,634 __bs: MainProcess Chudnovsky ... 138,000,000 iterations and 1615.09 seconds.\n[DEBUG] 2022-10-03 09:52:04,435 __bs: MainProcess Chudnovsky ... 139,000,000 iterations and 1623.89 seconds.\n[DEBUG] 2022-10-03 09:52:11,583 __bs: MainProcess Chudnovsky ... 140,000,000 iterations and 1631.04 seconds.\n[DEBUG] 2022-10-03 09:52:17,222 __bs: MainProcess Chudnovsky ... 141,000,000 iterations and 1636.68 seconds.\n[DEBUG] 2022-10-03 10:02:43,939 compute: MainProcess Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n calulation Done! 141,027,339 iterations and 2263.39 seconds.\n[INFO] 2022-10-03 10:09:07,119 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-03 10:09:07,119 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 10 Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n \n[INFO] 2022-10-03 10:09:07,120 <module>: MainProcess Calculation took 141,027,339 iterations and 0:44:06.398345.\n python pi-pourri.py -v -d 1,000,000,000 -a 11\n[INFO] 2022-10-03 14:33:34,729 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-03 14:33:34,729 compute: MainProcess Starting const_pi() function from the gmpy2 library formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-03 15:46:46,575 compute: MainProcess const_pi() function from the gmpy2 library calulation Done! 1 iterations and 4391.85 seconds.\n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 11 const_pi() function from the gmpy2 library \n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Calculation took 1 iterations and 1:13:11.845652.\n python pi-pourri.py -v -a 12 -d 1,000,000,000 \n[INFO] 2022-10-04 09:10:37,085 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-04 09:10:37,085 compute: MainProcess Starting mp.pi() function from the mpmath library formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-04 10:01:25,321 compute: MainProcess mp.pi() function from the mpmath library calulation Done! 1 iterations and 3048.22 seconds.\n[INFO] 2022-10-04 10:01:25,338 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-04 10:01:25,340 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 12 mp.pi() function from the mpmath library \n[INFO] 2022-10-04 10:01:25,343 <module>: MainProcess Calculation took 1 iterations and 0:50:48.250337.\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/19", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13/" ]
24
<p>If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?</p>
[ { "answer_id": 7189396, "author": "RuiDC", "author_id": 521586, "author_profile": "https://Stackoverflow.com/users/521586", "pm_score": 7, "selected": false, "text": "SIGNAL signal sqlstate '45000' set message_text = 'My Error Message';\n delimiter //\nuse test//\ncreate table trigger_test\n(\n id int not null\n)//\ndrop trigger if exists trg_trigger_test_ins //\ncreate trigger trg_trigger_test_ins before insert on trigger_test\nfor each row\nbegin\n declare msg varchar(128);\n if new.id < 0 then\n set msg = concat('MyTriggerError: Trying to insert a negative value in trigger_test: ', cast(new.id as char));\n signal sqlstate '45000' set message_text = msg;\n end if;\nend\n//\n\ndelimiter ;\n-- run the following as seperate statements:\ninsert into trigger_test values (1), (-1), (2); -- everything fails as one row is bad\nselect * from trigger_test;\ninsert into trigger_test values (1); -- succeeds as expected\ninsert into trigger_test values (-1); -- fails as expected\nselect * from trigger_test;\n" }, { "answer_id": 9046539, "author": "el.atomo", "author_id": 831797, "author_profile": "https://Stackoverflow.com/users/831797", "pm_score": 5, "selected": false, "text": "table_name doesn't exist table_name DELIMITER $$\n-- before inserting new id\nDROP TRIGGER IF EXISTS before_insert_id$$\nCREATE TRIGGER before_insert_id\n BEFORE INSERT ON test FOR EACH ROW\n BEGIN\n -- condition to check\n IF NEW.id < 0 THEN\n -- hack to solve absence of SIGNAL/prepared statements in triggers\n UPDATE `Error: invalid_id_test` SET x=1;\n END IF;\n END$$\n\nDELIMITER ;\n DELIMITER $$\n-- my_signal procedure\nCREATE PROCEDURE `my_signal`(in_errortext VARCHAR(255))\nBEGIN\n SET @sql=CONCAT('UPDATE `', in_errortext, '` SET x=1');\n PREPARE my_signal_stmt FROM @sql;\n EXECUTE my_signal_stmt;\n DEALLOCATE PREPARE my_signal_stmt;\nEND$$\n\nCREATE PROCEDURE insert_test(p_id INT)\nBEGIN\n IF NEW.id < 0 THEN\n CALL my_signal('Error: invalid_id_test; Id must be a positive integer');\n ELSE\n INSERT INTO test (id) VALUES (p_id);\n END IF;\nEND$$\nDELIMITER ;\n" }, { "answer_id": 13293014, "author": "Marinos An", "author_id": 1555615, "author_profile": "https://Stackoverflow.com/users/1555615", "pm_score": 4, "selected": false, "text": "create table mysql_error_generator(error_field varchar(64) unique) engine INNODB;\nDELIMITER $$\nCREATE PROCEDURE throwCustomError(IN errorText VARCHAR(44))\nBEGIN\n DECLARE errorWithDate varchar(64);\n select concat(\"[\",DATE_FORMAT(now(),\"%Y%m%d %T\"),\"] \", errorText) into errorWithDate;\n INSERT IGNORE INTO mysql_error_generator(error_field) VALUES (errorWithDate);\n INSERT INTO mysql_error_generator(error_field) VALUES (errorWithDate);\nEND;\n$$\nDELIMITER ;\n\n\ncall throwCustomError(\"Custom error message with log support.\");\n" }, { "answer_id": 36523822, "author": "PhotonFalcon", "author_id": 3088965, "author_profile": "https://Stackoverflow.com/users/3088965", "pm_score": 3, "selected": false, "text": "BEGIN\n -- Force one of the following to be assigned otherwise set required field to null which will throw an error\n IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN\n SET NEW.`required_id_field`=NULL;\n END IF;\nEND\n BEGIN\n -- Force one of the following to be assigned otherwise use signal sqlstate to throw a unique error\n IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN\n SIGNAL SQLSTATE '45000' set message_text='A unique identifier for nullable_field_1 OR nullable_field_2 is required!';\n END IF;\nEND\n" }, { "answer_id": 38924077, "author": "BHUVANESH MOHANKUMAR", "author_id": 456918, "author_profile": "https://Stackoverflow.com/users/456918", "pm_score": 3, "selected": false, "text": "CREATE TRIGGER sample_trigger_msg \n BEFORE INSERT\nFOR EACH ROW\n BEGIN\nIF(NEW.important_value) < (1*2) THEN\n DECLARE dummy INT;\n SELECT \n Enter your Message Here!!!\n INTO dummy \n FROM mytable\n WHERE mytable.id=new.id\nEND IF;\nEND;\n" }, { "answer_id": 62135883, "author": "Bashir", "author_id": 5988526, "author_profile": "https://Stackoverflow.com/users/5988526", "pm_score": 1, "selected": false, "text": "DELIMITER @@\nDROP TRIGGER IF EXISTS trigger_name @@\nCREATE TRIGGER trigger_name \nBEFORE UPDATE ON table_name\nFOR EACH ROW\nBEGIN\n\n --the condition of error is: \n --if NEW update value of the attribute age = 1 and OLD value was 0\n --key word OLD and NEW let you distinguish between the old and new value of an attribute\n\n IF (NEW.state = 1 AND OLD.state = 0) THEN\n signal sqlstate '-20000' set message_text = 'hey it's an error!'; \n END IF;\n\nEND @@ \nDELIMITER ;\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/24", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22/" ]
25
<p>I'm having issues getting the C sockets API to work properly in C++ on z/OS.</p> <p>Although I am including <code>sys/socket.h</code>, I still get compile time errors telling me that <code>AF_INET</code> is not defined.</p> <p>Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated?</p> <p>I discovered that there is an <code>#ifdef</code> that I'm hitting. Apparently z/OS isn't happy unless I define which &quot;type&quot; of sockets I'm using with:</p> <pre><code>#define _OE_SOCKETS </code></pre> <p>Now, I personally have no idea what this <code>_OE_SOCKETS</code> is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works?</p> <p>Test App</p> <pre><code>#include &lt;sys/socket.h&gt; int main() { return AF_INET; } </code></pre> <p>Compile/Link Output:</p> <pre><code>cxx -Wc,xplink -Wl,xplink -o inet_test inet.C &quot;./inet.C&quot;, line 5.16: CCN5274 (S) The name lookup for &quot;AF_INET&quot; did not find a declaration. CCN0797(I) Compilation failed for file ./inet.C. Object file not created. </code></pre> <p>A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any <code>#ifdef</code> statements.</p> <p>I have however noticed it contains the following:</p> <pre><code>#ifdef __cplusplus extern &quot;C&quot; { #endif </code></pre> <p>which encapsulates basically the whole file? Not sure if it matters.</p>
[ { "answer_id": 30, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": false, "text": "#include <sys/socket.h>\n\nint\nmain()\n{\n return AF_INET;\n}\n" }, { "answer_id": 73, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": false, "text": "extern \"C\" #include extern \"C\" {\n#include <sys/socket.h>\n// include other similarly non-compliant header files\n}\n extern \"C\"" }, { "answer_id": 35029, "author": "David Bryson", "author_id": 3663, "author_profile": "https://Stackoverflow.com/users/3663", "pm_score": 4, "selected": false, "text": "class my_sock {\n private int sock;\n private int socket_type;\n private socklen_t sock_len;\n private struct sockaddr_in server_addr;\n public char *server_ip;\n public unsigned short server_port;\n};\n int my_socket_connect()\n{\n int return_code = 0;\n\n if ( this->socket_type != CLIENT_SOCK ) {\n cout << \"This is a not a client socket!\\n\";\n return -1;\n }\n\n return_code = connect( this->local_sock, (struct sockaddr *) &this->server_addr, sizeof(this->server_addr));\n\n if( return_code < 0 ) {\n cout << \"Connect() failure! %s\\n\", strerror(errno);\n return return_code;\n }\n\n return return_code;\n}\n" }, { "answer_id": 110917, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 5, "selected": false, "text": "#define _OE_SOCKETS\n" }, { "answer_id": 1443907, "author": "Anthony Giorgio", "author_id": 9816, "author_profile": "https://Stackoverflow.com/users/9816", "pm_score": 8, "selected": true, "text": "#define _XOPEN_SOURCE_EXTENDED 1\n#include <sys/socket.h>\n\nint connect(int socket, const struct sockaddr *address, socklen_t address_len);\n #define _OE_SOCKETS\n#include <sys/types.h>\n#include <sys/socket.h>\n\nint connect(int socket, struct sockaddr *address, int address_len);\n" }, { "answer_id": 5626132, "author": "Hope T. Helps", "author_id": 702754, "author_profile": "https://Stackoverflow.com/users/702754", "pm_score": 4, "selected": false, "text": " -D_OE_SOCKETS\n bash-2.03$ c89 -D_OE_SOCKETS [filename].c\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/25", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23/" ]
34
<p>How do I forcefully unload a <code>ByteArray</code> from memory using ActionScript 3?</p> <p>I have tried the following:</p> <pre><code>// First non-working solution byteArray.length = 0; byteArray = new ByteArray(); // Second non-working solution for ( var i:int=0; i &lt; byteArray.length; i++ ) { byteArray[i] = null; } </code></pre>
[ { "answer_id": 52, "author": "Jax", "author_id": 23, "author_profile": "https://Stackoverflow.com/users/23", "pm_score": 4, "selected": false, "text": "private var gcCount:int;\nprivate function startGCCycle():void{\n gcCount = 0;\n addEventListener(Event.ENTER_FRAME, doGC);\n}\nprivate function doGC(evt:Event):void{\n flash.system.System.gc();\n if(++gcCount > 1){\n removeEventListener(Event.ENTER_FRAME, doGC);\n setTimeout(lastGC, 40);\n }\n}\nprivate function lastGC():void{\n flash.system.System.gc();\n}\n" }, { "answer_id": 53, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 5, "selected": false, "text": "byteArray byteArray flash.system.System.gc();\nflash.system.System.gc();\n" }, { "answer_id": 60, "author": "Redbaron", "author_id": 41, "author_profile": "https://Stackoverflow.com/users/41", "pm_score": 4, "selected": false, "text": "ByteArray var byteObject:Object = new Object();\n\nbyteObject.byteArray = new ByteArray();\n\n...\n\n//Then when you are finished delete the variable from byteObject\ndelete byteObject.byteArray;\n byteArray byteObject" }, { "answer_id": 81, "author": "Redbaron", "author_id": 41, "author_profile": "https://Stackoverflow.com/users/41", "pm_score": 4, "selected": false, "text": "System.totalMemory" }, { "answer_id": 11340, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 5, "selected": false, "text": "System.totalMemory" }, { "answer_id": 74515081, "author": "Manish", "author_id": 3958207, "author_profile": "https://Stackoverflow.com/users/3958207", "pm_score": 0, "selected": false, "text": "bytearray.clear()" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/34", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
36
<p>How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> and C#.</p> <p>I'd like to be able to support any <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#Genesis" rel="noreferrer">SQL Server 2000</a> SP4 or newer. My application is a bolt-on data visualization for another company's product. Our customer base is in the thousands, so I don't want to have to put in requirements that we modify the third-party vendor's table at every installation.</p> <p>By <em>"changes to a table"</em> I mean changes to table data, not changes to table structure.</p> <p>Ultimately, I would like the change to trigger an event in my application, instead of having to check for changes at an interval.</p> <hr> <p>The best course of action given my requirements (no triggers or schema modification, SQL Server 2000 and 2005) seems to be to use the <code>BINARY_CHECKSUM</code> function in <a href="http://en.wikipedia.org/wiki/Transact-SQL" rel="noreferrer">T-SQL</a>. The way I plan to implement is this:</p> <p>Every X seconds run the following query:</p> <pre><code>SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); </code></pre> <p>And compare that against the stored value. If the value has changed, go through the table row by row using the query:</p> <pre><code>SELECT row_id, BINARY_CHECKSUM(*) FROM sample_table WITH (NOLOCK); </code></pre> <p>And compare the returned checksums against stored values.</p>
[ { "answer_id": 82, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 4, "selected": false, "text": "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'ABC'\n" }, { "answer_id": 352, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 8, "selected": true, "text": "SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK);\n" }, { "answer_id": 695, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 4, "selected": false, "text": "CHECKSUM_AGG(BINARY_CHECKSUM(*)) NOLOCK" }, { "answer_id": 3009, "author": "caryden", "author_id": 313, "author_profile": "https://Stackoverflow.com/users/313", "pm_score": 4, "selected": false, "text": "SQLDependency System.Data.SqlClient" }, { "answer_id": 5486054, "author": "BitLauncher", "author_id": 519971, "author_profile": "https://Stackoverflow.com/users/519971", "pm_score": 5, "selected": false, "text": "CHECKSUM_AGG(BINARY_CHECKSUM(*)) \nSELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM \n(\n SELECT 1 as numA, 1 as numB\n UNION ALL\n SELECT 1 as numA, 1 as numB\n) q\n-- delivers 0!\n\nSELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM \n(\n SELECT 1 as numA, 2 as numB\n UNION ALL\n SELECT 1 as numA, 2 as numB\n) q\n-- delivers 0!\n\nSELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM \n(\n SELECT 0 as numA, 0 as numB\n UNION ALL\n SELECT 0 as numA, 0 as numB\n) q\n-- delivers 0!\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/36", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32/" ]
39
<p>I am aware that in <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a> there are three timer types (see <em><a href="http://msdn.microsoft.com/en-us/magazine/cc164015.aspx" rel="noreferrer">Comparing the Timer Classes in the .NET Framework Class Library</a></em>). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable.</p> <p>The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy.</p> <p>The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes.</p> <p>I tried adding a <code>while true</code> loop, but then the main thread is too busy when the timer does go off.</p>
[ { "answer_id": 44, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 5, "selected": false, "text": "Reset()" }, { "answer_id": 45, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 7, "selected": true, "text": "Console.ReadLine()" }, { "answer_id": 65238796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "private static void Main()\n{\n using AutoResetEvent autoResetEvent = new AutoResetEvent(false);\n using Timer timer = new Timer(state => Console.WriteLine(\"One second has passed\"), autoResetEvent, TimeSpan.Zero, new TimeSpan(0, 0, 1));\n autoResetEvent.WaitOne();\n}\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/39", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33/" ]
42
<p>I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface. </p> <p>How does one go about writing 'hooks' into their code so that plugins can attach to specific events?</p>
[ { "answer_id": 77, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 8, "selected": true, "text": "<?php\n\n/** Plugin system **/\n\n$listeners = array();\n\n/* Create an entry point for plugins */\nfunction hook() {\n global $listeners;\n\n $num_args = func_num_args();\n $args = func_get_args();\n\n if($num_args < 2)\n trigger_error(\"Insufficient arguments\", E_USER_ERROR);\n\n // Hook name should always be first argument\n $hook_name = array_shift($args);\n\n if(!isset($listeners[$hook_name]))\n return; // No plugins have registered this hook\n\n foreach($listeners[$hook_name] as $func) {\n $args = $func($args); \n }\n return $args;\n}\n\n/* Attach a function to a hook */\nfunction add_listener($hook, $function_name) {\n global $listeners;\n $listeners[$hook][] = $function_name;\n}\n\n/////////////////////////\n\n/** Sample Plugin **/\nadd_listener('a_b', 'my_plugin_func1');\nadd_listener('str', 'my_plugin_func2');\n\nfunction my_plugin_func1($args) {\n return array(4, 5);\n}\n\nfunction my_plugin_func2($args) {\n return str_replace('sample', 'CRAZY', $args[0]);\n}\n\n/////////////////////////\n\n/** Sample Application **/\n\n$a = 1;\n$b = 2;\n\nlist($a, $b) = hook('a_b', $a, $b);\n\n$str = \"This is my sample application\\n\";\n$str .= \"$a + $b = \".($a+$b).\"\\n\";\n$str .= \"$a * $b = \".($a*$b).\"\\n\";\n\n$str = hook('str', $str);\necho $str;\n?>\n This is my CRAZY application\n4 + 5 = 9\n4 * 5 = 20\n" }, { "answer_id": 136273, "author": "andy.gurin", "author_id": 22388, "author_profile": "https://Stackoverflow.com/users/22388", "pm_score": 5, "selected": false, "text": " <?php\n\nclass SignalsHandler {\n\n\n /**\n * hash of senders/signals to slots\n *\n * @var array\n */\n private static $connections = array();\n\n\n /**\n * current sender\n *\n * @var class|object\n */\n private static $sender;\n\n\n /**\n * connects an object/signal with a slot\n *\n * @param class|object $sender\n * @param string $signal\n * @param callable $slot\n */\n public static function connect($sender, $signal, $slot) {\n if (is_object($sender)) {\n self::$connections[spl_object_hash($sender)][$signal][] = $slot;\n }\n else {\n self::$connections[md5($sender)][$signal][] = $slot;\n }\n }\n\n\n /**\n * sends a signal, so all connected slots are called\n *\n * @param class|object $sender\n * @param string $signal\n * @param array $params\n */\n public static function signal($sender, $signal, $params = array()) {\n self::$sender = $sender;\n if (is_object($sender)) {\n if ( ! isset(self::$connections[spl_object_hash($sender)][$signal])) {\n return;\n }\n foreach (self::$connections[spl_object_hash($sender)][$signal] as $slot) {\n call_user_func_array($slot, (array)$params);\n }\n\n }\n else {\n if ( ! isset(self::$connections[md5($sender)][$signal])) {\n return;\n }\n foreach (self::$connections[md5($sender)][$signal] as $slot) {\n call_user_func_array($slot, (array)$params);\n }\n }\n\n self::$sender = null;\n }\n\n\n /**\n * returns a current signal sender\n *\n * @return class|object\n */\n public static function sender() {\n return self::$sender;\n }\n\n} \n\nclass User {\n\n public function login() {\n /**\n * try to login\n */\n if ( ! $logged ) {\n SignalsHandler::signal(this, 'loginFailed', 'login failed - username not valid' );\n }\n }\n\n}\n\nclass App {\n public static function onFailedLogin($message) {\n print $message;\n }\n}\n\n\n$user = new User();\nSignalsHandler::connect($user, 'loginFailed', array($Log, 'writeLog'));\nSignalsHandler::connect($user, 'loginFailed', array('App', 'onFailedLogin'));\n\n$user->login();\n\n?>\n" }, { "answer_id": 933700, "author": "Volomike", "author_id": 105539, "author_profile": "https://Stackoverflow.com/users/105539", "pm_score": 6, "selected": false, "text": "extends <?php\n\n////////////////////\n// PART 1\n////////////////////\n\nclass Plugin {\n\n private $_RefObject;\n private $_Class = '';\n\n public function __construct(&$RefObject) {\n $this->_Class = get_class(&$RefObject);\n $this->_RefObject = $RefObject;\n }\n\n public function __set($sProperty,$mixed) {\n $sPlugin = $this->_Class . '_' . $sProperty . '_setEvent';\n if (is_callable($sPlugin)) {\n $mixed = call_user_func_array($sPlugin, $mixed);\n } \n $this->_RefObject->$sProperty = $mixed;\n }\n\n public function __get($sProperty) {\n $asItems = (array) $this->_RefObject;\n $mixed = $asItems[$sProperty];\n $sPlugin = $this->_Class . '_' . $sProperty . '_getEvent';\n if (is_callable($sPlugin)) {\n $mixed = call_user_func_array($sPlugin, $mixed);\n } \n return $mixed;\n }\n\n public function __call($sMethod,$mixed) {\n $sPlugin = $this->_Class . '_' . $sMethod . '_beforeEvent';\n if (is_callable($sPlugin)) {\n $mixed = call_user_func_array($sPlugin, $mixed);\n }\n if ($mixed != 'BLOCK_EVENT') {\n call_user_func_array(array(&$this->_RefObject, $sMethod), $mixed);\n $sPlugin = $this->_Class . '_' . $sMethod . '_afterEvent';\n if (is_callable($sPlugin)) {\n call_user_func_array($sPlugin, $mixed);\n } \n } \n }\n\n} //end class Plugin\n\nclass Pluggable extends Plugin {\n} //end class Pluggable\n\n////////////////////\n// PART 2\n////////////////////\n\nclass Dog {\n\n public $Name = '';\n\n public function bark(&$sHow) {\n echo \"$sHow<br />\\n\";\n }\n\n public function sayName() {\n echo \"<br />\\nMy Name is: \" . $this->Name . \"<br />\\n\";\n }\n\n\n} //end class Dog\n\n$Dog = new Dog();\n\n////////////////////\n// PART 3\n////////////////////\n\n$PDog = new Pluggable($Dog);\n\nfunction Dog_bark_beforeEvent(&$mixed) {\n $mixed = 'Woof'; // Override saying 'meow' with 'Woof'\n //$mixed = 'BLOCK_EVENT'; // if you want to block the event\n return $mixed;\n}\n\nfunction Dog_bark_afterEvent(&$mixed) {\n echo $mixed; // show the override\n}\n\nfunction Dog_Name_setEvent(&$mixed) {\n $mixed = 'Coco'; // override 'Fido' with 'Coco'\n return $mixed;\n}\n\nfunction Dog_Name_getEvent(&$mixed) {\n $mixed = 'Different'; // override 'Coco' with 'Different'\n return $mixed;\n}\n\n////////////////////\n// PART 4\n////////////////////\n\n$PDog->Name = 'Fido';\n$PDog->Bark('meow');\n$PDog->SayName();\necho 'My New Name is: ' . $PDog->Name;\n require_once() Dog_bark_beforeEvent() $mixed = 'BLOCK_EVENT' eval()" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/42", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37/" ]
48
<p>Let's say you create a wizard in an HTML form. One button goes back, and one goes forward. Since the <em>back</em> button appears first in the markup when you press <kbd>Enter</kbd>, it will use that button to submit the form.</p> <p>Example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;form&gt; &lt;!-- Put your cursor in this field and press Enter --&gt; &lt;input type="text" name="field1" /&gt; &lt;!-- This is the button that will submit --&gt; &lt;input type="submit" name="prev" value="Previous Page" /&gt; &lt;!-- But this is the button that I WANT to submit --&gt; &lt;input type="submit" name="next" value="Next Page" /&gt; &lt;/form&gt;</code></pre> </div> </div> </p> <p>I would like to get to decide which button is used to submit the form when a user presses <kbd>Enter</kbd>. That way, when you press <kbd>Enter</kbd> the wizard will move to the next page, not the previous. Do you have to use <code>tabindex</code> to do this?</p>
[ { "answer_id": 56, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 6, "selected": false, "text": "<input type=\"submit\" name=\"submitButton\" value=\"Previous Page\" />\n<input type=\"submit\" name=\"submitButton\" value=\"Next Page\" />\n submitButton name/value If Request.Form(\"submitButton\") = \"Previous Page\" Then\n ' Code for the previous page\nElseIf Request.Form(\"submitButton\") = \"Next Page\" Then\n ' Code for the next page\nEnd If\n" }, { "answer_id": 58, "author": "Wally Lawless", "author_id": 37, "author_profile": "https://Stackoverflow.com/users/37", "pm_score": 6, "selected": false, "text": "<input type=\"button\" name=\"prev\" value=\"Previous Page\" />\n default <input type=\"submit\" name=\"next\" value=\"Next Page\" default />\n" }, { "answer_id": 411, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 5, "selected": false, "text": "float" }, { "answer_id": 679, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 4, "selected": false, "text": "<SCRIPT TYPE=\"text/javascript\">//<!--\nfunction submitenter(myfield,e) {\n var keycode;\n if (window.event) {\n keycode = window.event.keyCode;\n } else if (e) {\n keycode = e.which;\n } else {\n return true;\n }\n\n if (keycode == 13) {\n myfield.form.submit();\n return false;\n } else {\n return true;\n }\n}\n//--></SCRIPT>\n\n<INPUT NAME=\"MyText\" TYPE=\"Text\" onKeyPress=\"return submitenter(this,event)\" />\n" }, { "answer_id": 2452, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "<form>\n <input type=\"text\" name=\"field1\" /><!-- Put your cursor in this field and press Enter -->\n <input type=\"submit\" name=\"prev\" value=\"Previous Page\" /> <!-- This is the button that will submit -->\n <input type=\"submit\" name=\"next\" value=\"Next Page\" /> <!-- But this is the button that I WANT to submit -->\n</form>\n If \"prev\" submitted then\n Previous Page was click\nElse If \"next\" submitted then\n Next Page was click\nElse\n No button was click\n" }, { "answer_id": 31910, "author": "palotasb", "author_id": 3063, "author_profile": "https://Stackoverflow.com/users/3063", "pm_score": 8, "selected": true, "text": "float Prev Next Next .f {\n float: right;\n}\n.clr {\n clear: both;\n} <form action=\"action\" method=\"get\">\n <input type=\"text\" name=\"abc\">\n <div id=\"buttons\">\n <input type=\"submit\" class=\"f\" name=\"next\" value=\"Next\">\n <input type=\"submit\" class=\"f\" name=\"prev\" value=\"Prev\">\n <div class=\"clr\"></div><!-- This div prevents later elements from floating with the buttons. Keeps them 'inside' div#buttons -->\n </div>\n</form> type=\"submit\"" }, { "answer_id": 71322, "author": "Jolyon", "author_id": 11740, "author_profile": "https://Stackoverflow.com/users/11740", "pm_score": 4, "selected": false, "text": "<form>\n <p><input type=\"text\" name=\"field1\" /></p>\n <p><a href=\"previous.html\">\n <button type=\"button\">Previous Page</button></a>\n <button type=\"submit\">Next Page</button></p>\n</form>\n <form>\n <p><input type=\"text\" name=\"field1\" /></p>\n <p><a href=\"previous.html\">\n <button type=\"button\" onclick=\"window.location='previous.html'\">Previous Page</button></a>\n <button type=\"submit\">Next Page</button></p>\n</form>\n" }, { "answer_id": 71629, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": 4, "selected": false, "text": "Next Prev" }, { "answer_id": 10894669, "author": "jayu", "author_id": 1427636, "author_profile": "https://Stackoverflow.com/users/1427636", "pm_score": 3, "selected": false, "text": "<input type=\"submit\" name=\"prev\" value=\"Previous Page\"> \n<input type=\"submit\" name=\"prev\" value=\"Next Page\"> \n value btnID = \"\"\nif Request.Form(\"prev\") = \"Previous Page\" then\n btnID = \"1\"\nelse if Request.Form(\"prev\") = \"Next Page\" then\n btnID = \"2\"\nend if\n" }, { "answer_id": 13084655, "author": "netiul", "author_id": 669073, "author_profile": "https://Stackoverflow.com/users/669073", "pm_score": 5, "selected": false, "text": "<html>\n<head>\n <style>\n div.defaultsubmitbutton {\n display: none;\n }\n </style>\n</head>\n<body>\n <form action=\"action\" method=\"get\">\n <div class=\"defaultsubmitbutton\">\n <input type=\"submit\" name=\"next\" value=\"Next\">\n </div>\n <p><input type=\"text\" name=\"filter\"><input type=\"submit\" value=\"Filter\"></p>\n <p>Filtered results</p>\n <input type=\"radio\" name=\"choice\" value=\"1\">Filtered result 1\n <input type=\"radio\" name=\"choice\" value=\"2\">Filtered result 2\n <input type=\"radio\" name=\"choice\" value=\"3\">Filtered result 3\n <div>\n <input type=\"submit\" name=\"prev\" value=\"Prev\">\n <input type=\"submit\" name=\"next\" value=\"Next\">\n </div>\n </form>\n</body>\n</html>" }, { "answer_id": 22139927, "author": "Samuel Mugisha", "author_id": 1223431, "author_profile": "https://Stackoverflow.com/users/1223431", "pm_score": 3, "selected": false, "text": "if <form>\n <input type=\"text\" name=\"field1\" /> <!-- Put your cursor in this field and press Enter -->\n\n <input type=\"submit\" name=\"prev\" value=\"Previous Page\" /> <!-- This is the button that will submit -->\n <input type=\"submit\" name=\"next\" value=\"Next Page\" /> <!-- But this is the button that I WANT to submit -->\n</form>\n if(isset($_POST['prev']))\n{\n header(\"Location: previous.html\");\n die();\n}\n\nif(isset($_POST['next']))\n{\n header(\"Location: next.html\");\n die();\n}\n" }, { "answer_id": 22408408, "author": "user1591131", "author_id": 1591131, "author_profile": "https://Stackoverflow.com/users/1591131", "pm_score": 4, "selected": false, "text": "$(document).on(\"keydown\", function(event) {\n if (event.which.toString() == \"8\") {\n var findActiveElementsClosestForm = $(document.activeElement).closest(\"form\");\n\n if (findActiveElementsClosestForm && findActiveElementsClosestForm.length) {\n $(\"form#\" + findActiveElementsClosestForm[0].id + \" .secondary_button\").trigger(\"click\");\n }\n }\n}); <script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js\"></script>\n\n<form action=\"action\" method=\"get\" defaultbutton=\"TriggerOnEnter\">\n <input type=\"submit\" id=\"PreviousButton\" name=\"prev\" value=\"Prev\" class=\"secondary_button\" />\n <input type=\"submit\" id='TriggerOnEnter' name=\"next\" value=\"Next\" class=\"primary_button\" />\n</form>" }, { "answer_id": 29322619, "author": "nikkypx", "author_id": 1395009, "author_profile": "https://Stackoverflow.com/users/1395009", "pm_score": 3, "selected": false, "text": "<form>\n <input type=\"text\" name=\"field1\" /> <!-- put your cursor in this field and press Enter -->\n\n <input type=\"button\" name=\"prev\" value=\"Previous Page\" /> <!-- This is the button that will submit -->\n <input type=\"submit\" name=\"next\" value=\"Next Page\" /> <!-- But this is the button that I WANT to submit -->\n</form>\n" }, { "answer_id": 32007399, "author": "GuillaumeS", "author_id": 1448969, "author_profile": "https://Stackoverflow.com/users/1448969", "pm_score": 3, "selected": false, "text": "$('form').on('keypress', function(event) {\n if (event.which == 13) {\n $('input[name=\"prev\"]').prop('type', 'button');\n }\n});\n" }, { "answer_id": 32377058, "author": "MiddleAgedMutantNinjaProgrammer", "author_id": 832919, "author_profile": "https://Stackoverflow.com/users/832919", "pm_score": 3, "selected": false, "text": "@model myApp.Models.myModel\n\n<script type=\"text/javascript\">\n function doOperation(op) {\n document.getElementById(\"OperationId\").innerText = op;\n // you could also use Ajax to reference the element.\n }\n</script>\n\n<form>\n <input type=\"text\" id = \"TextFieldId\" name=\"TextField\" value=\"\" />\n <input type=\"hidden\" id=\"OperationId\" name=\"Operation\" value=\"\" />\n <input type=\"submit\" name=\"write\" value=\"Write\" onclick='doOperation(\"Write\")'/>\n <input type=\"submit\" name=\"read\" value=\"Read\" onclick='doOperation(\"Read\")'/>\n</form>\n // Do operation according to which submit button was clicked\n// based on the contents of the hidden Operation field.\nif (myModel.Operation == \"Read\")\n{\n // Do read logic\n}\nelse if (myModel.Operation == \"Write\")\n{\n // Do write logic\n}\nelse\n{\n // Do error logic\n}\n" }, { "answer_id": 36206414, "author": "Barry Franklin", "author_id": 680563, "author_profile": "https://Stackoverflow.com/users/680563", "pm_score": 3, "selected": false, "text": "UseSubmitBehavior <asp:Button runat=\"server\" ID=\"SumbitButton\" UseSubmitBehavior=\"False\" Text=\"Submit\" />\n" }, { "answer_id": 48171459, "author": "riskop", "author_id": 3760049, "author_profile": "https://Stackoverflow.com/users/3760049", "pm_score": 2, "selected": false, "text": "textfield <html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js\"></script>\n </head>\n\n <body>\n <form action=\"http://httpbin.org/post\" method=\"post\">\n If JavaScript is disabled, then you CAN submit the form\n with button1, button2 or button3.\n\n If you press enter on a text field, then the form is\n submitted with the first submit button.\n\n If JavaScript is enabled, then the submit typed buttons\n without the 'defaultSubmitButton' style are converted\n to button typed buttons.\n\n If you press Enter on a text field, then the form is\n submitted with the only submit button\n (the one with class defaultSubmitButton)\n\n If you click on any other button in the form, then the\n form is submitted with that button's value.\n\n <br />\n\n <input type=\"text\" name=\"text1\" ></input>\n <button type=\"submit\" name=\"action\" value=\"button1\" >button 1</button>\n <br />\n\n <input type=\"text\" name=\"text2\" ></input>\n <button type=\"submit\" name=\"action\" value=\"button2\" >button 2</button>\n <br />\n\n <input type=\"text\" name=\"text3\" ></input>\n <button class=\"defaultSubmitButton\" type=\"submit\" name=\"action\" value=\"button3\" >default button</button>\n </form>\n\n <script>\n $(document).ready(function(){\n\n /* Change submit typed buttons without the 'defaultSubmitButton'\n style to button typed buttons */\n $('form button[type=submit]').not('.defaultSubmitButton').each(function(){\n $(this).attr('type', 'button');\n });\n\n /* Clicking on button typed buttons results in:\n 1. Setting the form's submit button's value to\n the clicked button's value,\n 2. Clicking on the form's submit button */\n $('form button[type=button]').click(function( event ){\n var form = event.target.closest('form');\n var submit = $(\"button[type='submit']\",form).first();\n submit.val(event.target.value);\n submit.click();\n });\n });\n </script>\n </body>\n</html>" }, { "answer_id": 50015400, "author": "Jyoti mishra", "author_id": 4890885, "author_profile": "https://Stackoverflow.com/users/4890885", "pm_score": 1, "selected": false, "text": "Tabindex float HTML" }, { "answer_id": 65239408, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "input type=\"submit\" form <div id=\"carousel\" class=\"carousel slide\" data-ride=\"carousel\">\n <form action=\"index.php\" method=\"post\" class=\"carousel-inner\">\n <div class=\"carousel-item active\">\n <input type=\"text\" name=\"lastname\" placeholder=\"Lastname\"/>\n </div>\n <div class=\"carousel-item\">\n <input type=\"text\" name=\"firstname\" placeholder=\"Firstname\"/>\n </div>\n <div class=\"carousel-item\">\n <input type=\"submit\" name=\"submit\" value=\"Submit\"/>\n </div>\n </form>\n <a class=\"btn-secondary\" href=\"#carousel\" role=\"button\" data-slide=\"prev\">Previous page</a>\n <a class=\"btn-primary\" href=\"#carousel\" role=\"button\" data-slide=\"next\">Next page</a>\n</div>\n" }, { "answer_id": 65548916, "author": "Prince Owen", "author_id": 8058709, "author_profile": "https://Stackoverflow.com/users/8058709", "pm_score": -1, "selected": false, "text": "function(e) {\n const isArtificial = e.screenX === 0 && e.screenY === 0\n && e.x === 0 && e.y === 0\n && e.clientX === 0 && e.clientY === 0;\n\n if (isArtificial) {\n return; // DO NOTHING\n } else {\n // OPTIONAL: Don't submit the form when clicked\n // e.preventDefault();\n // e.stopPropagation();\n }\n\n // ...Natural code goes here\n}\n" }, { "answer_id": 65612020, "author": "Ajay Patidar", "author_id": 5340811, "author_profile": "https://Stackoverflow.com/users/5340811", "pm_score": 0, "selected": false, "text": "type button onclick jQuery(this).attr('type','submit'); type submit <form>\n <!-- Put your cursor in this field and press Enter -->\n <input type=\"text\" name=\"field1\" />\n\n <!-- This is the button that will submit -->\n <input type=\"button\" onclick=\"jQuery(this).attr('type','submit');\" name=\"prev\" value=\"Previous Page\" />\n\n <!-- But this is the button that I WANT to submit -->\n <input type=\"submit\" name=\"next\" value=\"Next Page\" />\n</form>\n" }, { "answer_id": 68941820, "author": "Stoppeye", "author_id": 14989607, "author_profile": "https://Stackoverflow.com/users/14989607", "pm_score": 1, "selected": false, "text": "order <div style=\"display: flex\">\n <input type=\"submit\" name=\"next\" value=\"Next Page\" style=\"order: 1\" />\n <input type=\"submit\" name=\"prev\" value=\"Previous Page\" style=\"order: 0\" />\n</div>\n" }, { "answer_id": 72097973, "author": "Motine", "author_id": 4007237, "author_profile": "https://Stackoverflow.com/users/4007237", "pm_score": 0, "selected": false, "text": "// example implementation\ndocument.addEventListener('DOMContentLoaded', (ev) => {\n for (const defaultSubmitInput of document.querySelectorAll('[data-default-submit]')) {\n for (const formInput of defaultSubmitInput.form.querySelectorAll('input')) {\n if (formInput.dataset.ignoreDefaultSubmit != undefined) { continue; }\n formInput.addEventListener('keypress', (ev) => {\n if (ev.keyCode == 13) {\n ev.preventDefault();\n defaultSubmitInput.click();\n }\n })\n }\n }\n}); <!-- example markup -->\n <form action=\"https://postman-echo.com/get\" method=\"get\">\n <input type=\"text\" name=\"field1\">\n <input type=\"submit\" name=\"submit\" value=\"other action\">\n <input type=\"submit\" name=\"submit\" value=\"default action\" data-default-submit> <!-- this button will be used on return -->\n </form> <input type=\"text\" name=\"field2\" data-ignore-default-submit> <!-- uses browser standard behaviour -->\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/48", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40/" ]
59
<p>I have a <code>DataTable</code> with a <code>Name</code> column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the <em>order by</em> clause.</p> <pre><code>var names = (from DataRow dr in dataTable.Rows orderby (string)dr["Name"] select (string)dr["Name"]).Distinct(); </code></pre> <p>Why does the <code>orderby</code> not get enforced?</p>
[ { "answer_id": 62, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 6, "selected": false, "text": "var names = (from DataRow dr in dataTable.Rows\n select (string)dr[\"Name\"]).Distinct().OrderBy( name => name );\n" }, { "answer_id": 4313, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "var names = (from dr in dataTable.Rows\n select (string)dr[\"Name\"]).Distinct().OrderBy(name => name);\n" }, { "answer_id": 43110, "author": "a7drew", "author_id": 4239, "author_profile": "https://Stackoverflow.com/users/4239", "pm_score": 6, "selected": true, "text": "x1 x1 x2 x2 x3" }, { "answer_id": 342600, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "var sortedTable = (from results in resultTable.AsEnumerable()\nselect (string)results[attributeList]).Distinct().OrderBy(name => name);\n" }, { "answer_id": 16261469, "author": "Gavin Fang", "author_id": 2010092, "author_profile": "https://Stackoverflow.com/users/2010092", "pm_score": 3, "selected": false, "text": "dataTable.Rows.Cast<DataRow>().select(dr => dr[\"Name\"].ToString()).Distinct().OrderBy(name => name);\n" }, { "answer_id": 51021828, "author": "Presto", "author_id": 8479567, "author_profile": "https://Stackoverflow.com/users/8479567", "pm_score": 2, "selected": false, "text": "dataTable.Rows.Cast<DataRow>().GroupBy(g => g[\"Name\"]).Select(s => s.First()).OrderBy(o => o[\"Name\"]);\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/59", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ]
66
<p>How do you page through a collection in LINQ given that you have a <code>startIndex</code> and a <code>count</code>?</p>
[ { "answer_id": 68, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 6, "selected": false, "text": "Skip Take var query = from i in ideas\n select i;\n\nvar paggedCollection = query.Skip(startIndex).Take(count);\n" }, { "answer_id": 4521, "author": "Mike Minutillo", "author_id": 358, "author_profile": "https://Stackoverflow.com/users/358", "pm_score": 7, "selected": true, "text": "IQueryable<T> var query = from i in ideas\n select i;\nvar pagedCollection = query.InPagesOf(10);\nvar pageOfIdeas = pagedCollection.Page(2);\n" }, { "answer_id": 6719914, "author": "Nico", "author_id": 452101, "author_profile": "https://Stackoverflow.com/users/452101", "pm_score": 4, "selected": false, "text": "const int pageSize = 10;\nconst int count = 100;\nconst int startIndex = 20;\n\nint took = 0;\nbool getNextPage;\nvar page = ideas.Skip(startIndex);\n\ndo\n{\n Console.WriteLine(\"Page {0}:\", (took / pageSize) + 1);\n foreach (var idea in page.Take(pageSize))\n {\n Console.WriteLine(idea);\n }\n\n took += pageSize;\n if (took < count)\n {\n Console.WriteLine(\"Next page (y/n)?\");\n char answer = Console.ReadLine().FirstOrDefault();\n getNextPage = default(char) != answer && 'y' == char.ToLowerInvariant(answer);\n\n if (getNextPage)\n {\n page = page.Skip(pageSize);\n }\n }\n}\nwhile (getNextPage && took < count);\n IEnumerator const int pageSize = 10;\nconst int count = 100;\nconst int startIndex = 20;\n\nint took = 0;\nbool getNextPage = true;\nusing (var page = ideas.Skip(startIndex).GetEnumerator())\n{\n do \n {\n Console.WriteLine(\"Page {0}:\", (took / pageSize) + 1);\n\n int currentPageItemNo = 0;\n while (currentPageItemNo++ < pageSize && page.MoveNext())\n {\n var idea = page.Current;\n Console.WriteLine(idea);\n }\n\n took += pageSize;\n if (took < count)\n {\n Console.WriteLine(\"Next page (y/n)?\");\n char answer = Console.ReadLine().FirstOrDefault();\n getNextPage = default(char) != answer && 'y' == char.ToLowerInvariant(answer);\n }\n }\n while (getNextPage && took < count);\n}\n Skip() ideas IEnumerable" }, { "answer_id": 9787122, "author": "Spoike", "author_id": 3713, "author_profile": "https://Stackoverflow.com/users/3713", "pm_score": 4, "selected": false, "text": "// assumes that the item collection is \"myItems\"\n\nint pageCount = (myItems.Count + PageSize - 1) / PageSize;\n\nIEnumerable<int> pageRange = Enumerable.Range(1, pageCount);\n // pageRange contains [1, 2, ... , pageCount]\n IEnumerable<Item> Skip Take pageRange IEnumerable<IEnumerable<Item>> pageRange\n .Select((page, index) => \n myItems\n .Skip(index*PageSize)\n .Take(PageSize));\n var pages = Enumerable\n .Range(0, pageCount)\n .Select((index) => myItems.Skip(index*PageSize).Take(PageSize));\n for (Enumerable<Item> page : pages) \n{\n // handle page\n\n for (Item item : page) \n {\n // handle item in page\n }\n}\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/66", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17/" ]
72
<p>I want to format my existing comments as 'RDoc comments' so they can be viewed using <code>ri</code>.</p> <p>What are some recommended resources for starting out using RDoc?</p>
[ { "answer_id": 23993, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 4, "selected": false, "text": ":main: --main :title: :section:" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/72", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
80
<p>I've written a database generation script in <a href="http://en.wikipedia.org/wiki/SQL" rel="noreferrer">SQL</a> and want to execute it in my <a href="http://en.wikipedia.org/wiki/Adobe_Integrated_Runtime" rel="noreferrer">Adobe AIR</a> application:</p> <pre><code>Create Table tRole ( roleID integer Primary Key ,roleName varchar(40) ); Create Table tFile ( fileID integer Primary Key ,fileName varchar(50) ,fileDescription varchar(500) ,thumbnailID integer ,fileFormatID integer ,categoryID integer ,isFavorite boolean ,dateAdded date ,globalAccessCount integer ,lastAccessTime date ,downloadComplete boolean ,isNew boolean ,isSpotlight boolean ,duration varchar(30) ); Create Table tCategory ( categoryID integer Primary Key ,categoryName varchar(50) ,parent_categoryID integer ); ... </code></pre> <p>I execute this in Adobe AIR using the following methods:</p> <pre><code>public static function RunSqlFromFile(fileName:String):void { var file:File = File.applicationDirectory.resolvePath(fileName); var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ) var strSql:String = stream.readUTFBytes(stream.bytesAvailable); NonQuery(strSql); } public static function NonQuery(strSQL:String):void { var sqlConnection:SQLConnection = new SQLConnection(); sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH)); var sqlStatement:SQLStatement = new SQLStatement(); sqlStatement.text = strSQL; sqlStatement.sqlConnection = sqlConnection; try { sqlStatement.execute(); } catch (error:SQLError) { Alert.show(error.toString()); } } </code></pre> <p>No errors are generated, however only <code>tRole</code> exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there a way to call multiple queries in one statement?</p>
[ { "answer_id": 124, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 5, "selected": true, "text": "var strSql:String = stream.readUTFBytes(stream.bytesAvailable); \nvar i:Number = 0;\nvar strSqlSplit:Array = strSql.split(\";\");\nfor (i = 0; i < strSqlSplit.length; i++){\n NonQuery(strSqlSplit[i].toString());\n}\n" }, { "answer_id": 10008, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": false, "text": "sqlite_prepare sqlite_prepare" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/80", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
85
<p>What are the best practices around creating flat file database structures in PHP?</p> <p>A lot of more matured PHP flat file frameworks out there which I attempt to implement SQL-like query syntax which is over the top for my purposes in most cases. (I would just use a database at that point).</p> <p>Are there any elegant tricks out there to get good performance and features with a small code overhead?</p>
[ { "answer_id": 87, "author": "saint_groceon", "author_id": 59, "author_profile": "https://Stackoverflow.com/users/59", "pm_score": 4, "selected": false, "text": "./content/YYYYMMDDHHMMSS/\n /tags \n/authors \n/comments \n glob() glob(\"content/*/tags/funny\"); \n" }, { "answer_id": 154, "author": "w-ll", "author_id": 146637, "author_profile": "https://Stackoverflow.com/users/146637", "pm_score": 7, "selected": true, "text": "$user = array(\"name\" => \"bob\", \n \"age\" => 20,\n \"websites\" => array(\"example.com\",\"bob.example.com\",\"bob2.example.com\"),\n \"and_one\" => \"more\");\n $dir = \"../userdata/\"; //make sure to put it bellow what the server can reach.\nfile_put_contents($dir.$user['name'],serialize($user));\n function &get_user($name){\n return unserialize(file_get_contents(\"../userdata/\".$name));\n}\n" }, { "answer_id": 90800, "author": "ofaurax", "author_id": 15209, "author_profile": "https://Stackoverflow.com/users/15209", "pm_score": 3, "selected": false, "text": "ofaurax|27|male|something|\nanother|24|unknown||\n...\n" }, { "answer_id": 111609, "author": "Mez", "author_id": 20010, "author_profile": "https://Stackoverflow.com/users/20010", "pm_score": 5, "selected": false, "text": "serialize() unserialize()" }, { "answer_id": 242850, "author": "Ryan McCue", "author_id": 2575, "author_profile": "https://Stackoverflow.com/users/2575", "pm_score": 3, "selected": false, "text": "<?php\n/**\n * Handler for persistent data files\n *\n * @author Ryan McCue <[email protected]>\n * @package Lilina\n * @version 1.0\n * @license http://opensource.org/licenses/gpl-license.php GNU Public License\n */\n\n/**\n * Handler for persistent data files\n *\n * @package Lilina\n */\nclass DataHandler {\n /**\n * Directory to store data.\n *\n * @since 1.0\n *\n * @var string\n */\n protected $directory;\n\n /**\n * Constructor, duh.\n *\n * @since 1.0\n * @uses $directory Holds the data directory, which the constructor sets.\n *\n * @param string $directory \n */\n public function __construct($directory = null) {\n if ($directory === null)\n $directory = get_data_dir();\n\n if (substr($directory, -1) != '/')\n $directory .= '/';\n\n $this->directory = (string) $directory;\n }\n\n /**\n * Prepares filename and content for saving\n *\n * @since 1.0\n * @uses $directory\n * @uses put()\n *\n * @param string $filename Filename to save to\n * @param string $content Content to save to cache\n */\n public function save($filename, $content) {\n $file = $this->directory . $filename;\n\n if(!$this->put($file, $content)) {\n trigger_error(get_class($this) . \" error: Couldn't write to $file\", E_USER_WARNING);\n return false;\n }\n\n return true;\n }\n\n /**\n * Saves data to file\n *\n * @since 1.0\n * @uses $directory\n *\n * @param string $file Filename to save to\n * @param string $data Data to save into $file\n */\n protected function put($file, $data, $mode = false) {\n if(file_exists($file) && file_get_contents($file) === $data) {\n touch($file);\n return true;\n }\n\n if(!$fp = @fopen($file, 'wb')) {\n return false;\n }\n\n fwrite($fp, $data);\n fclose($fp);\n\n $this->chmod($file, $mode);\n return true;\n\n }\n\n /**\n * Change the file permissions\n *\n * @since 1.0\n *\n * @param string $file Absolute path to file\n * @param integer $mode Octal mode\n */\n protected function chmod($file, $mode = false){\n if(!$mode)\n $mode = 0644;\n return @chmod($file, $mode);\n }\n\n /**\n * Returns the content of the cached file if it is still valid\n *\n * @since 1.0\n * @uses $directory\n * @uses check() Check if cache file is still valid\n *\n * @param string $id Unique ID for content type, used to distinguish between different caches\n * @return null|string Content of the cached file if valid, otherwise null\n */\n public function load($filename) {\n return $this->get($this->directory . $filename);\n }\n\n /**\n * Returns the content of the file\n *\n * @since 1.0\n * @uses $directory\n * @uses check() Check if file is valid\n *\n * @param string $id Filename to load data from\n * @return bool|string Content of the file if valid, otherwise null\n */\n protected function get($filename) {\n if(!$this->check($filename))\n return null;\n\n return file_get_contents($filename);\n }\n\n /**\n * Check a file for validity\n *\n * Basically just a fancy alias for file_exists(), made primarily to be\n * overriden.\n *\n * @since 1.0\n * @uses $directory\n *\n * @param string $id Unique ID for content type, used to distinguish between different caches\n * @return bool False if the cache doesn't exist or is invalid, otherwise true\n */\n protected function check($filename){\n return file_exists($filename);\n }\n\n /**\n * Delete a file\n *\n * @param string $filename Unique ID\n */\n public function delete($filename) {\n return unlink($this->directory . $filename);\n }\n}\n\n?>\n" }, { "answer_id": 13960906, "author": "jpcrevoisier", "author_id": 1916991, "author_profile": "https://Stackoverflow.com/users/1916991", "pm_score": 3, "selected": false, "text": "<?php\nfunction varname(&$var) {\n $oldvalue=$var;\n $var='AAAAB3NzaC1yc2EAAAABIwAAAQEAqytmUAQKMOj24lAjqKJC2Gyqhbhb+DmB9eDDb8+QcFI+QOySUpYDn884rgKB6EAtoFyOZVMA6HlNj0VxMKAGE+sLTJ40rLTcieGRCeHJ/TI37e66OrjxgB+7tngKdvoG5EF9hnoGc4eTMpVUDdpAK3ykqR1FIclgk0whV7cEn/6K4697zgwwb5R2yva/zuTX+xKRqcZvyaF3Ur0Q8T+gvrAX8ktmpE18MjnA5JuGuZFZGFzQbvzCVdN52nu8i003GEFmzp0Ny57pWClKkAy3Q5P5AR2BCUwk8V0iEX3iu7J+b9pv4LRZBQkDujaAtSiAaeG2cjfzL9xIgWPf+J05IQ==';\n foreach($GLOBALS as $var_name => $value) {\n if ($value === 'AAAAB3NzaC1yc2EAAAABIwAAAQEAqytmUAQKMOj24lAjqKJC2Gyqhbhb+DmB9eDDb8+QcFI+QOySUpYDn884rgKB6EAtoFyOZVMA6HlNj0VxMKAGE+sLTJ40rLTcieGRCeHJ/TI37e66OrjxgB+7tngKdvoG5EF9hnoGc4eTMpVUDdpAK3ykqR1FIclgk0whV7cEn/6K4697zgwwb5R2yva/zuTX+xKRqcZvyaF3Ur0Q8T+gvrAX8ktmpE18MjnA5JuGuZFZGFzQbvzCVdN52nu8i003GEFmzp0Ny57pWClKkAy3Q5P5AR2BCUwk8V0iEX3iu7J+b9pv4LRZBQkDujaAtSiAaeG2cjfzL9xIgWPf+J05IQ==')\n {\n $var=$oldvalue;\n return $var_name;\n }\n }\n $var=$oldvalue;\n return false;\n}\n\nfunction putphp(&$var, $file=false)\n {\n $varname=varname($var);\n if(!$file)\n {\n $file=$varname.'.php';\n }\n $pathinfo=pathinfo($file);\n if(file_exists($file))\n {\n if(is_dir($file))\n {\n $file=$pathinfo['dirname'].'/'.$pathinfo['basename'].'/'.$varname.'.php';\n }\n }\n file_put_contents($file,'<?php'.\"\\n\\$\".$varname.'='.var_export($var, true).\";\\n\");\n return true;\n}\n" }, { "answer_id": 14149357, "author": "Michael Burt", "author_id": 1947156, "author_profile": "https://Stackoverflow.com/users/1947156", "pm_score": 3, "selected": false, "text": "data|some text|more data\n\nrow 2 data|bla hbalh|more data\n #$% (Shift+345) ^&* (Shift+678) test data#$%blah blah#$%^&*new row#$%new row data 2 explode(\"#$%\", $data); use foreach, the explode again to separate columns" }, { "answer_id": 16339974, "author": "omran", "author_id": 2343402, "author_profile": "https://Stackoverflow.com/users/2343402", "pm_score": 3, "selected": false, "text": "- STRUCTURED\nRegular (table, row, column) format.\n[DATABASE]\n/ \\\nTX TableY\n \\_____________________________\n |ROW_0 Colum_0 Colum_1 Colum_2|\n |ROW_1 Colum_0 Colum_1 Colum_2|\n |_____________________________|\n- FREE\nMore creative data storing. You can store data in any structure you want for each (free) element, its similar to storing an array with a unique \"Id\".\n[DATABASE]\n/ \\\nEX ElementY (ID)\n \\________________\n |Field_0 Value_0 |\n |Field_1 Value_1 |\n |Field_2 Value_2 |\n |________________|\nrecall [ID]: get_free(\"ElementY\") --> array([Field_0]=>Value_0,[Field_1]=>Value_1...\n- MIXD (Mixed)\nMixed databases can store both free elements and tables.If you add a table to a free db or a free element to a structured db, flat fire will automatically convert FREE or SRCT to MIXD database.\n[DATABASE]\n/ \\\nEX TY\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/85", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59/" ]
88
<p>I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux).</p> <p>I have implemented <code>QueryPerformanceCounter</code> by giving the uSeconds since the process start up: </p> <pre><code>BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount) { gettimeofday(&amp;currentTimeVal, NULL); performanceCount-&gt;QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec); performanceCount-&gt;QuadPart *= (1000 * 1000); performanceCount-&gt;QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec); return true; } </code></pre> <p>This, coupled with <code>QueryPerformanceFrequency()</code> giving a constant 1000000 as the frequency, works well <b>on my machine</b>, giving me a 64-bit variable that contains <code>uSeconds</code> since the program's start-up.</p> <p>So <em>is this portable?</em> I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however.</p>
[ { "answer_id": 98, "author": "Louis Brandy", "author_id": 2089740, "author_profile": "https://Stackoverflow.com/users/2089740", "pm_score": 7, "selected": true, "text": "gettimeofday() gettimeofday() clock_gettime(CLOCK_MONOTONIC) clock_getres()" }, { "answer_id": 367, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 5, "selected": false, "text": "11867927879484732\n11867927879692217\nit took this long to call printf: 207485\n #include <stdio.h>\n#include <stdint.h>\n\ninline uint64_t rdtsc() {\n uint32_t lo, hi;\n __asm__ __volatile__ (\n \"xorl %%eax, %%eax\\n\"\n \"cpuid\\n\"\n \"rdtsc\\n\"\n : \"=a\" (lo), \"=d\" (hi)\n :\n : \"%ebx\", \"%ecx\");\n return (uint64_t)hi << 32 | lo;\n}\n\nmain()\n{\n unsigned long long x;\n unsigned long long y;\n x = rdtsc();\n printf(\"%lld\\n\",x);\n y = rdtsc();\n printf(\"%lld\\n\",y);\n printf(\"it took this long to call printf: %lld\\n\",y-x);\n}\n" }, { "answer_id": 522, "author": "Joe Shaw", "author_id": 156, "author_profile": "https://Stackoverflow.com/users/156", "pm_score": 3, "selected": false, "text": "gettimeofday() clock_gettime(CLOCK_MONOTONIC) clock_getres()" }, { "answer_id": 14807, "author": "Doug", "author_id": 1618, "author_profile": "https://Stackoverflow.com/users/1618", "pm_score": 2, "selected": false, "text": "clock_gettime(CLOCK_REALTIME) clock_getres(CLOCK_REALTIME)" }, { "answer_id": 14817, "author": "David Schlosnagle", "author_id": 1750, "author_profile": "https://Stackoverflow.com/users/1750", "pm_score": 4, "selected": false, "text": "clock_gettime(CLOCK_REALTIME)" }, { "answer_id": 11211298, "author": "bames53", "author_id": 365496, "author_profile": "https://Stackoverflow.com/users/365496", "pm_score": 3, "selected": false, "text": "<chrono> std::chrono::steady_clock std::chrono::duration std::chrono::microseconds" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/88", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
104
<p>In .NET perspective:</p> <ul> <li>What is a <a href="https://en.wikipedia.org/wiki/Memory_leak" rel="noreferrer">memory leak</a>?</li> <li>How can you determine whether your application leaks? What are the effects?</li> <li>How can you prevent a memory leak?</li> <li>If your application has memory leak, does it go away when the process exits or is killed? Or do memory leaks in your application affect other processes on the system even after process completion?</li> <li>And what about unmanaged code accessed via COM Interop and/or P/Invoke?</li> </ul>
[ { "answer_id": 2947, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 3, "selected": false, "text": "StreamReader sr;\nusing(sr = new StreamReader(\"somefile.txt\"))\n{\n //do some stuff\n}\n" }, { "answer_id": 4702, "author": "Joel Lucsy", "author_id": 645, "author_profile": "https://Stackoverflow.com/users/645", "pm_score": 3, "selected": false, "text": "IDispose IDispose Marshal.ReleaseCOMObject" }, { "answer_id": 12433, "author": "Martin", "author_id": 1529, "author_profile": "https://Stackoverflow.com/users/1529", "pm_score": 5, "selected": false, "text": "-=" }, { "answer_id": 30227, "author": "Gus Paul", "author_id": 3237, "author_profile": "https://Stackoverflow.com/users/3237", "pm_score": 4, "selected": false, "text": "SomeExternalClass.Changed += new EventHandler(HandleIt);\n .loadby sos mscorwks\n!dumpheap -stat -type <TypeName>\n System.GC.Collect() !dumpheap -stat -type <TypeName>" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39/" ]
109
<p>Recently our site has been deluged with the resurgence of the <a href="https://en.wikipedia.org/wiki/Asprox_botnet" rel="noreferrer">Asprox botnet</a> <a href="http://en.wikipedia.org/wiki/SQL_injection" rel="noreferrer">SQL injection</a> attack. Without going into details, the attack attempts to execute SQL code by encoding the <a href="http://en.wikipedia.org/wiki/Transact-SQL" rel="noreferrer">T-SQL</a> commands in an ASCII encoded BINARY string. It looks something like this:</p> <pre><code>DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x44004500...06F007200%20AS%20NVARCHAR(4000));EXEC(@S);-- </code></pre> <p>I was able to decode this in SQL, but I was a little wary of doing this since I didn't know exactly what was happening at the time.</p> <p>I tried to write a simple decode tool, so I could decode this type of text without even touching <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL&nbsp; Server</a>. The main part I need to be decoded is:</p> <pre><code>CAST(0x44004500...06F007200 AS NVARCHAR(4000)) </code></pre> <p>I've tried all of the following commands with no luck:</p> <pre><code>txtDecodedText.Text = System.Web.HttpUtility.UrlDecode(txtURLText.Text); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Convert.FromBase64String(txtURLText.Text)); </code></pre> <p>What is the proper way to translate this encoding without using SQL Server? Is it possible? I'll take VB.NET code since I'm familiar with that too.</p> <hr> <p>Okay, I'm sure I'm missing something here, so here's where I'm at.</p> <p>Since my input is a basic string, I started with just a snippet of the encoded portion - 4445434C41 (which translates to DECLA) - and the first attempt was to do this...</p> <pre><code>txtDecodedText.Text = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(txtURL.Text)); </code></pre> <p>...and all it did was return the exact same thing that I put in since it converted each character into is a byte.</p> <p>I realized that I need to parse every two characters into a byte manually since I don't know of any methods yet that will do that, so now my little decoder looks something like this:</p> <pre><code>while (!boolIsDone) { bytURLChar = byte.Parse(txtURLText.Text.Substring(intParseIndex, 2)); bytURL[intURLIndex] = bytURLChar; intParseIndex += 2; intURLIndex++; if (txtURLText.Text.Length - intParseIndex &lt; 2) { boolIsDone = true; } } txtDecodedText.Text = Encoding.UTF8.GetString(bytURL); </code></pre> <p>Things look good for the first couple of pairs, but then the loop balks when it gets to the "4C" pair and says that the string is in the incorrect format.</p> <p>Interestingly enough, when I step through the debugger and to the GetString method on the byte array that I was able to parse up to that point, I get ",-+" as the result.</p> <p>How do I figure out what I'm missing - do I need to do a "direct cast" for each byte instead of attempting to parse it?</p>
[ { "answer_id": 304, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": false, "text": "0x Encoding.UTF8.GetString 44 00 = D\n\n45 00 = E\n\n6F 00 = o\n\n72 00 = r\n" }, { "answer_id": 2585, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 6, "selected": true, "text": "Convert.ToString(Convert.ToChar(Int32.Parse(EncodedString.Substring(intParseIndex, 2), System.Globalization.NumberStyles.HexNumber)));\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
123
<p>Is there an existing application or library in <em>Java</em> which will allow me to convert a <code>CSV</code> data file to <code>XML</code> file? </p> <p>The <code>XML</code> tags would be provided through possibly the first row containing column headings.</p>
[ { "answer_id": 133, "author": "saint_groceon", "author_id": 59, "author_profile": "https://Stackoverflow.com/users/59", "pm_score": 2, "selected": false, "text": "String.split()" }, { "answer_id": 6726, "author": "Anthony Cramp", "author_id": 488, "author_profile": "https://Stackoverflow.com/users/488", "pm_score": 5, "selected": false, "text": "string,float1,float2,integer\nhello world,1.0,3.3,4\ngoodbye world,1e9,-3.3,45\nhello again,-1,23.33,456\nhello world 3,1.40,34.83,4999\nhello 2 world,9981.05,43.33,444\n #!/usr/bin/env groovy\n\ndef csvdata = []\nnew File(\"test.csv\").eachLine { line ->\n csvdata << line.split(',')\n}\n\ndef headers = csvdata[0]\ndef dataRows = csvdata[1..-1]\n\ndef xml = new groovy.xml.MarkupBuilder()\n\n// write 'root' element\nxml.root {\n dataRows.eachWithIndex { dataRow, index ->\n // write 'entry' element with 'id' attribute\n entry(id:index+1) {\n headers.eachWithIndex { heading, i ->\n // write each heading with associated content\n \"${heading}\"(dataRow[i])\n }\n }\n }\n}\n <root>\n <entry id='1'>\n <string>hello world</string>\n <float1>1.0</float1>\n <float2>3.3</float2>\n <integer>4</integer>\n </entry>\n <entry id='2'>\n <string>goodbye world</string>\n <float1>1e9</float1>\n <float2>-3.3</float2>\n <integer>45</integer>\n </entry>\n <entry id='3'>\n <string>hello again</string>\n <float1>-1</float1>\n <float2>23.33</float2>\n <integer>456</integer>\n </entry>\n <entry id='4'>\n <string>hello world 3</string>\n <float1>1.40</float1>\n <float2>34.83</float2>\n <integer>4999</integer>\n </entry>\n <entry id='5'>\n <string>hello 2 world</string>\n <float1>9981.05</float1>\n <float2>43.33</float2>\n <integer>444</integer>\n </entry>\n</root>\n" }, { "answer_id": 21413, "author": "Martin Klinke", "author_id": 1793, "author_profile": "https://Stackoverflow.com/users/1793", "pm_score": 4, "selected": false, "text": "BufferedReader reader = new BufferedReader(new InputStreamReader(\n Csv2Xml.class.getResourceAsStream(\"test.csv\")));\nStringBuilder xml = new StringBuilder();\nString lineBreak = System.getProperty(\"line.separator\");\nString line = null;\nList<String> headers = new ArrayList<String>();\nboolean isHeader = true;\nint count = 0;\nint entryCount = 1;\nxml.append(\"<root>\");\nxml.append(lineBreak);\nwhile ((line = reader.readLine()) != null) {\n StringTokenizer tokenizer = new StringTokenizer(line, \",\");\n if (isHeader) {\n isHeader = false;\n while (tokenizer.hasMoreTokens()) {\n headers.add(tokenizer.nextToken());\n }\n } else {\n count = 0;\n xml.append(\"\\t<entry id=\\\"\");\n xml.append(entryCount);\n xml.append(\"\\\">\");\n xml.append(lineBreak);\n while (tokenizer.hasMoreTokens()) {\n xml.append(\"\\t\\t<\");\n xml.append(headers.get(count));\n xml.append(\">\");\n xml.append(tokenizer.nextToken());\n xml.append(\"</\");\n xml.append(headers.get(count));\n xml.append(\">\");\n xml.append(lineBreak);\n count++;\n }\n xml.append(\"\\t</entry>\");\n xml.append(lineBreak);\n entryCount++;\n }\n}\nxml.append(\"</root>\");\nSystem.out.println(xml.toString());\n string,float1,float2,integer\nhello world,1.0,3.3,4\ngoodbye world,1e9,-3.3,45\nhello again,-1,23.33,456\nhello world 3,1.40,34.83,4999\nhello 2 world,9981.05,43.33,444\n <root>\n <entry id=\"1\">\n <string>hello world</string>\n <float1>1.0</float1>\n <float2>3.3</float2>\n <integer>4</integer>\n </entry>\n <entry id=\"2\">\n <string>goodbye world</string>\n <float1>1e9</float1>\n <float2>-3.3</float2>\n <integer>45</integer>\n </entry>\n <entry id=\"3\">\n <string>hello again</string>\n <float1>-1</float1>\n <float2>23.33</float2>\n <integer>456</integer>\n </entry>\n <entry id=\"4\">\n <string>hello world 3</string>\n <float1>1.40</float1>\n <float2>34.83</float2>\n <integer>4999</integer>\n </entry>\n <entry id=\"5\">\n <string>hello 2 world</string>\n <float1>9981.05</float1>\n <float2>43.33</float2>\n <integer>444</integer>\n </entry>\n</root>\n" }, { "answer_id": 53547, "author": "Laurent K", "author_id": 2965, "author_profile": "https://Stackoverflow.com/users/2965", "pm_score": 6, "selected": false, "text": "package fr.megiste.test;\n\nimport java.io.FileReader;\nimport java.io.FileWriter;\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport au.com.bytecode.opencsv.CSVReader;\n\nimport com.thoughtworks.xstream.XStream;\n\npublic class CsvToXml { \n\n public static void main(String[] args) {\n\n String startFile = \"./startData.csv\";\n String outFile = \"./outData.xml\";\n\n try {\n CSVReader reader = new CSVReader(new FileReader(startFile));\n String[] line = null;\n\n String[] header = reader.readNext();\n\n List out = new ArrayList();\n\n while((line = reader.readNext())!=null){\n List<String[]> item = new ArrayList<String[]>();\n for (int i = 0; i < header.length; i++) {\n String[] keyVal = new String[2];\n String string = header[i];\n String val = line[i];\n keyVal[0] = string;\n keyVal[1] = val;\n item.add(keyVal);\n }\n out.add(item);\n }\n\n XStream xstream = new XStream();\n\n xstream.toXML(out, new FileWriter(outFile,false));\n\n } catch (Exception e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n }\n}\n <list>\n <list>\n <string-array>\n <string>string</string>\n <string>hello world</string>\n </string-array>\n <string-array>\n <string>float1</string>\n <string>1.0</string>\n </string-array>\n <string-array>\n <string>float2</string>\n <string>3.3</string>\n </string-array>\n <string-array>\n <string>integer</string>\n <string>4</string>\n </string-array>\n </list>\n <list>\n <string-array>\n <string>string</string>\n <string>goodbye world</string>\n </string-array>\n <string-array>\n <string>float1</string>\n <string>1e9</string>\n </string-array>\n <string-array>\n <string>float2</string>\n <string>-3.3</string>\n </string-array>\n <string-array>\n <string>integer</string>\n <string>45</string>\n </string-array>\n </list>\n <list>\n <string-array>\n <string>string</string>\n <string>hello again</string>\n </string-array>\n <string-array>\n <string>float1</string>\n <string>-1</string>\n </string-array>\n <string-array>\n <string>float2</string>\n <string>23.33</string>\n </string-array>\n <string-array>\n <string>integer</string>\n <string>456</string>\n </string-array>\n </list>\n <list>\n <string-array>\n <string>string</string>\n <string>hello world 3</string>\n </string-array>\n <string-array>\n <string>float1</string>\n <string>1.40</string>\n </string-array>\n <string-array>\n <string>float2</string>\n <string>34.83</string>\n </string-array>\n <string-array>\n <string>integer</string>\n <string>4999</string>\n </string-array>\n </list>\n <list>\n <string-array>\n <string>string</string>\n <string>hello 2 world</string>\n </string-array>\n <string-array>\n <string>float1</string>\n <string>9981.05</string>\n </string-array>\n <string-array>\n <string>float2</string>\n <string>43.33</string>\n </string-array>\n <string-array>\n <string>integer</string>\n <string>444</string>\n </string-array>\n </list>\n</list>\n" }, { "answer_id": 144768, "author": "kolrie", "author_id": 14540, "author_profile": "https://Stackoverflow.com/users/14540", "pm_score": 4, "selected": false, "text": "@FixedLengthRecord()\npublic class Customer {\n @FieldFixedLength(4)\n public Integer custId;\n\n @FieldAlign(alignMode=AlignMode.Right)\n @FieldFixedLength(20)\n public String name;\n\n @FieldFixedLength(3)\n public Integer rating;\n\n @FieldTrim(trimMode=TrimMode.Right)\n @FieldFixedLength(10)\n @FieldConverter(converter = ConverterKind.Date, \n format = \"dd-MM-yyyy\")\n public Date addedDate;\n\n @FieldFixedLength(3)\n @FieldOptional\n public String stockSimbol; \n}\n FileHelperEngine<Customer> engine = \n new FileHelperEngine<Customer>(Customer.class); \nList<Customer> customers = \n new ArrayList<Customer>();\n\ncustomers = engine.readResource(\n \"/samples/customers-fixed.txt\");\n" }, { "answer_id": 161058, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 4, "selected": false, "text": "contacts.xml contactData.csv def file1 = new File('c:\\\\temp\\\\ContactData.csv')\ndef file2 = new File('c:\\\\temp\\\\contacts.xml')\n\ndef reader = new FileReader(file1)\ndef writer = new FileWriter(file2)\n\nreader.transformLine(writer) { line ->\n fields = line.split(',')\n\n text = \"\"\"<CLIENTS>\n <firstname> ${fields[2]} </firstname>\n <surname> ${fields[1]} </surname>\n <email> ${fields[9]} </email>\n <employeenumber> password </employeenumber>\n <title> ${fields[4]} </title>\n <phone> ${fields[3]} </phone>\n </CLIENTS>\"\"\"\n}\n" }, { "answer_id": 29953381, "author": "StaxMan", "author_id": 59501, "author_profile": "https://Stackoverflow.com/users/59501", "pm_score": 2, "selected": false, "text": "String List" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78/" ]
126
<p>What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method?</p> <p>I know that from outside of the object you should use a getter/setter, but from within would you just do:</p> <p>Java:</p> <pre><code>String property = this.property; </code></pre> <p>PHP:</p> <pre><code>$property = $this-&gt;property; </code></pre> <p>or would you do:</p> <p>Java:</p> <pre><code>String property = this.getProperty(); </code></pre> <p>PHP:</p> <pre><code>$property = $this-&gt;getProperty(); </code></pre> <p>Forgive me if my Java is a little off, it's been a year since I programmed in Java...</p> <p><strong>EDIT:</strong></p> <p>It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though...</p>
[ { "answer_id": 139, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 4, "selected": false, "text": "public function getName() {\n $this->incrementNameCalled();\n return $this->_getName();\n}\n\nprotected function _getName() {\n return $this->name;\n}\n $name = $this->_getName();\n" }, { "answer_id": 22111, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "get_property() $obj->object_property" }, { "answer_id": 98244, "author": "moffdub", "author_id": 10759, "author_profile": "https://Stackoverflow.com/users/10759", "pm_score": 5, "selected": false, "text": "getters getters setters getter getters setters Pen.dispenseInkOnto(Surface) Pen.getColor() getters" }, { "answer_id": 128396, "author": "Martin Spamer", "author_id": 15527, "author_profile": "https://Stackoverflow.com/users/15527", "pm_score": 3, "selected": false, "text": " doSomethingWithProperty() {\n doSomethingWith( this.property ) ;\n }\n doSomethingWithProperty( this.daysPerWeek() ) ;\n" }, { "answer_id": 128488, "author": "Unlabeled Meat", "author_id": 20291, "author_profile": "https://Stackoverflow.com/users/20291", "pm_score": 4, "selected": false, "text": "__get __set" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
145
<p>Does anyone know of a good way to compress or decompress files and folders in C# quickly? Handling large files might be necessary.</p>
[ { "answer_id": 2142, "author": "Dave Anderson", "author_id": 371, "author_profile": "https://Stackoverflow.com/users/371", "pm_score": 5, "selected": false, "text": "System.IO.Compression GZipStream DefaultStream public static byte[] Compress(byte[] data)\n{\n MemoryStream output = new MemoryStream();\n\n GZipStream gzip = new GZipStream(output, CompressionMode.Compress, true);\n gzip.Write(data, 0, data.Length);\n gzip.Close();\n\n return output.ToArray();\n}\n\npublic static byte[] Decompress(byte[] data)\n{\n MemoryStream input = new MemoryStream();\n input.Write(data, 0, data.Length);\n input.Position = 0;\n\n GZipStream gzip = new GZipStream(input, CompressionMode.Decompress, true);\n\n MemoryStream output = new MemoryStream();\n\n byte[] buff = new byte[64];\n int read = -1;\n\n read = gzip.Read(buff, 0, buff.Length);\n\n while (read > 0)\n {\n output.Write(buff, 0, read);\n read = gzip.Read(buff, 0, buff.Length);\n }\n\n gzip.Close();\n\n return output.ToArray();\n}\n" }, { "answer_id": 48174631, "author": "mohsen_1687", "author_id": 3311484, "author_profile": "https://Stackoverflow.com/users/3311484", "pm_score": 0, "selected": false, "text": "public async Task<string> CreateZipFile(string sourceDirectoryPath, string name)\n{\n var path = HostingEnvironment.MapPath(TempPath) + name;\n await Task.Run(() =>\n {\n if (File.Exists(path)) File.Delete(path);\n ZipFile.CreateFromDirectory(sourceDirectoryPath, path);\n });\n return path;\n}\n public async Task ExtractZipFile(string filePath, string destinationDirectoryName)\n{\n await Task.Run(() =>\n {\n var archive = ZipFile.Open(filePath, ZipArchiveMode.Read);\n foreach (var entry in archive.Entries)\n {\n entry.ExtractToFile(Path.Combine(destinationDirectoryName, entry.FullName), true);\n }\n archive.Dispose();\n });\n}\n public async Task ExtractZipFile(Stream zipFile, string destinationDirectoryName)\n{\n string filePath = HostingEnvironment.MapPath(TempPath) + Utility.GetRandomNumber(1, int.MaxValue);\n using (FileStream output = new FileStream(filePath, FileMode.Create))\n {\n await zipFile.CopyToAsync(output);\n }\n await Task.Run(() => ZipFile.ExtractToDirectory(filePath, destinationDirectoryName));\n await Task.Run(() => File.Delete(filePath));\n}\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87/" ]
146
<p>I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it. </p> <p>Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded?</p> <hr> <blockquote> <p>Is the play link a link to the actual mp3 file or to some javascript code that pops up a player?</p> <p>If the latter, you can easily add your own logging code in there to track the number of hits to it.</p> <p>If the former, you'll need something that can track the web server log itself and make that distinction. My hosting plan comes with Webalizer, which does this nicely.</p> </blockquote> <p>It's a javascript code so that answers that. </p> <p>However, it would be nice to know how to track downloads using the other method (without switching hosts).</p>
[ { "answer_id": 152, "author": "w-ll", "author_id": 146637, "author_profile": "https://Stackoverflow.com/users/146637", "pm_score": 6, "selected": true, "text": "$filename = base64_url_decode($_REQUEST['file']);\nheader(\"Cache-Control: public\");\nheader('Content-disposition: attachment; filename='.basename($filename));\nheader(\"Content-Transfer-Encoding: binary\");\nheader('Content-Length: '. filesize($filename));\n\n// Put either file counting code here, either a db or static files\n//\nreadfile($filename); //and spit the user the file\n\nfunction base64_url_decode($input) {\n return base64_decode(strtr($input, '-_,', '+/='));\n}\n function base64_url_encode($input) {\n return strtr(base64_encode($input), '+/=', '-_,');\n}\n" }, { "answer_id": 1507462, "author": "randomx", "author_id": 172896, "author_profile": "https://Stackoverflow.com/users/172896", "pm_score": 5, "selected": false, "text": "grep mp3 /var/log/httpd/access_log | wc\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30/" ]
163
<p>Stack Overflow has a subversion version number at the bottom:</p> <blockquote> <p>svn revision: 679</p> </blockquote> <p>I want to use such automatic versioning with my <code>.NET Web Site/Application</code>, Windows Forms, WPD projects/solutions.</p> <p>How do I implement this?</p>
[ { "answer_id": 166, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 5, "selected": false, "text": "$Id:$\n <div id=\"svnrevision\">svn revision: $Id:$</div>\n" }, { "answer_id": 9391, "author": "James Pogran", "author_id": 1083, "author_profile": "https://Stackoverflow.com/users/1083", "pm_score": 3, "selected": false, "text": "$rev" }, { "answer_id": 13258, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 5, "selected": false, "text": "CruiseControl.net" }, { "answer_id": 374153, "author": "Andrew", "author_id": 5662, "author_profile": "https://Stackoverflow.com/users/5662", "pm_score": 4, "selected": false, "text": "ASP.Net MVC" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
164
<p><strong>Edit:</strong> This question was written in 2008, which was like 3 internet ages ago. If this question is still relevant to your environment, please accept my condolences. Everyone else should convert into a format <a href="https://videojs.com/html5-video-support/" rel="noreferrer">supported by your browsers</a> (That would be H.264 if Internet Explorer is needed, and probably AV1, VP8/VP9 if not) and use the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video" rel="noreferrer"><code>&lt;video&gt;</code> element</a>.</p> <hr /> <p>We are using <a href="http://en.wikipedia.org/wiki/Windows_Media_Video" rel="noreferrer">WMV</a> videos on an internal site, and we are embedding them into web sites. This works quite well on Internet Explorer, but not on Firefox. I've found ways to make it work in Firefox, but then it stops working in Internet Explorer.</p> <p>We do not want to use Silverlight just yet, especially since we cannot be sure that all clients will be running Windows XP with Windows Media Player installed.</p> <p>Is there some sort of Universal Code that embeds WMP into both Internet Explorer and Firefox, or do we need to implement some user-agent-detection and deliver different HTML for different browsers?</p>
[ { "answer_id": 167, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 3, "selected": false, "text": "<![if !IE]>\n<p> Firefox only code</p>\n<![endif]>\n\n<!--[if IE]>\n<p>Internet Explorer only code</p>\n<![endif]-->\n" }, { "answer_id": 699, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 7, "selected": true, "text": "<object id=\"mediaplayer\" classid=\"clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95\" codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701\" standby=\"loading microsoft windows media player components...\" type=\"application/x-oleobject\" width=\"320\" height=\"310\">\n<param name=\"filename\" value=\"./test.wmv\">\n <param name=\"animationatstart\" value=\"true\">\n <param name=\"transparentatstart\" value=\"true\">\n <param name=\"autostart\" value=\"true\">\n <param name=\"showcontrols\" value=\"true\">\n <param name=\"ShowStatusBar\" value=\"true\">\n <param name=\"windowlessvideo\" value=\"true\">\n <embed src=\"./test.wmv\" autostart=\"true\" showcontrols=\"true\" showstatusbar=\"1\" bgcolor=\"white\" width=\"320\" height=\"310\">\n</object>\n" }, { "answer_id": 971, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 2, "selected": false, "text": "ffmpeg -i input.avi output.flv\n -b 500000" }, { "answer_id": 1227988, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": " <object id=\"MediaPlayer1\" width=\"690\" height=\"500\" classid=\"CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95\"\n codebase=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701\"\n standby=\"Loading Microsoft® Windows® Media Player components...\" type=\"application/x-oleobject\"\n >\n <param name=\"FileName\" value='<%= GetSource() %>' />\n <param name=\"AutoStart\" value=\"True\" />\n <param name=\"DefaultFrame\" value=\"mainFrame\" />\n <param name=\"ShowStatusBar\" value=\"0\" />\n <param name=\"ShowPositionControls\" value=\"0\" />\n <param name=\"showcontrols\" value=\"0\" />\n <param name=\"ShowAudioControls\" value=\"0\" />\n <param name=\"ShowTracker\" value=\"0\" />\n <param name=\"EnablePositionControls\" value=\"0\" />\n\n\n <!-- BEGIN PLUG-IN HTML FOR FIREFOX-->\n <embed type=\"application/x-mplayer2\" pluginspage=\"http://www.microsoft.com/Windows/MediaPlayer/\"\n src='<%= GetSource() %>' align=\"middle\" width=\"600\" height=\"500\" defaultframe=\"rightFrame\"\n id=\"MediaPlayer2\" />\n function playVideo() {\n try{\n if(-1 != navigator.userAgent.indexOf(\"MSIE\"))\n {\n var obj = document.getElementById(\"MediaPlayer1\");\n obj.Play();\n\n }\n else\n {\n var player = document.getElementById(\"MediaPlayer2\");\n player.controls.play();\n\n }\n } \n catch(error) {\n alert(error)\n } \n\n\n }\n" }, { "answer_id": 1689995, "author": "Vonzy", "author_id": 205189, "author_profile": "https://Stackoverflow.com/users/205189", "pm_score": 2, "selected": false, "text": "<object classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\" \n id=\"player\" width=\"320\" height=\"260\">\n <param name=\"url\" \n value=\"http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv\" />\n <param name=\"src\" \n value=\"http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv\" />\n <param name=\"showcontrols\" value=\"true\" />\n <param name=\"autostart\" value=\"true\" />\n <!--[if !IE]>-->\n <object type=\"video/x-ms-wmv\" \n data=\"http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv\" \n width=\"320\" height=\"260\">\n <param name=\"src\" \n value=\"http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv\" />\n <param name=\"autostart\" value=\"true\" />\n <param name=\"controller\" value=\"true\" />\n </object>\n <!--<![endif]-->\n</object>\n" }, { "answer_id": 16966864, "author": "Perseus", "author_id": 2354121, "author_profile": "https://Stackoverflow.com/users/2354121", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n function generateWindowsMediaPlayer(\n holderId, // String\n height, // Number\n width, // Number\n videoUrl // String\n // you can declare more arguments for more flexibility\n ) {\n var holder = document.getElementById(holderId);\n\n var player = '<object ';\n player += 'height=\"' + height.toString() + '\" ';\n player += 'width=\"' + width.toString() + '\" ';\n\n videoUrl = encodeURI(videoUrl); // Encode for special characters\n\n if (navigator.userAgent.indexOf(\"MSIE\") < 0) {\n // Chrome, Firefox, Opera, Safari\n //player += 'type=\"application/x-ms-wmp\" '; //Old Edition\n player += 'type=\"video/x-ms-wmp\" '; //New Edition, suggested by MNRSullivan (Read Comments)\n player += 'data=\"' + videoUrl + '\" >';\n }\n else {\n // Internet Explorer\n player += 'classid=\"clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6\" >';\n player += '<param name=\"url\" value=\"' + videoUrl + '\" />';\n }\n\n player += '<param name=\"autoStart\" value=\"false\" />';\n player += '<param name=\"playCount\" value=\"1\" />';\n player += '</object>';\n\n holder.innerHTML = player;\n }\n</script>\n <div id='wmpHolder'></div>\n\n<script type=\"text/javascript\"> \n window.addEventListener('load', generateWindowsMediaPlayer('wmpHolder', 240, 320, 'http://mysite.com/path/video.ext'));\n</script>\n" }, { "answer_id": 65250970, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<video>" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
173
<p>I want to get my databases under version control.</p> <p>I'll always want to have at least <em>some</em> data in there (as <a href="https://stackoverflow.com/users/80/alumb">alumb</a> mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurements.</p> <p>How would I apply version control to my database?</p>
[ { "answer_id": 516, "author": "ESV", "author_id": 150, "author_profile": "https://Stackoverflow.com/users/150", "pm_score": 9, "selected": true, "text": "create table VersionHistory (\n Version int primary key,\n UpgradeStart datetime not null,\n UpgradeEnd datetime\n );\n" }, { "answer_id": 125609, "author": "Andrew Swan", "author_id": 10433, "author_profile": "https://Stackoverflow.com/users/10433", "pm_score": 3, "selected": false, "text": " <Relationship RelationshipID=\"1\" InternalName=\"Manager\"/>\n <Relationship RelationshipID=\"2\" InternalName=\"Delegate\"/>\n etc.\n" }, { "answer_id": 126936, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 3, "selected": false, "text": "IF ISNULL(OBJECT_ID('last_run_sysversions'), 0) <> 0 DROP TABLE last_run_sysversions\nCREATE TABLE last_run_sysversions (\n name varchar(128), \n id int, base_schema_ver int,\n schema_ver int,\n type char(2)\n)\n IF ISNULL(OBJECT_ID('tempdb.dbo.#tmp'), 0) <> 0 DROP TABLE #tmp\nCREATE TABLE #tmp (\n name varchar(128), \n id int, base_schema_ver int,\n schema_ver int,\n type char(2)\n)\n\nSET NOCOUNT ON\n\n-- Insert the values from the end of the last run into #tmp\nINSERT #tmp (name, id, base_schema_ver, schema_ver, type) \nSELECT name, id, base_schema_ver, schema_ver, type FROM last_run_sysversions\n\nDELETE last_run_sysversions\nINSERT last_run_sysversions (name, id, base_schema_ver, schema_ver, type)\nSELECT name, id, base_schema_ver, schema_ver, type FROM sysobjects\n\n-- This next bit lists all differences to scripts.\nSET NOCOUNT OFF\n\n--Renamed.\nSELECT 'renamed' AS ChangeType, t.name, o.name AS extra_info, 1 AS Priority\nFROM sysobjects o INNER JOIN #tmp t ON o.id = t.id\nWHERE o.name <> t.name /*COLLATE*/\nAND o.type IN ('TR', 'P' ,'U' ,'V')\nUNION \n\n--Changed (using alter)\nSELECT 'changed' AS ChangeType, o.name /*COLLATE*/, \n 'altered' AS extra_info, 2 AS Priority\nFROM sysobjects o INNER JOIN #tmp t ON o.id = t.id \nWHERE (\n o.base_schema_ver <> t.base_schema_ver\nOR o.schema_ver <> t.schema_ver\n)\nAND o.type IN ('TR', 'P' ,'U' ,'V')\nAND o.name NOT IN ( SELECT oi.name \n FROM sysobjects oi INNER JOIN #tmp ti ON oi.id = ti.id\n WHERE oi.name <> ti.name /*COLLATE*/\n AND oi.type IN ('TR', 'P' ,'U' ,'V')) \nUNION\n\n--Changed (actually dropped and recreated [but not renamed])\nSELECT 'changed' AS ChangeType, t.name, 'dropped' AS extra_info, 2 AS Priority\nFROM #tmp t\nWHERE t.name IN ( SELECT ti.name /*COLLATE*/ FROM #tmp ti\n WHERE NOT EXISTS (SELECT * FROM sysobjects oi\n WHERE oi.id = ti.id))\nAND t.name IN ( SELECT oi.name /*COLLATE*/ FROM sysobjects oi\n WHERE NOT EXISTS (SELECT * FROM #tmp ti\n WHERE oi.id = ti.id)\n AND oi.type IN ('TR', 'P' ,'U' ,'V'))\nUNION\n\n--Deleted\nSELECT 'deleted' AS ChangeType, t.name, '' AS extra_info, 0 AS Priority\nFROM #tmp t\nWHERE NOT EXISTS (SELECT * FROM sysobjects o\n WHERE o.id = t.id)\nAND t.name NOT IN ( SELECT oi.name /*COLLATE*/ FROM sysobjects oi\n WHERE NOT EXISTS (SELECT * FROM #tmp ti\n WHERE oi.id = ti.id)\n AND oi.type IN ('TR', 'P' ,'U' ,'V'))\nUNION\n\n--Added\nSELECT 'added' AS ChangeType, o.name /*COLLATE*/, '' AS extra_info, 4 AS Priority\nFROM sysobjects o\nWHERE NOT EXISTS (SELECT * FROM #tmp t\n WHERE o.id = t.id)\nAND o.type IN ('TR', 'P' ,'U' ,'V')\nAND o.name NOT IN ( SELECT ti.name /*COLLATE*/ FROM #tmp ti\n WHERE NOT EXISTS (SELECT * FROM sysobjects oi\n WHERE oi.id = ti.id))\nORDER BY Priority ASC\n /* COLLATE */ COLLATE Latin1_General_CI_AI" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
174
<p>I want to print HTML from a C# web service. The web browser control is overkill, and does not function well in a service environment, nor does it function well on a system with very tight security constraints. Is there any sort of free <code>.NET</code> library that will support the printing of a basic HTML page? Here is the code I have so far, which does not run properly.</p> <pre><code>public void PrintThing(string document) { if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA) { Thread thread = new Thread((ThreadStart) delegate { PrintDocument(document); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); } else { PrintDocument(document); } } protected void PrintDocument(string document) { WebBrowser browser = new WebBrowser(); browser.DocumentText = document; while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } browser.Print(); } </code></pre> <p>This works fine when called from UI-type threads, but nothing happens when called from a service-type thread. Changing <code>Print()</code> to <code>ShowPrintPreviewDialog()</code> yields the following IE script error:</p> <blockquote> <p><strong>Error:</strong> <code>dialogArguments.___IE_PrintType</code> is null or not an object. </p> <p>URL: <code>res://ieframe.dll/preview.dlg</code></p> </blockquote> <p>And a small empty print preview dialog appears.</p>
[ { "answer_id": 768, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 5, "selected": false, "text": "using (Process printProcess = new Process())\n{\n string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System);\n printProcess.StartInfo.FileName = systemPath + @\"\\rundll32.exe\";\n printProcess.StartInfo.Arguments = systemPath + @\"\\mshtml.dll,PrintHTML \"\"\" + fileToPrint + @\"\"\"\";\n printProcess.Start();\n}\n" }, { "answer_id": 11970128, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "-print-to-default $file.pdf -print-to $printer_name $file.pdf" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ]
175
<p>I want to be able to display a normal YouTube video with overlaid annotations, consisting of coloured rectangles for each frame. The only requirement is that this should be done programmatically. </p> <p>YouTube has annotations now, but require you to use their front end to create them by hand. I want to be able to generate them. What's the best way of doing this?</p> <p>Some ideas:</p> <blockquote> <ol> <li>Build your own Flash player (ew?)</li> <li>Somehow draw over the YouTube Flash player. Will this work?</li> <li>Reverse engineer &amp; hijack YouTube's annotation system. Either messing with the local files or redirecting its attempt to download the annotations. (using Greasemonkey? Firefox plugin?)</li> </ol> </blockquote> <p>Idea that doesn't count: </p> <blockquote> <p>download the video</p> </blockquote>
[ { "answer_id": 7157, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 3, "selected": false, "text": "annotation-thingamajig" }, { "answer_id": 65659, "author": "nerdabilly", "author_id": 8349, "author_profile": "https://Stackoverflow.com/users/8349", "pm_score": 4, "selected": false, "text": "WMODE=\"transparent\" <script type=\"text/javascript\">\n\n var params = { allowScriptAccess: \"always\" };\n var atts = { id: \"myytplayer\", wmode: \"transparent\" };\n swfobject.embedSWF(\"http://www.youtube.com/v/VIDEO_ID&enablejsapi=1&playerapiid=ytplayer\", \n \"ytapiplayer\", \"425\", \"356\", \"8\", null, null, params, atts);\n\n </script>\n" }, { "answer_id": 106818, "author": "marstonstudio", "author_id": 19447, "author_profile": "https://Stackoverflow.com/users/19447", "pm_score": 3, "selected": false, "text": "ReviewTube" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089740/" ]
176
<p>On one Linux Server running Apache and PHP 5, we have multiple Virtual Hosts with separate log files. We cannot seem to separate the php <code>error_log</code> between virtual hosts.</p> <p>Overriding this setting in the <code>&lt;Location&gt;</code> of the <code>httpd.conf</code> does not seem to do anything.</p> <p>Is there a way to have separate php <code>error_logs</code> for each Virtual Host?</p>
[ { "answer_id": 207, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 7, "selected": true, "text": "<VirtualHost IP:Port>\n # Stuff,\n # More Stuff,\n ErrorLog /path/where/you/want/the/error.log\n</VirtualHost>\n" }, { "answer_id": 297, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 4, "selected": false, "text": ".htaccess vhost.conf php_admin_value error_log \"/var/www/vhosts/example.com/error_log\"\n" }, { "answer_id": 6568, "author": "ejunker", "author_id": 796, "author_profile": "https://Stackoverflow.com/users/796", "pm_score": 2, "selected": false, "text": "<VirtualHost myvhost:80>\n ServerAdmin [email protected]\n DocumentRoot /opt/web\n ServerName myvhost\n ErrorLog logs/myvhost-error_log\n CustomLog logs/myvhost-access_log common\n</VirtualHost>\n" }, { "answer_id": 34044, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 3, "selected": false, "text": "php_value error_log '/path/to/php_error_log" }, { "answer_id": 118200, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": " <VirtualHost myvhost:80>\n php_value error_log \"/var/log/httpd/vhost_php_error_log\"\n </Virtual Host>\n" }, { "answer_id": 118222, "author": "James Hartig", "author_id": 45530, "author_profile": "https://Stackoverflow.com/users/45530", "pm_score": 3, "selected": false, "text": "php_value error_log \"/var/log/php_log\" \n .htaccess ini_set() php.ini php.ini error_log" }, { "answer_id": 1077264, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "php_value error_log \"/var/log/httpd/vhost_php_error_log\"\n error_log" }, { "answer_id": 2569128, "author": "rkulla", "author_id": 308062, "author_profile": "https://Stackoverflow.com/users/308062", "pm_score": 3, "selected": false, "text": "error_log syslog eg /var/log/apache2 ErrorLog subdir php_value error_log \"/path/to/project/logs\" .htaccess php_flag log_errors" }, { "answer_id": 3576664, "author": "Clutch", "author_id": 25143, "author_profile": "https://Stackoverflow.com/users/25143", "pm_score": 7, "selected": false, "text": "<VirtualHost *:80>\n ServerName example.com\n DocumentRoot /var/www/domains/example.com/html\n ErrorLog /var/www/domains/example.com/apache.error.log\n CustomLog /var/www/domains/example.com/apache.access.log common\n php_flag log_errors on\n php_flag display_errors on\n php_value error_reporting 2147483647\n php_value error_log /var/www/domains/example.com/php.error.log\n</VirtualHost>\n display_error php.error.log error_reporting" }, { "answer_id": 50618440, "author": "Parveen Chauhan", "author_id": 7013481, "author_profile": "https://Stackoverflow.com/users/7013481", "pm_score": 2, "selected": false, "text": "thecontrolist.localhost 127.0.0.1 thecontrolist.localhost <VirtualHost *>\n ServerName thecontrolist.localhost\n ServerAlias thecontrolist.localhost\n DocumentRoot \"/xampp/htdocs/thecontrolist\"\n <Directory \"/xampp/htdocs/thecontrolist\">\n Options +Indexes +Includes +FollowSymLinks +MultiViews\n AllowOverride All\n Require local\n </Directory>\n</VirtualHost>\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
180
<p>This is something I've pseudo-solved many times and have never quite found a solution for.</p> <p>The problem is to come up with a way to generate <code>N</code> colors, that are as distinguishable as possible where <code>N</code> is a parameter.</p>
[ { "answer_id": 199, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 2, "selected": false, "text": "//colors entered as 0-255 [R, G, B]\ncolors = []; //holds final colors to be used\nrand = new Random();\n\n//assumes n is less than 16,777,216\nrandomGen(int n){\n while (len(colors) < n){\n //generate a random number between 0,255 for each color\n newRed = rand.next(256);\n newGreen = rand.next(256);\n newBlue = rand.next(256);\n temp = [newRed, newGreen, newBlue];\n //only adds new colors to the array\n if temp not in colors {\n colors.append(temp);\n }\n }\n}\n for item in color{\n itemSq = (item[0]^2 + item[1]^2 + item[2]^2])^(.5);\n tempSq = (temp[0]^2 + temp[1]^2 + temp[2]^2])^(.5);\n dist = itemSq - tempSq;\n dist = abs(dist);\n}\n//NUMBER can be your chosen distance apart.\nif dist < NUMBER and temp not in colors {\n colors.append(temp);\n}\n" }, { "answer_id": 539, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 6, "selected": true, "text": "n = 10\n" }, { "answer_id": 143966, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 3, "selected": false, "text": "class cColorPicker\n{\npublic:\n void Pick( vector<DWORD>&v_picked_cols, int count, int bright = 50 );\nprivate:\n DWORD HSL2RGB( int h, int s, int v );\n unsigned char ToRGB1(float rm1, float rm2, float rh);\n};\n/**\n\n Evenly allocate RGB colors around HSL color wheel\n\n @param[out] v_picked_cols a vector of colors in RGB format\n @param[in] count number of colors required\n @param[in] bright 0 is all black, 100 is all white, defaults to 50\n\n based on Fig 3 of http://epub.wu-wien.ac.at/dyn/virlib/wp/eng/mediate/epub-wu-01_c87.pdf?ID=epub-wu-01_c87\n\n*/\n\nvoid cColorPicker::Pick( vector<DWORD>&v_picked_cols, int count, int bright )\n{\n v_picked_cols.clear();\n for( int k_hue = 0; k_hue < 360; k_hue += 360/count )\n v_picked_cols.push_back( HSL2RGB( k_hue, 100, bright ) );\n}\n/**\n\n Convert HSL to RGB\n\n based on http://www.codeguru.com/code/legacy/gdi/colorapp_src.zip\n\n*/\n\nDWORD cColorPicker::HSL2RGB( int h, int s, int l )\n{\n DWORD ret = 0;\n unsigned char r,g,b;\n\n float saturation = s / 100.0f;\n float luminance = l / 100.f;\n float hue = (float)h;\n\n if (saturation == 0.0) \n {\n r = g = b = unsigned char(luminance * 255.0);\n }\n else\n {\n float rm1, rm2;\n\n if (luminance <= 0.5f) rm2 = luminance + luminance * saturation; \n else rm2 = luminance + saturation - luminance * saturation;\n rm1 = 2.0f * luminance - rm2; \n r = ToRGB1(rm1, rm2, hue + 120.0f); \n g = ToRGB1(rm1, rm2, hue);\n b = ToRGB1(rm1, rm2, hue - 120.0f);\n }\n\n ret = ((DWORD)(((BYTE)(r)|((WORD)((BYTE)(g))<<8))|(((DWORD)(BYTE)(b))<<16)));\n\n return ret;\n}\n\n\nunsigned char cColorPicker::ToRGB1(float rm1, float rm2, float rh)\n{\n if (rh > 360.0f) rh -= 360.0f;\n else if (rh < 0.0f) rh += 360.0f;\n\n if (rh < 60.0f) rm1 = rm1 + (rm2 - rm1) * rh / 60.0f; \n else if (rh < 180.0f) rm1 = rm2;\n else if (rh < 240.0f) rm1 = rm1 + (rm2 - rm1) * (240.0f - rh) / 60.0f; \n\n return static_cast<unsigned char>(rm1 * 255);\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n vector<DWORD> myCols;\n cColorPicker colpick;\n colpick.Pick( myCols, 20 );\n for( int k = 0; k < (int)myCols.size(); k++ )\n printf(\"%d: %d %d %d\\n\", k+1,\n ( myCols[k] & 0xFF0000 ) >>16,\n ( myCols[k] & 0xFF00 ) >>8,\n ( myCols[k] & 0xFF ) );\n\n return 0;\n}\n" }, { "answer_id": 7815745, "author": "Mauro", "author_id": 678455, "author_profile": "https://Stackoverflow.com/users/678455", "pm_score": 2, "selected": false, "text": "function random_color($i = null, $n = 10, $sat = .5, $br = .7) {\n $i = is_null($i) ? mt_rand(0,$n) : $i;\n $rgb = hsv2rgb(array($i*(360/$n), $sat, $br));\n for ($i=0 ; $i<=2 ; $i++) \n $rgb[$i] = dechex(ceil($rgb[$i]));\n return implode('', $rgb);\n}\n\nfunction hsv2rgb($c) { \n list($h,$s,$v)=$c; \n if ($s==0) \n return array($v,$v,$v); \n else { \n $h=($h%=360)/60; \n $i=floor($h); \n $f=$h-$i; \n $q[0]=$q[1]=$v*(1-$s); \n $q[2]=$v*(1-$s*(1-$f)); \n $q[3]=$q[4]=$v; \n $q[5]=$v*(1-$s*$f); \n return(array($q[($i+4)%6]*255,$q[($i+2)%6]*255,$q[$i%6]*255)); //[1] \n } \n}\n random_color() $i $n $sat $br" }, { "answer_id": 21634390, "author": "Adi Shavit", "author_id": 135862, "author_profile": "https://Stackoverflow.com/users/135862", "pm_score": 2, "selected": false, "text": "K=N" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2089740/" ]
192
<p>One of the fun parts of multi-cultural programming is number formats.</p> <ul> <li>Americans use 10,000.50</li> <li>Germans use 10.000,50</li> <li>French use 10 000,50</li> </ul> <p>My first approach would be to take the string, parse it backwards until I encounter a separator and use this as my decimal separator. There is an obvious flaw with that: 10.000 would be interpreted as 10.</p> <p>Another approach: if the string contains 2 different non-numeric characters, use the last one as the decimal separator and discard the others. If I only have one, check if it occurs more than once and discards it if it does. If it only appears once, check if it has 3 digits after it. If yes, discard it, otherwise, use it as decimal separator.</p> <p>The obvious "best solution" would be to detect the User's culture or Browser, but that does not work if you have a Frenchman using an en-US Windows/Browser.</p> <p>Does the .net Framework contain some mythical black magic floating point parser that is better than <code>Double.(Try)Parse()</code> in trying to auto-detect the number format?</p>
[ { "answer_id": 210, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 5, "selected": false, "text": "double d = double.Parse(\"100.20\", CultureInfo.CurrentCulture);\n// -- OR --\ndouble d = double.Parse(\"100.20\", CultureInfo.CurrentUICulture);\n" }, { "answer_id": 212, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": false, "text": "double d = Double.Parse(\"5,000.00\", NumberStyles.Any, CultureInfo.InvariantCulture);\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
227
<p>I have the following arrays:</p> <pre><code>$artist = array("the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"); $count = array(5, 3, 9, 1, 1, 3); </code></pre> <p>I want to generate a tag cloud that will have artists with a higher number in <code>$count</code> enclosed in <code>h6</code> tags and the lowest enclosed <code>h1</code> tags.</p>
[ { "answer_id": 253, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 5, "selected": false, "text": "$artist = array(\"the roots\",\"michael jackson\",\"billy idol\",\"more\",\"and more\",\"and_YET_MORE\");\n$count = array(5,3,9,1,1,3);\n$highest = max($count);\nfor (int $x = 0; $x < count($artist); $x++)\n{\n $normalized = $count[$x] / $highest;\n $heading = ceil($normalized * 6); // 6 heading types\n echo \"<h\".$heading.\">\".$artist[$x].\"</h\".$heading.\">\";\n}\n" }, { "answer_id": 274, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 3, "selected": false, "text": "$artist = array(\"the roots\",\"michael jackson\",\"billy idol\",\"more\",\"and more\",\"and_YET_MORE\");\n$count = array(5,3,9,1,1,3);\n$highest = max($count);\nfor ($x = 0; $x < count($artist); $x++) {\n $normalized = ($highest - $count[$x]+1) / $highest;\n $heading = ceil($normalized * 6); // 6 heading types\n echo \"<h$heading>{$artist[$x]}</h$heading>\";\n}\n" }, { "answer_id": 676, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 5, "selected": false, "text": "hX span ol" }, { "answer_id": 87863, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<div id=\"tags\">\n <div class=\"title\">Popular Searches</div>\n <?php\n // Snippet taken from [prism-perfect.net]\n\n include \"/path/to/public_html/search/settings/database.php\";\n include \"/path/to/public_html/search/settings/conf.php\";\n\n $query = \"SELECT query AS tag, COUNT(*) AS quantity\n FROM sphider_query_log\n WHERE results > 0\n GROUP BY query\n ORDER BY query ASC\n LIMIT 10\";\n\n $result = mysql_query($query) or die(mysql_error());\n\n while ($row = mysql_fetch_array($result)) {\n\n $tags[$row['tag']] = $row['quantity'];\n }\n\n // change these font sizes if you will\n $max_size = 30; // max font size in %\n $min_size = 11; // min font size in %\n\n // get the largest and smallest array values\n $max_qty = max(array_values($tags));\n $min_qty = min(array_values($tags));\n\n // find the range of values\n $spread = $max_qty - $min_qty;\n if (0 == $spread) { // we don't want to divide by zero\n $spread = 1;\n }\n\n // determine the font-size increment\n // this is the increase per tag quantity (times used)\n $step = ($max_size - $min_size)/($spread);\n\n // loop through our tag array\n foreach ($tags as $key => $value) {\n\n // calculate CSS font-size\n // find the $value in excess of $min_qty\n // multiply by the font-size increment ($size)\n // and add the $min_size set above\n $size = $min_size + (($value - $min_qty) * $step);\n // uncomment if you want sizes in whole %:\n // $size = ceil($size);\n\n // you'll need to put the link destination in place of the /search/search.php...\n // (assuming your tag links to some sort of details page)\n echo '<a href=\"/search/search.php?query='.$key.'&search=1\" style=\"font-size: '.$size.'px\"';\n // perhaps adjust this title attribute for the things that are tagged\n echo ' title=\"'.$value.' things tagged with '.$key.'\"';\n echo '>'.$key.'</a> ';\n // notice the space at the end of the link\n }\n ?>\n</div>\n" }, { "answer_id": 164758, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "def tag_cloud (strings, counts)\n max = counts.max\n strings.map { |a| \"<span style='font-size:#{((counts[strings.index(a)] * 4.0)/max).ceil}em'>#{a}</span> \" }\nend\n <%= tag_cloud($artists, $counts) %>\n <span style='font-size:_em'> <span style='font-size:3em'>the roots</span>\n<span style='font-size:2em'>michael jackson</span> \n<span style='font-size:4em'>billy idol</span> \n<span style='font-size:1em'>more</span> \n<span style='font-size:1em'>and more</span> \n<span style='font-size:2em'>and_YET_MORE</span> \n class h1-h6 <span>" }, { "answer_id": 2943318, "author": "berkes", "author_id": 73673, "author_profile": "https://Stackoverflow.com/users/73673", "pm_score": 6, "selected": true, "text": "db_query('SELECT COUNT(*) AS count, id, name FROM ... ORDER BY count DESC');\n\n$steps = 6;\n$tags = array();\n$min = 1e9;\n$max = -1e9;\n\nwhile ($tag = db_fetch_object($result)) {\n $tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it\n $tag->count = log($tag->count);\n $min = min($min, $tag->count);\n $max = max($max, $tag->count);\n $tags[$tag->tid] = $tag;\n}\n// Note: we need to ensure the range is slightly too large to make sure even\n// the largest element is rounded down.\n$range = max(.01, $max - $min) * 1.0001;\n\nforeach ($tags as $key => $value) {\n $tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range);\n}\n foreach ($tags as $tag) {\n $output .= \"<h$tag->weight>$tag->name</h$tag->weight>\"\n}\n" }, { "answer_id": 3249162, "author": "danieli", "author_id": 83382, "author_profile": "https://Stackoverflow.com/users/83382", "pm_score": 2, "selected": false, "text": "SQL/PostgreSQL ORM public function getAllForTagCloud($fontSizes = 10)\n{\n $sql = sprintf(\"SELECT count(tag) as tagcount,tag,slug, \n floor((count(*) * %d )/(select max(t) from \n (select count(tag) as t from magazine_tag group by tag) t)::numeric(6,2)) \n as ranking \n from magazine_tag mt group by tag,slug\", $fontSizes);\n\n $q = Doctrine_Manager::getInstance()->getCurrentConnection();\n return $q->execute($sql);\n}\n <?php foreach ($allTags as $tag): ?>\n <span class=\"<?php echo 'tagrank'.$tag['ranking'] ?>\">\n <?php echo sprintf('<a rel=\"tag\" href=\"/search/by/tag/%s\">%s</a>', \n $tag['slug'], $tag['tag']\n ); ?>\n </span>\n<?php endforeach; ?>\n CSS /* put your size of choice */\n.tagrank1{font-size: 0.3em;}\n.tagrank2{font-size: 0.4em;}\n.tagrank3{font-size: 0.5em;} \n/* go on till tagrank10 */\n HAVING TO -- minimum tag count is 8 --\n\nHAVING count(tag) > 7\n" }, { "answer_id": 41906389, "author": "Durgaprasad", "author_id": 3391693, "author_profile": "https://Stackoverflow.com/users/3391693", "pm_score": 2, "selected": false, "text": "<?php\n$input= array(\"vba\",\"macros\",\"excel\",\"outlook\",\"powerpoint\",\"access\",\"database\",\"interview questions\",\"sendkeys\",\"word\",\"excel projects\",\"visual basic projects\",\"excel vba\",\"macro\",\"excel visual basic\",\"tutorial\",\"programming\",\"learn macros\",\"vba examples\");\n\n$rand_tags = array_rand($input, 5);\nfor ($x = 0; $x <= 4; $x++) {\n $size = rand ( 1 , 4 );\n echo \"<font size='$size'>\" . $input[$rand_tags[$x]] . \" \" . \"</font>\";\n}\n\necho \"<br>\";\n$rand_tags = array_rand($input, 7);\nfor ($x = 0; $x <= 6; $x++) {\n $size = rand ( 1 , 4 );\n echo \"<font size='$size'>\" . $input[$rand_tags[$x]] . \" \" . \"</font>\";\n}\n\necho \"<br>\";\n$rand_tags = array_rand($input, 5);\nfor ($x = 0; $x <= 4; $x++) {\n $size = rand ( 1 , 4 );\n echo \"<font size='$size'>\" . $input[$rand_tags[$x]] . \" \" . \"</font>\";\n}\n?>\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146637/" ]
231
<p>How do I make it so <code>mailto:</code> links will be registered with my program?</p> <p>How would I then handle that event in my program?</p> <p>Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as &quot;set as default email client&quot;.</p> <p>#Edit: Removed reference to Delphi, because the answer is independent of your language.</p>
[ { "answer_id": 233, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": false, "text": "[HKEY_CLASSES_ROOT\\mailto\\shell\\open\\command] (Default) REG_SZ Mail program command-line Delphi 7" }, { "answer_id": 1812, "author": "Liron Yahdav", "author_id": 62, "author_profile": "https://Stackoverflow.com/users/62", "pm_score": 5, "selected": true, "text": "<a href=\"mailto:[email protected]\">Email me</a>\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/62/" ]
234
<p>MySQL has this incredibly useful yet proprietary <code>REPLACE INTO</code> SQL Command. </p> <p>Can this easily be emulated in SQL Server 2005?</p> <p>Starting a new Transaction, doing a <code>Select()</code> and then either <code>UPDATE</code> or <code>INSERT</code> and <code>COMMIT</code> is always a little bit of a pain, especially when doing it in the application and therefore always keeping 2 versions of the statement.</p> <p>I wonder if there is an easy and <strong>universal</strong> way to implement such a function into SQL Server 2005?</p>
[ { "answer_id": 243, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": false, "text": "IF EXISTS (SELECT * FROM [Table] WHERE Id = X)\n UPDATE [Table] SET...\nELSE\n INSERT INTO [Table]\n" }, { "answer_id": 12202, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 7, "selected": true, "text": "upsert exists update insert --try an update\nupdate tablename \nset field1 = 'new value',\n field2 = 'different value',\n ...\nwhere idfield = 7\n\n--insert if failed\nif @@rowcount = 0 and @@error = 0\n insert into tablename \n ( idfield, field1, field2, ... )\n values ( 7, 'value one', 'another value', ... )\n merge merge tablename as target\nusing (values ('new value', 'different value'))\n as source (field1, field2)\n on target.idfield = 7\nwhen matched then\n update\n set field1 = source.field1,\n field2 = source.field2,\n ...\nwhen not matched then\n insert ( idfield, field1, field2, ... )\n values ( 7, source.field1, source.field2, ... )\n" }, { "answer_id": 112313, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 3, "selected": false, "text": "update t\nset hitCount = hitCount + 1\nwhere pk = @id\n\nif @@rowcount < 1 \nbegin \n begin tran\n update t with (serializable)\n set hitCount = hitCount + 1\n where pk = @id\n if @@rowcount = 0\n begin\n insert t (pk, hitCount)\n values (@id,1)\n end\n commit tran\nend\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
260
<p>I have a little game written in C#. It uses a database as back-end. It's a <a href="http://en.wikipedia.org/wiki/Collectible_card_game" rel="noreferrer">trading card game</a>, and I wanted to implement the function of the cards as a script.</p> <p>What I mean is that I essentially have an interface, <code>ICard</code>, which a card class implements (<code>public class Card056: ICard</code>) and which contains a function that is called by the game.</p> <p>Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies).</p> <p>Is that possible? Register a class from a source file and then instantiate it, etc.</p> <pre><code>ICard Cards[current] = new MyGame.CardLibrary.Card056(); Cards[current].OnEnterPlay(ref currentGameState); </code></pre> <p>The language is C# but extra bonus if it's possible to write the script in any .NET language.</p>
[ { "answer_id": 7217, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "CodeDomProvider CodeDomProvider.CompileAssemblyFromSource" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
263
<p>I have been trying to implement Win32's <code>MessageBox</code> using GTK. The app uses SDL/OpenGL, so this isn't a GTK app.</p> <p>I handle the initialization (<code>gtk_init</code>) sort of stuff inside the <code>MessageBox</code> function as follows:</p> <pre><code>int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type) { GtkWidget *window = NULL; GtkWidget *dialog = NULL; gtk_init(&amp;gtkArgc, &amp;gtkArgv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window), &quot;delete_event&quot;, G_CALLBACK(delete_event), NULL); g_signal_connect(G_OBJECT(window), &quot;destroy&quot;, G_CALLBACK(destroy), NULL); // gcallback calls gtk_main_quit() gtk_init_add((GtkFunction)gcallback, NULL); if (type &amp; MB_YESNO) { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text); } else { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text); } gtk_window_set_title(GTK_WINDOW(dialog), caption); gint result = gtk_dialog_run(GTK_DIALOG(dialog)); gtk_main(); gtk_widget_destroy(dialog); if (type &amp; MB_YESNO) { switch (result) { default: case GTK_RESPONSE_DELETE_EVENT: case GTK_RESPONSE_NO: return IDNO; break; case GTK_RESPONSE_YES: return IDYES; break; } } return IDOK; } </code></pre> <p>Now, I am by no means an experienced GTK programmer, and I realize that I'm probably doing something horribly wrong.</p> <p>However, my problem is that the last dialog popped up with this function staying around until the process exits. Any ideas?</p>
[ { "answer_id": 537, "author": "Joe Shaw", "author_id": 156, "author_profile": "https://Stackoverflow.com/users/156", "pm_score": 3, "selected": false, "text": "window window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\ng_signal_connect(G_OBJECT(window), \"delete_event\", G_CALLBACK(delete_event), NULL);\ng_signal_connect(G_OBJECT(window), \"destroy\", G_CALLBACK(destroy), NULL);\n gtk_main() gtk_dialog_run() gtk_init_add() gtk_main() gtk_widget_destroy()" }, { "answer_id": 607, "author": "Joe Shaw", "author_id": 156, "author_profile": "https://Stackoverflow.com/users/156", "pm_score": 5, "selected": true, "text": "typedef struct {\n int type;\n int result;\n} DialogData;\n \nstatic gboolean\ndisplay_dialog(gpointer user_data)\n{\n DialogData *dialog_data = user_data;\n GtkWidget *dialog;\n \n if (dialog_data->type & MB_YESNO)\n dialog = gtk_message_dialog_new(...);\n else\n dialog = gtk_message_dialog_new(...);\n \n // Set title, etc.\n \n dialog_data->result = gtk_dialog_run(...);\n \n gtk_main_quit(); // Quits the main loop run in MessageBox()\n \n return FALSE;\n}\n \nint MessageBox(...)\n{\n DialogData dialog_data;\n \n dialog_data.type = type;\n \n gtk_idle_add(display_dialog, &dialog_data);\n \n gtk_main();\n \n // Do stuff based on dialog_data.result\n}\n gtk_idle_add() FALSE display_dialog() gtk_main() MessageBox()" }, { "answer_id": 2959398, "author": "Platypus", "author_id": 356325, "author_profile": "https://Stackoverflow.com/users/356325", "pm_score": 3, "selected": false, "text": "int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type)\n{\n GtkWidget *dialog ;\n\n /* Instead of 0, use GTK_DIALOG_MODAL to get a modal dialog box */\n\n if (type & MB_YESNO)\n dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text );\n else\n dialog = gtk_message_dialog_new(NULL, 0, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text );\n\n\n gtk_window_set_title(GTK_WINDOW(dialog), caption);\n gint result = gtk_dialog_run(GTK_DIALOG(dialog));\n gtk_widget_destroy( GTK_WIDGET(dialog) );\n\n if (type & MB_YESNO)\n {\n switch (result)\n {\n default:\n case GTK_RESPONSE_DELETE_EVENT:\n case GTK_RESPONSE_NO:\n return IDNO;\n case GTK_RESPONSE_YES:\n return IDYES;\n }\n return IDOK;\n } \n}\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
265
<p>What are the best practices for checking in BIN directories in a collaborative development environment using SVN? Should project level references be excluded from checkin? Is it easier to just add all bin directories?</p> <p>I develop a lot of DotNetNuke sites and it seems that in a multi-developer environment, it's always a huge task to get the environment setup correctly.</p> <p>The ultimate goal (of course) is to have a new developer checkout the trunk from SVN, restore the DNN database and have it all just 'work'...</p>
[ { "answer_id": 266, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 5, "selected": true, "text": "-Project\n--Project.sln\n--References\n---StructureMap.dll\n---NUnit.dll\n---System.Web.Mvc.dll\n--Project.Web\n---Project.Web.Proj\n---Project.Web.Proj files\n--Project\n---Project.Proj\n---Project.Proj files\n" }, { "answer_id": 268, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 2, "selected": false, "text": "bin" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105/" ]
289
<p>I often have to sort a dictionary (consisting of keys &amp; values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.</p> <p>There is a <code>SortedList</code> which is good for a single value (say frequency), that I want to map back to the word.</p> <p><a href="http://msdn.microsoft.com/en-us/library/f7fta44c.aspx" rel="noreferrer">SortedDictionary</a> orders by key, not value. Some resort to a <a href="http://www.codeproject.com/KB/recipes/lookupcollection.aspx" rel="noreferrer">custom class</a>, but is there a cleaner way?</p>
[ { "answer_id": 291, "author": "Kalid", "author_id": 109, "author_profile": "https://Stackoverflow.com/users/109", "pm_score": 7, "selected": false, "text": "foreach (KeyValuePair<string,int> item in keywordCounts.OrderBy(key=> key.Value))\n{ \n // do something with item.Key and item.Value\n}\n" }, { "answer_id": 292, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 6, "selected": false, "text": "Dictionary<string, string> s = new Dictionary<string, string>();\ns.Add(\"1\", \"a Item\");\ns.Add(\"2\", \"c Item\");\ns.Add(\"3\", \"b Item\");\n\nList<KeyValuePair<string, string>> myList = new List<KeyValuePair<string, string>>(s);\nmyList.Sort(\n delegate(KeyValuePair<string, string> firstPair,\n KeyValuePair<string, string> nextPair)\n {\n return firstPair.Value.CompareTo(nextPair.Value);\n }\n);\n" }, { "answer_id": 298, "author": "Leon Bambrick", "author_id": 49, "author_profile": "https://Stackoverflow.com/users/49", "pm_score": 10, "selected": true, "text": "using System.Linq.Enumerable;\n...\nList<KeyValuePair<string, string>> myList = aDictionary.ToList();\n\nmyList.Sort(\n delegate(KeyValuePair<string, string> pair1,\n KeyValuePair<string, string> pair2)\n {\n return pair1.Value.CompareTo(pair2.Value);\n }\n);\n var myList = aDictionary.ToList();\n\nmyList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));\n" }, { "answer_id": 1332, "author": "caryden", "author_id": 313, "author_profile": "https://Stackoverflow.com/users/313", "pm_score": 9, "selected": false, "text": "Dictionary<string, int> myDict = new Dictionary<string, int>();\nmyDict.Add(\"one\", 1);\nmyDict.Add(\"four\", 4);\nmyDict.Add(\"two\", 2);\nmyDict.Add(\"three\", 3);\n\nvar sortedDict = from entry in myDict orderby entry.Value ascending select entry;\n type-ahead StartsWith" }, { "answer_id": 2569558, "author": "Alex Ruiz", "author_id": 308018, "author_profile": "https://Stackoverflow.com/users/308018", "pm_score": 2, "selected": false, "text": "SortedDictionary //Sorts sections according to the key value stored on \"sections\" unsorted dictionary, which is passed as a constructor argument\nSystem.Collections.Generic.SortedDictionary<int, string> sortedSections = null;\nif (sections != null)\n{\n sortedSections = new SortedDictionary<int, string>(sections);\n}\n sortedSections sections" }, { "answer_id": 2697521, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 3, "selected": false, "text": "SortedDictionary ListView Dim MyDictionary As SortedDictionary(Of String, MyDictionaryEntry)\n\nMyDictionaryListView.ItemsSource = MyDictionary.Values.OrderByDescending(Function(entry) entry.MyValue)\n\nPublic Class MyDictionaryEntry ' Need Property for GridViewColumn DisplayMemberBinding\n Public Property MyString As String\n Public Property MyValue As Integer\nEnd Class\n <ListView Name=\"MyDictionaryListView\">\n <ListView.View>\n <GridView>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=MyString}\" Header=\"MyStringColumnName\"></GridViewColumn>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=MyValue}\" Header=\"MyValueColumnName\"></GridViewColumn>\n </GridView>\n </ListView.View>\n</ListView>\n" }, { "answer_id": 3148631, "author": "mythz", "author_id": 85785, "author_profile": "https://Stackoverflow.com/users/85785", "pm_score": 4, "selected": false, "text": "var dictionary = new Dictionary<string, int> { { \"c\", 3 }, { \"a\", 1 }, { \"b\", 2 } };\ndictionary.OrderBy(x => x.Value)\n .ForEach(x => Console.WriteLine(\"{0}={1}\", x.Key,x.Value));\n" }, { "answer_id": 4157151, "author": "sean", "author_id": 82371, "author_profile": "https://Stackoverflow.com/users/82371", "pm_score": 8, "selected": false, "text": "var ordered = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);\n" }, { "answer_id": 6438343, "author": "Matt Frear", "author_id": 32598, "author_profile": "https://Stackoverflow.com/users/32598", "pm_score": 7, "selected": false, "text": "dict = dict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);\n" }, { "answer_id": 11630804, "author": "pawan Kumar", "author_id": 1548685, "author_profile": "https://Stackoverflow.com/users/1548685", "pm_score": -1, "selected": false, "text": "Dictionary <<string, string>> ShareUserNewCopy = \n ShareUserCopy.OrderBy(x => x.Value).ToDictionary(pair => pair.Key,\n pair => pair.Value); \n" }, { "answer_id": 13854099, "author": "Zar Shardan", "author_id": 913845, "author_profile": "https://Stackoverflow.com/users/913845", "pm_score": 5, "selected": false, "text": "var dict = new SortedDictionary<string, int>();\n// ToDo: populate dict\n\nvar output = dict.OrderBy(e => e.Value).Select(e => new {frequency = e.Value, word = e.Key}).ToList();\n\nforeach (var entry in output)\n{\n Console.WriteLine(\"frequency:{0}, word: {1}\",entry.frequency,entry.word);\n}\n" }, { "answer_id": 23975034, "author": "aggaton", "author_id": 1575416, "author_profile": "https://Stackoverflow.com/users/1575416", "pm_score": -1, "selected": false, "text": "var x = (from c in dict orderby c.Value.Order ascending select c).ToDictionary(c => c.Key, c=>c.Value);\n" }, { "answer_id": 28275964, "author": "Akshay Kapoor", "author_id": 4519513, "author_profile": "https://Stackoverflow.com/users/4519513", "pm_score": 2, "selected": false, "text": "Dictionary<int, int> dict = new Dictionary<int, int>();\ndict.Add(21,1041);\ndict.Add(213, 1021);\ndict.Add(45, 1081);\ndict.Add(54, 1091);\ndict.Add(3425, 1061);\ndict.Add(768, 1011);\n Dictionary<int, int> dctTemp = new Dictionary<int, int>();\nforeach (KeyValuePair<int, int> pair in dict.OrderBy(key => key.Value))\n{\n dctTemp.Add(pair.Key, pair.Value);\n}\n" }, { "answer_id": 31514791, "author": "mrfazolka", "author_id": 3536395, "author_profile": "https://Stackoverflow.com/users/3536395", "pm_score": 4, "selected": false, "text": "Dictionary<string, string> dic= new Dictionary<string, string>();\nvar ordered = dic.OrderBy(x => x.Value);\nreturn ordered.ToDictionary(t => t.Key, t => t.Value);\n" }, { "answer_id": 35645695, "author": "Qwertie", "author_id": 22820, "author_profile": "https://Stackoverflow.com/users/22820", "pm_score": 3, "selected": false, "text": "Key Value Bijection<K1, K2> Bijection<K1, K2> var dict = new Bijection<Key, Value>(new Dictionary<Key,Value>(), \n new SortedDictionary<Value,Key>());\n dict IDictionary<K, V> dict.Inverse Value Bijection<K1, K2> Bijection Dictionary<Key,Value> BMultiMap<Value,Key>" }, { "answer_id": 54885808, "author": "Ashish Kamble", "author_id": 6440372, "author_profile": "https://Stackoverflow.com/users/6440372", "pm_score": 3, "selected": false, "text": "OrderBy() var items = new Dictionary<string, int>();\nitems.Add(\"cat\", 0);\nitems.Add(\"dog\", 20);\nitems.Add(\"bear\", 100);\nitems.Add(\"lion\", 50);\n\n// Call OrderBy() method here on each item and provide them the IDs.\nforeach (var item in items.OrderBy(k => k.Key))\n{\n Console.WriteLine(item);// items are in sorted order\n}\n var sortedDictByOrder = items.OrderBy(v => v.Value);\n var sortedKeys = from pair in dictName\n orderby pair.Value ascending\n select pair;\n ClassName: IComparable<ClassName> compareTo(ClassName c)" }, { "answer_id": 61875551, "author": "Jaydeep Shil", "author_id": 3428626, "author_profile": "https://Stackoverflow.com/users/3428626", "pm_score": 2, "selected": false, "text": "using System.Linq; Dictionary<string, int> counts = new Dictionary<string, int>();\ncounts.Add(\"one\", 1);\ncounts.Add(\"four\", 4);\ncounts.Add(\"two\", 2);\ncounts.Add(\"three\", 3);\n foreach (KeyValuePair<string, int> kvp in counts.OrderByDescending(key => key.Value))\n{\n// some processing logic for each item if you want.\n}\n foreach (KeyValuePair<string, int> kvp in counts.OrderBy(key => key.Value))\n{\n// some processing logic for each item if you want.\n}\n" }, { "answer_id": 64841771, "author": "PeterK", "author_id": 418332, "author_profile": "https://Stackoverflow.com/users/418332", "pm_score": 1, "selected": false, "text": "var items = from pair in players_Dic\n orderby pair.Value descending\n select pair;\n\n// Display results.\nforeach (KeyValuePair<string, int> pair in items)\n{\n Debug.Log(pair.Key + \" - \" + pair.Value);\n}\n" }, { "answer_id": 72756303, "author": "Vineet Agarwal", "author_id": 7621734, "author_profile": "https://Stackoverflow.com/users/7621734", "pm_score": 0, "selected": false, "text": "var list = dict.Values.OrderByDescending(x => x).ToList();\nvar sortedData = dict.OrderBy(x => list.IndexOf(x.Value));\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
308
<p>I often run into the following problem.</p> <p>I work on some changes to a project that require new tables or columns in the database. I make the database modifications and continue my work. Usually, I remember to write down the changes so that they can be replicated on the live system. However, I don't always remember what I've changed and I don't always remember to write it down.</p> <p>So, I make a push to the live system and get a big, obvious error that there is no <code>NewColumnX</code>, ugh.</p> <p>Regardless of the fact that this may not be the best practice for this situation, is there a version control system for databases? I don't care about the specific database technology. I just want to know if one exists. If it happens to work with MS SQL Server, then great.</p>
[ { "answer_id": 38419, "author": "Mike Farmer", "author_id": 4082, "author_profile": "https://Stackoverflow.com/users/4082", "pm_score": 3, "selected": false, "text": "DBMS_METADATA.GET_DDL DBMS_METADATA.SET_TRANSFORM_PARAM DBMS_METADATA.GET_GRANTED_DDL" }, { "answer_id": 141765, "author": "dar7yl", "author_id": 9505, "author_profile": "https://Stackoverflow.com/users/9505", "pm_score": 5, "selected": false, "text": "CREATE TABLE Config\n(\n cfg_tag VARCHAR(50),\n cfg_value VARCHAR(100)\n);\n\nINSERT INTO Config(cfg_tag, cfg_value) VALUES\n( 'db_version', '$Revision: $'),\n( 'db_revision', '$Revision: $');\n UPDATE Config SET cfg_value='$Revision: $' WHERE cfg_tag='db_revision';\n db_version db_revision" }, { "answer_id": 3220892, "author": "Karussell", "author_id": 194609, "author_profile": "https://Stackoverflow.com/users/194609", "pm_score": 4, "selected": false, "text": "<createTable tableName=\"USER\"> \n <column name=\"firstname\" type=\"varchar(255)\"/>\n</createTable>\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106/" ]
328
<p>What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place!</p>
[ { "answer_id": 331, "author": "cmcculloh", "author_id": 58, "author_profile": "https://Stackoverflow.com/users/58", "pm_score": 4, "selected": false, "text": "register_globals $_REQUEST $_GET $_POST $username = $_POST[\"username\"];\n $username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);\n $username = filter_input(INPUT_POST, 'username');\n" }, { "answer_id": 1611, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 2, "selected": false, "text": "if ($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']\n || $_SESSION['user_ip'] != $_SERVER['REMOTE_ADDR'])\n{\n //Something fishy is going on here?\n}\n" }, { "answer_id": 7488, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 7, "selected": true, "text": "$_SERVER['HTTP_USER_AGENT']" }, { "answer_id": 14938, "author": "Dinoboff", "author_id": 1771, "author_profile": "https://Stackoverflow.com/users/1771", "pm_score": 2, "selected": false, "text": "php_value session.save_path \"/home/example.com/html/session\"" }, { "answer_id": 6754508, "author": "Chad", "author_id": 852876, "author_profile": "https://Stackoverflow.com/users/852876", "pm_score": 2, "selected": false, "text": "$_SESSION['fingerprint'] = md5($_SERVER['HTTP_USER_AGENT'] . PHRASE . $_SERVER['REMOTE_ADDR']);\n session_start();\nif ($_SESSION['fingerprint'] != md5($_SERVER['HTTP_USER_AGENT'] . PHRASE . $_SERVER['REMOTE_ADDR'])) { \n session_destroy();\n header('Location: http://website login page/');\n exit(); \n}\n" }, { "answer_id": 7748887, "author": "user956584", "author_id": 979474, "author_profile": "https://Stackoverflow.com/users/979474", "pm_score": 2, "selected": false, "text": "session.cookie_httponly = 1\nchange session name from default PHPSESSID\n X-XSS-Protection 1\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/59/" ]
336
<p>When is it appropriate to use an unsigned variable over a signed one? What about in a <code>for</code> loop?</p> <p>I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus. </p> <pre><code>for (unsigned int i = 0; i &lt; someThing.length(); i++) { SomeThing var = someThing.at(i); // You get the idea. } </code></pre> <p>I know Java doesn't have unsigned values, and that must have been a concious decision on <a href="https://en.wikipedia.org/wiki/Sun_Microsystems" rel="noreferrer">Sun Microsystems</a>' part. </p>
[ { "answer_id": 347, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 3, "selected": false, "text": "#declare BIT1 (unsigned int 1)\n#declare BIT32 (unsigned int reallybignumber)\n" }, { "answer_id": 354, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 3, "selected": false, "text": "size_t size_type" }, { "answer_id": 278817, "author": "Keith Sirmons", "author_id": 1048, "author_profile": "https://Stackoverflow.com/users/1048", "pm_score": 3, "selected": false, "text": "uint" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
337
<p>I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it. </p> <p>Unfortunately, whilst I know the XML model fairly well in .NET, I'm uncertain what the pros and cons are of the XML models in Python. </p> <p>Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple.</p>
[ { "answer_id": 342, "author": "saint_groceon", "author_id": 59, "author_profile": "https://Stackoverflow.com/users/59", "pm_score": 6, "selected": true, "text": "for expandNode()" }, { "answer_id": 202259, "author": "giltay", "author_id": 21106, "author_profile": "https://Stackoverflow.com/users/21106", "pm_score": 3, "selected": false, "text": "str.encode(codec, errors=\"xmlcharrefreplace\")" }, { "answer_id": 13832269, "author": "Arcturus", "author_id": 1527852, "author_profile": "https://Stackoverflow.com/users/1527852", "pm_score": 2, "selected": false, "text": "SAX - Simple API for XML XML API DOM XML" }, { "answer_id": 23143835, "author": "Jan Vlcinsky", "author_id": 346478, "author_profile": "https://Stackoverflow.com/users/346478", "pm_score": 3, "selected": false, "text": ">>> from lxml.builder import E\n\n>>> html = page = (\n... E.html( # create an Element called \"html\"\n... E.head(\n... E.title(\"This is a sample document\")\n... ),\n... E.body(\n... E.h1(\"Hello!\"),\n... E.p(\"This is a paragraph with \", E.b(\"bold\"), \" text in it!\"),\n... E.p(\"This is another paragraph, with a\", \"\\n \",\n... E.a(\"link\", href=\"http://www.python.org\"), \".\"),\n... E.p(\"Here are some reserved characters: <spam&egg>.\"),\n... )\n... )\n... )\n\n>>> print(etree.tostring(page, pretty_print=True))\n<html>\n <head>\n <title>This is a sample document</title>\n </head>\n <body>\n <h1>Hello!</h1>\n <p>This is a paragraph with <b>bold</b> text in it!</p>\n <p>This is another paragraph, with a\n <a href=\"http://www.python.org\">link</a>.</p>\n <p>Here are some reserved characters: &lt;spam&amp;egg&gt;.</p>\n </body>\n</html>\n from lxml import etree\nfrom lxml.builder import E\nlst = [\"alfa\", \"beta\", \"gama\"]\nxml = E.root(*[E.record(itm) for itm in lst])\netree.tostring(xml, pretty_print=True)\n <root>\n <record>alfa</record>\n <record>beta</record>\n <record>gama</record>\n</root>\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111/" ]
361
<p>How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.</p> <p>Any language would work, but it should be portable.</p>
[ { "answer_id": 362, "author": "alumb", "author_id": 80, "author_profile": "https://Stackoverflow.com/users/80", "pm_score": 7, "selected": true, "text": "list = originalString.split('')\nindex = (0,0)\nlist = [\"\"]\nfor iteration n in 1 to y:\n index = (index[1], len(list))\n for string s in list.subset(index[0] to end):\n for character c in originalString:\n list.add(s + c)\n" }, { "answer_id": 364, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "def perms(x, y, possible_characters)\n all = [\"\"]\n current_array = all.clone\n 1.upto(y) { |iteration|\n next_array = []\n current_array.each { |string|\n possible_characters.each { |c|\n value = string + c\n next_array.insert next_array.length, value\n all.insert all.length, value\n }\n }\n current_array = next_array\n }\n all.delete_if { |string| string.length < x }\nend\n" }, { "answer_id": 388, "author": "Brian Willis", "author_id": 118, "author_profile": "https://Stackoverflow.com/users/118", "pm_score": 3, "selected": false, "text": "public class GeneratePermutations {\n public static void main(String[] args) {\n int lower = Integer.parseInt(args[0]);\n int upper = Integer.parseInt(args[1]);\n\n if (upper < lower || upper == 0 || lower == 0) {\n System.exit(0);\n }\n\n for (int length = lower; length <= upper; length++) {\n generate(length, \"\");\n }\n }\n\n private static void generate(int length, String partial) {\n if (length <= 0) {\n System.out.println(partial);\n } else {\n for (char c = 'a'; c <= 'z'; c++) {\n generate(length - 1, partial + c);\n }\n }\n }\n}\n" }, { "answer_id": 64961, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "str = \"a\"\n100_000_000.times {puts str.next!}\n" }, { "answer_id": 69559, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "(defun perms (x y original-string)\n (loop with all = (list \"\")\n with current-array = (list \"\")\n for iteration from 1 to y\n do (loop with next-array = nil\n for string in current-array\n do (loop for c across original-string\n for value = (concatenate 'string string (string c))\n do (push value next-array)\n (push value all))\n (setf current-array (reverse next-array)))\n finally (return (nreverse (delete-if #'(lambda (el) (< (length el) x)) all)))))\n (defun perms (x y original-string)\n (loop repeat y\n collect (loop for string in (or (car (last sets)) (list \"\"))\n append (loop for c across original-string\n collect (concatenate 'string string (string c)))) into sets\n finally (return (loop for set in sets\n append (loop for el in set when (>= (length el) x) collect el)))))\n" }, { "answer_id": 147211, "author": "Sarp Centel", "author_id": 16622, "author_profile": "https://Stackoverflow.com/users/16622", "pm_score": 3, "selected": false, "text": "int main (int argc, char * const argv[]) {\n string s = \"sarp\";\n bool used [4];\n permute(0, \"\", used, s);\n}\n\nvoid permute(int level, string permuted, bool used [], string &original) {\n int length = original.length();\n\n if(level == length) { // permutation complete, display\n cout << permuted << endl;\n } else {\n for(int i=0; i<length; i++) { // try to add an unused character\n if(!used[i]) {\n used[i] = true;\n permute(level+1, original[i] + permuted, used, original); // find the permutations starting with this string\n used[i] = false;\n }\n }\n}\n" }, { "answer_id": 217209, "author": "Crackerjack", "author_id": 13556, "author_profile": "https://Stackoverflow.com/users/13556", "pm_score": 3, "selected": false, "text": "public ArrayList CalculateWordPermutations(string[] letters, ArrayList words, int index)\n {\n bool finished = true;\n ArrayList newWords = new ArrayList();\n if (words.Count == 0)\n {\n foreach (string letter in letters)\n {\n words.Add(letter);\n }\n }\n\n for(int j=index; j<words.Count; j++)\n {\n string word = (string)words[j];\n for(int i =0; i<letters.Length; i++)\n {\n if(!word.Contains(letters[i]))\n {\n finished = false;\n string newWord = (string)word.Clone();\n newWord += letters[i];\n newWords.Add(newWord);\n }\n }\n }\n\n foreach (string newWord in newWords)\n { \n words.Add(newWord);\n }\n\n if(finished == false)\n {\n CalculateWordPermutations(letters, words, words.Count - newWords.Count);\n }\n return words;\n }\n string[] letters = new string[]{\"a\",\"b\",\"c\"};\nArrayList words = CalculateWordPermutations(letters, new ArrayList(), 0);\n" }, { "answer_id": 550628, "author": "Chris Lutz", "author_id": 60777, "author_profile": "https://Stackoverflow.com/users/60777", "pm_score": 3, "selected": false, "text": "my @result = (\"a\" .. \"zzzz\");\n \"a\" \"A\" \"zzzz\" \"ZZZZ\"" }, { "answer_id": 2575419, "author": "Lazer", "author_id": 113124, "author_profile": "https://Stackoverflow.com/users/113124", "pm_score": 4, "selected": false, "text": "public class permute {\n\n static void permute(int level, String permuted,\n boolean used[], String original) {\n int length = original.length();\n if (level == length) {\n System.out.println(permuted);\n } else {\n for (int i = 0; i < length; i++) {\n if (!used[i]) {\n used[i] = true;\n permute(level + 1, permuted + original.charAt(i),\n used, original);\n used[i] = false;\n }\n }\n }\n }\n\n public static void main(String[] args) {\n String s = \"hello\";\n boolean used[] = {false, false, false, false, false};\n permute(0, \"\", used, s);\n }\n}\n" }, { "answer_id": 3178268, "author": "Prakhar Gupta", "author_id": 383513, "author_profile": "https://Stackoverflow.com/users/383513", "pm_score": 4, "selected": false, "text": " static public IEnumerable<string> permute(string word)\n {\n if (word.Length > 1)\n {\n\n char character = word[0];\n foreach (string subPermute in permute(word.Substring(1)))\n {\n\n for (int index = 0; index <= subPermute.Length; index++)\n {\n string pre = subPermute.Substring(0, index);\n string post = subPermute.Substring(index);\n\n if (post.Contains(character))\n continue; \n\n yield return pre + character + post;\n }\n\n }\n }\n else\n {\n yield return word;\n }\n }\n" }, { "answer_id": 4010695, "author": "Swapneel Patil", "author_id": 251769, "author_profile": "https://Stackoverflow.com/users/251769", "pm_score": 3, "selected": false, "text": "import java.util.*;\n\npublic class all_subsets {\n public static void main(String[] args) {\n String a = \"abcd\";\n for(String s: all_perm(a)) {\n System.out.println(s);\n }\n }\n\n public static Set<String> concat(String c, Set<String> lst) {\n HashSet<String> ret_set = new HashSet<String>();\n for(String s: lst) {\n ret_set.add(c+s);\n }\n return ret_set;\n }\n\n public static HashSet<String> all_perm(String a) {\n HashSet<String> set = new HashSet<String>();\n if(a.length() == 1) {\n set.add(a);\n } else {\n for(int i=0; i<a.length(); i++) {\n set.addAll(concat(a.charAt(i)+\"\", all_perm(a.substring(0, i)+a.substring(i+1, a.length()))));\n }\n }\n return set;\n }\n}\n" }, { "answer_id": 4134431, "author": "rocksportrocker", "author_id": 233813, "author_profile": "https://Stackoverflow.com/users/233813", "pm_score": 4, "selected": false, "text": "def nextPermutation(perm):\n k0 = None\n for i in range(len(perm)-1):\n if perm[i]<perm[i+1]:\n k0=i\n if k0 == None:\n return None\n\n l0 = k0+1\n for i in range(k0+1, len(perm)):\n if perm[k0] < perm[i]:\n l0 = i\n\n perm[k0], perm[l0] = perm[l0], perm[k0]\n perm[k0+1:] = reversed(perm[k0+1:])\n return perm\n\nperm=list(\"12345\")\nwhile perm:\n print perm\n perm = nextPermutation(perm)\n" }, { "answer_id": 4927100, "author": "Peyman", "author_id": 556778, "author_profile": "https://Stackoverflow.com/users/556778", "pm_score": 3, "selected": false, "text": "void permute(const char *s, char *out, int *used, int len, int lev)\n{\n if (len == lev) {\n out[lev] = '\\0';\n puts(out);\n return;\n }\n\n int i;\n for (i = 0; i < len; ++i) {\n if (! used[i])\n continue;\n\n used[i] = 1;\n out[lev] = s[i];\n permute(s, out, used, len, lev + 1);\n used[i] = 0;\n }\n return;\n}\n" }, { "answer_id": 5082432, "author": "raj", "author_id": 628891, "author_profile": "https://Stackoverflow.com/users/628891", "pm_score": 3, "selected": false, "text": "public static void main(String[] args) {\n\n for (String str : permStr(\"ABBB\")){\n System.out.println(str);\n }\n}\n\nstatic Vector<String> permStr(String str){\n\n if (str.length() == 1){\n Vector<String> ret = new Vector<String>();\n ret.add(str);\n return ret;\n }\n\n char start = str.charAt(0);\n Vector<String> endStrs = permStr(str.substring(1));\n Vector<String> newEndStrs = new Vector<String>();\n for (String endStr : endStrs){\n for (int j = 0; j <= endStr.length(); j++){\n if (endStr.substring(0, j).endsWith(String.valueOf(start)))\n break;\n newEndStrs.add(endStr.substring(0, j) + String.valueOf(start) + endStr.substring(j));\n }\n }\n return newEndStrs;\n}\n" }, { "answer_id": 6140144, "author": "Pedro", "author_id": 482019, "author_profile": "https://Stackoverflow.com/users/482019", "pm_score": 2, "selected": false, "text": "allowed_characters [0,1] ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111'] def generate_permutations(chars = 4) :\n\n#modify if in need!\n allowed_chars = [\n '0',\n '1',\n ]\n\n status = []\n for tmp in range(chars) :\n status.append(0)\n\n last_char = len(allowed_chars)\n\n rows = []\n for x in xrange(last_char ** chars) :\n rows.append(\"\")\n for y in range(chars - 1 , -1, -1) :\n key = status[y]\n rows[x] = allowed_chars[key] + rows[x]\n\n for pos in range(chars - 1, -1, -1) :\n if(status[pos] == last_char - 1) :\n status[pos] = 0\n else :\n status[pos] += 1\n break;\n\n return rows\n\nimport sys\n\n\nprint generate_permutations()\n" }, { "answer_id": 6922856, "author": "orion elenzil", "author_id": 230851, "author_profile": "https://Stackoverflow.com/users/230851", "pm_score": 3, "selected": false, "text": "out push() function oxe_perm(src, depth, index)\n{\n var perm = src.slice(); // duplicates src.\n perm = perm.split(\"\");\n perm[depth] = src[index];\n perm[index] = src[depth];\n perm = perm.join(\"\");\n return perm;\n}\n\nfunction oxe_permutations(src)\n{\n out = new Array();\n\n out.push(src);\n\n for (depth = 0; depth < src.length; depth++) {\n var numInPreviousPass = out.length;\n for (var m = 0; m < numInPreviousPass; ++m) {\n for (var n = depth + 1; n < src.length; ++n) {\n out.push(oxe_perm(out[m], depth, n));\n }\n }\n }\n\n return out;\n}\n" }, { "answer_id": 7625511, "author": "Anonymous Coward", "author_id": 975258, "author_profile": "https://Stackoverflow.com/users/975258", "pm_score": 2, "selected": false, "text": "Perm(1 To N) Stack(3 To N) Level 2 NextPerm Option Explicit\n\nFunction NextPerm(Perm() As Long, Stack() As Long, Level As Long) As Boolean\nDim N As Long\nIf Level = 2 Then\n Swap Perm(1), Perm(2)\n Level = 3\nElse\n While Stack(Level) = Level - 1\n Stack(Level) = 0\n If Level = UBound(Stack) Then Exit Function\n Level = Level + 1\n Wend\n Stack(Level) = Stack(Level) + 1\n If Level And 1 Then N = 1 Else N = Stack(Level)\n Swap Perm(N), Perm(Level)\n Level = 2\nEnd If\nNextPerm = True\nEnd Function\n\nSub Swap(A As Long, B As Long)\nA = A Xor B\nB = A Xor B\nA = A Xor B\nEnd Sub\n\n'This is just for testing.\nPrivate Sub Form_Paint()\nConst Max = 8\nDim A(1 To Max) As Long, I As Long\nDim S(3 To Max) As Long, J As Long\nDim Test As New Collection, T As String\nFor I = 1 To UBound(A)\n A(I) = I\nNext\nCls\nScaleLeft = 0\nJ = 2\nDo\n If CurrentY + TextHeight(\"0\") > ScaleHeight Then\n ScaleLeft = ScaleLeft - TextWidth(\" 0 \") * (UBound(A) + 1)\n CurrentY = 0\n CurrentX = 0\n End If\n T = vbNullString\n For I = 1 To UBound(A)\n Print A(I);\n T = T & Hex(A(I))\n Next\n Print\n Test.Add Null, T\nLoop While NextPerm(A, S, J)\nJ = 1\nFor I = 2 To UBound(A)\n J = J * I\nNext\nIf J <> Test.Count Then Stop\nEnd Sub\n" }, { "answer_id": 8808091, "author": "Unnykrishnan S", "author_id": 1141488, "author_profile": "https://Stackoverflow.com/users/1141488", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n#include <string.h>\n\nvoid swap(char *a, char *b) {\n char temp;\n temp = *a;\n *a = *b;\n *b = temp;\n}\n\nvoid print(char *a, int i, int n) {\n int j;\n if(i == n) {\n printf(\"%s\\n\", a);\n } else {\n for(j = i; j <= n; j++) {\n swap(a + i, a + j);\n print(a, i + 1, n);\n swap(a + i, a + j);\n }\n }\n}\n\nint main(void) {\n char a[100];\n gets(a);\n print(a, 0, strlen(a) - 1);\n return 0;\n}\n" }, { "answer_id": 10238654, "author": "Kem Mason", "author_id": 398582, "author_profile": "https://Stackoverflow.com/users/398582", "pm_score": 3, "selected": false, "text": "class String\n def each_char_with_index\n 0.upto(size - 1) do |index|\n yield(self[index..index], index)\n end\n end\n def remove_char_at(index)\n return self[1..-1] if index == 0\n self[0..(index-1)] + self[(index+1)..-1]\n end\nend\n\ndef permute(str, prefix = '')\n if str.size == 0\n puts prefix\n return\n end\n str.each_char_with_index do |char, index|\n permute(str.remove_char_at(index), prefix + char)\n end\nend\n\n# example\n# permute(\"abc\")\n" }, { "answer_id": 11672570, "author": "wliao", "author_id": 150607, "author_profile": "https://Stackoverflow.com/users/150607", "pm_score": 0, "selected": false, "text": "public List<string> Permutations(char[] chars)\n {\n List<string> words = new List<string>();\n words.Add(chars[0].ToString());\n for (int i = 1; i < chars.Length; ++i)\n {\n int currLen = words.Count;\n for (int j = 0; j < currLen; ++j)\n {\n var w = words[j];\n for (int k = 0; k <= w.Length; ++k)\n {\n var nstr = w.Insert(k, chars[i].ToString());\n if (k == 0)\n words[j] = nstr;\n else\n words.Add(nstr);\n }\n }\n }\n return words;\n }\n" }, { "answer_id": 17182840, "author": "Ramy", "author_id": 796477, "author_profile": "https://Stackoverflow.com/users/796477", "pm_score": 3, "selected": false, "text": "//call it as permut(\"\",str);\n\npublic void permut(String str1,String str2){\n if(str2.length() != 0){\n char ch = str2.charAt(0);\n for(int i = 0; i <= str1.length();i++)\n permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),\n str2.substring(1,str2.length()));\n }else{\n System.out.println(str1);\n }\n}\n //call it as permut(\"\",str);\n\npublic void permut(String str1,String str2){\n if(str2.length() > 1){\n char ch = str2.charAt(0);\n for(int i = 0; i <= str1.length();i++)\n permut(str1.substring(0,i) + ch + str1.substring(i,str1.length()),\n str2.substring(1,str2.length()));\n }else{\n char ch = str2.charAt(0);\n for(int i = 0; i <= str1.length();i++)\n System.out.println(str1.substring(0,i) + ch + str1.substring(i,str1.length()),\n str2.substring(1,str2.length()));\n }\n}\n" }, { "answer_id": 17480974, "author": "Winster", "author_id": 1440435, "author_profile": "https://Stackoverflow.com/users/1440435", "pm_score": 0, "selected": false, "text": "perms['ab'] = ['ab','ba'] perms = {}\ndef perm(input_string):\n global perms\n if input_string in perms:\n return perms[input_string] # This will send a list of all permutations\n elif len(input_string) == 2:\n perms[input_string] = [input_string, input_string[-1] + input_string [-2]]\n return perms[input_string]\n else:\n perms[input_string] = []\n for index in range(0, len(input_string)):\n new_string = input_string[0:index] + input_string[index +1:]\n perm(new_string)\n for entries in perms[new_string]:\n perms[input_string].append(input_string[index] + entries)\n return perms[input_string]\n" }, { "answer_id": 18387484, "author": "abkds", "author_id": 2537745, "author_profile": "https://Stackoverflow.com/users/2537745", "pm_score": 0, "selected": false, "text": "def gen( x,y,list): #to generate all strings inserting y at different positions\nlist = []\nlist.append( y+x )\nfor i in range( len(x) ):\n list.append( func(x,0,i) + y + func(x,i+1,len(x)-1) )\nreturn list \n\ndef func( x,i,j ): #returns x[i..j]\nz = '' \nfor i in range(i,j+1):\n z = z+x[i]\nreturn z \n\ndef perm( x , length , list ): #perm function\nif length == 1 : # base case\n list.append( x[len(x)-1] )\n return list \nelse:\n lists = perm( x , length-1 ,list )\n lists_temp = lists #temporarily storing the list \n lists = []\n for i in range( len(lists_temp) ) :\n list_temp = gen(lists_temp[i],x[length-2],lists)\n lists += list_temp \n return lists\n" }, { "answer_id": 19461362, "author": "Neo", "author_id": 2263483, "author_profile": "https://Stackoverflow.com/users/2263483", "pm_score": 0, "selected": false, "text": "main() public class AllPermutationsOfString {\npublic static void stringPermutations(String newstring, String remaining) {\n if(remaining.length()==0)\n System.out.println(newstring);\n\n for(int i=0; i<remaining.length(); i++) {\n String newRemaining = remaining.replaceFirst(remaining.charAt(i)+\"\", \"\");\n stringPermutations(newstring+remaining.charAt(i), newRemaining);\n }\n}\n\npublic static void main(String[] args) {\n String string = \"abc\";\n AllPermutationsOfString.stringPermutations(\"\", string); \n}\n" }, { "answer_id": 20993674, "author": "gd1", "author_id": 671092, "author_profile": "https://Stackoverflow.com/users/671092", "pm_score": 4, "selected": false, "text": "#include <string>\n#include <iostream>\n\ntemplate<typename Consume>\nvoid permutations(std::string s, Consume consume, std::size_t start = 0) {\n if (start == s.length()) consume(s);\n for (std::size_t i = start; i < s.length(); i++) {\n std::swap(s[start], s[i]);\n permutations(s, consume, start + 1);\n }\n}\n\nint main(void) {\n std::string s = \"abcd\";\n permutations(s, [](std::string s) {\n std::cout << s << std::endl;\n });\n}\n" }, { "answer_id": 21298759, "author": "Paté", "author_id": 474321, "author_profile": "https://Stackoverflow.com/users/474321", "pm_score": 0, "selected": false, "text": "def permutation(str)\n posibilities = []\n str.split('').each do |char|\n if posibilities.size == 0\n posibilities[0] = char.downcase\n posibilities[1] = char.upcase\n else\n posibilities_count = posibilities.length\n posibilities = posibilities + posibilities\n posibilities_count.times do |i|\n posibilities[i] += char.downcase\n posibilities[i+posibilities_count] += char.upcase\n end\n end\n end\n posibilities\nend\n" }, { "answer_id": 24720609, "author": "Abdul Fatir", "author_id": 2605733, "author_profile": "https://Stackoverflow.com/users/2605733", "pm_score": 0, "selected": false, "text": "from itertools import permutations\ns = 'ABCDEF'\np = [''.join(x) for x in permutations(s)]\n" }, { "answer_id": 31086857, "author": "Adilli Adil", "author_id": 2172507, "author_profile": "https://Stackoverflow.com/users/2172507", "pm_score": 0, "selected": false, "text": "public static StringBuilder[] permutations(String s) {\n if (s.length() == 0)\n return null;\n int length = fact(s.length());\n StringBuilder[] sb = new StringBuilder[length];\n for (int i = 0; i < length; i++) {\n sb[i] = new StringBuilder();\n }\n for (int i = 0; i < s.length(); i++) {\n char ch = s.charAt(i);\n int times = length / (i + 1);\n for (int j = 0; j < times; j++) {\n for (int k = 0; k < length / times; k++) {\n sb[j * length / times + k].insert(k, ch);\n }\n }\n }\n return sb;\n }\n" }, { "answer_id": 37639997, "author": "Achilles Ram Nakirekanti", "author_id": 3052383, "author_profile": "https://Stackoverflow.com/users/3052383", "pm_score": 0, "selected": false, "text": "public static int totalPermutationsCount = 0;\n public static void main(String[] args) {\n\n Scanner sc = new Scanner(System.in);\n System.out.println(\"input string : \");\n String inputString = sc.nextLine();\n System.out.println(\"given input String ==> \"+inputString+ \" :: length is = \"+inputString.length());\n findPermuationsOfString(-1, inputString);\n System.out.println(\"**************************************\");\n System.out.println(\"total permutation strings ==> \"+totalPermutationsCount);\n }\n\n\n public static void findPermuationsOfString(int fixedIndex, String inputString) {\n int currentIndex = fixedIndex +1;\n\n for (int i = currentIndex; i < inputString.length(); i++) {\n //swap elements and call the findPermuationsOfString()\n\n char[] carr = inputString.toCharArray();\n char tmp = carr[currentIndex];\n carr[currentIndex] = carr[i];\n carr[i] = tmp;\n inputString = new String(carr);\n\n //System.out.println(\"chat At : current String ==> \"+inputString.charAt(currentIndex));\n if(currentIndex == inputString.length()-1) {\n totalPermutationsCount++;\n System.out.println(\"permuation string ==> \"+inputString);\n } else {\n //System.out.println(\"in else block>>>>\");\n findPermuationsOfString(currentIndex, inputString);\n char[] rarr = inputString.toCharArray();\n char rtmp = carr[i];\n carr[i] = carr[currentIndex];\n carr[currentIndex] = rtmp;\n inputString = new String(carr);\n }\n }\n }\n" }, { "answer_id": 42061222, "author": "Naresh Dhiman", "author_id": 2130204, "author_profile": "https://Stackoverflow.com/users/2130204", "pm_score": -1, "selected": false, "text": "public static String insertCharAt(String s, int index, char c) {\n StringBuffer sb = new StringBuffer(s);\n StringBuffer sbb = sb.insert(index, c);\n return sbb.toString();\n}\n\npublic static ArrayList<String> getPerm(String s, int index) {\n ArrayList<String> perm = new ArrayList<String>();\n\n if (index == s.length()-1) {\n perm.add(String.valueOf(s.charAt(index)));\n return perm;\n }\n\n ArrayList<String> p = getPerm(s, index+1);\n char c = s.charAt(index);\n\n for(String pp : p) {\n for (int idx=0; idx<pp.length()+1; idx++) {\n String ss = insertCharAt(pp, idx, c);\n perm.add(ss);\n }\n }\n\n return perm; \n}\n\npublic static void testGetPerm(String s) {\n ArrayList<String> perm = getPerm(s,0);\n System.out.println(s+\" --> total permutation are :: \"+perm.size());\n System.out.println(perm.toString());\n}\n" }, { "answer_id": 63979467, "author": "mourya venkat", "author_id": 7522482, "author_profile": "https://Stackoverflow.com/users/7522482", "pm_score": 1, "selected": false, "text": "func StringPermutations(inputStr string) (permutations []string) {\n for i := 0; i < len(inputStr); i++ {\n inputStr = inputStr[1:] + inputStr[0:1]\n if len(inputStr) <= 2 {\n permutations = append(permutations, inputStr)\n continue\n }\n leftPermutations := StringPermutations(inputStr[0 : len(inputStr)-1])\n for _, leftPermutation := range leftPermutations {\n permutations = append(permutations, leftPermutation+inputStr[len(inputStr)-1:])\n }\n }\n return\n}\n" }, { "answer_id": 66228704, "author": "Bhaskar13", "author_id": 11930483, "author_profile": "https://Stackoverflow.com/users/11930483", "pm_score": 2, "selected": false, "text": "class Permutation {\n\n /* runtime -O(n) for generating nextPermutaion\n * and O(n*n!) for generating all n! permutations with increasing sorted array as start\n * return true, if there exists next lexicographical sequence\n * e.g [a,b,c],3-> true, modifies array to [a,c,b]\n * e.g [c,b,a],3-> false, as it is largest lexicographic possible */\n public static boolean nextPermutation(char[] seq, int len) {\n // 1\n if (len <= 1)\n return false;// no more perm\n // 2: Find last j such that seq[j] <= seq[j+1]. Terminate if no such j exists\n int j = len - 2;\n while (j >= 0 && seq[j] >= seq[j + 1]) {\n --j;\n }\n if (j == -1)\n return false;// no more perm\n // 3: Find last l such that seq[j] <= seq[l], then exchange elements j and l\n int l = len - 1;\n while (seq[j] >= seq[l]) {\n --l;\n }\n swap(seq, j, l);\n // 4: Reverse elements j+1 ... count-1:\n reverseSubArray(seq, j + 1, len - 1);\n // return seq, add store next perm\n\n return true;\n }\n private static void swap(char[] a, int i, int j) {\n char temp = a[i];\n a[i] = a[j];\n a[j] = temp;\n }\n\n private static void reverseSubArray(char[] a, int lo, int hi) {\n while (lo < hi) {\n swap(a, lo, hi);\n ++lo;\n --hi;\n }\n }\n public static void main(String[] args) {\n String str = \"abcdefg\";\n char[] array = str.toCharArray();\n Arrays.sort(array);\n int cnt=0;\n do {\n System.out.println(new String(array));\n cnt++;\n }while(nextPermutation(array, array.length));\n System.out.println(cnt);//5040=7!\n }\n //if we use \"bab\"-> \"abb\", \"bab\", \"bba\", 3(#permutations)\n}\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
371
<p>This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly <em>spamish</em> terminology.</p> <p>Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it.</p> <p>This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam</p> <p>I figure this is a big topic in which I am essentially an ignorant simpleton.</p>
[ { "answer_id": 396, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 9, "selected": true, "text": "\"John Smith\" <[email protected]> [email protected] [email protected]" }, { "answer_id": 2579555, "author": "Pekka", "author_id": 187606, "author_profile": "https://Stackoverflow.com/users/187606", "pm_score": 5, "selected": false, "text": "[email protected] reply-to" }, { "answer_id": 12715357, "author": "Mike", "author_id": 811240, "author_profile": "https://Stackoverflow.com/users/811240", "pm_score": 4, "selected": false, "text": "Go to your account now: <a href=\"http://www.paypal.com.phishers-anonymous.org/\">http://www.paypal.com</a>\n Go to your account now: <a href=\"http://www.yourdomain.org/\">http://www.yourdomain.org</a>\n <a href=\"http://www.yourdomain.org/\">Click here to go to your account</a>\n" }, { "answer_id": 57564315, "author": "Mike", "author_id": 811240, "author_profile": "https://Stackoverflow.com/users/811240", "pm_score": 1, "selected": false, "text": "-f -r From: mail() domain.com host.com mail($to,$subject,$message,$headers); // Wrong way\n Return-Path: <[email protected]>\nFrom: <[email protected]>\n mail() mail($to,$subject,$message,$headers, '-r [email protected]'); // Right way\n Return-Path: <[email protected]>\nFrom: <[email protected]>\n domain.com" }, { "answer_id": 62389816, "author": "vikram sahu", "author_id": 10232486, "author_profile": "https://Stackoverflow.com/users/10232486", "pm_score": 2, "selected": false, "text": " **dig a +short (domain-name).(blacklist-domain-name)**\n\n ie. dig a +short example.com.dsn.rfc-clueless.org\n > 127.0.0.2\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49/" ]
387
<p>In Lucene if you had multiple indexes that covered only one partition each. Why does the same search on different indexes return results with different scores? The results from different servers match exactly. </p> <p>i.e. if I searched for :</p> <ul> <li>Name - John Smith</li> <li>DOB - 11/11/1934</li> </ul> <p><strong>Partition 0</strong> would return a score of 0.345</p> <p><strong>Partition 1</strong> would return a score of 0.337</p> <p>Both match exactly on name and DOB.</p>
[ { "answer_id": 551, "author": "Joe Shaw", "author_id": 156, "author_profile": "https://Stackoverflow.com/users/156", "pm_score": 3, "selected": false, "text": "explain() Explanation" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/134/" ]
402
<p>Please note that this question is from 2008 and now is of only historic interest.</p> <hr> <p>What's the best way to create an iPhone application that runs in landscape mode from the start, regardless of the position of the device?</p> <p>Both programmatically and using the Interface Builder.</p>
[ { "answer_id": 36884, "author": "Michael Pryor", "author_id": 245, "author_profile": "https://Stackoverflow.com/users/245", "pm_score": 5, "selected": false, "text": "<key>UIInterfaceOrientation</key>\n<string>UIInterfaceOrientationLandscapeRight</string>\n" }, { "answer_id": 36899, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "- (void)applicationDidFinishLaunchingUIApplication *)application {\n application.statusBarOrientation = UIInterfaceOrientationLandscapeRight;\n}\n [[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];\n [application setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:NO];\n window makeKeyAndVisible;" }, { "answer_id": 1773197, "author": "samvermette", "author_id": 87158, "author_profile": "https://Stackoverflow.com/users/87158", "pm_score": 3, "selected": false, "text": "<key>UIInterfaceOrientation</key>\n<string>UIInterfaceOrientationLandscapeRight</string>\n CGAffineTransform rotate = CGAffineTransformMakeRotation(1.57079633);\n[window setTransform:rotate];\n\nCGRect contentRect = CGRectMake(0, 0, 480, 320); \nwindow.bounds = contentRect; \n[window setCenter:CGPointMake(160.0f, 240.0f)]; \n" }, { "answer_id": 2530953, "author": "Fattie", "author_id": 294884, "author_profile": "https://Stackoverflow.com/users/294884", "pm_score": 7, "selected": true, "text": "[window addSubview:happyThing.view];\n[window makeKeyAndVisible];\n" }, { "answer_id": 2787997, "author": "IlDan", "author_id": 103529, "author_profile": "https://Stackoverflow.com/users/103529", "pm_score": 5, "selected": false, "text": "UISupportedInterfaceOrientations Info.plist shouldAutorotateToInterfaceOrientation: self.view.frame = CGRectMake(0, 0, 480, 320) viewDidLoad" }, { "answer_id": 4290617, "author": "Arlen Anderson", "author_id": 247151, "author_profile": "https://Stackoverflow.com/users/247151", "pm_score": 3, "selected": false, "text": "shouldAutorotateToInterfaceOrientation viewWillAppear viewDidAppear viewWillAppear - (void)viewWillAppear:(BOOL)animated\n{\n if ( dummy != nil ) {\n [dummy setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];\n [self presentModalViewController:dummy animated:NO];\n [dummy release];\n dummy = nil;\n }\n...\n}\n" }, { "answer_id": 5209365, "author": "nicc", "author_id": 499901, "author_profile": "https://Stackoverflow.com/users/499901", "pm_score": 2, "selected": false, "text": "[[UIDevice currentDevice] setOrientation:UIInterfaceOrientationLandscapeRight];\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136/" ]
427
<p>Is there any way to launch IE Mobile's "Favorites" screen directly by specifying any command line parameter?</p>
[ { "answer_id": 5019863, "author": "hellkrusher", "author_id": 620104, "author_profile": "https://Stackoverflow.com/users/620104", "pm_score": 2, "selected": false, "text": "26#\"\\Windows\\iexplore.exe\" -f" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/123/" ]
469
<p>I am using the Photoshop's javascript API to find the fonts in a given PSD.</p> <p>Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc.</p> <p>This is all happening in a python program running on OSX so I guess I'm looking for one of:</p> <ul> <li>Some Photoshop javascript</li> <li>A Python function</li> <li>An OSX API that I can call from python</li> </ul>
[ { "answer_id": 497, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 3, "selected": false, "text": "locate InsertFontHere\n" }, { "answer_id": 518, "author": "jaredg", "author_id": 153, "author_profile": "https://Stackoverflow.com/users/153", "pm_score": 3, "selected": false, "text": "/System/Library/Fonts /Library/Fonts ~/Library/Fonts" }, { "answer_id": 195170, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 3, "selected": false, "text": "import os\ndef get_font_list():\n fonts = []\n for font_path in [\"/Library/Fonts\", os.path.expanduser(\"~/Library/Fonts\")]:\n if os.path.isdir(font_path):\n fonts.extend(\n [os.path.join(font_path, cur_font) \n for cur_font in os.listdir(font_path)\n ]\n )\n return fonts\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147/" ]
482
<p>Assume you are doing something like the following</p> <pre><code>List&lt;string&gt; myitems = new List&lt;string&gt; { "Item 1", "Item 2", "Item 3" }; ComboBox box = new ComboBox(); box.DataSource = myitems; ComboBox box2 = new ComboBox(); box2.DataSource = myitems </code></pre> <p>So now we have 2 combo boxes bound to that array, and everything works fine. But when you change the value of one combo box, it changes BOTH combo boxes to the one you just selected.</p> <p>Now, I know that Arrays are always passed by reference (learned that when i learned C :D), but why on earth would the combo boxes change together? I don't believe the combo box control is modifying the collection at all. </p> <p>As a workaround, don't this would achieve the functionality that is expected/desired</p> <pre><code>ComboBox box = new ComboBox(); box.DataSource = myitems.ToArray(); </code></pre>
[ { "answer_id": 509, "author": "Robert Höglund", "author_id": 143, "author_profile": "https://Stackoverflow.com/users/143", "pm_score": 6, "selected": true, "text": "BindingContext BindingContext DataSource ComboBox BindingContext ConcurrenyMangager ConcurrenyManager DataSource ComboBox BindingContext ConcurrencyManager" }, { "answer_id": 20142, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 5, "selected": false, "text": "BindingSource using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication2\n{\n public partial class Form1 : Form\n {\n private BindingSource source1 = new BindingSource();\n private BindingSource source2 = new BindingSource();\n\n public Form1()\n {\n InitializeComponent();\n Load += new EventHandler(Form1Load);\n }\n\n void Form1Load(object sender, EventArgs e)\n {\n List<string> myitems = new List<string>\n {\n \"Item 1\",\n \"Item 2\",\n \"Item 3\"\n };\n\n ComboBox box = new ComboBox();\n box.Bounds = new Rectangle(10, 10, 100, 50);\n source1.DataSource = myitems;\n box.DataSource = source1;\n\n ComboBox box2 = new ComboBox();\n box2.Bounds = new Rectangle(10, 80, 100, 50);\n source2.DataSource = myitems;\n box2.DataSource = source2;\n\n Controls.Add(box);\n Controls.Add(box2);\n }\n }\n}\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/77/" ]
502
<p>I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.</p> <p>On the Mac I am spawning <a href="http://web.archive.org/web/20090309234215/http://developer.apple.com:80/documentation/Darwin/Reference/ManPages/man1/sips.1.html" rel="noreferrer">sips</a>. Is there something similarly simple I can do on Windows?</p>
[ { "answer_id": 536, "author": "Federico Builes", "author_id": 161, "author_profile": "https://Stackoverflow.com/users/161", "pm_score": 4, "selected": false, "text": "Convert taxes.pdf taxes.jpg \n convert -size 120x120 taxes.jpg.0 -geometry 120x120 +profile '*' thumbnail.jpg\n convert -size 120x120 taxes.pdf -geometry 120x120 +profile '*' thumbnail.jpg\n" }, { "answer_id": 7090, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "ps:alpha gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \\\n-dMaxBitmap=500000000 -dLastPage=1 -dAlignToPixels=0 -dGridFitTT=0 \\\n-sDEVICE=jpeg -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -r72x72 \\\n-sOutputFile=$OUTPUT -f$INPUT\n $OUTPUT $INPUT 72x72 -sDEVICE=jpeg -sDEVICE=png16m" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147/" ]
549
<blockquote> <h4>Moderator note:</h4> <p>This question is not a good fit for our question and answer format with the <a href="/help/on-topic">topicality rules</a> which currently apply for Stack Overflow. We normally use a &quot;historical lock&quot; for such questions where the content still has value. However, the answers on this question are actively maintained and a historical lock doesn't permit editing of the answers. As such, a &quot;wiki answer&quot; lock has been applied to allow the answers to be edited. You should assume the topicality issues which are normally handled by a historical lock are present (i.e. this question not a good example of an on-topic question for Stack Overflow).</p> </blockquote> <h2>Form-based authentication for websites</h2> <p>We believe that Stack Overflow should not just be a resource for very specific technical questions, but also for general guidelines on how to solve variations on common problems. &quot;Form based authentication for websites&quot; should be a fine topic for such an experiment.</p> <h3>It should include topics such as:</h3> <ul> <li>How to log in</li> <li>How to log out</li> <li>How to remain logged in</li> <li>Managing cookies (including recommended settings)</li> <li>SSL/HTTPS encryption</li> <li>How to store passwords</li> <li>Using secret questions</li> <li>Forgotten username/password functionality</li> <li>Use of <a href="https://en.wikipedia.org/wiki/Cryptographic_nonce" rel="nofollow noreferrer">nonces</a> to prevent <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="nofollow noreferrer">cross-site request forgeries (CSRF)</a></li> <li><a href="http://openid.net/" rel="nofollow noreferrer">OpenID</a></li> <li>&quot;Remember me&quot; checkbox</li> <li>Browser autocompletion of usernames and passwords</li> <li>Secret URLs (public <a href="https://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="nofollow noreferrer">URL</a> protected by digest)</li> <li>Checking password strength</li> <li>E-mail validation</li> <li><em>and much more about</em> <a href="http://en.wikipedia.org/wiki/Form-based_authentication" rel="nofollow noreferrer">form based authentication</a>...</li> </ul> <h3>It should not include things like:</h3> <ul> <li>Roles and authorization</li> <li>HTTP basic authentication</li> </ul> <h3>Please help us by:</h3> <ol> <li>Suggesting subtopics</li> <li>Submitting good articles about this subject</li> <li>Editing the official answer</li> </ol>
[ { "answer_id": 6984591, "author": "Charlie", "author_id": 139320, "author_profile": "https://Stackoverflow.com/users/139320", "pm_score": 7, "selected": false, "text": "@" }, { "answer_id": 10701801, "author": "Pieter888", "author_id": 192310, "author_profile": "https://Stackoverflow.com/users/192310", "pm_score": 7, "selected": false, "text": "<form> <input type=\"text\" name=\"email\" style=\"display:none\" />\n input type hidden text email 0 display:none" }, { "answer_id": 29932630, "author": "Mike Robinson", "author_id": 4811873, "author_profile": "https://Stackoverflow.com/users/4811873", "pm_score": 4, "selected": false, "text": "404 Not Found" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136/" ]
561
<p>I would like to test a function with a tuple from a set of fringe cases and normal values. For example, while testing a function which returns <code>true</code> whenever given three lengths that form a valid triangle, I would have specific cases, negative / small / large numbers, values close-to being overflowed, etc.; what is more, main aim is to generate combinations of these values, <em>with</em> or <em>without</em> repetition, in order to get a set of test data.</p> <pre><code>(inf,0,-1), (5,10,1000), (10,5,5), (0,-1,5), (1000,inf,inf), ... </code></pre> <blockquote> <p><em>As a note: I actually know the answer to this, but it might be helpful for others, and a challenge for people here! --will post my answer later on.</em></p> </blockquote>
[ { "answer_id": 589, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "if f(1,2,3) returns true" }, { "answer_id": 794, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 5, "selected": true, "text": "/** [combination c n p x]\n * get the [x]th lexicographically ordered set of [p] elements in [n]\n * output is in [c], and should be sizeof(int)*[p] */\nvoid combination(int* c,int n,int p, int x){\n int i,r,k = 0;\n for(i=0;i<p-1;i++){\n c[i] = (i != 0) ? c[i-1] : 0;\n do {\n c[i]++;\n r = choose(n-c[i],p-(i+1));\n k = k + r;\n } while(k < x);\n k = k - r;\n }\n c[p-1] = c[p-2] + x - k;\n}\n" }, { "answer_id": 170010, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 2, "selected": false, "text": "import itertools\n\nprint list(itertools.product([1,2,3], [4,5,6]))\n [(1, 4), (1, 5), (1, 6),\n (2, 4), (2, 5), (2, 6),\n (3, 4), (3, 5), (3, 6)]\n print list(itertools.product([1,2], repeat=3))\n[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),\n(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]\n print list(itertools.combinations('123', 2))\n[('1', '2'), ('1', '3'), ('2', '3')]\n print list(itertools.permutations([1,2,3,4], 2))\n[(1, 2), (1, 3), (1, 4),\n (2, 1), (2, 3), (2, 4),\n (3, 1), (3, 2), (3, 4),\n (4, 1), (4, 2), (4, 3)]\n" } ]
2008/08/02
[ "https://Stackoverflow.com/questions/561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/157/" ]
564
<p>I was reading <em><a href="https://rads.stackoverflow.com/amzn/click/com/1430209879" rel="noreferrer" rel="nofollow noreferrer">More Joel on Software</a></em> when I came across <a href="http://en.wikipedia.org/wiki/Joel_Spolsky" rel="noreferrer">Joel Spolsky</a> saying something about a particular type of programmer knowing the difference between an <code>int</code> and an <code>Integer</code> in Java/C# (Object-Oriented Programming Languages).</p> <p>So, what is the difference?</p>
[ { "answer_id": 566, "author": "Matt", "author_id": 154, "author_profile": "https://Stackoverflow.com/users/154", "pm_score": 9, "selected": true, "text": "System.Int32" }, { "answer_id": 568, "author": "cmcculloh", "author_id": 58, "author_profile": "https://Stackoverflow.com/users/58", "pm_score": 7, "selected": false, "text": "Integer i = new Integer(6);\n String s = i.toString();//sets s the string representation of i\n int i = 6;\n String s = i.toString();//will not work!!!\n" }, { "answer_id": 583, "author": "huseyint", "author_id": 39, "author_profile": "https://Stackoverflow.com/users/39", "pm_score": 4, "selected": false, "text": "System.Int32 System.String System.Double using System;" }, { "answer_id": 608, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": false, "text": "int Integer int int List Map Deque<Integer> queue;\n\nvoid add(int n) {\n queue.add(n);\n}\n\nint remove() {\n return queue.remove();\n}\n Deque queue;\n\nvoid add(int n) {\n queue.add(Integer.valueOf(n));\n}\n\nint remove() {\n return ((Integer) queue.remove()).intValue();\n}\n" }, { "answer_id": 1266, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 5, "selected": false, "text": "int System.Int32 float System.Float System.Single System.Int32 float int System.Int32 int i;\n i System.Int32 object o = i;\n i" }, { "answer_id": 1582, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 3, "selected": false, "text": "void DoStuff()\n{\n System.Console.WriteLine( SomeMethod((int)5) );\n System.Console.WriteLine( GetTypeName<int>() );\n}\n\nstring SomeMethod(object someParameter)\n{\n return string.Format(\"Some text {0}\", someParameter.ToString());\n}\n\nstring GetTypeName<T>()\n{\n return (typeof (T)).FullName;\n}\n" }, { "answer_id": 2823, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 4, "selected": false, "text": "Integer i1 = new Integer(127);\nInteger i2 = new Integer(127);\nSystem.out.println(i1 == i2); // true\n Integer i1 = new Integer(128);\nInteger i2 = new Integer(128);\nSystem.out.println(i1 == i2); // false\n System.out.println(i1.equals(i2)); // true\n" }, { "answer_id": 3285, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 4, "selected": false, "text": "int aNumber = 4;\nint anotherNum = aNumber;\naNumber += 6;\nSystem.out.println(anotherNum); // Prints 4\n Integer aNumber = Integer.valueOf(4);\nInteger anotherNumber = aNumber; // anotherNumber references the \n // same object as aNumber\n public int add(int a, int b) {\n return a + b;\n}\nfinal int two = 2;\nint sum = add(1, two);\n public int add(Integer a, Integer b) {\n return a.intValue() + b.intValue();\n}\nfinal Integer two = Integer.valueOf(2);\nint sum = add(Integer.valueOf(1), two);\n public void increment(int x) {\n x = x + 1;\n}\nint a = 1;\nincrement(a);\n// a is now 2\n public void increment(Integer x) {\n x = Integer.valueOf(x.intValue() + 1);\n}\nInteger a = Integer.valueOf(1);\nincrement(a);\n// a is now 2\n" }, { "answer_id": 498102, "author": "mP.", "author_id": 56524, "author_profile": "https://Stackoverflow.com/users/56524", "pm_score": 3, "selected": false, "text": "int Integer" }, { "answer_id": 8462531, "author": "nagarajn89", "author_id": 1055140, "author_profile": "https://Stackoverflow.com/users/1055140", "pm_score": 3, "selected": false, "text": "e.g. int i=10;\n Integer a = new Integer();\n" }, { "answer_id": 23711054, "author": "Mr.Q", "author_id": 3593084, "author_profile": "https://Stackoverflow.com/users/3593084", "pm_score": 3, "selected": false, "text": "int x;\nInteger y; \n Integer.toString(x);\n" }, { "answer_id": 24795920, "author": "Bindumalini KK", "author_id": 3790709, "author_profile": "https://Stackoverflow.com/users/3790709", "pm_score": 2, "selected": false, "text": "int System.Int32 java.lang.Integer int Integer toString() parseInt() valueOf() System.Int32.Any System.Int32.When int.Parse() int.ToString() System.Int32 Int32.Parse() Int32.ToString()" }, { "answer_id": 25180570, "author": "Rufaro Muchedzi", "author_id": 3917868, "author_profile": "https://Stackoverflow.com/users/3917868", "pm_score": 2, "selected": false, "text": "int number = 7;\n int int Integer Integer number = new Integer(5);\n" }, { "answer_id": 35686676, "author": "Aqeel Haider", "author_id": 4165553, "author_profile": "https://Stackoverflow.com/users/4165553", "pm_score": 2, "selected": false, "text": "double doubleValue = 156.5d;\nDouble doubleObject = new Double(doubleValue);\nByte myByteValue = doubleObject.byteValue ();\nString myStringValue = doubleObject.toString();\n" }, { "answer_id": 37797743, "author": "J-Alex", "author_id": 5898696, "author_profile": "https://Stackoverflow.com/users/5898696", "pm_score": 3, "selected": false, "text": "int double long byte float double short boolean char Double Float Long Integer Short Byte Character Boolean java.lang Integer(int num)\nInteger(String str) throws NumberFormatException\nDouble(double num)\nDouble(String str) throws NumberFormatException\n class ManualBoxing {\n public static void main(String args[]) {\n Integer objInt = new Integer(20); // Manually box the value 20.\n int i = objInt.intValue(); // Manually unbox the value 20\n System.out.println(i + \" \" + iOb); // displays 20 20\n }\n}\n class AutoBoxing {\n public static void main(String args[]) {\n Integer objInt = 40; // autobox an int\n int i = objInt ; // auto-unbox\n System.out.println(i + \" \" + iOb); // displays 40 40\n }\n}\n" }, { "answer_id": 39635844, "author": "Aatu Dave", "author_id": 6863552, "author_profile": "https://Stackoverflow.com/users/6863552", "pm_score": 0, "selected": false, "text": "Integer a = new Integer() Integer int" }, { "answer_id": 42617947, "author": "Mausam Sinha", "author_id": 6201874, "author_profile": "https://Stackoverflow.com/users/6201874", "pm_score": 1, "selected": false, "text": "int Integer" }, { "answer_id": 43651213, "author": "thamashi97", "author_id": 7859659, "author_profile": "https://Stackoverflow.com/users/7859659", "pm_score": 2, "selected": false, "text": "int Integer int System.Int32 integer" }, { "answer_id": 48816251, "author": "Rishabh Agarwal", "author_id": 3878948, "author_profile": "https://Stackoverflow.com/users/3878948", "pm_score": 0, "selected": false, "text": "int int a;\n//assuming a value you are getting from data base which is null\nif(a ==null) // this is wrong - cannot compare primitive to null\n{\ndo something...}\n\nInstead you will use,\nInteger a;\n//assuming a value you are getting from data base which is null\nif(a ==null) // this is correct/legal\n{ do something...}\n" }, { "answer_id": 50699096, "author": "Priyantha", "author_id": 7467246, "author_profile": "https://Stackoverflow.com/users/7467246", "pm_score": 1, "selected": false, "text": "Integer value1 = null; //OK\n\nint value2 = null //Error\n List<Integer> element = new ArrayList<>();\nint valueInt = 10;\nInteger valueInteger = new Integer(value);\nelement.add(valueInteger);\n List<Integer> element = new ArrayList<>();\nelement.add(5);\n autoboxing." } ]
2008/08/02
[ "https://Stackoverflow.com/questions/564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
588
<p>I'm writing a CMS application in PHP and one of the requirements is that it must be able to interface with the customer's Exchange server. I've written up this functionality a few times before and have always used <a href="http://en.wikipedia.org/wiki/WebDAV" rel="noreferrer">WebDAV</a> to do it, but now I'm leaning away from that.</p> <p>I will be running the site on IIS OR Apache (no preference) on Windows server 2008. A few things I would need to do include adding contacts to a given user's address book, sending emails as a given user and running reports on contacts for a user.</p> <p>All of this is pretty easy to do with WebDAV, but if there is a better way that doesn't require any functionality that is likely to be deprecated any time soon.</p> <p>Any ideas?</p> <h3>Update:</h3> <p>Justin, I love the idea of using com objects, I just worry about maintaining a 3rd product to make everything work...</p> <p>John, I can write a web service in C# to interface with for these functions and access it with my PHP app, but it's also a little bit out of the way.</p> <p>So far, I'm not 100% convinced that either of these is better than WebDAV...</p> <p>Can anyone show me where I'm being silly?</p>
[ { "answer_id": 611, "author": "Justin Walgran", "author_id": 173, "author_profile": "https://Stackoverflow.com/users/173", "pm_score": 3, "selected": false, "text": "$outlook = COM(\"Outlook.Application\")\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172/" ]
594
<p>There are several ways to iterate over a result set. What are the tradeoff of each?</p>
[ { "answer_id": 595, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 7, "selected": true, "text": "curs.execute('select * from people')\nfor row in curs:\n print row\n fetchall() for row in curs.fetchall():\n print row\n curs.execute('select first_name from people')\nnames = [row[0] for row in curs.fetchall()]\n fetchone() curs.execute('select max(x) from t')\nmaxValue = curs.fetchone()[0]\n row = curs.fetchone()\nwhile row:\n print row\n row = curs.fetchone()\n" }, { "answer_id": 25213, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 3, "selected": false, "text": "psyco-pg" }, { "answer_id": 125140, "author": "Aurelio Martin Massoni", "author_id": 20037, "author_profile": "https://Stackoverflow.com/users/20037", "pm_score": 5, "selected": false, "text": "curs.execute('select * from people')\ncurs.arraysize = 256\nfor row in curs:\n print row\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
601
<p>I'm looking for a performant, reasonably robust RNG using no special hardware. It can use mathematical methods (Mersenne Twister, etc), it can "collect entropy" from the machine, whatever. On Linux/etc we have a <code>drand48()</code> which generates 48 random bits. I'd like a similar function/class for C++ or C# which can generate more than 32 bits of randomness and which low-order bits are equally as random as high-order bits.</p> <p>It doesn't have to be cryptographically secure but it must not use or be based on the C-language <code>rand()</code> or .NET <code>System.Random</code>.</p> <p>Any source code, links to source, etc. would be appreciated! Failing that, what TYPE of RNG should I be looking for?</p>
[ { "answer_id": 602, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 6, "selected": true, "text": "nondet_random" }, { "answer_id": 9923618, "author": "Rohit Vipin Mathews", "author_id": 1155650, "author_profile": "https://Stackoverflow.com/users/1155650", "pm_score": 2, "selected": false, "text": "Boost.Random" }, { "answer_id": 11211443, "author": "bames53", "author_id": 365496, "author_profile": "https://Stackoverflow.com/users/365496", "pm_score": 3, "selected": false, "text": "std::random_device #include <random>" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
609
<p>An MFC application that I'm trying to migrate uses <code>afxext.h</code>, which causes <code>_AFXDLL</code> to get set, which causes this error if I set <code>/MT</code>:</p> <blockquote> <p>Please use the /MD switch for _AFXDLL builds</p> </blockquote> <p>My research to date indicates that it is impossible to build an application for execution on Windows NT 4.0 using Visual Studio (C++, in this case) 2005.</p> <p>Is this really true? Are there any workaround available?</p>
[ { "answer_id": 200955, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "GetLongPathNameW GetLongPathNameW ret = 0;" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/179/" ]
622
<p>I want to print the first 10000 prime numbers. Can anyone give me the most efficient code for this? Clarifications:</p> <ol> <li>It does not matter if your code is inefficient for n >10000.</li> <li>The size of the code does not matter.</li> <li>You cannot just hard code the values in any manner.</li> </ol>
[ { "answer_id": 791, "author": "engtech", "author_id": 175, "author_profile": "https://Stackoverflow.com/users/175", "pm_score": 3, "selected": false, "text": "/^1?$|^(11+?)\\1+$/\n 1 1 1" }, { "answer_id": 2753, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 3, "selected": false, "text": "ArrayList primeNumbers = new ArrayList();\n\nfor(int i = 2; primeNumbers.Count < 10000; i++) {\n bool divisible = false;\n\n foreach(int number in primeNumbers) {\n if(i % number == 0) {\n divisible = true;\n }\n }\n\n if(divisible == false) {\n primeNumbers.Add(i);\n Console.Write(i + \" \");\n }\n}\n" }, { "answer_id": 19088, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdbool.h>\n#include <math.h>\n\nint main(void)\n{\n unsigned int lim, i, j;\n\n printf(\"Find primes upto: \");\n scanf(\"%d\", &lim);\n lim += 1;\n bool *primes = calloc(lim, sizeof(bool));\n\n unsigned int sqrtlim = sqrt(lim);\n for (i = 2; i <= sqrtlim; i++)\n if (!primes[i])\n for (j = i * i; j < lim; j += i)\n primes[j] = true;\n\n printf(\"\\nListing prime numbers between 2 and %d:\\n\\n\", lim - 1);\n for (i = 2; i < lim; i++)\n if (!primes[i])\n printf(\"%d\\n\", i);\n\n return 0;\n}\n" }, { "answer_id": 31176, "author": "palotasb", "author_id": 3063, "author_profile": "https://Stackoverflow.com/users/3063", "pm_score": 4, "selected": false, "text": "break if foreach ArrayList primeNumbers = new ArrayList();\n\nfor(int i = 2; primeNumbers.Count < 10000; i++) {\n bool divisible = false;\n\n foreach(int number in primeNumbers) {\n if(i % number == 0) {\n divisible = true;\n break;\n }\n }\n\n if(divisible == false) {\n primeNumbers.Add(i);\n Console.Write(i + \" \");\n }\n}\n" }, { "answer_id": 34090, "author": "hoyhoy", "author_id": 3499, "author_profile": "https://Stackoverflow.com/users/3499", "pm_score": 3, "selected": false, "text": "#include <stdio.h>\n#include <gmp.h>\n\nint main() {\n mpz_t prime;\n mpz_init(prime);\n mpz_set_ui(prime, 1);\n int i;\n char* num = malloc(4000);\n for(i=0; i<10000; i++) {\n mpz_nextprime(prime, prime);\n printf(\"%s, \", mpz_get_str(NULL,10,prime));\n }\n}\n time ./a.out > /dev/null\n\nreal 0m0.033s\nuser 0m0.029s\nsys 0m0.003s\n time ./a.out > /dev/null\n\nreal 0m14.824s\nuser 0m14.606s\nsys 0m0.086s\n" }, { "answer_id": 175956, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "O(N/log log N) O(N) O(N) O(N/log(log(N))) N=10_000 10_000 num1" }, { "answer_id": 552319, "author": "Pat Hermens", "author_id": 1677, "author_profile": "https://Stackoverflow.com/users/1677", "pm_score": 2, "selected": false, "text": " public IEnumerable<long> PrimeNumbers(long number)\n {\n List<long> primes = new List<long>();\n for (int i = 2; primes.Count < number; i++)\n {\n bool divisible = false;\n\n foreach (int num in primes)\n {\n if (i % num == 0)\n divisible = true;\n\n if (num > Math.Sqrt(i))\n break;\n }\n\n if (divisible == false)\n primes.Add(i);\n }\n return primes;\n }\n" }, { "answer_id": 1390584, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 2, "selected": false, "text": "#\n# generate a list of primes up to a specific target using a sieve of eratosthenes\n#\nfunction getPrimes { #sieve of eratosthenes, http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n param ($target,$count = 0)\n $sieveBound = [math]::ceiling(( $target - 1 ) / 2) #not storing evens so count is lower than $target\n $sieve = @($false) * $sieveBound\n $crossLimit = [math]::ceiling(( [math]::sqrt($target) - 1 ) / 2)\n for ($i = 1; $i -le $crossLimit; $i ++) {\n if ($sieve[$i] -eq $false) {\n $prime = 2 * $i + 1\n write-debug \"Found: $prime\"\n for ($x = 2 * $i * ( $i + 1 ); $x -lt $sieveBound; $x += 2 * $i + 1) {\n $sieve[$x] = $true\n }\n }\n }\n $primes = @(2)\n for ($i = 1; $i -le $sieveBound; $i ++) {\n if($count -gt 0 -and $primes.length -ge $count) {\n break;\n }\n if($sieve[$i] -eq $false) {\n $prime = 2 * $i + 1\n write-debug \"Output: $prime\"\n $primes += $prime\n }\n }\n return $primes\n}\n" }, { "answer_id": 2309490, "author": "John La Rooy", "author_id": 174728, "author_profile": "https://Stackoverflow.com/users/174728", "pm_score": 1, "selected": false, "text": "import gmpy\np=1\nfor i in range(10000):\n p=gmpy.next_prime(p)\n print p \n" }, { "answer_id": 4540559, "author": "Brijesh", "author_id": 555202, "author_profile": "https://Stackoverflow.com/users/555202", "pm_score": 0, "selected": false, "text": "n n 2 sqrt(n) n import math\nprint (\"You want prime till which number??\")\na = input()\na = int(a)\nx = 0\nx = int(x)\ncount = 1\nprint(\"2 is prime number\")\nfor c in range(3,a+1):\n b = math.sqrt(c)\n b = int(b)\n x = 0\n for b in range(2,b+1):\n e = c % b\n e = int(e)\n if (e == 0):\n x = x+1\n if (x == 0):\n print(\"%d is prime number\" % c)\n count = count + 1\nprint(\"Total number of prime till %d is %d\" % (a,count))\n" }, { "answer_id": 5268325, "author": "Chris Stevenson", "author_id": 654631, "author_profile": "https://Stackoverflow.com/users/654631", "pm_score": 1, "selected": false, "text": "Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles \nButton1.Click\n\n Dim TestNum As Integer\n Dim X As Integer\n Dim Z As Integer\n Dim TM As Single\n Dim TS As Single\n Dim TMS As Single\n Dim UnPrime As Boolean\n Dim Sentinal As Integer\n Button1.Text = \"Thinking\"\n Button1.Refresh()\n Sentinal = Val(SentinalTxt.Text)\n UnPrime = True\n Primes(0) = 2\n Primes(1) = 3\n Z = 1\n TM = TimeOfDay.Minute\n TS = TimeOfDay.Second\n TMS = TimeOfDay.Millisecond\n For TestNum = 5 To Sentinal Step 2\n Do While Primes(X) <> 0 And UnPrime And Primes(X) ^ 2 <= TestNum\n If Int(TestNum / Primes(X)) - (TestNum / Primes(X)) = 0 Then\n UnPrime = False\n End If\n X = X + 1\n\n Loop\n If UnPrime = True Then\n X = X + 1\n Z = Z + 1\n Primes(Z) = TestNum\n End If\n UnPrime = True\n X = 0\n Next\n Button1.Text = \"Finished with \" & Z\n TM = TimeOfDay.Minute - TM\n TS = TimeOfDay.Second - TS\n TMS = TimeOfDay.Millisecond - TMS\n ShowTime.Text = TM & \":\" & TS & \":\" & TMS\nEnd Sub\n" }, { "answer_id": 10287195, "author": "namibj", "author_id": 1352184, "author_profile": "https://Stackoverflow.com/users/1352184", "pm_score": 0, "selected": false, "text": "calcPrimes() import java.io.*;\nclass Primzahlengenerator {\n long[] Primzahlen;\n int LastUnknown = 2;\n public static void main(String[] args) {\n Primzahlengenerator Generator = new Primzahlengenerator();\n switch(args.length) {\n case 0: //Wenn keine Argumente übergeben worden:\n Generator.printHelp(); //Hilfe ausgeben\n return; //Durchfallen verhindern\n case 1:\n try {\n Generator.Primzahlen = new long[Integer.decode(args[0]).intValue()];\n }\n catch (NumberFormatException e) {\n System.out.println(\"Das erste Argument muss eine Zahl sein, und nicht als Wort z.B. \\\"Tausend\\\", sondern in Ziffern z.B. \\\"1000\\\" ausgedrückt werden.\");//Hinweis, wie man die Argumente angeben muss ausgeben\n Generator.printHelp(); //Generelle Hilfe ausgeben\n return;\n }\n break;//dutchfallen verhindern\n\n case 2:\n switch (args[1]) {\n case \"-l\":\n System.out.println(\"Sie müsen auch eine Datei angeben!\"); //Hilfemitteilung ausgeben\n Generator.printHelp(); //Generelle Hilfe ausgeben\n return;\n }\n break;//durchfallen verhindern\n case 3:\n try {\n Generator.Primzahlen = new long[Integer.decode(args[0]).intValue()];\n }\n catch (NumberFormatException e) {\n System.out.println(\"Das erste Argument muss eine Zahl sein, und nicht als Wort z.B. \\\"Tausend\\\", sondern in Ziffern z.B. \\\"1000\\\" ausgedrückt werden.\");//Hinweis, wie man die Argumente angeben muss ausgeben\n Generator.printHelp(); //Generelle Hilfe ausgeben\n return;\n }\n switch(args[1]) {\n case \"-l\":\n Generator.loadFromFile(args[2]);//Datei Namens des Inhalts von Argument 3 lesen, falls Argument 2 = \"-l\" ist\n break;\n default:\n Generator.printHelp();\n break;\n }\n break;\n default:\n Generator.printHelp();\n return;\n }\n Generator.calcPrims();\n }\n void printHelp() {\n System.out.println(\"Sie müssen als erstes Argument angeben, die wieviel ersten Primzahlen sie berechnen wollen.\"); //Anleitung wie man das Programm mit Argumenten füttern muss\n System.out.println(\"Als zweites Argument können sie \\\"-l\\\" wählen, worauf die Datei, aus der die Primzahlen geladen werden sollen,\");\n System.out.println(\"folgen muss. Sie muss genauso aufgebaut sein, wie eine Datei Primzahlen.txt, die durch den Aufruf \\\"java Primzahlengenerator 1000 > Primzahlen.txt\\\" entsteht.\");\n }\n void loadFromFile(String File) {\n // System.out.println(\"Lese Datei namens: \\\"\" + File + \"\\\"\");\n try{\n int x = 0;\n BufferedReader in = new BufferedReader(new FileReader(File));\n String line;\n while((line = in.readLine()) != null) {\n Primzahlen[x] = new Long(line).longValue();\n x++;\n }\n LastUnknown = x;\n } catch(FileNotFoundException ex) {\n System.out.println(\"Die angegebene Datei existiert nicht. Bitte geben sie eine existierende Datei an.\");\n } catch(IOException ex) {\n System.err.println(ex);\n } catch(ArrayIndexOutOfBoundsException ex) {\n System.out.println(\"Die Datei enthält mehr Primzahlen als der reservierte Speicherbereich aufnehmen kann. Bitte geben sie als erstes Argument eine größere Zahl an,\");\n System.out.println(\"damit alle in der Datei enthaltenen Primzahlen aufgenommen werden können.\");\n }\n /* for(long prim : Primzahlen) {\n System.out.println(\"\" + prim);\n } */\n //Hier soll code stehen, der von der Datei mit angegebenem Namen ( Wie diese aussieht einfach durch angeben von folgendem in cmd rausfinden:\n //java Primzahlengenerator 1000 > 1000Primzahlen.txt\n //da kommt ne textdatei, die die primzahlen enthält. mit Long.decode(String ziffern).longValue();\n //erhält man das was an der entsprechenden stelle in das array soll. die erste zeile soll in [0] , die zweite zeile in [1] und so weiter.\n //falls im arry der platz aus geht(die exception kenn ich grad nich, aber mach mal:\n //int[] foo = { 1, 2, 3};\n //int bar = foo[4];\n //dann kriegst ne exception, das ist die gleiche die man kriegt, wenn im arry der platzt aus geht.\n }\n void calcPrims() {\n int PrimzahlNummer = LastUnknown;\n // System.out.println(\"LAstUnknown ist: \" + LastUnknown);\n Primzahlen[0] = 2;\n Primzahlen[1] = 3;\n long AktuelleZahl = Primzahlen[PrimzahlNummer - 1];\n boolean IstPrimzahl;\n // System.out.println(\"2\");\n // System.out.println(\"3\");\n int Limit = Primzahlen.length;\n while(PrimzahlNummer < Limit) {\n IstPrimzahl = true;\n double WurzelDerAktuellenZahl = java.lang.Math.sqrt(AktuelleZahl);\n for(int i = 1;i < PrimzahlNummer;i++) {\n if(AktuelleZahl % Primzahlen[i] == 0) {\n IstPrimzahl = false;\n break;\n }\n if(Primzahlen[i] > WurzelDerAktuellenZahl) break;\n }\n if(IstPrimzahl) {\n Primzahlen[PrimzahlNummer] = AktuelleZahl;\n PrimzahlNummer++;\n // System.out.println(\"\" + AktuelleZahl);\n }\n AktuelleZahl = AktuelleZahl + 2;\n }\n for(long prim : Primzahlen) {\n System.out.println(\"\" + prim);\n }\n }\n}\n" }, { "answer_id": 10302076, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 4, "selected": false, "text": "import Data.List.Ordered (minus, union)\n\nprimes = 2 : minus [3..] (foldr (\\p r -> p*p : union [p*p+p, p*p+2*p..] r)\n [] primes)\n primes !! 10000 primes = 2 : 3 : minus [5,7..] (foldr (\\p r -> p*p : union [p*p+2*p, p*p+4*p..] r) [] (tail primes)) primes = 2 : _Y ( (3:) . sieve 5 . _U . map (\\p -> [p*p, p*p+2*p..]) )\n where\n _Y g = g (_Y g) -- non-sharing fixpoint combinator\n _U ((x:xs):t) = x : (union xs . _U . pairs) t -- ~= nub.sort.concat\n pairs (xs:ys:t) = union xs ys : pairs t\n sieve k s@(x:xs) | k < x = k : sieve (k+2) s -- ~= [k,k+2..]\\\\s,\n | otherwise = sieve (k+2) xs -- when s⊂[k,k+2..]\n (:) (.) (f . g) x = (\\y -> f (g y)) x = f (g x)" }, { "answer_id": 10492469, "author": "Sumanth", "author_id": 1381156, "author_profile": "https://Stackoverflow.com/users/1381156", "pm_score": -1, "selected": false, "text": "using System;\n\nnamespace ConsoleApplication2\n{\n class Program\n {\n static void Main(string[] args)\n {\n int n, i = 3, j, c;\n Console.WriteLine(\"Please enter your integer: \");\n n = Convert.ToInt32(Console.ReadLine());\n if (n >= 1)\n {\n Console.WriteLine(\"First \" + n + \" Prime Numbers are\");\n Console.WriteLine(\"2\");\n }\n for(j=2;j<=n;)\n {\n for(c=2;c<=i-1;c++)\n {\n if(i%c==0)\n break;\n }\n if(c==i)\n {\n Console.WriteLine(i);\n j++;\n }\n i++; \n }\n Console.Read();\n }\n }\n}\n" }, { "answer_id": 36668089, "author": "BenGoldberg", "author_id": 3093194, "author_profile": "https://Stackoverflow.com/users/3093194", "pm_score": 1, "selected": false, "text": "#include <iostream>\n#include <deque>\n\ntypedef std::deque<int> mydeque;\n\nvoid my_insert( mydeque & factors, int factor ) {\n int where = factor, count = factors.size();\n while( where < count && factors[where] ) where += factor;\n if( where >= count ) factors.resize( where + 1 );\n factors[ where ] = factor;\n}\n\nint main() {\n mydeque primes;\n mydeque factors;\n int a_prime = 3, a_square_prime = 9, maybe_prime = 3;\n int cnt = 2;\n factors.resize(3);\n std::cout << \"2 3 \";\n\n while( cnt < 10000 ) {\n int factor = factors.front();\n maybe_prime += 2;\n if( factor ) {\n my_insert( factors, factor );\n } else if( maybe_prime < a_square_prime ) {\n std::cout << maybe_prime << \" \";\n primes.push_back( maybe_prime );\n ++cnt;\n } else {\n my_insert( factors, a_prime );\n a_prime = primes.front();\n primes.pop_front();\n a_square_prime = a_prime * a_prime;\n }\n factors.pop_front();\n }\n\n std::cout << std::endl;\n return 0;\n}\n deque O(1) push_back pop_front resize O(n) n while my_insert O(log log n) n maybe_prime while maybe_prime my_insert O(n log log n) n" }, { "answer_id": 36725003, "author": "DarthGizka", "author_id": 4156577, "author_profile": "https://Stackoverflow.com/users/4156577", "pm_score": 2, "selected": false, "text": "List<int> static List<int> deque_sieve (int n = 10000)\n{\n Trace.Assert(n >= 3);\n\n var primes = new List<int>() { 2, 3 };\n var sieve = new List<int>() { 0, 0, 0 };\n\n for (int sieve_base = 5, current_prime_index = 1, current_prime_squared = 9; ; )\n {\n int base_factor = sieve[0];\n\n if (base_factor != 0)\n {\n // the sieve base has a non-trivial factor - put that factor back into circulation\n mark_next_unmarked_multiple(sieve, base_factor);\n }\n else if (sieve_base < current_prime_squared) // no non-trivial factor -> found a non-composite\n {\n primes.Add(sieve_base);\n\n if (primes.Count == n)\n return primes;\n }\n else // sieve_base == current_prime_squared\n {\n // bring the current prime into circulation by injecting it into the sieve ...\n mark_next_unmarked_multiple(sieve, primes[current_prime_index]);\n\n // ... and elect a new current prime\n current_prime_squared = square(primes[++current_prime_index]);\n }\n\n // slide the sieve one step forward\n sieve.RemoveAt(0); sieve_base += 2;\n }\n}\n static void mark_next_unmarked_multiple (List<int> sieve, int prime)\n{\n int i = prime, e = sieve.Count;\n\n while (i < e && sieve[i] != 0)\n i += prime;\n\n for ( ; e <= i; ++e) // no List<>.Resize()...\n sieve.Add(0);\n\n sieve[i] = prime;\n}\n\nstatic int square (int n)\n{\n return n * n;\n}\n sieve[0] sieve[0] sieve_base sieve_front window_base sieve[0] sieve_base sieve[0] sieve[0] sieve_base == current_prime_squared sieve[0] == 0 sieve[0] == 0 && sieve_base < current_prime_squared sieve_base int ushort static List<int> small_odd_primes_up_to (int n)\n{\n var result = new List<int>();\n\n if (n < 3)\n return result;\n\n int sqrt_n_halved = (int)(Math.Sqrt(n) - 1) >> 1, max_bit = (n - 1) >> 1;\n var odd_composite = new bool[max_bit + 1];\n\n for (int i = 3 >> 1; i <= sqrt_n_halved; ++i)\n if (!odd_composite[i])\n for (int p = (i << 1) + 1, j = p * p >> 1; j <= max_bit; j += p)\n odd_composite[j] = true;\n\n result.Add(3); // needs to be handled separately because of the mod 3 wheel\n\n // read out the sieved primes\n for (int i = 5 >> 1, d = 1; i <= max_bit; i += d, d ^= 3)\n if (!odd_composite[i])\n result.Add((i << 1) + 1);\n\n return result;\n}\n int uint uint unsigned std::deque<unsigned> unsigned short deque vs simple: 1.802 ms vs 0.182 ms\ndeque vs simple: 1.836 ms vs 0.170 ms \ndeque vs simple: 1.729 ms vs 0.173 ms\n List<int> deque vs simple: 1895.521 ms vs 432.763 ms\ndeque vs simple: 1847.594 ms vs 429.766 ms\ndeque vs simple: 1859.462 ms vs 430.625 ms\n class CCWriter\n{\n const int SPACE_RESERVE = 11; // UInt31 + '\\n'\n\n public static System.IO.Stream BaseStream;\n static byte[] m_buffer = new byte[1 << 16]; // need 55k..60k for a maximum-size range\n static int m_write_pos = 0;\n public static long BytesWritten = 0; // for statistics\n\n internal static ushort[] m_double_digit_lookup = create_double_digit_lookup();\n\n internal static ushort[] create_double_digit_lookup ()\n {\n var lookup = new ushort[100];\n\n for (int lo = 0; lo < 10; ++lo)\n for (int hi = 0; hi < 10; ++hi)\n lookup[hi * 10 + lo] = (ushort)(0x3030 + (hi << 8) + lo);\n\n return lookup;\n }\n\n public static void Flush ()\n {\n if (BaseStream != null && m_write_pos > 0)\n BaseStream.Write(m_buffer, 0, m_write_pos);\n\n BytesWritten += m_write_pos;\n m_write_pos = 0;\n }\n\n public static void WriteLine ()\n {\n if (m_buffer.Length - m_write_pos < 1)\n Flush();\n\n m_buffer[m_write_pos++] = (byte)'\\n';\n }\n\n public static void WriteLinesSorted (int[] values, int count)\n {\n int digits = 1, max_value = 9;\n\n for (int i = 0; i < count; ++i)\n {\n int x = values[i];\n\n if (m_buffer.Length - m_write_pos < SPACE_RESERVE)\n Flush();\n\n while (x > max_value)\n if (++digits < 10)\n max_value = max_value * 10 + 9;\n else\n max_value = int.MaxValue; \n\n int n = x, p = m_write_pos + digits, e = p + 1;\n\n m_buffer[p] = (byte)'\\n';\n\n while (n >= 10)\n {\n int q = n / 100, w = m_double_digit_lookup[n - q * 100];\n n = q;\n m_buffer[--p] = (byte)w;\n m_buffer[--p] = (byte)(w >> 8);\n }\n\n if (n != 0 || x == 0)\n m_buffer[--p] = (byte)((byte)'0' + n);\n\n m_write_pos = e;\n }\n }\n}\n" }, { "answer_id": 37176847, "author": "S_R", "author_id": 4004421, "author_profile": "https://Stackoverflow.com/users/4004421", "pm_score": 1, "selected": false, "text": "/// Get non-negative prime numbers until n using Sieve of Eratosthenes.\npublic int[] GetPrimes(int n) {\n if (n <= 1) {\n return new int[] { };\n }\n\n var mark = new bool[n];\n for(var i = 2; i < n; i++) {\n mark[i] = true;\n }\n\n for (var i = 2; i < Math.Sqrt(n); i++) {\n if (mark[i]) {\n for (var j = (i * i); j < n; j += i) {\n mark[j] = false;\n }\n }\n }\n\n var primes = new List<int>();\n for(var i = 3; i < n; i++) {\n if (mark[i]) {\n primes.Add(i);\n }\n }\n\n return primes.ToArray();\n}\n" }, { "answer_id": 38938100, "author": "Richard Ledbetter", "author_id": 5739951, "author_profile": "https://Stackoverflow.com/users/5739951", "pm_score": 0, "selected": false, "text": "import static java.lang.Math.sqrt;\nimport java.io.PrintWriter;\nimport java.io.File;\npublic class finder {\n public static void main(String[] args) {\n primelist primes = new primelist();\n primes.insert(3);\n primes.insert(5);\n File file = new File(\"C:/Users/Richard/Desktop/directory/file0024.txt\");\n file.getParentFile().mkdirs();\n long time = System.nanoTime();\n try{\n PrintWriter printWriter = new PrintWriter (\"file0024.txt\"); \n int linenum = 0;\n printWriter.print(\"2\");\n printWriter.print (\" , \");\n printWriter.print(\"3\");\n printWriter.print (\" , \");\n int up;\n int down; \n for(int i =1; i<357913941;i++){//\n if(linenum%10000==0){\n printWriter.println (\"\");\n linenum++;\n }\n down = i*6-1;\n if(primes.check(down)){\n primes.insert(down);\n //System.out.println(i*6-1);\n printWriter.print ( down );\n printWriter.print (\" , \");\n linenum++; \n }\n up = i*6+1;\n if(primes.check(up)){\n primes.insert(up);\n //System.out.println(i*6+1);\n printWriter.print ( up );\n printWriter.print (\" , \");\n linenum++; \n }\n }\n printWriter.println (\"Time to execute\");\n printWriter.println (System.nanoTime()-time);\n //System.out.println(primes.length);\n printWriter.close ();\n }catch(Exception e){}\n } \n}\nclass node{\n node next;\n int x;\n public node (){\n node next;\n x = 3;\n }\n public node(int z) {\n node next;\n x = z;\n }\n}\nclass primelist{\n node first;\n int length =0;\n node current;\n public void insert(int x){\n node y = new node(x);\n if(current == null){\n current = y;\n first = y;\n }else{\n current.next = y;\n current = y;\n }\n length++;\n }\n public boolean check(int x){\n int p = (int)sqrt(x);\n node y = first;\n for(int i = 0;i<length;i++){\n if(y.x>p){\n return true;\n }else if(x%y.x ==0){\n return false;\n }\n y = y.next;\n }\n return true;\n }\n}\n" }, { "answer_id": 43820084, "author": "Sagar", "author_id": 7835716, "author_profile": "https://Stackoverflow.com/users/7835716", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n#include <math.h>\n#include <time.h>\n#include <limits.h>\n\n/* Finding prime numbers */\nint main()\n{ \n //pre-phase\n char d,w;\n int l,o;\n printf(\" 1. Find first n number of prime numbers or Find all prime numbers smaller than n ?\\n\"); // this question helps in setting the limits on m or n value i.e l or o \n printf(\" Enter 1 or 2 to get anwser of first or second question\\n\");\n // decision making\n do\n {\n printf(\" -->\");\n scanf(\"%c\",&d);\n while ((w=getchar()) != '\\n' && w != EOF);\n if ( d == '1')\n {\n printf(\"\\n 2. Enter the target no. of primes you will like to find from 3 to 2,000,000 range\\n -->\");\n scanf(\"%10d\",&l);\n o=INT_MAX;\n printf(\" Here we go!\\n\\n\");\n break;\n }\n else if ( d == '2' )\n {\n printf(\"\\n 2.Enter the limit under which to find prime numbers from 5 to 2,000,000 range\\n -->\");\n scanf(\"%10d\",&o);\n l=o/log(o)*1.25;\n printf(\" Here we go!\\n\\n\");\n break;\n }\n else printf(\"\\n Try again\\n\");\n }while ( d != '1' || d != '2' );\n\n clock_t start, end;\n double cpu_time_used;\n start = clock(); /* starting the clock for time keeping */\n\n // main program starts here\n int i,j,c,m,n; /* i ,j , c and m are all prime array 'p' variables and n is the number that is being tested */\n int s,x;\n\n int p[ l ]; /* p is the array for storing prime numbers and l sets the array size, l was initialized in pre-phase */\n p[1]=2;\n p[2]=3;\n p[3]=5;\n printf(\"%10dst:%10d\\n%10dnd:%10d\\n%10drd:%10d\\n\",1,p[1],2,p[2],3,p[3]); // first three prime are set\n for ( i=4;i<=l;++i ) /* this loop sets all the prime numbers greater than 5 in the p array to 0 */\n p[i]=0;\n\n n=6; /* prime number testing begins with number 6 but this can lowered if you wish but you must remember to update other variables too */\n s=sqrt(n); /* 's' does two things it stores the root value so that program does not have to calaculate it again and again and also it stores it in integer form instead of float*/\n x=2; /* 'x' is the biggest prime number that is smaller or equal to root of the number 'n' being tested */\n\n /* j ,x and c are related in this way, p[j] <= prime number x <= p[c] */\n\n // the main loop begins here\n for ( m=4,j=1,c=2; m<=l && n <= o;)\n /* this condition checks if all the first 'l' numbers of primes are found or n does not exceed the set limit o */\n {\n // this will divide n by prime number in p[j] and tries to rule out non-primes\n if ( n%p[j]==0 )\n {\n /* these steps execute if the number n is found to be non-prime */\n\n ++n; /* this increases n by 1 and therefore sets the next number 'n' to be tested */\n s=sqrt(n); /* this calaulates and stores in 's' the new root of number 'n' */\n if ( p[c] <= s && p[c] != x ) /* 'The Magic Setting' tests the next prime number candidate p[c] and if passed it updates the prime number x */\n {\n x=p[c];\n ++c;\n }\n j=1;\n /* these steps sets the next number n to be tested and finds the next prime number x if possible for the new number 'n' and also resets j to 1 for the new cycle */\n continue; /* and this restarts the loop for the new cycle */\n }\n // confirmation test for the prime number candidate n\n else if ( n%p[j]!=0 && p[j]==x )\n {\n /* these steps execute if the number is found to be prime */\n p[m]=n;\n printf(\"%10dth:%10d\\n\",m,p[m]);\n ++n;\n s = sqrt(n);\n ++m;\n j=1;\n /* these steps stores and prints the new prime number and moves the 'm' counter up and also sets the next number n to be tested and also resets j to 1 for the new cycle */\n continue; /* and this restarts the loop */\n /* the next number which will be a even and non-prime will trigger the magic setting in the next cycle and therfore we do not have to add another magic setting here*/\n }\n ++j; /* increases p[j] to next prime number in the array for the next cycle testing of the number 'n' */\n // if the cycle reaches this point that means the number 'n' was neither divisible by p[j] nor was it a prime number\n // and therfore it will test the same number 'n' again in the next cycle with a bigger prime number\n }\n // the loops ends\n printf(\" All done !!\\n\");\n end = clock();\n cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;\n printf(\" Time taken : %lf sec\\n\",cpu_time_used);\n}\n" }, { "answer_id": 48358041, "author": "bumblebee", "author_id": 8552409, "author_profile": "https://Stackoverflow.com/users/8552409", "pm_score": 0, "selected": false, "text": "enter code here\n#include <cmath>\n#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\n\nint main() {\n/* Enter your code here. Read input from STDIN. Print output to STDOUT*/ \n\nunsigned long int n;\n\nint prime(unsigned long int);\n\nscanf(\"%ld\",&n);\n\nunsigned long int val;\n\nfor(unsigned long int i=0;i<n;i++)\n{\n int flag=0;\n\n scanf(\"%ld\",&val);\n\n flag=prime(val);\n\n if(flag==1)\n printf(\"yes\\n\");\n\n else\n printf(\"no\\n\");\n}\n\nreturn 0;\n\n}\n\nint prime(unsigned long int n)\n{\n\nif(n==2) return 1;\n\nelse if (n == 1||n%2==0) return 0;\n\nfor (unsigned long int i=3; i<=sqrt(n); i+=2)\n if (n%i == 0)\n return 0;\n\nreturn 1;\n}\n" }, { "answer_id": 50778831, "author": "Flavio", "author_id": 3310801, "author_profile": "https://Stackoverflow.com/users/3310801", "pm_score": 0, "selected": false, "text": "function isPrime (number) {\n\n function prime(element) {\n let start = 2;\n while (start <= Math.sqrt(element)) {\n if (element % start++ < 1) {\n return false;\n }\n }\n return element > 1;\n }\n\n return [number].find(prime)\n\n}\n\nfunction logPrimes (n) {\n\n let count = 0\n let nth = n\n\n let i = 0\n while (count < nth) {\n if (isPrime(i)) {\n count++\n console.log('i', i) //NOTE: If this line is ommited time to find 10,000th prime is 121.157ms\n if (count === nth) {\n console.log('while i', i)\n console.log('count', count)\n }\n }\n i++\n }\n\n}\n\nconsole.time(logPrimes)\n\nlogPrimes(10000)\n\nconsole.timeEnd(logPrimes) // 2214.486ms\n" }, { "answer_id": 53332013, "author": "itsjwala", "author_id": 9485283, "author_profile": "https://Stackoverflow.com/users/9485283", "pm_score": 0, "selected": false, "text": "boolean isPrime(int n){\n//even but is prime\n if(n==2)\n return true;\n//even numbers filtered already \n if(n==0 || n==1 || n%2==0)\n return false;\n\n// loop for checking only odd factors\n// i*i <= n (same as i<=sqrt(n), avoiding floating point calculations)\n for(int i=3 ; i*i <=n ; i+=2){\n // if any odd factor divides n then its not a prime!\n if(n%i==0)\n return false;\n }\n// its prime now\n return true;\n}\n for(int i=1 ; i<=1000 ; i++){\n if(isPrime(i)){\n //do something\n }\n}\n" }, { "answer_id": 58829625, "author": "Steven Armstrong", "author_id": 1946543, "author_profile": "https://Stackoverflow.com/users/1946543", "pm_score": 0, "selected": false, "text": "check x = null $ filter ((==0) . (x `mod`)) $ [<primes up to 101>]\nPrelude> length $ filter check [101,103..85600]\n>>> 9975\n(0.30 secs, 125,865,152 bytes\n\na = 16294579238595022365 :: Word64\nb = 14290787196698157718\npre = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]\nprimes = (pre ++) $ filter ((==1) . gcd a) $ filter ((==1) . gcd b) [99,101..85600]\nmain = print $ length primes\n\nPrelude> main\n>>> 10000\n(0.05 secs, 36,387,520 bytes)\n length int64 BigInt ...\\Haskell\\8.6\\Testbed>Primes.exe +RTS -s\n10000\n606,280 bytes allocated in the heap\nTotal time 0.000s ( 0.004s elapsed)\n main = print 10000 ...Haskell\\8.6\\Testbed>Primes.exe +RTS -s\n10000\n47,688 bytes allocated in the heap\nTotal time 0.000s ( 0.001s elapsed)\n wheel = scanl (+) 7 $ cycle [4, 2, 4, 2, 4, 6, 2, 6]\nprimes = (pre ++) $ filter ((==1) . gcd a) $ filter ((==1) . gcd b) $ takeWhile (<85600) wheel\n\nTotal time 0.000s ( 0.003s elapsed)\n main = print 10000 Tue Nov 12 21:13 2019 Time and Allocation Profiling Report (Final)\n\n Primes.exe +RTS -p -RTS\n\ntotal time = 0.00 secs (2 ticks @ 1000 us, 1 processor)\ntotal alloc = 967,120 bytes (excludes profiling overheads)\n" }, { "answer_id": 61831666, "author": "mohamad eldimardash", "author_id": 9234603, "author_profile": "https://Stackoverflow.com/users/9234603", "pm_score": 0, "selected": false, "text": "def compute_primes(bound):\n\"\"\"\nReturn a list of the prime numbers in range(2, bound)\nImplement the Sieve of Eratosthenes\nhttps://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\n\"\"\"\nprimeNumber = [True for i in range(bound + 1)]\nstart_prime_number = 2\nprimes = []\nwhile start_prime_number * start_prime_number <=bound:\n # If primeNumber[start_prime_number] is not changed, then it is a prime\n if primeNumber[start_prime_number]:\n # Update all multiples of start_prime_number\n for i in range(start_prime_number * start_prime_number, bound + 1, start_prime_number):\n primeNumber[i] = False\n start_prime_number += 1\n\n# Print all prime numbers\nfor start_prime_number in range(2, bound + 1):\n if primeNumber[start_prime_number]:\n primes.append(start_prime_number)\n\nreturn primes\n" }, { "answer_id": 74401260, "author": "1729-Shivam-Maurya", "author_id": 19608147, "author_profile": "https://Stackoverflow.com/users/19608147", "pm_score": 0, "selected": false, "text": "import math\n \nk=0\n\nfactor=0\n\npl=[]\n\nfor i in range(1,1000000):\n\n k=int(math.sqrt(i))\n if i==2 or i==3:\n pl.append(i)\n for j in range(2,k+1):\n if i%j==0:\n factor=factor+1\n elif factor==0 and j==k:\n pl.append(i)\n factor=0\n\nprint(pl) \nprint(len(pl))\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
626
<p>In Ruby 1.8, there are subtle differences between proc/lambda on the one hand, and <code>Proc.new</code> on the other. </p> <ul> <li>What are those differences?</li> <li>Can you give guidelines on how to decide which one to choose?</li> <li>In Ruby 1.9, proc and lambda are different. What's the deal?</li> </ul>
[ { "answer_id": 629, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 5, "selected": false, "text": "Proc.new lambda Proc.new nil" }, { "answer_id": 723, "author": "Joey deVilla", "author_id": 216, "author_profile": "https://Stackoverflow.com/users/216", "pm_score": 10, "selected": true, "text": "lambda Proc.new return lambda return Proc.new return lambda return def whowouldwin\n\n mylambda = lambda {return \"Freddy\"}\n mylambda.call\n\n # mylambda gets called and returns \"Freddy\", and execution\n # continues on the next line\n\n return \"Jason\"\n\nend\n\n\nwhowouldwin\n#=> \"Jason\"\n Proc.new return def whowouldwin2\n\n myproc = Proc.new {return \"Freddy\"}\n myproc.call\n\n # myproc gets called and returns \"Freddy\", \n # but also returns control from whowhouldwin2!\n # The line below *never* gets executed.\n\n return \"Jason\"\n\nend\n\n\nwhowouldwin2 \n#=> \"Freddy\"\n lambda Proc.new" }, { "answer_id": 7484, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "return" }, { "answer_id": 48054, "author": "Peeja", "author_id": 4937, "author_profile": "https://Stackoverflow.com/users/4937", "pm_score": 2, "selected": false, "text": "Proc.new lambda {...} return Proc.new" }, { "answer_id": 303428, "author": "webmat", "author_id": 6349, "author_profile": "https://Stackoverflow.com/users/6349", "pm_score": 4, "selected": false, "text": "stabby = ->(msg='inside the stabby lambda') { puts msg }\n # under 1.8\nl = lambda { |msg = 'inside the stabby lambda'| puts msg }\nSyntaxError: compile error\n(irb):1: syntax error, unexpected '=', expecting tCOLON2 or '[' or '.'\nl = lambda { |msg = 'inside the stabby lambda'| puts msg }\n l = lambda { |msg = 'inside the regular lambda'| puts msg }\n#=> #<Proc:0x0e5dbc@(irb):1 (lambda)>\nl.call\n#=> inside the regular lambda\nl.call('jeez')\n#=> jeez\n" }, { "answer_id": 1043390, "author": "Dave Rapin", "author_id": 34210, "author_profile": "https://Stackoverflow.com/users/34210", "pm_score": 3, "selected": false, "text": "def meth1\n puts \"method start\"\n\n pr = lambda { return }\n pr.call\n\n puts \"method end\" \nend\n\ndef meth2\n puts \"method start\"\n\n pr = Proc.new { return }\n pr.call\n\n puts \"method end\" \nend\n\ndef meth3\n puts \"method start\"\n\n pr = proc { return }\n pr.call\n\n puts \"method end\" \nend\n\nputs \"Using lambda\"\nmeth1\nputs \"--------\"\nputs \"using Proc.new\"\nmeth2\nputs \"--------\"\nputs \"using proc\"\nmeth3\n" }, { "answer_id": 1515670, "author": "Peter Wagenet", "author_id": 181916, "author_profile": "https://Stackoverflow.com/users/181916", "pm_score": 7, "selected": false, "text": "Proc.new concat = ->(a, b=2){ \"#{a}#{b}\" }\nconcat.call(4,5) # => \"45\"\nconcat.call(1) # => \"12\"\n break next redo raise retry proc Proc.new" }, { "answer_id": 7678836, "author": "Evan Moran", "author_id": 47593, "author_profile": "https://Stackoverflow.com/users/47593", "pm_score": 4, "selected": false, "text": "return" }, { "answer_id": 26635646, "author": "weakish", "author_id": 222893, "author_profile": "https://Stackoverflow.com/users/222893", "pm_score": 3, "selected": false, "text": "Proc.new return Proc.new def some_method\n myproc = Proc.new {return \"End.\"}\n myproc.call\n\n # Any code below will not get executed!\n # ...\nend\n Proc.new Proc.new Proc.new Proc.new irb(main):021:0> l = -> (x) { x.to_s }\n=> #<Proc:0x8b63750@(irb):21 (lambda)>\nirb(main):022:0> p = Proc.new { |x| x.to_s}\n=> #<Proc:0x8b59494@(irb):22>\nirb(main):025:0> l.call\nArgumentError: wrong number of arguments (0 for 1)\n from (irb):21:in `block in irb_binding'\n from (irb):25:in `call'\n from (irb):25\n from /usr/bin/irb:11:in `<main>'\nirb(main):026:0> p.call\n=> \"\"\nirb(main):049:0> l.call 1, 2\nArgumentError: wrong number of arguments (2 for 1)\n from (irb):47:in `block in irb_binding'\n from (irb):49:in `call'\n from (irb):49\n from /usr/bin/irb:11:in `<main>'\nirb(main):050:0> p.call 1, 2\n=> \"1\"\n proc Proc.new" }, { "answer_id": 29920634, "author": "Aleksei Matiushkin", "author_id": 2035262, "author_profile": "https://Stackoverflow.com/users/2035262", "pm_score": 2, "selected": false, "text": "Proc.new Proc::new Proc Proc.new def m1\n yield 'Finally!' if block_given?\nend\n\ndef m2\n m1 &Proc.new\nend\n\nm2 { |e| puts e } \n#⇒ Finally!\n" }, { "answer_id": 53316814, "author": "ComDubh", "author_id": 1445986, "author_profile": "https://Stackoverflow.com/users/1445986", "pm_score": 2, "selected": false, "text": "return def foo\n proc = Proc.new{return}\n foobar(proc)\n puts 'foo'\nend\n\ndef foobar(proc)\n proc.call\n puts 'foobar'\nend\n\nfoo\n foobar foo return foo foobar return" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136/" ]
644
<p>I have a database table and one of the fields (not the primary key) is having a unique index on it. Now I want to swap values under this column for two rows. How could this be done? Two hacks I know are:</p> <ol> <li>Delete both rows and re-insert them.</li> <li>Update rows with some other value and swap and then update to actual value.</li> </ol> <p>But I don't want to go for these as they do not seem to be the appropriate solution to the problem. Could anyone help me out?</p>
[ { "answer_id": 73258, "author": "Andy Irving", "author_id": 8553, "author_profile": "https://Stackoverflow.com/users/8553", "pm_score": 2, "selected": false, "text": "CREATE TABLE testing\n(\n cola int NOT NULL,\n colb CHAR(1) NOT NULL\n);\n\nCREATE UNIQUE INDEX UIX_testing_a ON testing(colb);\n\nINSERT INTO testing VALUES (1, 'b');\nINSERT INTO testing VALUES (2, 'a');\n\nSELECT * FROM testing;\n\nUPDATE testing\nSET colb = CASE cola WHEN 1 THEN 'a'\n WHEN 2 THEN 'b'\n END\nWHERE cola IN (1,2);\n\nSELECT * FROM testing;\n cola colb\n------------\n1 b\n2 a\n cola colb\n------------\n1 a\n2 b\n" }, { "answer_id": 355870, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "UPDATE DOCDATA \nSET LNUM = CASE LNUM\n WHEN 0 THEN 1\n WHEN 1 THEN 2 \n WHEN 2 THEN 0 \n END\nWHERE (pID = 10) \n AND (LNUM IN (0, 1, 2))\n" }, { "answer_id": 10018113, "author": "Mark Gaulin", "author_id": 811161, "author_profile": "https://Stackoverflow.com/users/811161", "pm_score": 3, "selected": false, "text": "-- setup initial data values:\ninsert into data_table(id, name) values(1, 'A')\ninsert into data_table(id, name) values(2, 'B')\n\n-- create temp table that matches live table\nselect top 0 * into #tmp_data_table from data_table\n\n-- insert records to be swapped\ninsert into #tmp_data_table(id, name) values(1, 'B')\ninsert into #tmp_data_table(id, name) values(2, 'A')\n\n-- update both rows at once! No index violations!\nupdate data_table set name = #tmp_data_table.name\nfrom data_table join #tmp_data_table on (data_table.id = #tmp_data_table.id)\n" }, { "answer_id": 12437451, "author": "wildplasser", "author_id": 905902, "author_profile": "https://Stackoverflow.com/users/905902", "pm_score": 5, "selected": false, "text": "DROP TABLE ztable CASCADE;\nCREATE TABLE ztable\n ( id integer NOT NULL PRIMARY KEY\n , payload varchar\n );\nINSERT INTO ztable(id,payload) VALUES (1,'one' ), (2,'two' ), (3,'three' );\nSELECT * FROM ztable;\n\n\n -- This works, because there is no constraint\nUPDATE ztable t1\nSET payload=t2.payload\nFROM ztable t2\nWHERE t1.id IN (2,3)\nAND t2.id IN (2,3)\nAND t1.id <> t2.id\n ;\nSELECT * FROM ztable;\n\nALTER TABLE ztable ADD CONSTRAINT OMG_WTF UNIQUE (payload)\n DEFERRABLE INITIALLY DEFERRED\n ;\n\n -- This should also work, because the constraint \n -- is deferred until \"commit time\"\nUPDATE ztable t1\nSET payload=t2.payload\nFROM ztable t2\nWHERE t1.id IN (2,3)\nAND t2.id IN (2,3)\nAND t1.id <> t2.id\n ;\nSELECT * FROM ztable;\n DROP TABLE\nNOTICE: CREATE TABLE / PRIMARY KEY will create implicit index \"ztable_pkey\" for table \"ztable\"\nCREATE TABLE\nINSERT 0 3\n id | payload\n----+---------\n 1 | one\n 2 | two\n 3 | three\n(3 rows)\n\nUPDATE 2\n id | payload\n----+---------\n 1 | one\n 2 | three\n 3 | two\n(3 rows)\n\nNOTICE: ALTER TABLE / ADD UNIQUE will create implicit index \"omg_wtf\" for table \"ztable\"\nALTER TABLE\nUPDATE 2\n id | payload\n----+---------\n 1 | one\n 2 | two\n 3 | three\n(3 rows)\n" }, { "answer_id": 36892474, "author": "TheBakker", "author_id": 3215673, "author_profile": "https://Stackoverflow.com/users/3215673", "pm_score": 2, "selected": false, "text": "SET CONSTRAINT emp_no_fk_par DEFERRED; \n" }, { "answer_id": 53168583, "author": "Lazy Programmer", "author_id": 9355939, "author_profile": "https://Stackoverflow.com/users/9355939", "pm_score": 1, "selected": false, "text": "id student \n\n1 Abbot \n2 Doris \n3 Emerson \n4 Green \n5 Jeames \n 1 Doris \n2 Abbot \n3 Green \n4 Emerson \n5 Jeames \n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
650
<p>I would like the version property of my application to be incremented for each build but I'm not sure on how to enable this functionality in Visual Studio (2005/2008). I have tried to specify the AssemblyVersion as 1.0.* but it doesn't get me exactly what I want. </p> <p>I'm also using a settings file and in earlier attempts when the assembly version changed my settings got reset to the default since the application looked for the settings file in another directory. </p> <p>I would like to be able to display a version number in the form of 1.1.38 so when a user finds a problem I can log the version they are using as well as tell them to upgrade if they have an old release.</p> <p>A short explanation of how the versioning works would also be appreciated. When does the build and revision number get incremented?</p>
[ { "answer_id": 655, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 8, "selected": true, "text": "Version v = Assembly.GetExecutingAssembly().GetName().Version;\nstring About = string.Format(CultureInfo.InvariantCulture, @\"YourApp Version {0}.{1}.{2} (r{3})\", v.Major, v.Minor, v.Build, v.Revision);\n" }, { "answer_id": 155067, "author": "Solracnapod", "author_id": 8900, "author_profile": "https://Stackoverflow.com/users/8900", "pm_score": 4, "selected": false, "text": "' Version information for an assembly consists of the following four values:\n'\n' Major Version\n' Minor Version \n' Build Number\n' Revision\n'\n' You can specify all the values or you can default the Build and Revision Numbers \n' by using the '*' as shown below:\n' <Assembly: AssemblyVersion(\"1.0.*\")> \n\n<Assembly: AssemblyVersion(\"1.0.0.0\")> \n<Assembly: AssemblyFileVersion(\"1.0.0.0\")> \n" }, { "answer_id": 15211000, "author": "user8128167", "author_id": 351154, "author_profile": "https://Stackoverflow.com/users/351154", "pm_score": 4, "selected": false, "text": "System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString(\"yyyy.MM.dd.HH.mm.ss\")\n System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();\nobject[] attributes = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyFileVersionAttribute), false);\nobject attribute = null;\n\nif (attributes.Length > 0)\n{\n attribute = attributes[0] as System.Reflection.AssemblyFileVersionAttribute;\n}\n" }, { "answer_id": 43894925, "author": "Nacho Coll", "author_id": 7975865, "author_profile": "https://Stackoverflow.com/users/7975865", "pm_score": 3, "selected": false, "text": "Microsoft.Build.Utilities.Task using Microsoft.Build.Framework;\nusing System;\nusing System.Collections.Generic;\nusing System.Text;\n\npublic class RefreshVersion : Microsoft.Build.Utilities.Task\n{\n [Output]\n public string NewVersionString { get; set; }\n public string CurrentVersionString { get; set; } \n\n public override bool Execute()\n { \n Version currentVersion = new Version(CurrentVersionString ?? \"1.0.0\");\n\n DateTime d = DateTime.Now;\n NewVersionString = new Version(currentVersion.Major, \n currentVersion.Minor, currentVersion.Build+1).ToString();\n return true;\n }\n\n}\n <Project Sdk=\"Microsoft.NET.Sdk\"> \n...\n<UsingTask TaskName=\"RefreshVersion\" AssemblyFile=\"$(MSBuildThisFileFullPath)\\..\\..\\<dll path>\\BuildTasks.dll\" />\n<Target Name=\"RefreshVersionBuildTask\" BeforeTargets=\"Pack\" Condition=\"'$(Configuration)|$(Platform)'=='Release|AnyCPU'\">\n <RefreshVersion CurrentVersionString=\"$(PackageVersion)\">\n <Output TaskParameter=\"NewVersionString\" PropertyName=\"NewVersionString\" /> \n </RefreshVersion>\n <Message Text=\"Updating package version number to $(NewVersionString)...\" Importance=\"high\" />\n <XmlPoke XmlInputPath=\"$(MSBuildProjectDirectory)\\mustache.website.sdk.dotNET.csproj\" Query=\"/Project/PropertyGroup/PackageVersion\" Value=\"$(NewVersionString)\" />\n</Target>\n...\n<PropertyGroup>\n ..\n <PackageVersion>1.1.4</PackageVersion>\n ..\n BeforeTargets=\"Build\" XmlPoke <Message Text=\"Uploading package to NuGet...\" Importance=\"high\" />\n<Exec WorkingDirectory=\"$(MSBuildProjectDirectory)\\bin\\release\" Command=\"c:\\nuget\\nuget push *.nupkg -Source https://www.nuget.org/api/v2/package\" IgnoreExitCode=\"true\" />\n c:\\nuget\\nuget nuget SetApiKey <my-api-key>" }, { "answer_id": 67165881, "author": "GrahamS", "author_id": 79591, "author_profile": "https://Stackoverflow.com/users/79591", "pm_score": 0, "selected": false, "text": "AssemblyVersion AssemblyFileVersion BUILD_NUMBER if (Test-Path env:BUILD_NUMBER) {\n Write-Host \"Updating AssemblyVersion to $env:BUILD_NUMBER\"\n\n # Get the AssemblyInfo.cs\n $assemblyInfo = Get-Content -Path .\\MyShinyApplication\\Properties\\AssemblyInfo.cs\n\n # Replace last digit of AssemblyVersion\n $assemblyInfo = $assemblyInfo -replace \n \"^\\[assembly: AssemblyVersion\\(`\"([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.[0-9]+`\"\\)]\", \n ('[assembly: AssemblyVersion(\"$1.$2.$3.' + $env:BUILD_NUMBER + '\")]')\n Write-Host ($assemblyInfo -match '^\\[assembly: AssemblyVersion')\n \n # Replace last digit of AssemblyFileVersion\n $assemblyInfo = $assemblyInfo -replace \n \"^\\[assembly: AssemblyFileVersion\\(`\"([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.[0-9]+`\"\\)]\", \n ('[assembly: AssemblyFileVersion(\"$1.$2.$3.' + $env:BUILD_NUMBER + '\")]')\n Write-Host ($assemblyInfo -match '^\\[assembly: AssemblyFileVersion')\n \n $assemblyInfo | Set-Content -Path .\\MyShinyApplication\\Properties\\AssemblyInfo.cs -Encoding UTF8\n} else {\n Write-Warning \"BUILD_NUMBER is not set.\"\n}\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/143/" ]
651
<p>I've been having trouble getting my ASP.NET application to automatically log users into the Intranet site I'm building. No matter the googling or the experimentation I applied, there is always a login box displayed by IE7.</p> <p>I've got Windows authentication mode set in the Web.config, disabled anonymous access and configured the correct default domain in IIS, but it's still asking the user to log in and, more annoyingly, the user is required to provide the domain too (<em>DOMAIN\auser</em>), which is causing problems with non-technical visitors. Thank Zeus for password remembering functionality.</p> <p>I'm not the network administrator so it's possible that something about Active Directory is set up incorrectly, or it could just be me missing something very simple. Please note that I don't want to impersonate the user, I just need to know that the IPrincipal.Name property matches that of a valid record in my user database, hence authenticating the user to my application.</p> <p>To this end, it would be very useful to have a checklist of all configuration requirements for AD, ASP.NET and IIS to work together in this manner as a reference for debugging and hopefully reducing some user friction.</p>
[ { "answer_id": 90759, "author": "Dani", "author_id": 17330, "author_profile": "https://Stackoverflow.com/users/17330", "pm_score": 1, "selected": false, "text": "Active Directory Users and Computers computers TreeView" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
657
<p>What is the fastest, yet secure way to encrypt passwords (in PHP preferably), and for whichever method you choose, is it portable?</p> <p>In other words, if I later migrate my website to a different server, will my passwords continue to work?</p> <p>The method I am using now, as I was told, is dependent on the exact versions of the libraries installed on the server.</p>
[ { "answer_id": 85951, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 3, "selected": false, "text": "password1 PasswordSaltDesignedForThisQuestion String s = HashStringSHA256(\"password1PasswordSaltDesignedForThisQuestion\");\n" }, { "answer_id": 38409027, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 1, "selected": false, "text": "bcrypt" }, { "answer_id": 50417253, "author": "Jeff Harris", "author_id": 4722264, "author_profile": "https://Stackoverflow.com/users/4722264", "pm_score": 0, "selected": false, "text": "password_hash ( string $password , int $algo [, array $options ] ) password_hash() password_hash() crypt() crypt() password_hash()" }, { "answer_id": 58778226, "author": "Femostica ", "author_id": 12325376, "author_profile": "https://Stackoverflow.com/users/12325376", "pm_score": 0, "selected": false, "text": "}else{\necho \"password not correct\";\n}\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
683
<p>I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like,</p> <pre><code>foo in iter_attr(array of python objects, attribute name)</code></pre> <p>I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers</p>
[ { "answer_id": 701, "author": "saalon", "author_id": 111, "author_profile": "https://Stackoverflow.com/users/111", "pm_score": 3, "selected": false, "text": " files = os.listdir(path) \n test = re.compile(\"test\\.py$\", re.IGNORECASE) \n files = [f for f in files if test.search(f)]\n" }, { "answer_id": 735, "author": "akdom", "author_id": 145, "author_profile": "https://Stackoverflow.com/users/145", "pm_score": 0, "selected": false, "text": "#!/bin/python\nbar in dict(Foo)\n has_key() in dict foo bar #!/bin/python\nbaz = dict([(key, value) for key, value in foo if bar in value])\n if bar in value baz" }, { "answer_id": 745, "author": "Matt", "author_id": 154, "author_profile": "https://Stackoverflow.com/users/154", "pm_score": 4, "selected": false, "text": "result = [obj for obj in listOfObjs if hasattr(obj, 'attributeName')]\n" }, { "answer_id": 750, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 3, "selected": false, "text": "foo = 12\nfoo in iter_attr(bar, 'id') foo = 12\nfoo in [obj.id for obj in bar]" }, { "answer_id": 31126, "author": "dwestbrook", "author_id": 3119, "author_profile": "https://Stackoverflow.com/users/3119", "pm_score": 3, "selected": false, "text": "def iterattr(iterator, attributename):\n for obj in iterator:\n yield getattr(obj, attributename)\n" }, { "answer_id": 57833, "author": "Will Harris", "author_id": 4702, "author_profile": "https://Stackoverflow.com/users/4702", "pm_score": 7, "selected": true, "text": "in foo = 12\nfoo in (obj.id for obj in bar)\n obj.id == 12 bar bar hasattr bar id foo = 12\nfoo in (obj.id for obj in bar if hasattr(obj, 'id'))\n" }, { "answer_id": 4905822, "author": "shang", "author_id": 572606, "author_profile": "https://Stackoverflow.com/users/572606", "pm_score": 3, "selected": false, "text": "operator.attrgettter import operator\nids = map(operator.attrgetter(\"id\"), bar) any(obj.id == 12 for obj in bar) import operator,itertools\nfoo = 12\nfoo in itertools.imap(operator.attrgetter(\"id\"), bar)\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/199/" ]
705
<p>I was (and still am) looking for an embedded database to be used in a .net (c#) application. The caveat: The Application (or at least the database) is stored on a Network drive, but only used by 1 user at a time.</p> <p>Now, my first idea was <a href="http://www.microsoft.com/sql/editions/compact/default.mspx" rel="nofollow noreferrer">SQL Server Compact edition</a>. That is really nicely integreated, but it can not run off a network.</p> <p><a href="http://web.archive.org/web/20100615004036/http://firebirdsql.org/dotnetfirebird/" rel="nofollow noreferrer">Firebird</a> seems to have the same issue, but the .net Integration seems to be not really first-class and is largely undocumented.</p> <p><a href="http://web.archive.org/web/20150510070451/http://www.codegear.com/products/blackfish" rel="nofollow noreferrer">Blackfish SQL</a> looks interesting, but there is no trial of the .net Version. Pricing is also OK.</p> <p>Any other suggestions of something that works well with .net <strong>and</strong> runs off a network without the need of actually installing a server software?</p>
[ { "answer_id": 737, "author": "Justin Walgran", "author_id": 173, "author_profile": "https://Stackoverflow.com/users/173", "pm_score": 3, "selected": false, "text": "Dim catalog as New ADOX.Catalog\nCatalog.Create(\"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\server\\path\\to\\db.mdb\")\n" }, { "answer_id": 6751, "author": "Fabio Gomes", "author_id": 727, "author_profile": "https://Stackoverflow.com/users/727", "pm_score": 3, "selected": false, "text": "using FirebirdSql.Data.FirebirdClient;\n\npublic static IDbConnection MyConnection()\n{\n FbConnection cn = new FbConnection(\"...\");\n return cn;\n}\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
717
<p>I wrote a windows service using VB that read some legacy data from Visual Foxpro Databases to be inserted in SQL 2005. The problem is this use to run fine in Windows server 2003 32-Bits, but the client recently moved to Windows 2003 64-Bits and now the service won't work. I'm getting a message the the VFP .NET OLEdb provider is not found. I researched and everything seems to point out that there is no solution. Any Help, please...</p>
[ { "answer_id": 799, "author": "Paul G", "author_id": 162, "author_profile": "https://Stackoverflow.com/users/162", "pm_score": 5, "selected": true, "text": "x86 \"Any CPU\" OLEDB" }, { "answer_id": 877, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 3, "selected": false, "text": "CPU x86 32 bit VFP OLE Db provider 64-bit Visual FoxPro 2015 OLE DB VFP 9" }, { "answer_id": 4074, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 1, "selected": false, "text": "Sybase Anywhere OLEDB provider VFP 64 bit Windows OLEDB provider" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
742
<p><a href="http://www.djangoproject.com/" rel="noreferrer">Django</a> view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach.</p> <p>For example, I have a page that displays a user. This page is very similar to page that displays a group, but it's still not so similar to just use another data model. Group also has members etc...</p> <p>One way would be to point views to class methods and then extend that class. Has anyone tried this approach or has any other idea? </p>
[ { "answer_id": 27792, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 2, "selected": false, "text": "__call__" }, { "answer_id": 33957, "author": "Carl Meyer", "author_id": 3207, "author_profile": "https://Stackoverflow.com/users/3207", "pm_score": 7, "selected": true, "text": "__call__" }, { "answer_id": 2921293, "author": "Erik Allik", "author_id": 351981, "author_profile": "https://Stackoverflow.com/users/351981", "pm_score": 4, "selected": false, "text": "class CallableViewClass(type):\n def __call__(cls, *args, **kwargs):\n if args and isinstance(args[0], HttpRequest):\n instance = super(CallableViewClass, cls).__call__()\n return instance.__call__(*args, **kwargs)\n else:\n instance = super(CallableViewClass, cls).__call__(*args, **kwargs)\n return instance\n\n\nclass View(object):\n __metaclass__ = CallableViewClass\n\n def __call__(self, request, *args, **kwargs):\n if hasattr(self, request.method):\n handler = getattr(self, request.method)\n if hasattr(handler, '__call__'):\n return handler(request, *args, **kwargs)\n return HttpResponseBadRequest('Method Not Allowed', status=405)\n __call__ HttpRequest HttpRequest class MyView(View):\n def __init__(self, arg=None):\n self.arg = arg\n def GET(request):\n return HttpResponse(self.arg or 'no args provided')\n\n@login_required\nclass MyOtherView(View):\n def POST(request):\n pass\n\n# And all the following work as expected.\nurlpatterns = patterns(''\n url(r'^myview1$', 'myapp.views.MyView', name='myview1'),\n url(r'^myview2$', myapp.views.MyView, name='myview2'),\n url(r'^myview3$', myapp.views.MyView('foobar'), name='myview3'),\n url(r'^myotherview$', 'myapp.views.MyOtherView', name='otherview'),\n)\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/189/" ]
746
<p>How do I format a string to <a href="http://www.grammar-monster.com/lessons/capital_letters_title_case.htm" rel="noreferrer">title case</a>?</p>
[ { "answer_id": 747, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 4, "selected": false, "text": "public static string ToTitleCaseInvariant(string targetString)\n{\n return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(targetString);\n}\n" }, { "answer_id": 749, "author": "cmcculloh", "author_id": 58, "author_profile": "https://Stackoverflow.com/users/58", "pm_score": 3, "selected": false, "text": "$HelloWorld = ucwords('hello world');\n" }, { "answer_id": 751, "author": "Rudd Zwolinski", "author_id": 219, "author_profile": "https://Stackoverflow.com/users/219", "pm_score": -1, "selected": false, "text": "\nconvert first character to uppercase.\nfor each character in string,\n if the previous character is whitespace,\n convert character to uppercase.\n" }, { "answer_id": 754, "author": "Lehane", "author_id": 142, "author_profile": "https://Stackoverflow.com/users/142", "pm_score": 3, "selected": false, "text": "ToTitleCase" }, { "answer_id": 771, "author": "engtech", "author_id": 175, "author_profile": "https://Stackoverflow.com/users/175", "pm_score": 3, "selected": false, "text": "'some string here'.gsub(/\\b\\w/){$&.upcase}\n" }, { "answer_id": 71282, "author": "robbiebow", "author_id": 11782, "author_profile": "https://Stackoverflow.com/users/11782", "pm_score": -1, "selected": false, "text": "my $tc_string = join ' ', map { ucfirst($\\_) } split /\\s+/, $string;\n" }, { "answer_id": 151018, "author": "Randal Schwartz", "author_id": 22483, "author_profile": "https://Stackoverflow.com/users/22483", "pm_score": 3, "selected": false, "text": "$string =~ s/(\\w+)/\\u\\L$1/g;\n" }, { "answer_id": 151181, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <vector>\n#include <cctype>\n#include <set>\n\nusing namespace std;\n\ntypedef vector<pair<string, int> > subDivision;\nset<string> nonUpperCaseAble;\n\nsubDivision split(string & cadena, string delim = \" \"){\n subDivision retorno;\n int pos, inic = 0;\n while((pos = cadena.find_first_of(delim, inic)) != cadena.npos){\n if(pos-inic > 0){\n retorno.push_back(make_pair(cadena.substr(inic, pos-inic), inic));\n }\n inic = pos+1;\n }\n if(inic != cadena.length()){\n retorno.push_back(make_pair(cadena.substr(inic, cadena.length() - inic), inic));\n }\n return retorno;\n}\n\nstring firstUpper (string & pal){\n pal[0] = toupper(pal[0]);\n return pal;\n}\n\nint main()\n{\n nonUpperCaseAble.insert(\"the\");\n nonUpperCaseAble.insert(\"of\");\n nonUpperCaseAble.insert(\"in\");\n // ...\n\n string linea, resultado;\n cout << \"Type the line you want to convert: \" << endl;\n getline(cin, linea);\n\n subDivision trozos = split(linea);\n for(int i = 0; i < trozos.size(); i++){\n if(trozos[i].second == 0)\n {\n resultado += firstUpper(trozos[i].first);\n }\n else if (linea[trozos[i].second-1] == ' ')\n {\n if(nonUpperCaseAble.find(trozos[i].first) == nonUpperCaseAble.end())\n {\n resultado += \" \" + firstUpper(trozos[i].first);\n }else{\n resultado += \" \" + trozos[i].first;\n }\n }\n else\n {\n resultado += trozos[i].first;\n } \n }\n\n cout << resultado << endl;\n getchar();\n return 0;\n}\n" }, { "answer_id": 1861303, "author": "user226515", "author_id": 226515, "author_profile": "https://Stackoverflow.com/users/226515", "pm_score": 1, "selected": false, "text": "string sourceName = txtTextBox.Text.ToLower();\nstring destinationName = sourceName[0].ToUpper();\n\nfor (int i = 0; i < (sourceName.Length - 1); i++) {\n if (sourceName[i + 1] == \"\") {\n destinationName += sourceName[i + 1];\n }\n else {\n destinationName += sourceName[i + 1];\n }\n}\ntxtTextBox.Text = desinationName;\n" }, { "answer_id": 3003034, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 1, "selected": false, "text": "PROPER(n)" }, { "answer_id": 3003038, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 2, "selected": false, "text": "http://titlecase.com/" }, { "answer_id": 3003080, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 3, "selected": false, "text": "ToTitleCase TextInfo public string TitleCase(string str)\n {\n return Regex.Replace(str, @\"\\w+\", (m) =>\n {\n string tmp = m.Value;\n return char.ToUpper(tmp[0]) + tmp.Substring(1, tmp.Length - 1).ToLower();\n });\n }\n" }, { "answer_id": 5174338, "author": "rumbu", "author_id": 642072, "author_profile": "https://Stackoverflow.com/users/642072", "pm_score": 2, "selected": false, "text": "public static string ExcelProper(string s) {\n bool upper_needed = true;\n string result = \"\";\n foreach (char c in s) {\n bool is_letter = Char.IsLetter(c);\n if (is_letter)\n if (upper_needed)\n result += Char.ToUpper(c);\n else\n result += Char.ToLower(c);\n else\n result += c;\n upper_needed = !is_letter;\n }\n return result;\n}\n" }, { "answer_id": 35744634, "author": "Ritesh Shakya", "author_id": 5452950, "author_profile": "https://Stackoverflow.com/users/5452950", "pm_score": 3, "selected": false, "text": "public String titleCase(String str) {\n char[] chars = str.toCharArray();\n for (int i = 0; i < chars.length; i++) {\n if (i == 0) {\n chars[i] = Character.toUpperCase(chars[i]);\n } else if ((i + 1) < chars.length && chars[i] == ' ') {\n chars[i + 1] = Character.toUpperCase(chars[i + 1]);\n }\n }\n return new String(chars);\n}\n" }, { "answer_id": 47831875, "author": "Simony", "author_id": 9019502, "author_profile": "https://Stackoverflow.com/users/9019502", "pm_score": 1, "selected": false, "text": "public static string ToTitleCaseInvariant(string str)\n{\n return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str);\n}\n" }, { "answer_id": 58643270, "author": "Avid Programmer", "author_id": 3992001, "author_profile": "https://Stackoverflow.com/users/3992001", "pm_score": 0, "selected": false, "text": "using System.Globalization; \nusing System.Threading; \nprotected void Page_Load(object sender, EventArgs e) \n{ \n CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; \n TextInfo textInfo = cultureInfo.TextInfo; \n Response.Write(textInfo.ToTitleCase(\"WelcometoHome<br />\")); \n Response.Write(textInfo.ToTitleCase(\"Welcome to Home\")); \nResponse.Write(textInfo.ToTitleCase(\"Welcome@to$home<br/>\").Replace(\"@\",\"\").Replace(\"$\", \"\")); \n}\n" }, { "answer_id": 65265979, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "CultureInfo.InvariantCulture.TextInfo.ToTitleCase(str.ToLowerInvariant())\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
752
<p>One may not always know the <code>Type</code> of an object at compile-time, but may need to create an instance of the <code>Type</code>. </p> <p>How do you get a new object instance from a <code>Type</code>?</p>
[ { "answer_id": 755, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 11, "selected": true, "text": "Activator System ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);\n\nObjectType instance = (ObjectType)Activator.CreateInstance(\"MyAssembly\",\"MyNamespace.ObjectType\");\n" }, { "answer_id": 26031, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 4, "selected": false, "text": "ConstructorInfo.Invoke() IL DynamicMethod" }, { "answer_id": 26033, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 7, "selected": false, "text": "ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);\n Activator ObjectType instance = Activator.CreateInstance<ObjectType>();\n" }, { "answer_id": 3503517, "author": "Brady Moritz", "author_id": 177242, "author_profile": "https://Stackoverflow.com/users/177242", "pm_score": 4, "selected": false, "text": "T t = new T();" }, { "answer_id": 12343731, "author": "vikram nayak", "author_id": 196857, "author_profile": "https://Stackoverflow.com/users/196857", "pm_score": 3, "selected": false, "text": "public AbstractType New\n{\n get\n {\n return (AbstractType) Activator.CreateInstance(GetType());\n }\n}\n" }, { "answer_id": 17797389, "author": "BSharp", "author_id": 2237957, "author_profile": "https://Stackoverflow.com/users/2237957", "pm_score": 4, "selected": false, "text": "System.Activator System.ComponentModel.TypeDescriptor ObjectType instance = \n (ObjectType)System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(\n typeName: objectType.FulName, // string including namespace of the type\n ignoreCase: false,\n bindingAttr: BindingFlags.Default,\n binder: null, // use default binder\n args: new object[] { args, to, constructor },\n culture: null, // use CultureInfo from current thread\n activationAttributes: null\n );\n TypeDescriptor ObjectType instance = \n (ObjectType)System.ComponentModel.TypeDescriptor.CreateInstance(\n provider: null, // use standard type description provider, which uses reflection\n objectType: objectType,\n argTypes: new Type[] { types, of, args },\n args: new object[] { args, to, constructor }\n );\n" }, { "answer_id": 26708746, "author": "Sarath Subramanian", "author_id": 3312636, "author_profile": "https://Stackoverflow.com/users/3312636", "pm_score": 5, "selected": false, "text": "Car Vehicles Vehicles.Car Car public object GetInstance(string strNamesapace)\n{ \n Type t = Type.GetType(strNamesapace); \n return Activator.CreateInstance(t); \n}\n Vehicles.Car Type.GetType Type public object GetInstance(string strFullyQualifiedName)\n{\n Type type = Type.GetType(strFullyQualifiedName);\n if (type != null)\n return Activator.CreateInstance(type);\n foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())\n {\n type = asm.GetType(strFullyQualifiedName);\n if (type != null)\n return Activator.CreateInstance(type);\n }\n return null;\n }\n object objClassInstance = GetInstance(\"Vehicles.Car\");\n" }, { "answer_id": 29239907, "author": "Darrel Lee", "author_id": 307968, "author_profile": "https://Stackoverflow.com/users/307968", "pm_score": 2, "selected": false, "text": "Public Function CloneObject(Of T As New)(ByVal src As T) As T\n Dim result As T = Nothing\n Dim cloneable = TryCast(src, ICloneable)\n If cloneable IsNot Nothing Then\n result = cloneable.Clone()\n Else\n result = New T\n CopySimpleProperties(src, result, Nothing, \"clone\")\n End If\n Return result\nEnd Function\n Public Function CloneObject(ByVal src As Object) As Object\n Dim result As Object = Nothing\n Dim cloneable As ICloneable\n Try\n cloneable = TryCast(src, ICloneable)\n If cloneable IsNot Nothing Then\n result = cloneable.Clone()\n Else\n result = Activator.CreateInstance(src.GetType())\n CopySimpleProperties(src, result, Nothing, \"clone\")\n End If\n Catch ex As Exception\n Trace.WriteLine(\"!!! CloneObject(): \" & ex.Message)\n End Try\n Return result\nEnd Function\n" }, { "answer_id": 29972767, "author": "Serj-Tm", "author_id": 1034136, "author_profile": "https://Stackoverflow.com/users/1034136", "pm_score": 7, "selected": false, "text": "static readonly Func<X> YCreator = Expression.Lambda<Func<X>>(\n Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))\n ).Compile();\n\nX x = YCreator();\n Iterations: 5000000\n 00:00:00.8481762, Activator.CreateInstance(string, string)\n 00:00:00.8416930, Activator.CreateInstance(type)\n 00:00:06.6236752, ConstructorInfo.Invoke\n 00:00:00.1776255, Compiled expression\n 00:00:00.0462197, new\n Iterations: 5000000\n 00:00:00.2659981, Activator.CreateInstance(string, string)\n 00:00:00.2603770, Activator.CreateInstance(type)\n 00:00:00.7478936, ConstructorInfo.Invoke\n 00:00:00.0700757, Compiled expression\n 00:00:00.0286710, new\n Iterations: 5000000\n 00:00:00.3541501, Activator.CreateInstance(string, string)\n 00:00:00.3686861, Activator.CreateInstance(type)\n 00:00:00.9492354, ConstructorInfo.Invoke\n 00:00:00.0719072, Compiled expression\n 00:00:00.0229387, new\n Iterations: 5000000\n No args\n 00:00:00.3897563, Activator.CreateInstance(string assemblyName, string typeName)\n 00:00:00.3500748, Activator.CreateInstance(Type type)\n 00:00:01.0100714, ConstructorInfo.Invoke\n 00:00:00.1375767, Compiled expression\n 00:00:00.1337920, Compiled expression (type)\n 00:00:00.0593664, new\n Single arg\n 00:00:03.9300630, Activator.CreateInstance(Type type)\n 00:00:01.3881770, ConstructorInfo.Invoke\n 00:00:00.1425534, Compiled expression\n 00:00:00.0717409, new\n Iterations: 5000000\nNo args\n00:00:00.3287835, Activator.CreateInstance(string assemblyName, string typeName)\n00:00:00.3122015, Activator.CreateInstance(Type type)\n00:00:00.8035712, ConstructorInfo.Invoke\n00:00:00.0692854, Compiled expression\n00:00:00.0662223, Compiled expression (type)\n00:00:00.0337862, new\nSingle arg\n00:00:03.8081959, Activator.CreateInstance(Type type)\n00:00:01.2507642, ConstructorInfo.Invoke\n00:00:00.0671756, Compiled expression\n00:00:00.0301489, new\n Iterations: 5000000\nNo args\n00:00:00.3226895, Activator.CreateInstance(string assemblyName, string typeName)\n00:00:00.2786803, Activator.CreateInstance(Type type)\n00:00:00.6183554, ConstructorInfo.Invoke\n00:00:00.0483217, Compiled expression\n00:00:00.0485119, Compiled expression (type)\n00:00:00.0434534, new\nSingle arg\n00:00:03.4389401, Activator.CreateInstance(Type type)\n00:00:01.0803609, ConstructorInfo.Invoke\n00:00:00.0554756, Compiled expression\n00:00:00.0462232, new\n static X CreateY_New()\n{\n return new Y();\n}\n\nstatic X CreateY_New_Arg(int z)\n{\n return new Y(z);\n}\n\nstatic X CreateY_CreateInstance()\n{\n return (X)Activator.CreateInstance(typeof(Y));\n}\n\nstatic X CreateY_CreateInstance_String()\n{\n return (X)Activator.CreateInstance(\"Program\", \"Y\").Unwrap();\n}\n\nstatic X CreateY_CreateInstance_Arg(int z)\n{\n return (X)Activator.CreateInstance(typeof(Y), new object[] { z, });\n}\n\nprivate static readonly System.Reflection.ConstructorInfo YConstructor =\n typeof(Y).GetConstructor(Type.EmptyTypes);\nprivate static readonly object[] Empty = new object[] { };\nstatic X CreateY_Invoke()\n{\n return (X)YConstructor.Invoke(Empty);\n}\n\nprivate static readonly System.Reflection.ConstructorInfo YConstructor_Arg =\n typeof(Y).GetConstructor(new[] { typeof(int), });\nstatic X CreateY_Invoke_Arg(int z)\n{\n return (X)YConstructor_Arg.Invoke(new object[] { z, });\n}\n\nprivate static readonly Func<X> YCreator = Expression.Lambda<Func<X>>(\n Expression.New(typeof(Y).GetConstructor(Type.EmptyTypes))\n).Compile();\nstatic X CreateY_CompiledExpression()\n{\n return YCreator();\n}\n\nprivate static readonly Func<X> YCreator_Type = Expression.Lambda<Func<X>>(\n Expression.New(typeof(Y))\n).Compile();\nstatic X CreateY_CompiledExpression_Type()\n{\n return YCreator_Type();\n}\n\nprivate static readonly ParameterExpression YCreator_Arg_Param = Expression.Parameter(typeof(int), \"z\");\nprivate static readonly Func<int, X> YCreator_Arg = Expression.Lambda<Func<int, X>>(\n Expression.New(typeof(Y).GetConstructor(new[] { typeof(int), }), new[] { YCreator_Arg_Param, }),\n YCreator_Arg_Param\n).Compile();\nstatic X CreateY_CompiledExpression_Arg(int z)\n{\n return YCreator_Arg(z);\n}\n\nstatic void Main(string[] args)\n{\n const int iterations = 5000000;\n\n Console.WriteLine(\"Iterations: {0}\", iterations);\n\n Console.WriteLine(\"No args\");\n foreach (var creatorInfo in new[]\n {\n new {Name = \"Activator.CreateInstance(string assemblyName, string typeName)\", Creator = (Func<X>)CreateY_CreateInstance},\n new {Name = \"Activator.CreateInstance(Type type)\", Creator = (Func<X>)CreateY_CreateInstance},\n new {Name = \"ConstructorInfo.Invoke\", Creator = (Func<X>)CreateY_Invoke},\n new {Name = \"Compiled expression\", Creator = (Func<X>)CreateY_CompiledExpression},\n new {Name = \"Compiled expression (type)\", Creator = (Func<X>)CreateY_CompiledExpression_Type},\n new {Name = \"new\", Creator = (Func<X>)CreateY_New},\n })\n {\n var creator = creatorInfo.Creator;\n\n var sum = 0;\n for (var i = 0; i < 1000; i++)\n sum += creator().Z;\n\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (var i = 0; i < iterations; ++i)\n {\n var x = creator();\n sum += x.Z;\n }\n stopwatch.Stop();\n Console.WriteLine(\"{0}, {1}\", stopwatch.Elapsed, creatorInfo.Name);\n }\n\n Console.WriteLine(\"Single arg\");\n foreach (var creatorInfo in new[]\n {\n new {Name = \"Activator.CreateInstance(Type type)\", Creator = (Func<int, X>)CreateY_CreateInstance_Arg},\n new {Name = \"ConstructorInfo.Invoke\", Creator = (Func<int, X>)CreateY_Invoke_Arg},\n new {Name = \"Compiled expression\", Creator = (Func<int, X>)CreateY_CompiledExpression_Arg},\n new {Name = \"new\", Creator = (Func<int, X>)CreateY_New_Arg},\n })\n {\n var creator = creatorInfo.Creator;\n\n var sum = 0;\n for (var i = 0; i < 1000; i++)\n sum += creator(i).Z;\n\n var stopwatch = new Stopwatch();\n stopwatch.Start();\n for (var i = 0; i < iterations; ++i)\n {\n var x = creator(i);\n sum += x.Z;\n }\n stopwatch.Stop();\n Console.WriteLine(\"{0}, {1}\", stopwatch.Elapsed, creatorInfo.Name);\n }\n}\n\npublic class X\n{\n public X() { }\n public X(int z) { this.Z = z; }\n public int Z;\n}\n\npublic class Y : X\n{\n public Y() {}\n public Y(int z) : base(z) {}\n}\n" }, { "answer_id": 31138841, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "private T Create<T>() where T : class, new()\n{\n return new T();\n}\n" }, { "answer_id": 31143718, "author": "Thulani Chivandikwa", "author_id": 611628, "author_profile": "https://Stackoverflow.com/users/611628", "pm_score": 4, "selected": false, "text": "System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject()\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
761
<p>What is the best way to localise a date format descriptor?</p> <p>As anyone from a culture which does not use the mm/dd/yyyy format knows, it is annoying to have to enter dates in this format. The .NET framework provides some very good localisation support, so it's trivial to parse dates according to the users culture, but you often want to also display a helpful hint as to the format required (especially to distinguish between yy and yyyy which is interchangeable in most cultures).</p> <p>What is the best way to do this in a way that make sense to most users (e.g. dd/M/yyy is confusing because of the change in case and the switching between one and two letters).</p>
[ { "answer_id": 762, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 3, "selected": true, "text": "Regex singleMToDoubleRegex = new Regex(\"(?<!m)m(?!m)\");\nRegex singleDToDoubleRegex = new Regex(\"(?<!d)d(?!d)\");\nCultureInfo currentCulture = CultureInfo.CurrentUICulture;\n\n// If the culture is netural there is no date pattern to use, so use the default.\nif (currentCulture.IsNeutralCulture)\n{\n currentCulture = CultureInfo.InvariantCulture;\n}\n\n// Massage the format into a more general user friendly form.\nstring shortDatePattern = CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.ToLower();\nshortDatePattern = singleMToDoubleRegex.Replace(shortDatePattern, \"mm\");\nshortDatePattern = singleDToDoubleRegex.Replace(shortDatePattern, \"dd\");\n" }, { "answer_id": 770, "author": "engtech", "author_id": 175, "author_profile": "https://Stackoverflow.com/users/175", "pm_score": 3, "selected": false, "text": "Date and time (current at page generation) expressed according to ISO 8601:\nDate: 2014-07-05\nCombined date and time in UTC: 2014-07-05T04:00:25+00:00\n 2014-07-05T04:00:25Z\nWeek: 2014-W27\nDate with week number: 2014-W27-6\nOrdinal date: 2014-186\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/214/" ]
766
<p>I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host.</p> <p>I found <a href="http://barryp.org/software/bpgsql/" rel="noreferrer">bpgsql</a> really good because it does not require an install, it's a single file that I can look at, read and then call the functions of. Does anybody know of something like this for MySQL?</p>
[ { "answer_id": 777, "author": "ESV", "author_id": 150, "author_profile": "https://Stackoverflow.com/users/150", "pm_score": 3, "selected": false, "text": "#!/usr/bin/python\n\nmodule_name = 'MySQLdb'\nhead = '''Content-Type: text/html\n\n%s is ''' % module_name\n\ntry:\n __import__(module_name)\n print head + 'installed'\nexcept ImportError:\n print head + 'not installed'\n" }, { "answer_id": 802, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 3, "selected": false, "text": "Premature end of script headers\n import cgi\nimport cgitb; cgitb.enable()\nimport MySQLdb\n import MySQLdb\nimport cgi\nimport cgitb; cgitb.enable()\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
769
<p>I need to programmatically solve a system of linear equations in C, Objective C, or (if needed) C++.</p> <p>Here's an example of the equations:</p> <pre><code>-44.3940 = a * 50.0 + b * 37.0 + tx -45.3049 = a * 43.0 + b * 39.0 + tx -44.9594 = a * 52.0 + b * 41.0 + tx </code></pre> <p>From this, I'd like to get the best approximation for <code>a</code>, <code>b</code>, and <code>tx</code>.</p>
[ { "answer_id": 26637, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 2, "selected": false, "text": "void GetInverse(const Array2D<double>& A, Array2D<double>& invA)\n {\n QR<double> qr(A); \n invA = qr.solve(I); \n }\n" }, { "answer_id": 83758, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "> y <- c(-44.394, -45.3049, -44.9594)\n> a <- c(50.0, 43.0, 52.0)\n> b <- c(37.0, 39.0, 41.0)\n> regression = lm(y ~ a + b)\n> regression\n\nCall:\nlm(formula = y ~ a + b)\n\nCoefficients:\n(Intercept) a b \n -41.63759 0.07852 -0.18061 \n" }, { "answer_id": 590060, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": false, "text": "-44.3940 = 50a + 37b + c (A)\n-45.3049 = 43a + 39b + c (B)\n-44.9594 = 52a + 41b + c (C)\n\n(A-B): 0.9109 = 7a - 2b (D)\n(B-C): 0.3455 = -9a - 2b (E)\n\n(D-E): 1.2564 = 16a (F)\n\n(F/16): a = 0.078525 (G)\n\nFeed G into D:\n 0.9109 = 7a - 2b\n => 0.9109 = 0.549675 - 2b (substitute a)\n => 0.361225 = -2b (subtract 0.549675 from both sides)\n => -0.1806125 = b (divide both sides by -2) (H)\n\nFeed H/G into A:\n -44.3940 = 50a + 37b + c\n => -44.3940 = 3.92625 - 6.6826625 + c (substitute a/b)\n => -41.6375875 = c (subtract 3.92625 - 6.6826625 from both sides)\n a = 0.0785250\nb = -0.1806125\nc = -41.6375875\n 7a + 2b = 50\n14a + 4b = 100\n 0 = 0 + 0\n main #include <stdio.h>\n\ntypedef struct { double r, a, b, c; } tEquation;\ntEquation equ1[] = {\n { -44.3940, 50, 37, 1 }, // -44.3940 = 50a + 37b + c (A)\n { -45.3049, 43, 39, 1 }, // -45.3049 = 43a + 39b + c (B)\n { -44.9594, 52, 41, 1 }, // -44.9594 = 52a + 41b + c (C)\n};\ntEquation equ2[2], equ3[1];\n\nstatic void dumpEqu (char *desc, tEquation *e, char *post) {\n printf (\"%10s: %12.8lf = %12.8lfa + %12.8lfb + %12.8lfc (%s)\\n\",\n desc, e->r, e->a, e->b, e->c, post);\n}\n\nint main (void) {\n double a, b, c;\n // First step, populate equ2 based on removing c from equ.\n\n dumpEqu (\">\", &(equ1[0]), \"A\");\n dumpEqu (\">\", &(equ1[1]), \"B\");\n dumpEqu (\">\", &(equ1[2]), \"C\");\n puts (\"\");\n\n // A - B\n equ2[0].r = equ1[0].r * equ1[1].c - equ1[1].r * equ1[0].c;\n equ2[0].a = equ1[0].a * equ1[1].c - equ1[1].a * equ1[0].c;\n equ2[0].b = equ1[0].b * equ1[1].c - equ1[1].b * equ1[0].c;\n equ2[0].c = 0;\n\n // B - C\n equ2[1].r = equ1[1].r * equ1[2].c - equ1[2].r * equ1[1].c;\n equ2[1].a = equ1[1].a * equ1[2].c - equ1[2].a * equ1[1].c;\n equ2[1].b = equ1[1].b * equ1[2].c - equ1[2].b * equ1[1].c;\n equ2[1].c = 0;\n\n dumpEqu (\"A-B\", &(equ2[0]), \"D\");\n dumpEqu (\"B-C\", &(equ2[1]), \"E\");\n puts (\"\");\n // Next step, populate equ3 based on removing b from equ2.\n\n // D - E\n equ3[0].r = equ2[0].r * equ2[1].b - equ2[1].r * equ2[0].b;\n equ3[0].a = equ2[0].a * equ2[1].b - equ2[1].a * equ2[0].b;\n equ3[0].b = 0;\n equ3[0].c = 0;\n\n dumpEqu (\"D-E\", &(equ3[0]), \"F\");\n puts (\"\");\n number1 = unknown * number2 unknown <- number1 / number2 // Finally, substitute values back into equations.\n\n a = equ3[0].r / equ3[0].a;\n printf (\"From (F ), a = %12.8lf (G)\\n\", a);\n\n b = (equ2[0].r - equ2[0].a * a) / equ2[0].b;\n printf (\"From (D,G ), b = %12.8lf (H)\\n\", b);\n\n c = (equ1[0].r - equ1[0].a * a - equ1[0].b * b) / equ1[0].c;\n printf (\"From (A,G,H), c = %12.8lf (I)\\n\", c);\n\n return 0;\n}\n >: -44.39400000 = 50.00000000a + 37.00000000b + 1.00000000c (A)\n >: -45.30490000 = 43.00000000a + 39.00000000b + 1.00000000c (B)\n >: -44.95940000 = 52.00000000a + 41.00000000b + 1.00000000c (C)\n\n A-B: 0.91090000 = 7.00000000a + -2.00000000b + 0.00000000c (D)\n B-C: -0.34550000 = -9.00000000a + -2.00000000b + 0.00000000c (E)\n\n D-E: -2.51280000 = -32.00000000a + 0.00000000b + 0.00000000c (F)\n\nFrom (F ), a = 0.07852500 (G)\nFrom (D,G ), b = -0.18061250 (H)\nFrom (A,G,H), c = -41.63758750 (I)\n" }, { "answer_id": 770947, "author": "Bobby Ortiz", "author_id": 25843, "author_profile": "https://Stackoverflow.com/users/25843", "pm_score": 3, "selected": false, "text": " SolverContext context = SolverContext.GetContext();\n Model model = context.CreateModel();\n\n Decision a = new Decision(Domain.Real, \"a\");\n Decision b = new Decision(Domain.Real, \"b\");\n Decision c = new Decision(Domain.Real, \"c\");\n model.AddDecisions(a,b,c);\n model.AddConstraint(\"eqA\", -44.3940 == 50*a + 37*b + c);\n model.AddConstraint(\"eqB\", -45.3049 == 43*a + 39*b + c);\n model.AddConstraint(\"eqC\", -44.9594 == 52*a + 41*b + c);\n Solution solution = context.Solve();\n string results = solution.GetReport().ToString();\n Console.WriteLine(results); \n" }, { "answer_id": 27708081, "author": "Bulent S.", "author_id": 4405846, "author_profile": "https://Stackoverflow.com/users/4405846", "pm_score": 1, "selected": false, "text": "function x = LinSolve(A,y)\n%\n% Recursive Solution of Linear System Ax=y\n% matlab equivalent: x = A\\y \n% x = n x 1\n% A = n x n\n% y = n x 1\n% Uses stack space extensively. Not efficient.\n% C allows recursion, so convert it into C. \n% ----------------------------------------------\nn=length(y);\nx=zeros(n,1);\nif(n>1)\n x(1:n-1,1) = LinSolve( A(1:n-1,1:n-1) - (A(1:n-1,n)*A(n,1:n-1))./A(n,n) , ...\n y(1:n-1,1) - A(1:n-1,n).*(y(n,1)/A(n,n))); \n x(n,1) = (y(n,1) - A(n,1:n-1)*x(1:n-1,1))./A(n,n); \nelse\n x = y(1,1) / A(1,1);\nend\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/79/" ]
773
<p>I haven't been able to find an understandable explanation of how to actually use Python's <code>itertools.groupby()</code> function. What I'm trying to do is this:</p> <ul> <li>Take a list - in this case, the children of an objectified <code>lxml</code> element</li> <li>Divide it into groups based on some criteria</li> <li>Then later iterate over each of these groups separately.</li> </ul> <p>I've reviewed <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="noreferrer">the documentation</a>, but I've had trouble trying to apply them beyond a simple list of numbers.</p> <p>So, how do I use of <code>itertools.groupby()</code>? Is there another technique I should be using? Pointers to good &quot;prerequisite&quot; reading would also be appreciated.</p>
[ { "answer_id": 783, "author": "Seb", "author_id": 189, "author_profile": "https://Stackoverflow.com/users/189", "pm_score": 6, "selected": false, "text": "groups = []\nuniquekeys = []\nfor k, g in groupby(data, keyfunc):\n groups.append(list(g)) # Store group iterator as a list\n uniquekeys.append(k)\n keyfunc groupby() groupby groupby" }, { "answer_id": 7286, "author": "James Sulak", "author_id": 207, "author_profile": "https://Stackoverflow.com/users/207", "pm_score": 11, "selected": true, "text": "groups = []\nuniquekeys = []\nfor k, g in groupby(data, keyfunc):\n groups.append(list(g)) # Store group iterator as a list\n uniquekeys.append(k)\n k g groupby from itertools import groupby\n\nthings = [(\"animal\", \"bear\"), (\"animal\", \"duck\"), (\"plant\", \"cactus\"), (\"vehicle\", \"speed boat\"), (\"vehicle\", \"school bus\")]\n\nfor key, group in groupby(things, lambda x: x[0]):\n for thing in group:\n print(\"A %s is a %s.\" % (thing[1], key))\n print(\"\")\n \n things groupby() lambda x: x[0] groupby() for groupby for key, group in groupby(things, lambda x: x[0]):\n listOfThings = \" and \".join([thing[1] for thing in group])\n print(key + \"s: \" + listOfThings + \".\")\n" }, { "answer_id": 37252, "author": "nimish", "author_id": 3926, "author_profile": "https://Stackoverflow.com/users/3926", "pm_score": 6, "selected": false, "text": "[(c,len(list(cgen))) for c,cgen in groupby(some_string)]\n itertools.groupby GROUP BY" }, { "answer_id": 1573195, "author": "pedromanoel", "author_id": 83284, "author_profile": "https://Stackoverflow.com/users/83284", "pm_score": 3, "selected": false, "text": "from itertools import groupby \n[(c,len(list(cs))) for c,cs in groupby('Pedro Manoel')]\n [('P', 1), ('e', 1), ('d', 1), ('r', 1), ('o', 1), (' ', 1), ('M', 1), ('a', 1), ('n', 1), ('o', 1), ('e', 1), ('l', 1)]\n name = list('Pedro Manoel')\nname.sort()\n[(c,len(list(cs))) for c,cs in groupby(name)]\n [(' ', 1), ('M', 1), ('P', 1), ('a', 1), ('d', 1), ('e', 2), ('l', 1), ('n', 1), ('o', 2), ('r', 1)]\n" }, { "answer_id": 14443477, "author": "user650654", "author_id": 650654, "author_profile": "https://Stackoverflow.com/users/650654", "pm_score": 5, "selected": false, "text": "for key, igroup in itertools.groupby(xrange(12), lambda x: x // 5):\n print key, list(igroup)\n 0 [0, 1, 2, 3, 4]\n1 [5, 6, 7, 8, 9]\n2 [10, 11]\n igroup def chunker(items, chunk_size):\n '''Group items in chunks of chunk_size'''\n for _key, group in itertools.groupby(enumerate(items), lambda x: x[0] // chunk_size):\n yield (g[1] for g in group)\n\nwith open('file.txt') as fobj:\n for chunk in chunker(fobj):\n process(chunk)\n groupby xx yy xx = range(10)\nyy = [0, 0, 0, 1, 1, 1, 0, 0, 0, 0]\nfor group in itertools.groupby(iter(xx), lambda x: yy[x]):\n print group[0], list(group[1])\n 0 [0, 1, 2]\n1 [3, 4, 5]\n0 [6, 7, 8, 9]\n" }, { "answer_id": 16427674, "author": "kiriloff", "author_id": 1141493, "author_profile": "https://Stackoverflow.com/users/1141493", "pm_score": 4, "selected": false, "text": "from itertools import groupby\n\nthings = [(\"vehicle\", \"bear\"), (\"animal\", \"duck\"), (\"animal\", \"cactus\"), (\"vehicle\", \"speed boat\"), (\"vehicle\", \"school bus\")]\n\nfor key, group in groupby(things, lambda x: x[0]):\n for thing in group:\n print \"A %s is a %s.\" % (thing[1], key)\n print \" \"\n A bear is a vehicle.\n\nA duck is a animal.\nA cactus is a animal.\n\nA speed boat is a vehicle.\nA school bus is a vehicle.\n" }, { "answer_id": 20013133, "author": "RussellStewart", "author_id": 2237635, "author_profile": "https://Stackoverflow.com/users/2237635", "pm_score": 5, "selected": false, "text": "for x in list(groupby(range(10))):\n print(list(x[1]))\n []\n[]\n[]\n[]\n[]\n[]\n[]\n[]\n[]\n[9]\n def groupbylist(*args, **kwargs):\n return [(k, list(g)) for k, g in groupby(*args, **kwargs)]\n" }, { "answer_id": 31660194, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 3, "selected": false, "text": "groupby(iterable[, keyfunc]) -> create an iterator which returns\n(key, sub-iterator) grouped by each value of key(value).\n coroutine.send import itertools\n\n\ndef grouper(iterable, n):\n def coroutine(n):\n yield # queue up coroutine\n for i in itertools.count():\n for j in range(n):\n yield i\n groups = coroutine(n)\n next(groups) # queue up coroutine\n\n for c, objs in itertools.groupby(iterable, groups.send):\n yield c, list(objs)\n # or instead of materializing a list of objs, just:\n # return itertools.groupby(iterable, groups.send)\n\nlist(grouper(range(10), 3))\n [(0, [0, 1, 2]), (1, [3, 4, 5]), (2, [6, 7, 8]), (3, [9])]\n" }, { "answer_id": 44617583, "author": "Arko", "author_id": 7933904, "author_profile": "https://Stackoverflow.com/users/7933904", "pm_score": 2, "selected": false, "text": "from itertools import groupby\n\n#user input\n\nmyinput = input()\n\n#creating empty list to store output\n\nmyoutput = []\n\nfor k,g in groupby(myinput):\n\n myoutput.append((len(list(g)),int(k)))\n\nprint(*myoutput)\n" }, { "answer_id": 45431237, "author": "Satyajit Das", "author_id": 8137464, "author_profile": "https://Stackoverflow.com/users/8137464", "pm_score": 3, "selected": false, "text": "from itertools import groupby\n\nval = [{'name': 'satyajit', 'address': 'btm', 'pin': 560076}, \n {'name': 'Mukul', 'address': 'Silk board', 'pin': 560078},\n {'name': 'Preetam', 'address': 'btm', 'pin': 560076}]\n\n\nfor pin, list_data in groupby(sorted(val, key=lambda k: k['pin']),lambda x: x['pin']):\n... print pin\n... for rec in list_data:\n... print rec\n... \no/p:\n\n560076\n{'name': 'satyajit', 'pin': 560076, 'address': 'btm'}\n{'name': 'Preetam', 'pin': 560076, 'address': 'btm'}\n560078\n{'name': 'Mukul', 'pin': 560078, 'address': 'Silk board'}\n" }, { "answer_id": 45873519, "author": "pylang", "author_id": 4531270, "author_profile": "https://Stackoverflow.com/users/4531270", "pm_score": 7, "selected": false, "text": "itertools.groupby # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D groupby # Define a printer for comparing outputs\n>>> def print_groupby(iterable, keyfunc=None):\n... for k, g in it.groupby(iterable, keyfunc):\n... print(\"key: '{}'--> group: {}\".format(k, list(g)))\n # Feature A: group consecutive occurrences\n>>> print_groupby(\"BCAACACAADBBB\")\nkey: 'B'--> group: ['B']\nkey: 'C'--> group: ['C']\nkey: 'A'--> group: ['A', 'A']\nkey: 'C'--> group: ['C']\nkey: 'A'--> group: ['A']\nkey: 'C'--> group: ['C']\nkey: 'A'--> group: ['A', 'A']\nkey: 'D'--> group: ['D']\nkey: 'B'--> group: ['B', 'B', 'B']\n\n# Feature B: group all occurrences\n>>> print_groupby(sorted(\"BCAACACAADBBB\"))\nkey: 'A'--> group: ['A', 'A', 'A', 'A', 'A']\nkey: 'B'--> group: ['B', 'B', 'B', 'B']\nkey: 'C'--> group: ['C', 'C', 'C']\nkey: 'D'--> group: ['D']\n\n# Feature C: group by a key function\n>>> # islower = lambda s: s.islower() # equivalent\n>>> def islower(s):\n... \"\"\"Return True if a string is lowercase, else False.\"\"\" \n... return s.islower()\n>>> print_groupby(sorted(\"bCAaCacAADBbB\"), keyfunc=islower)\nkey: 'False'--> group: ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D']\nkey: 'True'--> group: ['a', 'a', 'b', 'b', 'c']\n groupby sorted() max() min() # OP: Yes, you can use `groupby`, e.g. \n[do_something(list(g)) for _, g in groupby(lxml_elements, criteria_func)]\n" }, { "answer_id": 61048516, "author": "Tiago", "author_id": 9726459, "author_profile": "https://Stackoverflow.com/users/9726459", "pm_score": 3, "selected": false, "text": "arr = [(1, \"A\"), (1, \"B\"), (1, \"C\"), (2, \"D\"), (2, \"E\"), (3, \"F\")]\n\nfor k,g in groupby(arr, lambda x: x[0]):\n print(\"--\", k, \"--\")\n for tup in g:\n print(tup[1]) # tup[0] == k\n -- 1 --\nA\nB\nC\n-- 2 --\nD\nE\n-- 3 --\nF\n" }, { "answer_id": 68091577, "author": "andrewdotn", "author_id": 14558, "author_profile": "https://Stackoverflow.com/users/14558", "pm_score": 3, "selected": false, "text": "itertools.groupby() def my_group_by(iterable, keyfunc):\n \"\"\"Because itertools.groupby is tricky to use\n\n The stdlib method requires sorting in advance, and returns iterators not\n lists, and those iterators get consumed as you try to use them, throwing\n everything off if you try to look at something more than once.\n \"\"\"\n ret = defaultdict(list)\n for k in iterable:\n ret[keyfunc(k)].append(k)\n return dict(ret)\n def first_letter(x):\n return x[0]\n\nmy_group_by('four score and seven years ago'.split(), first_letter)\n {'f': ['four'], 's': ['score', 'seven'], 'a': ['and', 'ago'], 'y': ['years']}\n" }, { "answer_id": 69783850, "author": "Ankit Gupta", "author_id": 7864006, "author_profile": "https://Stackoverflow.com/users/7864006", "pm_score": 2, "selected": false, "text": "from random import randint\nfrom itertools import groupby\n\n l = [randint(1, 3) for _ in range(20)]\n\n d = {}\n for k, g in groupby(l, lambda x: x):\n if not d.get(k, None):\n d[k] = list(g)\n else:\n d[k] = d[k] + list(g)\n l = [2, 1, 2, 3, 1, 3, 2, 1, 3, 3, 1, 3, 2, 3, 1, 2, 1, 3, 2, 3]\n for k, g in groupby(l, lambda x:x):\n print(k, list(g))\n\n2 [2]\n1 [1]\n2 [2]\n3 [3]\n1 [1]\n3 [3]\n2 [2]\n1 [1]\n3 [3, 3]\n1 [1]\n3 [3]\n2 [2]\n3 [3]\n1 [1]\n2 [2]\n1 [1]\n3 [3]\n2 [2]\n3 [3]\n {2: [2, 2, 2, 2, 2, 2], 1: [1, 1, 1, 1, 1, 1], 3: [3, 3, 3, 3, 3, 3, 3, 3]}\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207/" ]
810
<p>I'm trying to maintain a Setup Project in <code>Visual Studio 2003</code> (yes, it's a legacy application). The problem we have at the moment is that we need to write registry entries to <code>HKCU</code> for every user on the computer. They need to be in the <code>HKCU</code> rather than <code>HKLM</code> because they are the default user settings, and they do change per user. My feeling is that</p> <ol> <li>This isn't possible</li> <li>This isn't something the installer should be doing, but something the application should be doing (after all what happens when a user profile is created after the install?).</li> </ol> <p>With that in mind, I still want to change as little as possible in the application, so my question is, <strong>is it possible to add registry entries for every user in a <code>Visual Studio 2003</code> setup project?</strong> </p> <p>And, at the moment the project lists five registry root keys (<code>HKEY_CLASSES_ROOT, HKEY_CURRENT_USER</code>, <code>HKEY_LOCAL_MACHINE</code>, <code>HKEY_USERS</code>, and User/Machine Hive). I don't really know anything about the Users root key, and haven't seen User/Machine Hive. Can anyone enlighten me on what they are? Perhaps they could solve my problem above.</p>
[ { "answer_id": 820, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 4, "selected": true, "text": "const HKEY_USERS = &H80000003\nstrComputer = \".\"\nSet objReg=GetObject(\"winmgmts:{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\default:StdRegProv\")\nstrKeyPath = \"\"\nobjReg.EnumKey HKEY_USERS, strKeyPath, arrSubKeys\nstrKeyPath = \"\\Software\\Microsoft\\Windows\\CurrentVersion\\WinTrust\\Trust Providers\\Software Publishing\"\nFor Each subkey In arrSubKeys\n objReg.SetDWORDValue HKEY_USERS, subkey & strKeyPath, \"State\", 146944\nNext\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
826
<p>You have an ascending list of numbers, what is the most efficient algorithm you can think of to get the ascending list of sums of every two numbers in that list. Duplicates in the resulting list are irrelevant, you can remove them or avoid them if you like.</p> <p>To be clear, I'm interested in the algorithm. Feel free to post code in any language and paradigm that you like.</p>
[ { "answer_id": 840, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 1, "selected": false, "text": "matrixOfSums list = [[a+b | b <- list, b >= a] | a <- list]\n\nsortedSums = foldl merge [] matrixOfSums\n\n--A normal merge, save that we remove duplicates\nmerge xs [] = xs\nmerge [] ys = ys\nmerge (x:xs) (y:ys) = case compare x y of\n LT -> x:(merge xs (y:ys))\n EQ -> x:(merge xs (dropWhile (==x) ys))\n GT -> y:(merge (x:xs) ys)\n -- wide-merge does a standard merge (ala merge-sort) across an arbitrary number of lists\n-- wideNubMerge does this while eliminating duplicates\nwideNubMerge :: Ord a => [[a]] -> [a]\nwideNubMerge ls = wideNubMerge1 $ filter (/= []) ls\nwideNubMerge1 [] = []\nwideNubMerge1 ls = mini:(wideNubMerge rest)\n where mini = minimum $ map head ls\n rest = map (dropWhile (== mini)) ls\n\nbetterSortedSums = wideNubMerge matrixOfSums\n foldl merge []" }, { "answer_id": 884, "author": "Holtorf", "author_id": 159, "author_profile": "https://Stackoverflow.com/users/159", "pm_score": 2, "selected": false, "text": "step 1 (startinglist) \nfor each number num1 in startinglist\n for each number num2 in startinglist\n add num1 plus num2 into templist\n add templist to sumlist\nreturn sumlist \n step 2 (sumlist) \ncreate an empty list mergedlist\nfor each list templist in sumlist\n set mergelist equal to: merge(mergedlist,templist)\nreturn mergedlist\n" }, { "answer_id": 6458, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 1, "selected": false, "text": "create table numbers(n int not null)\ninsert into numbers(n) values(1),(1), (2), (2), (3), (4)\n\n\nselect distinct num1.n+num2.n sum2n\nfrom numbers num1\ninner join numbers num2 \n on num1.n<>num2.n\norder by sum2n\n List<int> num = new List<int>{ 1, 1, 2, 2, 3, 4};\nvar uNum = num.Distinct().ToList();\nvar sums=(from num1 in uNum\n from num2 in uNum \n where num1!=num2\n select num1+num2).Distinct();\nforeach (var s in sums)\n{\n Console.WriteLine(s);\n}\n" }, { "answer_id": 7842, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "allSums = set(a+b for a in X for b in X)\nallSums = sorted(allSums)\n n^2 n*(n-1)/2 X = [1,2,4,...,2^n] n^2/2 X+Y (n!)" }, { "answer_id": 20701, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 1, "selected": false, "text": "(a[i], a[j]) | j>=i (a[i], a[j]) | i<=j i i+1 a[i] a[i+1] (a[i + 1], a[j]) i (a[i], a[j]) (a[i + 1], a[j + 1]) j j" }, { "answer_id": 97294, "author": "porges", "author_id": 10311, "author_profile": "https://Stackoverflow.com/users/10311", "pm_score": 5, "selected": true, "text": "1 4 5 6 8 9\n---------------\n2 5 6 7 9 10\n 8 9 10 12 13\n 10 11 13 14\n 12 14 15\n 16 17\n 18\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/101/" ]
832
<p>SQL:</p> <pre><code>SELECT u.id, u.name, isnull(MAX(h.dateCol), '1900-01-01') dateColWithDefault FROM universe u LEFT JOIN history h ON u.id=h.id AND h.dateCol&lt;GETDATE()-1 GROUP BY u.Id, u.name </code></pre>
[ { "answer_id": 837, "author": "vzczc", "author_id": 224, "author_profile": "https://Stackoverflow.com/users/224", "pm_score": 4, "selected": true, "text": "var collection=\n from u in db.Universe\n select new\n {\n u.id,\n u.name,\n MaxDate =(DateTime?)\n (\n from h in db.History\n where u.Id == h.Id\n && h.dateCol < yesterday\n select h.dateCol \n ).Max()\n };\n" }, { "answer_id": 33140, "author": "AdamB", "author_id": 2176, "author_profile": "https://Stackoverflow.com/users/2176", "pm_score": 0, "selected": false, "text": "var collection = \nfrom u in db.Universe\njoin history in db.History on u.id = history.id into temp\nfrom h in temp.DefaultIfEmpty()\nwhere h.dateCol < DateTime.Now.Date.AddDays(-1)\nselect u.id, u.name, h.dateCol ?? '1900-01-01'\n groupby isnull" }, { "answer_id": 80296, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 0, "selected": false, "text": "join into TestContext db = new TestContext(CreateSparqlTripleStore());\nvar q = from a in db.Album\n join t in db.Track on a.Name equals t.AlbumName into tracks\n select new Album{Name = a.Name, Tracks = tracks};\nforeach(var album in q){\n Console.WriteLine(album.Name);\n foreach (Track track in album.Tracks)\n {\n Console.WriteLine(track.Title);\n }\n}\n" }, { "answer_id": 36693733, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var collection=\n from u in db.Universe\n select new\n {\n u.id,\n u.name,\n MaxDate =(DateTime?)\n (\n from h in db.History\n where u.Id == h.Id\n && h.dateCol < yesterday\n select h.dateCol \n ).Max()\n };\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224/" ]
833
<p>I have designed database tables (normalised, on an MS SQL server) and created a standalone windows front end for an application that will be used by a handful of users to add and edit information. We will add a web interface to allow searching accross our production area at a later date.</p> <p>I am concerned that if two users start editing the same record then the last to commit the update would be the 'winner' and important information may be lost. A number of solutions come to mind but I'm not sure if I am going to create a bigger headache.</p> <ol> <li>Do nothing and hope that two users are never going to be editing the same record at the same time. <em>- Might never happed but what if it does?</em></li> <li>Editing routine could store a copy of the original data as well as the updates and then compare when the user has finished editing. If they differ show user and comfirm update <em>- Would require two copies of data to be stored.</em></li> <li>Add last updated DATETIME column and check it matches when we update, if not then show differences. <em>- requires new column in each of the relevant tables.</em></li> <li>Create an editing table that registers when users start editing a record that will be checked and prevent other users from editing same record. <em>- would require carful thought of program flow to prevent deadlocks and records becoming locked if a user crashes out of the program.</em></li> </ol> <p>Are there any better solutions or should I go for one of these?</p>
[ { "answer_id": 1620, "author": "karlgrz", "author_id": 318, "author_profile": "https://Stackoverflow.com/users/318", "pm_score": 2, "selected": false, "text": "SELECT ... FOR UPDATE SELECT UPDLOCK" }, { "answer_id": 10437, "author": "Guy", "author_id": 993, "author_profile": "https://Stackoverflow.com/users/993", "pm_score": 1, "selected": false, "text": "SELECT \n customer_nm,\n customer_nm AS customer_nm_orig\nFROM demo_customer\nWHERE customer_id = @p_customer_id\n UPDATE demo_customer\nSET customer_nm = @p_customer_name_new\nWHERE customer_id = @p_customer_id\nAND customer_name = @p_customer_nm_old\n\nIF @@ROWCOUNT = 0\n RAISERROR( 'Update failed: Data changed' );\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/186/" ]
835
<p>I'm trying to setup CruiseControl.net at the moment. So far it works nice, but I have a Problem with the MSBuild Task.</p> <p>According to the <a href="http://confluence.public.thoughtworks.org/display/CCNET/MsBuild+Task" rel="noreferrer">Documentation</a>, it passes CCNetArtifactDirectory to MSBuild. But how do I use it?</p> <p>I tried this:</p> <pre><code>&lt;buildArgs&gt; /noconsolelogger /p:OutputPath=$(CCNetArtifactDirectory)\test &lt;/buildArgs&gt; </code></pre> <p>But that does not work. In fact, it kills the service with this error:</p> <blockquote> <p>ThoughtWorks.CruiseControl.Core.Config.Preprocessor.EvaluationException: Reference to unknown symbol CCNetArtifactDirectory</p> </blockquote> <p>Documentation is rather sparse, and google und mainly offers modifying the .sln Project file, which is what I want to avoid in order to be able to manually build this project later - I would really prefer <code>/p:OutputPath</code>.</p>
[ { "answer_id": 1023, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 4, "selected": true, "text": "<executable>c:\\WINDOWS\\Microsoft.NET\\Framework\\v3.5\\MSBuild.exe</executable>\n<workingDirectory>C:\\data\\projects\\FooSolution\\</workingDirectory>\n<projectFile>FooSolution.sln</projectFile>\n<buildArgs>/noconsolelogger /p:Configuration=Debug </buildArgs>\n <publishers>\n <xmllogger />\n <buildpublisher>\n <sourceDir>C:\\data\\projects\\FooSolution\\FooProject\\bin\\Debug</sourceDir>\n <publishDir>C:\\published\\FooSolution\\</publishDir>\n <useLabelSubDirectory>false</useLabelSubDirectory>\n </buildpublisher>\n</publishers>\n" }, { "answer_id": 1281, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": false, "text": "<Exec\n Command='FxCopCmd.exe /project:\"$(MSBuildProjectDirectory)\\FXCopRules.FxCop\" /out:\"$(CCNetArtifactDirectory)\\ProjectName.FxCop.xml\"'\n WorkingDirectory=\"C:\\Program Files\\Microsoft FxCop 1.35\"\n ContinueOnError=\"true\"\n IgnoreExitCode=\"true\"\n/>\n" }, { "answer_id": 2343524, "author": "The Chairman", "author_id": 38029, "author_profile": "https://Stackoverflow.com/users/38029", "pm_score": 2, "selected": false, "text": "CCNetArtifactDirectory CCNET <cb:define project.artifactDirectory=\"C:\\foo\">\n<project>\n <!-- [...] -->\n <artifactDirectory>$(project.artifactDirectory)</artifactDirectory>\n <!-- [...] -->\n <tasks>\n <!-- [...] -->\n <msbuild>\n <!-- [...] -->\n <buildArgs>/noconsolelogger /p:OutputPath=$(project.artifactDirectory)\\test</buildArgs>\n <!-- [...] -->\n </msbuild>\n <!-- [...] -->\n </tasks>\n <!-- [...] -->\n</project>\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
845
<p>Suppose I have the following CSS rule in my page:</p> <pre class="lang-css prettyprint-override"><code>body { font-family: Calibri, Trebuchet MS, Helvetica, sans-serif; } </code></pre> <p>How could I detect which one of the defined fonts were used in the user's browser?</p> <p>For people wondering why I want to do this is because the font I'm detecting contains glyphs that are <em>not</em> available in other fonts. If the user does <em>not</em> have the font, then I want it to display a link asking the user to download that font (so they can use my web application with the correct font).</p> <p>Currently, I am displaying the download font link for all users. I want to only display this for people who do <em>not</em> have the correct font installed.</p>
[ { "answer_id": 27035, "author": "runeh", "author_id": 2906, "author_profile": "https://Stackoverflow.com/users/2906", "pm_score": 4, "selected": false, "text": "/**\n * Get the font used for a given element\n * @argument {HTMLElement} the element to check font for\n * @returns {string} The name of the used font or null if font could not be detected\n */\nfunction getFontForElement(ele) {\n if (ele.currentStyle) { // sort of, but not really, works in IE\n return ele.currentStyle[\"fontFamily\"];\n } else if (document.defaultView) { // works in Opera and FF\n return document.defaultView.getComputedStyle(ele,null).getPropertyValue(\"font-family\");\n } else {\n return null;\n }\n}\n #fonttester {\n font-family: sans-serif, arial, helvetica;\n}\n" }, { "answer_id": 887291, "author": "philoye", "author_id": 109864, "author_profile": "https://Stackoverflow.com/users/109864", "pm_score": 4, "selected": false, "text": "font-family: \"my fake font\", helvetica, san-serif;\n" }, { "answer_id": 7866425, "author": "Facebiz", "author_id": 1009517, "author_profile": "https://Stackoverflow.com/users/1009517", "pm_score": 3, "selected": false, "text": "function getFont() {\n return document.getElementById('header').style.font;\n}\n" }, { "answer_id": 8307897, "author": "Naeem Ul Wahhab", "author_id": 1067051, "author_profile": "https://Stackoverflow.com/users/1067051", "pm_score": 3, "selected": false, "text": "element.style.font function getUserBrowsersFont() {\n var browserHeader = document.getElementById('header');\n return browserHeader.style.font;\n}\n" }, { "answer_id": 8741592, "author": "PaulnOZ", "author_id": 1131991, "author_profile": "https://Stackoverflow.com/users/1131991", "pm_score": 3, "selected": false, "text": "@font-face @font-face {\n font-family: \"Calibri\";\n src: url(\"http://www.yourwebsite.com/fonts/Calibri.eot\");\n src: local(\"Calibri\"), url(\"http://www.yourwebsite.com/fonts/Calibri.ttf\") format(\"truetype\");\n}\n .eot .ttf" }, { "answer_id": 47571799, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 2, "selected": false, "text": "font-family: Arial, 'Adobe Blank';\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238/" ]
871
<p>I've been using <a href="http://en.wikipedia.org/wiki/Apache_Subversion" rel="nofollow noreferrer">Subversion</a> for a few years and after using <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_SourceSafe" rel="nofollow noreferrer">SourceSafe</a>, I just love Subversion. Combined with <a href="http://en.wikipedia.org/wiki/TortoiseSVN" rel="nofollow noreferrer">TortoiseSVN</a>, I can't really imagine how it could be any better. </p> <p>Yet there's a growing number of developers claiming that Subversion has problems and that we should be moving to the new breed of distributed version control systems, such as <a href="http://git.or.cz/" rel="nofollow noreferrer" title="Git Distributed Version Control System">Git</a>. </p> <p>How does Git improve upon Subversion?</p>
[ { "answer_id": 162148, "author": "Andre Bossard", "author_id": 21027, "author_profile": "https://Stackoverflow.com/users/21027", "pm_score": 4, "selected": false, "text": "backup/public" }, { "answer_id": 531042, "author": "sebnow", "author_id": 64423, "author_profile": "https://Stackoverflow.com/users/64423", "pm_score": 6, "selected": false, "text": "svn checkout svn://foo.com/bar bar\ncd bar\n# edit\nsvn commit -m \"foo\"\n git clone [email protected]:foo/bar.git\ncd bar\n# edit\ngit commit -a -m \"foo\"\ngit push\n" }, { "answer_id": 1245254, "author": "William Pursell", "author_id": 140750, "author_profile": "https://Stackoverflow.com/users/140750", "pm_score": 2, "selected": false, "text": "git add --patch" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/203/" ]
879
<p>Are PHP variables passed by value or by reference?</p>
[ { "answer_id": 881, "author": "cmcculloh", "author_id": 58, "author_profile": "https://Stackoverflow.com/users/58", "pm_score": 5, "selected": false, "text": "$var1 = \"test\";\n$var2 = $var1;\n$var2 = \"new test\";\n$var3 = &$var2;\n$var3 = \"final test\";\n\nprint (\"var1: $var1, var2: $var2, var3: $var3);\n $var1 = \"foo\";\n$var2 = \"bar\";\n\nchangeThem($var1, $var2);\n\nprint \"var1: $var1, var2: $var2\";\n\nfunction changeThem($var1, &$var2){\n $var1 = \"FOO\";\n $var2 = \"BAR\";\n}\n class Foo{\n public $var1;\n\n function __construct(){\n $this->var1 = \"foo\";\n }\n\n public function printFoo(){\n print $this->var1;\n }\n}\n\n\n$foo = new Foo();\n\nchangeFoo($foo);\n\n$foo->printFoo();\n\nfunction changeFoo($foo){\n $foo->var1 = \"FOO\";\n}\n" }, { "answer_id": 885, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 10, "selected": true, "text": "<?php\nfunction add_some_extra(&$string)\n{\n $string .= 'and something extra.';\n}\n\n$str = 'This is a string, ';\nadd_some_extra($str);\necho $str; // outputs 'This is a string, and something extra.'\n?>\n" }, { "answer_id": 7483, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 6, "selected": false, "text": "<?php\nclass Holder {\n private $value;\n\n public function __construct($value) {\n $this->value = $value;\n }\n\n public function getValue() {\n return $this->value;\n }\n}\n\nfunction swap($x, $y) {\n $tmp = $x;\n $x = $y;\n $y = $tmp;\n}\n\n$a = new Holder('a');\n$b = new Holder('b');\nswap($a, $b);\n\necho $a->getValue() . \", \" . $b->getValue() . \"\\n\";\n a, b\n <?php\nfunction swap(&$x, &$y) {\n $tmp = $x;\n $x = $y;\n $y = $tmp;\n}\n\n$a = new Holder('a');\n$b = new Holder('b');\nswap($a, $b);\n\necho $a->getValue() . \", \" . $b->getValue() . \"\\n\";\n b, a\n" }, { "answer_id": 574631, "author": "Bingy", "author_id": 69518, "author_profile": "https://Stackoverflow.com/users/69518", "pm_score": 3, "selected": false, "text": " $fred = 5;\n $larry = & $fred;\n $larry = 8;\n echo $fred;//this will output 8, as larry and fred are now the same reference.\n" }, { "answer_id": 2812176, "author": "Ricardo Saracino", "author_id": 338456, "author_profile": "https://Stackoverflow.com/users/338456", "pm_score": 1, "selected": false, "text": "class Holder\n{\n private $value;\n\n public function __construct( $value )\n {\n $this->value = $value;\n }\n\n public function getValue()\n {\n return $this->value;\n }\n\n public function setValue( $value )\n {\n return $this->value = $value;\n }\n}\n\nclass Swap\n{ \n public function SwapObjects( Holder $x, Holder $y )\n {\n $tmp = $x;\n\n $x = $y;\n\n $y = $tmp;\n }\n\n public function SwapValues( Holder $x, Holder $y )\n {\n $tmp = $x->getValue();\n\n $x->setValue($y->getValue());\n\n $y->setValue($tmp);\n }\n}\n\n\n$a1 = new Holder('a');\n\n$b1 = new Holder('b');\n\n\n\n$a2 = new Holder('a');\n\n$b2 = new Holder('b');\n\n\nSwap::SwapValues($a1, $b1);\n\nSwap::SwapObjects($a2, $b2);\n\n\n\necho 'SwapValues: ' . $a2->getValue() . \", \" . $b2->getValue() . \"<br>\";\n\necho 'SwapObjects: ' . $a1->getValue() . \", \" . $b1->getValue() . \"<br>\";\n" }, { "answer_id": 9696799, "author": "hardik", "author_id": 805437, "author_profile": "https://Stackoverflow.com/users/805437", "pm_score": 7, "selected": false, "text": "class X {\n var $abc = 10; \n}\n\nclass Y {\n\n var $abc = 20; \n function changeValue($obj)\n {\n $obj->abc = 30;\n }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x->abc; //outputs 10\n$y->changeValue($x);\necho $x->abc; //outputs 30\n class X {\n var $abc = 10; \n}\n\nclass Y {\n\n var $abc = 20; \n function changeValue($obj)\n {\n $obj = new Y();\n }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x->abc; //outputs 10\n$y->changeValue($x);\necho $x->abc; //outputs 10 not 20 same as java does.\n class X {\n var $abc = 10; \n}\n\nclass Y {\n\n var $abc = 20; \n function changeValue(&$obj)\n {\n $obj = new Y();\n }\n}\n\n$x = new X();\n$y = new Y();\n\necho $x->abc; //outputs 10\n$y->changeValue($x);\necho $x->abc; //outputs 20 not possible in java.\n" }, { "answer_id": 27588152, "author": "Mahsin", "author_id": 3699965, "author_profile": "https://Stackoverflow.com/users/3699965", "pm_score": 3, "selected": false, "text": "<?php\nfunction changeValue(&$var)\n{\n $var++;\n}\n\n$result=5;\nchangeValue($result);\n\necho $result; // $result is 6 here\n?>\n" }, { "answer_id": 49587783, "author": "PPL", "author_id": 9411789, "author_profile": "https://Stackoverflow.com/users/9411789", "pm_score": 0, "selected": false, "text": "function add(&$var){ // The &amp; is before the argument $var\n $var++;\n}\n$a = 1;\n$b = 10;\nadd($a);\necho \"a is $a,\";\nadd($b);\necho \" a is $a, and b is $b\"; // Note: $a and $b are NOT referenced\n" }, { "answer_id": 60082753, "author": "AleksandrH", "author_id": 5323344, "author_profile": "https://Stackoverflow.com/users/5323344", "pm_score": 3, "selected": false, "text": "& <?php\n\n//The two are meant to be the same\n$a = \"Clark Kent\"; //a==Clark Kent\n$b = &$a; //The two will now share the same fate.\n\n$b=\"Superman\"; // $a==\"Superman\" too.\necho $a;\necho $a=\"Clark Kent\"; // $b==\"Clark Kent\" too.\nunset($b); // $b divorced from $a\n$b=\"Bizarro\";\necho $a; // $a==\"Clark Kent\" still, since $b is a free agent pointer now.\n\n//The two are NOT meant to be the same.\n$c=\"King\";\n$d=\"Pretender to the Throne\";\necho $c.\"\\n\"; // $c==\"King\"\necho $d.\"\\n\"; // $d==\"Pretender to the Throne\"\nswapByValue($c, $d);\necho $c.\"\\n\"; // $c==\"King\"\necho $d.\"\\n\"; // $d==\"Pretender to the Throne\"\nswapByRef($c, $d);\necho $c.\"\\n\"; // $c==\"Pretender to the Throne\"\necho $d.\"\\n\"; // $d==\"King\"\n\nfunction swapByValue($x, $y){\n$temp=$x;\n$x=$y;\n$y=$temp;\n//All this beautiful work will disappear\n//because it was done on COPIES of pointers.\n//The originals pointers still point as they did.\n}\n\nfunction swapByRef(&$x, &$y){\n$temp=$x;\n$x=$y;\n$y=$temp;\n//Note the parameter list: now we switched 'em REAL good.\n}\n\n?>\n" }, { "answer_id": 67052160, "author": "CGeorgian", "author_id": 4195727, "author_profile": "https://Stackoverflow.com/users/4195727", "pm_score": 1, "selected": false, "text": "<?php\n class Example \n {\n public $value;\n \n }\n \n function test1($x) \n {\n //let's say $x is 0x34313131\n $x->value = 1; //will reflect outsite of this function\n //php use pointer 0x34313131 and search for the \n //address of 'value' and change it to 1\n\n }\n \n function test2($x) \n {\n //$x is 0x34313131\n $x = new Example;\n //now $x is 0x88888888\n //this will NOT reflect outside of this function \n //you need to rewrite it as \"test2(&$x)\"\n $x->value = 1000; //this is 1000 JUST inside this function\n \n \n }\n \n $example = new Example;\n \n $example->value = 0;\n \n test1($example); // $example->value changed to 1\n \n test2($example); // $example did NOT changed to a new object \n // $example->value is still 1\n \n ?>\n" }, { "answer_id": 68130959, "author": "HSLM", "author_id": 2763028, "author_profile": "https://Stackoverflow.com/users/2763028", "pm_score": 0, "selected": false, "text": "class Type {}\n\n$x = new Type();\n$y = $x;\n$y = \"New value\";\n\nvar_dump($x); // Will print the object.\nvar_dump($y); // Will print the \"New value\"\n\n$z = &$x; // $z is a reference of $x\n\n$z = \"New value\";\nvar_dump($x); // Will print \"New value\"\nvar_dump($z); // Will print \"New value\"\n\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
888
<p>How do you debug <strong>PHP</strong> scripts?</p> <p>I am aware of basic debugging such as using the Error Reporting. The breakpoint debugging in <strong>PHPEclipse</strong> is also quite useful.</p> <p>What is the <strong>best</strong> (in terms of fast and easy) way to debug in phpStorm or any other IDE?</p>
[ { "answer_id": 890, "author": "John Downey", "author_id": 200, "author_profile": "https://Stackoverflow.com/users/200", "pm_score": 8, "selected": true, "text": "var_dump() die()" }, { "answer_id": 1758, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 0, "selected": false, "text": "echo '<pre>';\nprint_r($arrayOrObject);\n" }, { "answer_id": 4172, "author": "jlleblanc", "author_id": 586, "author_profile": "https://Stackoverflow.com/users/586", "pm_score": 4, "selected": false, "text": "echo \"<pre>\";\nprint_r();\necho \"</pre>\";\n" }, { "answer_id": 22681, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "var_dump() debug_print_backtrace()" }, { "answer_id": 22691, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 5, "selected": false, "text": "var_dump() print_r() <pre> <?php var_dump(__FILE__, __LINE__, $_REQUEST); ?>\n" }, { "answer_id": 89699, "author": "Nathan Strong", "author_id": 9780, "author_profile": "https://Stackoverflow.com/users/9780", "pm_score": 2, "selected": false, "text": "echo \"<pre>\".print_r($var, true).\"</pre>\";\n" }, { "answer_id": 224986, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 3, "selected": false, "text": " ob_start();var_dump(); user_error(ob_get_contents()); ob_get_clean();\n" }, { "answer_id": 1058375, "author": "eisberg", "author_id": 113154, "author_profile": "https://Stackoverflow.com/users/113154", "pm_score": 5, "selected": false, "text": "error_reporting(-1);\nassert_options(ASSERT_ACTIVE, 1);\nassert_options(ASSERT_WARNING, 0);\nassert_options(ASSERT_BAIL, 0);\nassert_options(ASSERT_QUIET_EVAL, 0);\nassert_options(ASSERT_CALLBACK, 'assert_callcack');\nset_error_handler('error_handler');\nset_exception_handler('exception_handler');\nregister_shutdown_function('shutdown_handler');\n\nfunction assert_callcack($file, $line, $message) {\n throw new Customizable_Exception($message, null, $file, $line);\n}\n\nfunction error_handler($errno, $error, $file, $line, $vars) {\n if ($errno === 0 || ($errno & error_reporting()) === 0) {\n return;\n }\n\n throw new Customizable_Exception($error, $errno, $file, $line);\n}\n\nfunction exception_handler(Exception $e) {\n // Do what ever!\n echo '<pre>', print_r($e, true), '</pre>';\n exit;\n}\n\nfunction shutdown_handler() {\n try {\n if (null !== $error = error_get_last()) {\n throw new Customizable_Exception($error['message'], $error['type'], $error['file'], $error['line']);\n }\n } catch (Exception $e) {\n exception_handler($e);\n }\n}\n\nclass Customizable_Exception extends Exception {\n public function __construct($message = null, $code = null, $file = null, $line = null) {\n if ($code === null) {\n parent::__construct($message);\n } else {\n parent::__construct($message, $code);\n }\n if ($file !== null) {\n $this->file = $file;\n }\n if ($line !== null) {\n $this->line = $line;\n }\n }\n}\n" }, { "answer_id": 2801537, "author": "Petr Peller", "author_id": 190438, "author_profile": "https://Stackoverflow.com/users/190438", "pm_score": 1, "selected": false, "text": "var_dump" }, { "answer_id": 2801595, "author": "CafeHey", "author_id": 269404, "author_profile": "https://Stackoverflow.com/users/269404", "pm_score": 2, "selected": false, "text": "error.log tail -f app/tmp/logs/error.log\n $this->log('xxxx');\n" }, { "answer_id": 32886213, "author": "shekh danishuesn", "author_id": 5291660, "author_profile": "https://Stackoverflow.com/users/5291660", "pm_score": 2, "selected": false, "text": "display_errors = Off\nerror_reporting = E_ALL \ndisplay_errors = On\n error_log();\nconsole_log();\n" }, { "answer_id": 36131176, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 1, "selected": false, "text": "require('php_error.php');\n\\php_error\\reportErrors();\n --enable-dtrace sudo dtrace -qn 'php*:::function-entry { printf(\"%Y: PHP function-entry:\\t%s%s%s() in %s:%d\\n\", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }'\n ~/.bashrc ~/.bash_aliases alias trace-php='sudo dtrace -qn \"php*:::function-entry { printf(\\\"%Y: PHP function-entry:\\t%s%s%s() in %s:%d\\n\\\", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2); }\"'\n trace-php dtruss-php.d chmod +x dtruss-php.d #!/usr/sbin/dtrace -Zs\n# See: https://github.com/kenorb/dtruss-lamp/blob/master/dtruss-php.d\n\n#pragma D option quiet\n\nphp*:::compile-file-entry\n{\n printf(\"%Y: PHP compile-file-entry:\\t%s (%s)\\n\", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1));\n}\n\nphp*:::compile-file-return\n{\n printf(\"%Y: PHP compile-file-return:\\t%s (%s)\\n\", walltimestamp, basename(copyinstr(arg0)), basename(copyinstr(arg1)));\n}\n\nphp*:::error\n{\n printf(\"%Y: PHP error message:\\t%s in %s:%d\\n\", walltimestamp, copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);\n}\n\nphp*:::exception-caught\n{\n printf(\"%Y: PHP exception-caught:\\t%s\\n\", walltimestamp, copyinstr(arg0));\n}\n\nphp*:::exception-thrown\n{\n printf(\"%Y: PHP exception-thrown:\\t%s\\n\", walltimestamp, copyinstr(arg0));\n}\n\nphp*:::execute-entry\n{\n printf(\"%Y: PHP execute-entry:\\t%s:%d\\n\", walltimestamp, basename(copyinstr(arg0)), (int)arg1);\n}\n\nphp*:::execute-return\n{\n printf(\"%Y: PHP execute-return:\\t%s:%d\\n\", walltimestamp, basename(copyinstr(arg0)), (int)arg1);\n}\n\nphp*:::function-entry\n{\n printf(\"%Y: PHP function-entry:\\t%s%s%s() in %s:%d\\n\", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);\n}\n\nphp*:::function-return\n{\n printf(\"%Y: PHP function-return:\\t%s%s%s() in %s:%d\\n\", walltimestamp, copyinstr(arg3), copyinstr(arg4), copyinstr(arg0), basename(copyinstr(arg1)), (int)arg2);\n}\n\nphp*:::request-shutdown\n{\n printf(\"%Y: PHP request-shutdown:\\t%s at %s via %s\\n\", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1), copyinstr(arg2));\n}\n\nphp*:::request-startup\n{\n printf(\"%Y, PHP request-startup:\\t%s at %s via %s\\n\", walltimestamp, basename(copyinstr(arg0)), copyinstr(arg1), copyinstr(arg2));\n}\n sudo dtruss-php.d php -r \"phpinfo();\" index.php php -S localhost:8080\n yum install systemtap-sdt-devel all_probes.stp probe process(\"sapi/cli/php\").provider(\"php\").mark(\"compile__file__entry\") {\n printf(\"Probe compile__file__entry\\n\");\n printf(\" compile_file %s\\n\", user_string($arg1));\n printf(\" compile_file_translated %s\\n\", user_string($arg2));\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"compile__file__return\") {\n printf(\"Probe compile__file__return\\n\");\n printf(\" compile_file %s\\n\", user_string($arg1));\n printf(\" compile_file_translated %s\\n\", user_string($arg2));\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"error\") {\n printf(\"Probe error\\n\");\n printf(\" errormsg %s\\n\", user_string($arg1));\n printf(\" request_file %s\\n\", user_string($arg2));\n printf(\" lineno %d\\n\", $arg3);\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"exception__caught\") {\n printf(\"Probe exception__caught\\n\");\n printf(\" classname %s\\n\", user_string($arg1));\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"exception__thrown\") {\n printf(\"Probe exception__thrown\\n\");\n printf(\" classname %s\\n\", user_string($arg1));\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"execute__entry\") {\n printf(\"Probe execute__entry\\n\");\n printf(\" request_file %s\\n\", user_string($arg1));\n printf(\" lineno %d\\n\", $arg2);\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"execute__return\") {\n printf(\"Probe execute__return\\n\");\n printf(\" request_file %s\\n\", user_string($arg1));\n printf(\" lineno %d\\n\", $arg2);\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"function__entry\") {\n printf(\"Probe function__entry\\n\");\n printf(\" function_name %s\\n\", user_string($arg1));\n printf(\" request_file %s\\n\", user_string($arg2));\n printf(\" lineno %d\\n\", $arg3);\n printf(\" classname %s\\n\", user_string($arg4));\n printf(\" scope %s\\n\", user_string($arg5));\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"function__return\") {\n printf(\"Probe function__return: %s\\n\", user_string($arg1));\n printf(\" function_name %s\\n\", user_string($arg1));\n printf(\" request_file %s\\n\", user_string($arg2));\n printf(\" lineno %d\\n\", $arg3);\n printf(\" classname %s\\n\", user_string($arg4));\n printf(\" scope %s\\n\", user_string($arg5));\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"request__shutdown\") {\n printf(\"Probe request__shutdown\\n\");\n printf(\" file %s\\n\", user_string($arg1));\n printf(\" request_uri %s\\n\", user_string($arg2));\n printf(\" request_method %s\\n\", user_string($arg3));\n}\nprobe process(\"sapi/cli/php\").provider(\"php\").mark(\"request__startup\") {\n printf(\"Probe request__startup\\n\");\n printf(\" file %s\\n\", user_string($arg1));\n printf(\" request_uri %s\\n\", user_string($arg2));\n printf(\" request_method %s\\n\", user_string($arg3));\n}\n stap -c 'sapi/cli/php test.php' all_probes.stp\n" } ]
2008/08/03
[ "https://Stackoverflow.com/questions/888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
898
<p>How have you implemented Internationalization (i18n) in actual projects you've worked on?</p> <p>I took an interest in making software cross-cultural after I read the famous post by Joel, <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a>. However, I have yet to able to take advantage of this in a real project, besides making sure I used Unicode strings where possible. But making all your strings Unicode and ensuring you understand what encoding everything you work with is in is just the tip of the i18n iceberg.</p> <p>Everything I have worked on to date has been for use by a controlled set of US English speaking people, or i18n just wasn't something we had time to work on before pushing the project live. So I am looking for any tips or war stories people have about making software more localized in real world projects.</p>
[ { "answer_id": 906, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "String message = \"The \" + item + \" is on sale!\";\n String message = String.Format(\"The {0} is on sale!\", item);\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200/" ]
904
<p>Given a relatively simple CSS:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>div { width: 150px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div&gt; 12333-2333-233-23339392-332332323 &lt;/div&gt;</code></pre> </div> </div> </p> <blockquote> <p>How do I make it so that the string stays constrained to the <code>width</code> of <strong>150</strong>, and wraps to a new line on the <em>hyphen</em>?</p> </blockquote>
[ { "answer_id": 911, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 7, "selected": true, "text": "&shy;\n div {\n width: 150px;\n} <div>\n 12333&shy;2333&shy;233&shy;23339392&shy;332332323\n</div>" }, { "answer_id": 67878, "author": "Dave Rutledge", "author_id": 2486915, "author_profile": "https://Stackoverflow.com/users/2486915", "pm_score": 3, "selected": false, "text": "&shy;" }, { "answer_id": 343686, "author": "Peter T. LaComb Jr.", "author_id": 8513, "author_profile": "https://Stackoverflow.com/users/8513", "pm_score": 3, "selected": false, "text": "<div style=\"width:150px;\">\n <span>12333-</span><span>2333-</span><span>233-</span><span>23339392-</span><span>332332323</span>\n</div>" }, { "answer_id": 3725181, "author": "Orion", "author_id": 449300, "author_profile": "https://Stackoverflow.com/users/449300", "pm_score": 3, "selected": false, "text": "hyphen soft hyphen zero width space 111111&shy;222222&shy;-333333&#8203;444444-&#8203;555555" }, { "answer_id": 9060345, "author": "aeskr", "author_id": 1125471, "author_profile": "https://Stackoverflow.com/users/1125471", "pm_score": 5, "selected": false, "text": "<wbr> <wbr> <div style=\"width: 150px;\">\n 12333-<wbr>2333-<wbr>233-<wbr>23339392-<wbr>332332323\n</div>\n div {\n width: 150px;\n} <div>\n 12333-<wbr>2333-<wbr>233-<wbr>23339392-<wbr>332332323\n</div>" }, { "answer_id": 22570418, "author": "ImaJedi4ever", "author_id": 3329778, "author_profile": "https://Stackoverflow.com/users/3329778", "pm_score": 0, "selected": false, "text": "&#8209;\n" }, { "answer_id": 30229247, "author": "TObject", "author_id": 4736743, "author_profile": "https://Stackoverflow.com/users/4736743", "pm_score": 0, "selected": false, "text": "- &hyphen; \\u2010 <wbr>" }, { "answer_id": 32249676, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 2, "selected": false, "text": "word-break:break-all;\n <div style='width:10px'>ababababababbabaabababababababbabababa</div>\n abababababa\nababababbba\nabbabbababa\nababb\n" }, { "answer_id": 45979734, "author": "Mohammed Wahed Khan", "author_id": 8040185, "author_profile": "https://Stackoverflow.com/users/8040185", "pm_score": 0, "selected": false, "text": "<br>" }, { "answer_id": 52311670, "author": "jcubic", "author_id": 387194, "author_profile": "https://Stackoverflow.com/users/387194", "pm_score": 0, "selected": false, "text": "div {\n width: 150px;\n} <div>\n 12333-&#8203;2333-&#8203;233-&#8203;23339392-&#8203;332332323\n</div> &#8203;-" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34/" ]
930
<p>What's the simplest way to connect and query a database for a set of records in C#?</p>
[ { "answer_id": 940, "author": "Goyuix", "author_id": 243, "author_profile": "https://Stackoverflow.com/users/243", "pm_score": 4, "selected": false, "text": "using (OleDBConnection conn = new OleDbConnection())\n{\n conn.ConnectionString = \"Whatever connection string\";\n\n using (OleDbCommand cmd = new OleDbCommand())\n {\n cmd.Connection = conn;\n cmd.CommandText = \"Select * from CoolTable\";\n\n using (OleDbDataReader dr = cmd.ExecuteReader())\n {\n while (dr.Read())\n {\n // do something like Console.WriteLine(dr[\"column name\"] as String);\n }\n }\n }\n}\n" }, { "answer_id": 951, "author": "Leon Bambrick", "author_id": 49, "author_profile": "https://Stackoverflow.com/users/49", "pm_score": 6, "selected": true, "text": "using System.Data.OleDb;\n...\n\nusing (OleDbConnection conn = new OleDbConnection())\n{\n conn.ConnectionString = \"Provider=sqloledb;Data Source=yourServername\\\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;\";\n\n using (OleDbCommand cmd = new OleDbCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = \"Select * from yourTable\";\n\n using (OleDbDataReader dr = cmd.ExecuteReader())\n {\n while (dr.Read())\n {\n Console.WriteLine(dr[\"columnName\"]);\n }\n }\n }\n}\n" }, { "answer_id": 1022, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 4, "selected": false, "text": "MyDB db = new MyDB(\"Data Source=...\");\nvar q = from db.MyTable\n select c;\nforeach (var c in q)\n Console.WriteLine(c.MyField.ToString());\n" }, { "answer_id": 2369, "author": "Marek Grzenkowicz", "author_id": 95, "author_profile": "https://Stackoverflow.com/users/95", "pm_score": 3, "selected": false, "text": "string s = \"\";\nSqlConnection conn = new SqlConnection(\"Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;\");\nSqlDataAdapter da = new SqlDataAdapter(\"SELECT TOP 5 name, dbid FROM sysdatabases\", conn);\nDataTable dt = new DataTable();\n\nda.Fill(dt);\n\nfor (int i = 0; i < dt.Rows.Count; i++)\n{\n s += dt.Rows[i][\"name\"].ToString() + \" -- \" + dt.Rows[i][\"dbid\"].ToString() + \"\\n\";\n}\n\nMessageBox.Show(s);\n" }, { "answer_id": 65774, "author": "DamienG", "author_id": 5720, "author_profile": "https://Stackoverflow.com/users/5720", "pm_score": 2, "selected": false, "text": "using (DbDataReader dr = cmd.ExecuteReader()) {\n if (dr.Read()) {\n int idxColumnName = dr.GetOrdinal(\"columnName\");\n int idxSomethingElse = dr.GetOrdinal(\"somethingElse\");\n\n do {\n Console.WriteLine(dr.GetString(idxColumnName));\n Console.WriteLine(dr.GetInt32(idxSomethingElse));\n } while (dr.Read());\n }\n}\n" }, { "answer_id": 12288220, "author": "kril", "author_id": 1650003, "author_profile": "https://Stackoverflow.com/users/1650003", "pm_score": 1, "selected": false, "text": "using (SchoolDBEntities ctx = new SchoolDBEntities())\n{\n IList<Course> courseList = ctx.GetCoursesByStudentId(1).ToList<Course>();\n //do something with courselist here\n}\n" }, { "answer_id": 56179247, "author": "Josué Martínez", "author_id": 11507342, "author_profile": "https://Stackoverflow.com/users/11507342", "pm_score": 0, "selected": false, "text": "using MySql.Data.MySqlClient;\n public static MySqlConnection obtenerconexion()\n{\n string server = \"Server\";\n string database = \"Name_Database\";\n string Uid = \"User\";\n string pwd = \"Password\";\n MySqlConnection conect = new MySqlConnection(\"server = \" + server + \";\" + \"database =\" + database + \";\" + \"Uid =\" + Uid + \";\" + \"pwd=\" + pwd + \";\");\n\n try\n {\n conect.Open();\n return conect;\n }\n catch (Exception)\n {\n MessageBox.Show(\"Error. Ask the administrator\", \"An error has occurred while trying to connect to the system\", MessageBoxButtons.OK, MessageBoxIcon.Error);\n return conect;\n }\n}\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/245/" ]
935
<p>Attempting to insert an escape character into a table results in a warning. </p> <p>For example:</p> <pre><code>create table EscapeTest (text varchar(50)); insert into EscapeTest (text) values ('This is the first part \n And this is the second'); </code></pre> <p>Produces the warning:</p> <pre><code>WARNING: nonstandard use of escape in a string literal </code></pre> <p>(<em>Using PSQL 8.2</em>)</p> <p>Anyone know how to get around this?</p>
[ { "answer_id": 938, "author": "rjohnston", "author_id": 246, "author_profile": "https://Stackoverflow.com/users/246", "pm_score": 8, "selected": true, "text": "insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');\n insert into EscapeTest (text) values (E'This is the first part \\\\n And this is the second');\n" }, { "answer_id": 104780, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 2, "selected": false, "text": "milen@dev:~$ psql\nWelcome to psql 8.2.7, the PostgreSQL interactive terminal.\n\nType: \\copyright for distribution terms\n \\h for help with SQL commands\n \\? for help with psql commands\n \\g or terminate with semicolon to execute query\n \\q to quit\n\nmilen=> create table EscapeTest (text varchar(50));\nCREATE TABLE\nmilen=> insert into EscapeTest (text) values ('This will be inserted \\n This will not be');\nWARNING: nonstandard use of escape in a string literal\nLINE 1: insert into EscapeTest (text) values ('This will be inserted...\n ^\nHINT: Use the escape string syntax for escapes, e.g., E'\\r\\n'.\nINSERT 0 1\nmilen=> select * from EscapeTest;\n text\n------------------------\n This will be inserted\n This will not be\n(1 row)\n\nmilen=>\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/246/" ]
944
<p>I'm maintaining a .NET 1.1 application and one of the things I've been tasked with is making sure the user doesn't see any unfriendly error notifications.</p> <p>I've added handlers to <code>Application.ThreadException</code> and <code>AppDomain.CurrentDomain.UnhandledException</code>, which do get called. My problem is that the standard CLR error dialog is still displayed (before the exception handler is called).</p> <p>Jeff talks about this problem on his blog <a href="https://blog.codinghorror.com/console-apps-and-appdomain-currentdomain-unhandledexception/" rel="noreferrer">here</a> and <a href="https://blog.codinghorror.com/improved-unhandled-exception-behavior-in-net-20/" rel="noreferrer">here</a>. But there's no solution. So what is the standard way in .NET 1.1 to handle uncaught exceptions and display a friendly dialog box?</p> <p>Jeff's response was marked as the correct answer because the link he provided has the most complete information on how to do what's required.</p>
[ { "answer_id": 108550, "author": "HTTP 410", "author_id": 13118, "author_profile": "https://Stackoverflow.com/users/13118", "pm_score": 3, "selected": false, "text": "App.Config Application.ThreadException += new\nThreading.ThreadExceptionHandler(CatchFormsExceptions);\n AppDomain.CurrentDomain.UnhandledException += new\nSystem.UnhandledExceptionEventHandler(CatchClrExceptions);\n" }, { "answer_id": 70889762, "author": "Umar Hassan", "author_id": 1520030, "author_profile": "https://Stackoverflow.com/users/1520030", "pm_score": 0, "selected": false, "text": "AppDomain.CurrentDomain.FirstChanceException += MyFirstChanceExceptionHandler;\nApplication.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); // not sure if this is important or not.\nAppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; // can't use Lambda here. need to Unsub this event later.\nApplication.ThreadException += (s, e) => MyUnhandledExceptionHandler(e.Exception);\n\nstatic void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n{\n MyUnhandledExceptionHandler((Exception)e.ExceptionObject);\n}\nprivate void CurrentDomain_FirstChanceException(object sender, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs eventArgs)\n{\n // detect the pattern of the exception which we won't be able to get in Fatal events.\n if (eventArgs.Exception.Message.StartsWith(\"HRESULT\"))\n MyUnhandledExceptionHandler(eventArgs.Exception);\n}\n static void MyUnhandledExceptionHandler(Exception ex)\n{\n AppDomain.CurrentDomain.UnhandledException -= MyUnhandledExceptionHandler; // this is important. Any exception occuring in the logging mechanism can cause a stack overflow exception which triggers the window's own JIT message/App crash message if Win JIT is not available.\n // LogTheException()\n // Collect user data\n // inform the user in a civil way to restart/close the app\n Environment.Exit(0);\n}\n MyForm.Load += (s,e) => new Thread(()=>{/* My Form_Load code*/ }).Start();" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
947
<p>I have imported the <code>kernel32</code> library. So, I have the <code>createMutex</code> function available but I am not quite sure of the various parameters and return values.</p> <p>This is classic Visual Basic, not Visual Basic.NET but I can probably work with either language in the form of an answer.</p>
[ { "answer_id": 1028, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "hMutex = CreateMutex(ByVal 0&, 1, ByVal 0&)\n SECURITY_ATTRIBUTES TRUE FALSE VB VB BSTR" }, { "answer_id": 82335, "author": "MarkJ", "author_id": 15639, "author_profile": "https://Stackoverflow.com/users/15639", "pm_score": 3, "selected": false, "text": "Public Type SECURITY_ATTRIBUTES\n nLength As Long\n lpSecurityDescriptor As Long\n bInheritHandle As Long \nEnd Type\n\nPublic Declare Function CreateMutex Lib \"kernel32\" Alias \"CreateMutexA\" _\n (lpMutexAttributes As SECURITY_ATTRIBUTES, ByVal bInitialOwner As Long, _\n ByVal lpName As String) As Long\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/243/" ]
972
<p>I've read that it is possible to add a method to an existing object (i.e., not in the class definition) in Python. </p> <p>I understand that it's not always good to do so. But how might one do this?</p>
[ { "answer_id": 982, "author": "John Downey", "author_id": 200, "author_profile": "https://Stackoverflow.com/users/200", "pm_score": 5, "selected": false, "text": "from SomeOtherProduct.SomeModule import SomeClass\ndef speak(self):\n return \"ook ook eee eee eee!\"\nSomeClass.speak = speak\n speak" }, { "answer_id": 2982, "author": "Jason Pratt", "author_id": 99, "author_profile": "https://Stackoverflow.com/users/99", "pm_score": 11, "selected": true, "text": ">>> def foo():\n... print \"foo\"\n...\n>>> class A:\n... def bar( self ):\n... print \"bar\"\n...\n>>> a = A()\n>>> foo\n<function foo at 0x00A98D70>\n>>> a.bar\n<bound method A.bar of <__main__.A instance at 0x00A9BC88>>\n>>>\n >>> def fooFighters( self ):\n... print \"fooFighters\"\n...\n>>> A.fooFighters = fooFighters\n>>> a2 = A()\n>>> a2.fooFighters\n<bound method A.fooFighters of <__main__.A instance at 0x00A9BEB8>>\n>>> a2.fooFighters()\nfooFighters\n >>> a.fooFighters()\nfooFighters\n >>> def barFighters( self ):\n... print \"barFighters\"\n...\n>>> a.barFighters = barFighters\n>>> a.barFighters()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: barFighters() takes exactly 1 argument (0 given)\n >>> a.barFighters\n<function barFighters at 0x00A98EF0>\n >>> import types\n>>> a.barFighters = types.MethodType( barFighters, a )\n>>> a.barFighters\n<bound method ?.barFighters of <__main__.A instance at 0x00A9BC88>>\n>>> a.barFighters()\nbarFighters\n >>> a2.barFighters()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: A instance has no attribute 'barFighters'\n" }, { "answer_id": 4600, "author": "HS.", "author_id": 618, "author_profile": "https://Stackoverflow.com/users/618", "pm_score": 4, "selected": false, "text": "setattr >>> def printme(s): print repr(s)\n>>> class A: pass\n>>> setattr(A,'printme',printme)\n>>> a = A()\n>>> a.printme() # s becomes the implicit 'self' variable\n< __ main __ . A instance at 0xABCDEFG>\n" }, { "answer_id": 22525, "author": "Acuminate", "author_id": 2482, "author_profile": "https://Stackoverflow.com/users/2482", "pm_score": 2, "selected": false, "text": ">>> class Test(object):\n... def a(self):\n... pass\n... \n>>> def b(self):\n... pass\n... \n>>> Test.b = b\n>>> type(b)\n<type 'function'>\n>>> type(Test.a)\n<type 'instancemethod'>\n>>> type(Test.b)\n<type 'instancemethod'>\n" }, { "answer_id": 959064, "author": "Evgeny", "author_id": 110274, "author_profile": "https://Stackoverflow.com/users/110274", "pm_score": 7, "selected": false, "text": "patch_me() import types\n\nclass A(object):#but seems to work for old style objects too\n pass\n\ndef patch_me(target):\n def method(target,x):\n print \"x=\",x\n print \"called from\", target\n target.method = types.MethodType(method,target)\n #add more if needed\n\na = A()\nprint a\n#out: <__main__.A object at 0x2b73ac88bfd0> \npatch_me(a) #patch instance\na.method(5)\n#out: x= 5\n#out: called from <__main__.A object at 0x2b73ac88bfd0>\npatch_me(A)\nA.method(6) #can patch class too\n#out: x= 6\n#out: called from <class '__main__.A'>\n" }, { "answer_id": 8961717, "author": "Tomasz Zieliński", "author_id": 176186, "author_profile": "https://Stackoverflow.com/users/176186", "pm_score": 5, "selected": false, "text": "class A(object):\n def m(self):\n pass\n In [2]: A.m\nOut[2]: <unbound method A.m>\n In [5]: A.__dict__['m']\nOut[5]: <function m at 0xa66b8b4>\n In [11]: class MetaA(type):\n ....: def __getattribute__(self, attr_name):\n ....: print str(self), '-', attr_name\n\nIn [12]: class A(object):\n ....: __metaclass__ = MetaA\n\nIn [23]: A.m\n<class '__main__.A'> - m\n<class '__main__.A'> - m\n In [28]: A.__dict__['m'].__get__(None, A)\nOut[28]: <unbound method A.m>\n B.m = m\n b.m = types.MethodType(m, b)\n In [2]: A.m\nOut[2]: <unbound method A.m>\n\nIn [59]: type(A.m)\nOut[59]: <type 'instancemethod'>\n\nIn [60]: type(b.m)\nOut[60]: <type 'instancemethod'>\n\nIn [61]: types.MethodType\nOut[61]: <type 'instancemethod'>\n" }, { "answer_id": 9041763, "author": "Nisan.H", "author_id": 841337, "author_profile": "https://Stackoverflow.com/users/841337", "pm_score": 3, "selected": false, "text": "#!/usr/bin/python -u\nimport types\nimport inspect\n\n## dynamically adding methods to a unique instance of a class\n\n\n# get a list of a class's method type attributes\ndef listattr(c):\n for m in [(n, v) for n, v in inspect.getmembers(c, inspect.ismethod) if isinstance(v,types.MethodType)]:\n print m[0], m[1]\n\n# externally bind a function as a method of an instance of a class\ndef ADDMETHOD(c, method, name):\n c.__dict__[name] = types.MethodType(method, c)\n\nclass C():\n r = 10 # class attribute variable to test bound scope\n\n def __init__(self):\n pass\n\n #internally bind a function as a method of self's class -- note that this one has issues!\n def addmethod(self, method, name):\n self.__dict__[name] = types.MethodType( method, self.__class__ )\n\n # predfined function to compare with\n def f0(self, x):\n print 'f0\\tx = %d\\tr = %d' % ( x, self.r)\n\na = C() # created before modified instnace\nb = C() # modified instnace\n\n\ndef f1(self, x): # bind internally\n print 'f1\\tx = %d\\tr = %d' % ( x, self.r )\ndef f2( self, x): # add to class instance's .__dict__ as method type\n print 'f2\\tx = %d\\tr = %d' % ( x, self.r )\ndef f3( self, x): # assign to class as method type\n print 'f3\\tx = %d\\tr = %d' % ( x, self.r )\ndef f4( self, x): # add to class instance's .__dict__ using a general function\n print 'f4\\tx = %d\\tr = %d' % ( x, self.r )\n\n\nb.addmethod(f1, 'f1')\nb.__dict__['f2'] = types.MethodType( f2, b)\nb.f3 = types.MethodType( f3, b)\nADDMETHOD(b, f4, 'f4')\n\n\nb.f0(0) # OUT: f0 x = 0 r = 10\nb.f1(1) # OUT: f1 x = 1 r = 10\nb.f2(2) # OUT: f2 x = 2 r = 10\nb.f3(3) # OUT: f3 x = 3 r = 10\nb.f4(4) # OUT: f4 x = 4 r = 10\n\n\nk = 2\nprint 'changing b.r from {0} to {1}'.format(b.r, k)\nb.r = k\nprint 'new b.r = {0}'.format(b.r)\n\nb.f0(0) # OUT: f0 x = 0 r = 2\nb.f1(1) # OUT: f1 x = 1 r = 10 !!!!!!!!!\nb.f2(2) # OUT: f2 x = 2 r = 2\nb.f3(3) # OUT: f3 x = 3 r = 2\nb.f4(4) # OUT: f4 x = 4 r = 2\n\nc = C() # created after modifying instance\n\n# let's have a look at each instance's method type attributes\nprint '\\nattributes of a:'\nlistattr(a)\n# OUT:\n# attributes of a:\n# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FD88>>\n# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FD88>>\n# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FD88>>\n\nprint '\\nattributes of b:'\nlistattr(b)\n# OUT:\n# attributes of b:\n# __init__ <bound method C.__init__ of <__main__.C instance at 0x000000000230FE08>>\n# addmethod <bound method C.addmethod of <__main__.C instance at 0x000000000230FE08>>\n# f0 <bound method C.f0 of <__main__.C instance at 0x000000000230FE08>>\n# f1 <bound method ?.f1 of <class __main__.C at 0x000000000237AB28>>\n# f2 <bound method ?.f2 of <__main__.C instance at 0x000000000230FE08>>\n# f3 <bound method ?.f3 of <__main__.C instance at 0x000000000230FE08>>\n# f4 <bound method ?.f4 of <__main__.C instance at 0x000000000230FE08>>\n\nprint '\\nattributes of c:'\nlistattr(c)\n# OUT:\n# attributes of c:\n# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002313108>>\n# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002313108>>\n# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002313108>>\n def y(self, x):\n pass\nd = C()\nfor i in range(1,5):\n ADDMETHOD(d, y, 'f%d' % i)\nprint '\\nattributes of d:'\nlistattr(d)\n# OUT:\n# attributes of d:\n# __init__ <bound method C.__init__ of <__main__.C instance at 0x0000000002303508>>\n# addmethod <bound method C.addmethod of <__main__.C instance at 0x0000000002303508>>\n# f0 <bound method C.f0 of <__main__.C instance at 0x0000000002303508>>\n# f1 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>\n# f2 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>\n# f3 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>\n# f4 <bound method ?.y of <__main__.C instance at 0x0000000002303508>>\n" }, { "answer_id": 9636303, "author": "Tamzin Blake", "author_id": 650551, "author_profile": "https://Stackoverflow.com/users/650551", "pm_score": 3, "selected": false, "text": "a.methodname = function () { console.log(\"Yay, a new method!\") }\n" }, { "answer_id": 16240409, "author": "ndpu", "author_id": 1099876, "author_profile": "https://Stackoverflow.com/users/1099876", "pm_score": 4, "selected": false, "text": "types.MethodType >>> class A:\n... def m(self):\n... print 'im m, invoked with: ', self\n\n>>> a = A()\n>>> a.m()\nim m, invoked with: <__main__.A instance at 0x973ec6c>\n>>> a.m\n<bound method A.m of <__main__.A instance at 0x973ec6c>>\n>>> \n>>> def foo(firstargument):\n... print 'im foo, invoked with: ', firstargument\n\n>>> foo\n<function foo at 0x978548c>\n >>> a.foo = foo.__get__(a, A) # or foo.__get__(a, type(a))\n>>> a.foo()\nim foo, invoked with: <__main__.A instance at 0x973ec6c>\n>>> a.foo\n<bound method A.foo of <__main__.A instance at 0x973ec6c>>\n >>> instancemethod = type(A.m)\n>>> instancemethod\n<type 'instancemethod'>\n>>> a.foo2 = instancemethod(foo, a, type(a))\n>>> a.foo2()\nim foo, invoked with: <__main__.A instance at 0x973ec6c>\n>>> a.foo2\n<bound method instance.foo of <__main__.A instance at 0x973ec6c>>\n" }, { "answer_id": 24748849, "author": "ChristopherC", "author_id": 1640404, "author_profile": "https://Stackoverflow.com/users/1640404", "pm_score": 2, "selected": false, "text": "needle() guineapig import gorilla\nimport guineapig\[email protected](guineapig)\ndef needle():\n print(\"awesome\")\n" }, { "answer_id": 24865663, "author": "Evgeny Prokurat", "author_id": 3748584, "author_profile": "https://Stackoverflow.com/users/3748584", "pm_score": 4, "selected": false, "text": "def run(self):\n print self._instanceString\n\nclass A(object):\n def __init__(self):\n self._instanceString = \"This is instance string\"\n\na = A()\na.run = lambda: run(a)\na.run()\n This is instance string\n" }, { "answer_id": 28060251, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 7, "selected": false, "text": "object Foo.sample_method = sample_method\n class Foo(object):\n '''An empty class to demonstrate adding a method to an instance'''\n foo = Foo()\n def sample_method(self, bar, baz):\n print(bar + baz)\n __get__ __get__ foo.sample_method = sample_method.__get__(foo)\n >>> foo.sample_method(1,2)\n3\n import types\n types (function, instance) foo.sample_method = types.MethodType(sample_method, foo)\n >>> foo.sample_method(1,2)\n3\n (function, instance, class) foo.sample_method = types.MethodType(sample_method, foo, Foo)\n def bind(instance, method):\n def binding_scope_fn(*args, **kwargs): \n return method(instance, *args, **kwargs)\n return binding_scope_fn\n >>> foo.sample_method = bind(foo, sample_method) \n>>> foo.sample_method(1,2)\n3\n >>> from functools import partial\n>>> foo.sample_method = partial(sample_method, foo)\n>>> foo.sample_method(1,2)\n3 \n >>> foo.sample_method = sample_method\n>>> foo.sample_method(1,2)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: sample_method() takes exactly 3 arguments (2 given)\n self >>> foo.sample_method(foo, 1, 2)\n3\n" }, { "answer_id": 32076685, "author": "Max", "author_id": 5010481, "author_profile": "https://Stackoverflow.com/users/5010481", "pm_score": 3, "selected": false, "text": "# this class resides inside ReloadCodeDemo.py\nclass A:\n def bar( self ):\n print \"bar1\"\n \n def reloadCode(self, methodName):\n ''' use this function to reload any function of class A'''\n import types\n import ReloadCodeDemo as ReloadMod # import the code as module\n reload (ReloadMod) # force a reload of the module\n myM = getattr(ReloadMod.A,methodName) #get reloaded Method\n myTempFunc = types.FunctionType(# convert the method to a simple function\n myM.im_func.func_code, #the methods code\n globals(), # globals to use\n argdefs=myM.im_func.func_defaults # default values for variables if any\n ) \n myNewM = types.MethodType(myTempFunc,self,self.__class__) #convert the function to a method\n setattr(self,methodName,myNewM) # add the method to the function\n\nif __name__ == '__main__':\n a = A()\n a.bar()\n # now change your code and save the file\n a.reloadCode('bar') # reloads the file\n a.bar() # now executes the reloaded code\n" }, { "answer_id": 34404761, "author": "lain", "author_id": 4548106, "author_profile": "https://Stackoverflow.com/users/4548106", "pm_score": 3, "selected": false, "text": "def binder (function, instance):\n copy_of_function = type (function) (function.func_code, {})\n copy_of_function.__bind_to__ = instance\n def bound_function (*args, **kwargs):\n return copy_of_function (copy_of_function.__bind_to__, *args, **kwargs)\n return bound_function\n\n\nclass SupaClass (object):\n def __init__ (self):\n self.supaAttribute = 42\n\n\ndef new_method (self):\n print self.supaAttribute\n\n\nsupaInstance = SupaClass ()\nsupaInstance.supMethod = binder (new_method, supaInstance)\n\notherInstance = SupaClass ()\notherInstance.supaAttribute = 72\notherInstance.supMethod = binder (new_method, otherInstance)\n\notherInstance.supMethod ()\nsupaInstance.supMethod ()\n" }, { "answer_id": 43703054, "author": "Yu Feng", "author_id": 3781929, "author_profile": "https://Stackoverflow.com/users/3781929", "pm_score": 3, "selected": false, "text": "def addmethod(obj, name, func):\n klass = obj.__class__\n subclass = type(klass.__name__, (klass,), {})\n setattr(subclass, name, func)\n obj.__class__ = subclass\n" }, { "answer_id": 45341362, "author": "Arturo Morales Rangel", "author_id": 4475534, "author_profile": "https://Stackoverflow.com/users/4475534", "pm_score": 2, "selected": false, "text": "from types import MethodType\n\ndef method(self):\n print 'hi!'\n\n\nsetattr( targetObj, method.__name__, MethodType(method, targetObj, type(method)) )\n" }, { "answer_id": 64950870, "author": "danbst", "author_id": 1190453, "author_profile": "https://Stackoverflow.com/users/1190453", "pm_score": -1, "selected": false, "text": "__repr__ __str__ repr() str() # Instance monkeypatch\n[ins] In [55]: x.__str__ = show.__get__(x) \n\n[ins] In [56]: x \nOut[56]: <__main__.X at 0x7fc207180c10>\n\n[ins] In [57]: str(x) \nOut[57]: '<__main__.X object at 0x7fc207180c10>'\n\n[ins] In [58]: x.__str__() \nNice object!\n\n# Class monkeypatch\n[ins] In [62]: X.__str__ = lambda _: \"From class\" \n\n[ins] In [63]: str(x) \nOut[63]: 'From class'\n" }, { "answer_id": 70662971, "author": "Gerard G", "author_id": 7452220, "author_profile": "https://Stackoverflow.com/users/7452220", "pm_score": 0, "selected": false, "text": "class UnderWater:\n def __init__(self):\n self.net = 'underwater'\n\nmarine = UnderWater() # Instantiate the class\n\n# Recover the class from the instance and add attributes to it.\nclass SubMarine(marine.__class__): \n def __init__(self):\n super().__init__()\n self.sound = 'Sonar'\n \nprint(SubMarine, SubMarine.__name__, SubMarine().net, SubMarine().sound)\n\n# Output\n# (__main__.SubMarine,'SubMarine', 'underwater', 'Sonar')\n" }, { "answer_id": 73486831, "author": "Hans", "author_id": 15096247, "author_profile": "https://Stackoverflow.com/users/15096247", "pm_score": 1, "selected": false, "text": "from types import MethodType\nimport re\nfrom string import ascii_letters\n\n\nclass DynamicAttr:\n def __init__(self):\n self.dict_all_files = {}\n\n def _copy_files(self, *args, **kwargs):\n print(f'copy {args[0][\"filename\"]} {args[0][\"copy_command\"]}')\n\n def _delete_files(self, *args, **kwargs):\n print(f'delete {args[0][\"filename\"]} {args[0][\"delete_command\"]}')\n\n def _create_properties(self):\n for key, item in self.dict_all_files.items():\n setattr(\n self,\n key,\n self.dict_all_files[key],\n )\n setattr(\n self,\n key + \"_delete\",\n MethodType(\n self._delete_files,\n {\n \"filename\": key,\n \"delete_command\": f'del {item}',\n },\n ),\n )\n setattr(\n self,\n key + \"_copy\",\n MethodType(\n self._copy_files,\n {\n \"filename\": key,\n \"copy_command\": f'copy {item}',\n },\n ),\n )\n def add_files_to_class(self, filelist: list):\n for _ in filelist:\n attr_key = re.sub(rf'[^{ascii_letters}]+', '_', _).strip('_')\n self.dict_all_files[attr_key] = _\n self._create_properties()\ndy = DynamicAttr()\ndy.add_files_to_class([r\"C:\\Windows\\notepad.exe\", r\"C:\\Windows\\regedit.exe\"])\n\ndy.add_files_to_class([r\"C:\\Windows\\HelpPane.exe\", r\"C:\\Windows\\win.ini\"])\n#output\nprint(dy.C_Windows_HelpPane_exe)\ndy.C_Windows_notepad_exe_delete()\ndy.C_Windows_HelpPane_exe_copy()\nC:\\Windows\\HelpPane.exe\ndelete C_Windows_notepad_exe del C:\\Windows\\notepad.exe\ncopy C_Windows_HelpPane_exe copy C:\\Windows\\HelpPane.exe\n import inspect\nimport re\nfrom copy import deepcopy\nfrom string import ascii_letters\n\n\ndef copy_func(f):\n if callable(f):\n if inspect.ismethod(f) or inspect.isfunction(f):\n g = lambda *args, **kwargs: f(*args, **kwargs)\n t = list(filter(lambda prop: not (\"__\" in prop), dir(f)))\n i = 0\n while i < len(t):\n setattr(g, t[i], getattr(f, t[i]))\n i += 1\n return g\n dcoi = deepcopy([f])\n return dcoi[0]\n\n\nclass FlexiblePartial:\n def __init__(self, func, this_args_first, *args, **kwargs):\n\n try:\n self.f = copy_func(func) # create a copy of the function\n except Exception:\n self.f = func\n self.this_args_first = this_args_first # where should the other (optional) arguments be that are passed when the function is called\n try:\n self.modulename = args[0].__class__.__name__ # to make repr look good\n except Exception:\n self.modulename = \"self\"\n\n try:\n self.functionname = func.__name__ # to make repr look good\n except Exception:\n try:\n self.functionname = func.__qualname__ # to make repr look good\n except Exception:\n self.functionname = \"func\"\n\n self.args = args\n self.kwargs = kwargs\n\n self.name_to_print = self._create_name() # to make repr look good\n\n def _create_name(self):\n stra = self.modulename + \".\" + self.functionname + \"(self, \"\n for _ in self.args[1:]:\n stra = stra + repr(_) + \", \"\n for key, item in self.kwargs.items():\n stra = stra + str(key) + \"=\" + repr(item) + \", \"\n stra = stra.rstrip().rstrip(\",\")\n stra += \")\"\n if len(stra) > 100:\n stra = stra[:95] + \"...)\"\n return stra\n\n def __call__(self, *args, **kwargs):\n newdic = {}\n newdic.update(self.kwargs)\n newdic.update(kwargs)\n if self.this_args_first:\n return self.f(*self.args[1:], *args, **newdic)\n\n else:\n\n return self.f(*args, *self.args[1:], **newdic)\n\n def __str__(self):\n return self.name_to_print\n\n def __repr__(self):\n return self.__str__()\n\n\nclass AddMethodsAndProperties:\n def add_methods(self, dict_to_add):\n for key_, item in dict_to_add.items():\n key = re.sub(rf\"[^{ascii_letters}]+\", \"_\", str(key_)).rstrip(\"_\")\n if isinstance(item, dict):\n if \"function\" in item: # for adding methods\n if not isinstance(\n item[\"function\"], str\n ): # for external functions that are not part of the class\n setattr(\n self,\n key,\n FlexiblePartial(\n item[\"function\"],\n item[\"this_args_first\"],\n self,\n *item[\"args\"],\n **item[\"kwargs\"],\n ),\n )\n\n else:\n setattr(\n self,\n key,\n FlexiblePartial(\n getattr(\n self, item[\"function\"]\n ), # for internal functions - part of the class\n item[\"this_args_first\"],\n self,\n *item[\"args\"],\n **item[\"kwargs\"],\n ),\n )\n else: # for adding props\n setattr(self, key, item)\n class NewClass(AddMethodsAndProperties): #inherit from AddMethodsAndProperties to add the method add_methods\n def __init__(self):\n self.bubu = 5\n\n def _delete_files(self, file): #some random methods \n print(f\"File will be deleted: {file}\")\n\n def delete_files(self, file):\n self._delete_files(file)\n\n def _copy_files(self, file, dst):\n print(f\"File will be copied: {file} Dest: {dst}\")\n\n def copy_files(self, file, dst):\n self._copy_files(file, dst)\n\n def _create_files(self, file, folder):\n print(f\"File will be created: {file} {folder}\")\n\n def create_files(self, file, folder):\n self._create_files(file, folder)\n\n def method_with_more_kwargs(self, file, folder, one_more):\n print(file, folder, one_more)\n return self\n\n\nnc = NewClass()\ndict_all_files = {\n r\"C:\\Windows\\notepad.exe_delete\": {\n \"function\": \"delete_files\",\n \"args\": (),\n \"kwargs\": {\"file\": r\"C:\\Windows\\notepad.exe\"},\n \"this_args_first\": True,\n },\n r\"C:\\Windows\\notepad.exe_argsfirst\": {\n \"function\": \"delete_files\",\n \"args\": (),\n \"kwargs\": {\"file\": r\"C:\\Windows\\notepad.exe\"},\n \"this_args_first\": True,\n },\n r\"C:\\Windows\\notepad.exe_copy\": {\n \"function\": \"copy_files\",\n \"args\": (),\n \"kwargs\": {\n \"file\": r\"C:\\Windows\\notepad.exe\",\n \"dst\": r\"C:\\Windows\\notepad555.exe\",\n },\n \"this_args_first\": True,\n },\n r\"C:\\Windows\\notepad.exe_create\": {\n \"function\": \"create_files\",\n \"args\": (),\n \"kwargs\": {\"file\": r\"C:\\Windows\\notepad.exe\", \"folder\": \"c:\\\\windows95\"},\n \"this_args_first\": True,\n },\n r\"C:\\Windows\\notepad.exe_upper\": {\n \"function\": str.upper,\n \"args\": (r\"C:\\Windows\\notepad.exe\",),\n \"kwargs\": {},\n \"this_args_first\": True,\n },\n r\"C:\\Windows\\notepad.exe_method_with_more_kwargs\": {\n \"function\": \"method_with_more_kwargs\",\n \"args\": (),\n \"kwargs\": {\"file\": r\"C:\\Windows\\notepad.exe\", \"folder\": \"c:\\\\windows95\"},\n \"this_args_first\": True,\n },\n r\"C:\\Windows\\notepad.exe_method_with_more_kwargs_as_args_first\": {\n \"function\": \"method_with_more_kwargs\",\n \"args\": (r\"C:\\Windows\\notepad.exe\", \"c:\\\\windows95\"),\n \"kwargs\": {},\n \"this_args_first\": True,\n },\n r\"C:\\Windows\\notepad.exe_method_with_more_kwargs_as_args_last\": {\n \"function\": \"method_with_more_kwargs\",\n \"args\": (r\"C:\\Windows\\notepad.exe\", \"c:\\\\windows95\"),\n \"kwargs\": {},\n \"this_args_first\": False,\n },\n \"this_is_a_list\": [55, 3, 3, 1, 4, 43],\n}\n\nnc.add_methods(dict_all_files)\n\n\nprint(nc.C_Windows_notepad_exe_delete)\nprint(nc.C_Windows_notepad_exe_delete(), end=\"\\n\\n\")\nprint(nc.C_Windows_notepad_exe_argsfirst)\nprint(nc.C_Windows_notepad_exe_argsfirst(), end=\"\\n\\n\")\nprint(nc.C_Windows_notepad_exe_copy)\nprint(nc.C_Windows_notepad_exe_copy(), end=\"\\n\\n\")\nprint(nc.C_Windows_notepad_exe_create)\nprint(nc.C_Windows_notepad_exe_create(), end=\"\\n\\n\")\nprint(nc.C_Windows_notepad_exe_upper)\nprint(nc.C_Windows_notepad_exe_upper(), end=\"\\n\\n\")\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs(\n one_more=\"f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs(\n one_more=\"f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs(\n one_more=\"f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\n ),\n end=\"\\n\\n\",\n)\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n \"f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa\"\n ),\n end=\"\\n\\n\",\n)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n \"f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n \"f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_first(\n \"f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\n ),\n end=\"\\n\\n\",\n)\nprint(nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\n ),\n end=\"\\n\\n\",\n)\nprint(\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\n ),\n end=\"\\n\\n\",\n)\nprint(nc.this_is_a_list)\ncheckit = (\n nc.C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\blaaaaaaaaaaaaaaaaaaaaaaaa\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\"\n )\n .C_Windows_notepad_exe_method_with_more_kwargs_as_args_last(\n \"f:\\\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\n )\n)\nprint(f'nc is checkit? -> {nc is checkit}')\n\n\n#output:\n\n\nNewClass.delete_files(self, file='C:\\\\Windows\\\\notepad.exe')\nFile will be deleted: C:\\Windows\\notepad.exe\nNone\n\n\nNewClass.delete_files(self, file='C:\\\\Windows\\\\notepad.exe')\nFile will be deleted: C:\\Windows\\notepad.exe\nNone\n\n\nNewClass.copy_files(self, file='C:\\\\Windows\\\\notepad.exe', dst='C:\\\\Windows\\\\notepad555.exe')\nFile will be copied: C:\\Windows\\notepad.exe Dest: C:\\Windows\\notepad555.exe\nNone\n\n\nNewClass.create_files(self, file='C:\\\\Windows\\\\notepad.exe', folder='c:\\\\windows95')\nFile will be created: C:\\Windows\\notepad.exe c:\\windows95\nNone\n\n\nNewClass.upper(self, 'C:\\\\Windows\\\\notepad.exe')\nC:\\WINDOWS\\NOTEPAD.EXE\n\n\nNewClass.method_with_more_kwargs(self, file='C:\\\\Windows\\\\notepad.exe', folder='c:\\\\windows95')\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\nC:\\Windows\\notepad.exe c:\\windows95 f:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\nC:\\Windows\\notepad.exe c:\\windows95 f:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\nNewClass.method_with_more_kwargs(self, 'C:\\\\Windows\\\\notepad.exe', 'c:\\\\windows95')\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\nC:\\Windows\\notepad.exe c:\\windows95 f:\\blaaaaaaaaaaaaaaaaaaaaaaaa\nC:\\Windows\\notepad.exe c:\\windows95 f:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ\nC:\\Windows\\notepad.exe c:\\windows95 f:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\nNewClass.method_with_more_kwargs(self, 'C:\\\\Windows\\\\notepad.exe', 'c:\\\\windows95')\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n<__main__.NewClass object at 0x0000000005F199A0>\n\n\n[55, 3, 3, 1, 4, 43]\n\n\nf:\\blaaaaaaaaaaaaaaaaaaaaaaaa C:\\Windows\\notepad.exe c:\\windows95\nf:\\ASJVASDFASÇDFJASÇDJFÇASWFJASÇ C:\\Windows\\notepad.exe c:\\windows95\nf:\\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX C:\\Windows\\notepad.exe c:\\windows95\n\n\nnc is checkit? -> True\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
1,005
<p>Often while editing config files, I'll open one with vi and then when I go to save it realize that I didn't type</p> <pre><code>sudo vi filename </code></pre> <p>Is there any way to give vi sudo privileges to save the file? I seem to recall seeing something about this while looking up some stuff about vi a while ago, but now I can't find it.</p>
[ { "answer_id": 1012, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "sudoedit :r :w!" }, { "answer_id": 1065, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 5, "selected": false, "text": ":w !sudo tee myfile\n" }, { "answer_id": 2930, "author": "num1", "author_id": 306, "author_profile": "https://Stackoverflow.com/users/306", "pm_score": -1, "selected": false, "text": "ls -l test.file (to see the permissions of the file)\nchmod 777 test.file\n[This is where you save in vim]\nchmod xxx test.file (restore the permissions you found in the first step)\n" }, { "answer_id": 9113, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 2, "selected": false, "text": "-- INSERT -- W10: Warning: Changing a readonly file\n :w ~/edited_blah.tmp\n:q\n sudo \"cat edited_blah.tmp > /etc/blah\"\n sudo mv edited_blah.tmp /etc/blah\n" }, { "answer_id": 37042, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 9, "selected": true, "text": "% :w !sudo tee %\n vim [L] .vimrc command W w !sudo tee % >/dev/null\n :W<Enter> cmap w!! w !sudo tee >/dev/null %\n :w!! %" }, { "answer_id": 125383, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "sudo:" }, { "answer_id": 662081, "author": "pisswillis", "author_id": 78414, "author_profile": "https://Stackoverflow.com/users/78414", "pm_score": 0, "selected": false, "text": "alias svim='sudo vim'\n" }, { "answer_id": 12870763, "author": "Zenexer", "author_id": 1188377, "author_profile": "https://Stackoverflow.com/users/1188377", "pm_score": 4, "selected": false, "text": "sudo tee \" On POSIX (Linux/Mac/BSD):\n:silent execute 'write !sudo tee ' . shellescape(@%, 1) . ' >/dev/null'\n\n\" Depending on the implementation, you might need this on Windows:\n:silent execute 'write !sudo tee ' . shellescape(@%, 1) . ' >NUL'\n :sil exec 'w !sudo tee ' . shellescape(@%, 1) . ' >/dev/null'\n:sil exec 'w !sudo tee ' . shellescape(@%, 1) . ' >NUL'\n : sil[ent] Press any key to continue :! exec[ute] :write ! :! :write :write :! bash -c :write stdin sudo tee stdin :write stdin tee shellescape() @% % % % >NUL >/dev/null stdout stdin NUL ~/.vimrc command W silent execute 'write !sudo tee ' . shellescape(@%, 1) . ' >/dev/null'\n ~/.vimrc ~/.vimrc #!vim\n\" Use za (not a command; the keys) in normal mode to toggle a fold.\n\" META_COMMENT Modeline Definition: {{{1\n\" vim: ts=4 sw=4 sr sts=4 fdm=marker ff=unix fenc=utf-8\n\" ts: Actual tab character stops.\n\" sw: Indentation commands shift by this much.\n\" sr: Round existing indentation when using shift commands.\n\" sts: Virtual tab stops while using tab key.\n\" fdm: Folds are manually defined in file syntax.\n\" ff: Line endings should always be <NL> (line feed #09).\n\" fenc: Should always be UTF-8; #! must be first bytes, so no BOM.\n\n\n\" General Commands: User Ex commands. {{{1\n command W call WriteAsSuperUser(@%) \" Write file as super-user.\n\n\n\" Helper Functions: Used by user Ex commands. {{{1\n function GetNullDevice() \" Gets the path to the null device. {{{2\n if filewritable('/dev/null')\n return '/dev/null'\n else\n return 'NUL'\n endif\n endfunction\n\n function WriteAsSuperUser(file) \" Write buffer to a:file as the super user (on POSIX, root). {{{2\n exec '%write !sudo tee ' . shellescape(a:file, 1) . ' >' . GetNullDevice()\n endfunction\n\n\n\" }}}1\n\" EOF\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
1,010
<p>I need to grab the <code>base64-encoded</code> representation of the <code>ViewState</code>. Obviously, this would not be available until fairly late in the request lifecycle, which is OK.</p> <p>For example, if the output of the page includes:</p> <pre><code>&lt;input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" /&gt; </code></pre> <p>I need a way on the server-side to get the value <code>"/wEPDwUJODU0Njc5MD...=="</code></p> <p>To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being <em>sent</em> to the client, not the ViewState I'm getting back from them.</p>
[ { "answer_id": 2058, "author": "Dave Anderson", "author_id": 371, "author_profile": "https://Stackoverflow.com/users/371", "pm_score": 2, "selected": false, "text": "protected override void SavePageStateToPersistenceMedium(object viewState)\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67/" ]
1,024
<p>After upgrading a rails 1.2 website to 2.1, the <a href="http://agilewebdevelopment.com/plugins/exception_notifier" rel="noreferrer">ExceptionNotifier plugin</a> no longer works, complaining about this error:</p> <blockquote> <p>ActionView::TemplateFinder::InvalidViewPath: Unprocessed view path found: "/path/to/appname/vendor/plugins/exception_notification/lib/../views". Set your view paths with #append_view_path, #prepend_view_path, or #view_paths=.</p> </blockquote> <p>What causes it and how do I fix it?</p>
[ { "answer_id": 1026, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "init.rb vendor/plugins/exception_notification ActionController::Base.class_eval do\n append_view_path File.dirname(__FILE__) + '/lib/../views'\nend\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
1,033
<p>Does anyone know any simple way to retrieve the country from a given IP Address, preferably in ISO_3166-1 format?</p>
[ { "answer_id": 2056874, "author": "Niklas Rosencrantz", "author_id": 108207, "author_profile": "https://Stackoverflow.com/users/108207", "pm_score": 2, "selected": false, "text": "latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);\nlocation = \"IP location: \" + getFormattedLocation();\ndocument.getElementById(\"location\").innerHTML = location;\n" }, { "answer_id": 11717563, "author": "pckabeer", "author_id": 1298003, "author_profile": "https://Stackoverflow.com/users/1298003", "pm_score": 2, "selected": false, "text": " <?php $ip = $_SERVER['REMOTE_ADDR'];\n $json = file_get_contents(\"http://api.easyjquery.com/ips/?ip=\".$ip.\"&full=true\");\n $json = json_decode($json,true);\n $timezone = $json[localTimeZone];?>\n" }, { "answer_id": 23872935, "author": "user3463375", "author_id": 3463375, "author_profile": "https://Stackoverflow.com/users/3463375", "pm_score": 2, "selected": false, "text": "see example of service: http://ip-api.com and usage: http://whatmyip.info\n" }, { "answer_id": 25498255, "author": "Ben Dowling", "author_id": 36191, "author_profile": "https://Stackoverflow.com/users/36191", "pm_score": 2, "selected": false, "text": "$ curl ipinfo.io/8.8.8.8\n{\n \"ip\": \"8.8.8.8\",\n \"hostname\": \"google-public-dns-a.google.com\",\n \"loc\": \"37.385999999999996,-122.0838\",\n \"org\": \"AS15169 Google Inc.\",\n \"city\": \"Mountain View\",\n \"region\": \"CA\",\n \"country\": \"US\",\n \"phone\": 650\n}\n $ curl ipinfo.io/8.8.8.8/country\nUS\n function ip_details($ip) {\n $json = file_get_contents(\"http://ipinfo.io/{$ip}\");\n $details = json_decode($json);\n return $details;\n}\n\n$details = ip_details(\"8.8.8.8\");\n\necho $details->city; // => Mountain View\necho $details->country; // => US\necho $details->org; // => AS15169 Google Inc.\necho $details->hostname; // => google-public-dns-a.google.com\n $_SERVER['REMOTE_ADDR']" }, { "answer_id": 48855469, "author": "Jonathan", "author_id": 3176550, "author_profile": "https://Stackoverflow.com/users/3176550", "pm_score": 1, "selected": false, "text": "curl https://api.ipdata.co/78.8.53.5\n{\n \"ip\": \"78.8.53.5\",\n \"city\": \"G\\u0142og\\u00f3w\",\n \"region\": \"Lower Silesia\",\n \"region_code\": \"DS\",\n \"country_name\": \"Poland\",\n \"country_code\": \"PL\",\n \"continent_name\": \"Europe\",\n \"continent_code\": \"EU\",\n \"latitude\": 51.6461,\n \"longitude\": 16.1678,\n \"asn\": \"AS12741\",\n \"organisation\": \"Netia SA\",\n \"postal\": \"67-200\",\n \"currency\": \"PLN\",\n \"currency_symbol\": \"z\\u0142\",\n \"calling_code\": \"48\",\n \"flag\": \"https://ipdata.co/flags/pl.png\",\n \"emoji_flag\": \"\\ud83c\\uddf5\\ud83c\\uddf1\",\n \"time_zone\": \"Europe/Warsaw\",\n \"is_eu\": true,\n \"suspicious_factors\": {\n \"is_tor\": false\n }\n}⏎ \n" }, { "answer_id": 49001745, "author": "Vlam", "author_id": 6647585, "author_profile": "https://Stackoverflow.com/users/6647585", "pm_score": 1, "selected": false, "text": "CREATE DATABASE ip2location;\nUSE ip2location;\nCREATE TABLE `ip2location_db1`(\n `ip_from` INT(10) UNSIGNED,\n `ip_to` INT(10) UNSIGNED,\n `country_code` CHAR(2),\n `country_name` VARCHAR(64),\n INDEX `idx_ip_to` (`ip_to`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;\n LOAD DATA LOCAL\n INFILE 'IP2LOCATION-LITE-DB1.CSV'\nINTO TABLE\n `ip2location_db1`\nFIELDS TERMINATED BY ','\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\r\\n'\nIGNORE 0 LINES;\n <?php\n// Replace this MYSQL server variables with actual configuration\n$mysql_server = \"mysql_server.com\";\n$mysql_user_name = \"UserName\";\n$mysql_user_pass = \"Password\";\n\n// Retrieve visitor IP address from server variable REMOTE_ADDR\n$ipaddress = $_SERVER[\"REMOTE_ADDR\"];\n\n// Convert IP address to IP number for querying database\n$ipno = Dot2LongIP($ipaddress);\n\n// Connect to the database server\n$link = mysql_connect($mysql_server, $mysql_user_name, $mysql_user_pass) or die(\"Could not connect to MySQL database\");\n\n// Connect to the IP2Location database\nmysql_select_db(\"ip2location\") or die(\"Could not select database\");\n\n// SQL query string to match the recordset that the IP number fall between the valid range\n$query = \"SELECT * FROM ip2location_db1 WHERE $ipno <= ip_to LIMIT 1\";\n\n// Execute SQL query\n$result = mysql_query($query) or die(\"IP2Location Query Failed\");\n\n// Retrieve the recordset (only one)\n$row = mysql_fetch_object($result);\n\n// Keep the country information into two different variables\n$country_code = $row->country_code;\n$country_name = $row->country_name;\n\necho \"Country_code: \" . $country_code . \"<br/>\";\necho \"Country_name: \" . $country_name . \"<br />\";\n\n// Free recordset and close database connection\nmysql_free_result($result);\nmysql_close($link);\n\n// Function to convert IP address (xxx.xxx.xxx.xxx) to IP number (0 to 256^4-1)\nfunction Dot2LongIP ($IPaddr) {\n if ($IPaddr == \"\")\n {\n return 0;\n } else {\n $ips = explode(\".\", $IPaddr);\n return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256);\n }\n}\n?>\n" }, { "answer_id": 65161079, "author": "bre_dev", "author_id": 1378258, "author_profile": "https://Stackoverflow.com/users/1378258", "pm_score": -1, "selected": false, "text": "curl https://api.astroip.co/70.163.7.1\n{\n \"status_code\": 200,\n \"geo\": {\n \"is_metric\": false,\n \"is_eu\": false,\n \"longitude\": -77.0924,\n \"latitude\": 38.7591,\n \"country_geo_id\": 6252001,\n \"zip_code\": \"22306\",\n \"city\": \"Alexandria\",\n \"region_code\": \"VA\",\n \"region_name\": \"Virginia\",\n \"continent_code\": \"NA\",\n \"continent_name\": \"North America\",\n \"capital\": \"Washington\",\n \"country_name\": \"United States\",\n \"country_code\": \"US\"\n },\n \"asn\": {\n \"route\": \"70.160.0.0/14\",\n \"type\": \"isp\",\n \"domain\": \"cox.net\",\n \"organization\": \"ASN-CXA-ALL-CCI-22773-RDC\",\n \"asn\": \"AS22773\"\n },\n \"currency\": {\n \"native_name\": \"US Dollar\",\n \"code\": \"USD\",\n \"name\": \"US Dollar\",\n \"symbol\": \"$\"\n },\n \"timezone\": {\n \"is_dst\": false,\n \"gmt_offset\": -18000,\n \"date_time\": \"2020-12-05T17:04:48-05:00\",\n \"microsoft_name\": \"Eastern Standard Time\",\n \"iana_name\": \"America/New_York\"\n },\n \"security\": {\n \"is_crawler\": false,\n \"is_proxy\": false,\n \"is_tor\": false,\n \"tor_insights\": null,\n \"proxy_insights\": null,\n \"crawler_insights\": null\n },\n \"error\": null,\n \"ip_type\": \"ipv4\",\n \"ip\": \"70.163.7.1\"\n}\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87/" ]
1,040
<p>I'm looking for a way to delete a file which is locked by another process using C#. I suspect the method must be able to find which process is locking the file (perhaps by tracking the handles, although I'm not sure how to do this in C#) then close that process before being able to complete the file delete using <code>File.Delete()</code>.</p>
[ { "answer_id": 1043, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 3, "selected": false, "text": "REGEDT32 (W2K) REGEDIT (WXP) HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\Session Manager\n REG_MULTI_SZ PendingFileRenameOperations PendingFileRenameOperations \"\\??\\\" + filename C:\\Long Directory Name\\Long File Name.exe \\??\\C:\\Long Directory Name\\Long File Name.exe\n REGEDT32/REGEDIT" }, { "answer_id": 1044, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 6, "selected": true, "text": "MoveFileEx" }, { "answer_id": 1050, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "mv %WINDIR%\\System32\\mfc42.dll %WINDIR\\System32\\mfc42.dll.old\nInstall new mfc42.dll\nTell user to save work and restart applications\n mfc42.dll PendingFileOperations" }, { "answer_id": 610598, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "Excel.Applications" }, { "answer_id": 41902743, "author": "vapcguy", "author_id": 1181535, "author_profile": "https://Stackoverflow.com/users/1181535", "pm_score": 2, "selected": false, "text": "List<Processes> using System.Runtime.InteropServices;\nusing System.Diagnostics;\n\nstatic public class FileUtil\n{\n [StructLayout(LayoutKind.Sequential)]\n struct RM_UNIQUE_PROCESS\n {\n public int dwProcessId;\n public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;\n }\n\n const int RmRebootReasonNone = 0;\n const int CCH_RM_MAX_APP_NAME = 255;\n const int CCH_RM_MAX_SVC_NAME = 63;\n\n enum RM_APP_TYPE\n {\n RmUnknownApp = 0,\n RmMainWindow = 1,\n RmOtherWindow = 2,\n RmService = 3,\n RmExplorer = 4,\n RmConsole = 5,\n RmCritical = 1000\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n struct RM_PROCESS_INFO\n {\n public RM_UNIQUE_PROCESS Process;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]\n public string strAppName;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]\n public string strServiceShortName;\n\n public RM_APP_TYPE ApplicationType;\n public uint AppStatus;\n public uint TSSessionId;\n [MarshalAs(UnmanagedType.Bool)]\n public bool bRestartable;\n }\n\n [DllImport(\"rstrtmgr.dll\", CharSet = CharSet.Unicode)]\n static extern int RmRegisterResources(uint pSessionHandle,\n UInt32 nFiles,\n string[] rgsFilenames,\n UInt32 nApplications,\n [In] RM_UNIQUE_PROCESS[] rgApplications,\n UInt32 nServices,\n string[] rgsServiceNames);\n\n [DllImport(\"rstrtmgr.dll\", CharSet = CharSet.Auto)]\n static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);\n\n [DllImport(\"rstrtmgr.dll\")]\n static extern int RmEndSession(uint pSessionHandle);\n\n [DllImport(\"rstrtmgr.dll\")]\n static extern int RmGetList(uint dwSessionHandle,\n out uint pnProcInfoNeeded,\n ref uint pnProcInfo,\n [In, Out] RM_PROCESS_INFO[] rgAffectedApps,\n ref uint lpdwRebootReasons);\n\n /// <summary>\n /// Find out what process(es) have a lock on the specified file.\n /// </summary>\n /// <param name=\"path\">Path of the file.</param>\n /// <returns>Processes locking the file</returns>\n /// <remarks>See also:\n /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx\n /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)\n /// \n /// </remarks>\n static public List<Process> WhoIsLocking(string path)\n {\n uint handle;\n string key = Guid.NewGuid().ToString();\n List<Process> processes = new List<Process>();\n\n int res = RmStartSession(out handle, 0, key);\n if (res != 0) throw new Exception(\"Could not begin restart session. Unable to determine file locker.\");\n\n try\n {\n const int ERROR_MORE_DATA = 234;\n uint pnProcInfoNeeded = 0,\n pnProcInfo = 0,\n lpdwRebootReasons = RmRebootReasonNone;\n\n string[] resources = new string[] { path }; // Just checking on one resource.\n\n res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);\n\n if (res != 0) throw new Exception(\"Could not register resource.\"); \n\n //Note: there's a race condition here -- the first call to RmGetList() returns\n // the total number of process. However, when we call RmGetList() again to get\n // the actual processes this number may have increased.\n res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);\n\n if (res == ERROR_MORE_DATA)\n {\n // Create an array to store the process results\n RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];\n pnProcInfo = pnProcInfoNeeded;\n\n // Get the list\n res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);\n if (res == 0)\n {\n processes = new List<Process>((int)pnProcInfo);\n\n // Enumerate all of the results and add them to the \n // list to be returned\n for (int i = 0; i < pnProcInfo; i++)\n {\n try\n {\n processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));\n }\n // catch the error -- in case the process is no longer running\n catch (ArgumentException) { }\n }\n }\n else throw new Exception(\"Could not list processes locking resource.\"); \n }\n else if (res != 0) throw new Exception(\"Could not list processes locking resource. Failed to get size of result.\"); \n }\n finally\n {\n RmEndSession(handle);\n }\n\n return processes;\n }\n}\n string[] files = Directory.GetFiles(target_dir);\n List<Process> lstProcs = new List<Process>();\n\n foreach (string file in files)\n {\n lstProcs = ProcessHandler.WhoIsLocking(file);\n if (lstProcs.Count > 0) // deal with the file lock\n {\n foreach (Process p in lstProcs)\n {\n if (p.MachineName == \".\")\n ProcessHandler.localProcessKill(p.ProcessName);\n else\n ProcessHandler.remoteProcessKill(p.MachineName, txtUserName.Text, txtPassword.Password, p.ProcessName);\n }\n File.Delete(file);\n }\n else\n File.Delete(file);\n }\n public static void localProcessKill(string processName)\n{\n foreach (Process p in Process.GetProcessesByName(processName))\n {\n p.Kill();\n }\n}\n public static void remoteProcessKill(string computerName, string fullUserName, string pword, string processName)\n{\n var connectoptions = new ConnectionOptions();\n connectoptions.Username = fullUserName; // @\"YourDomainName\\UserName\";\n connectoptions.Password = pword;\n\n ManagementScope scope = new ManagementScope(@\"\\\\\" + computerName + @\"\\root\\cimv2\", connectoptions);\n\n // WMI query\n var query = new SelectQuery(\"select * from Win32_process where name = '\" + processName + \"'\");\n\n using (var searcher = new ManagementObjectSearcher(scope, query))\n {\n foreach (ManagementObject process in searcher.Get()) \n {\n process.InvokeMethod(\"Terminate\", null);\n process.Dispose();\n }\n }\n}\n" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/254/" ]
1,041
<p>I'm looking for a robust, easy-to-use, regular expression evaluator for native C++, either platform-independent or Windows-specific.</p> <p>Requirements:</p> <ul> <li>Can't use Boost or ACE regex libraries (unfortunately)</li> <li>Can't use .NET Regex (or any managed code)</li> </ul> <p>The main requirement is that it should be standalone and open.</p>
[ { "answer_id": 7564, "author": "martinsb", "author_id": 837, "author_profile": "https://Stackoverflow.com/users/837", "pm_score": 2, "selected": false, "text": "CAtlRegExp atlrx.h" }, { "answer_id": 37100978, "author": "Trevor Hickey", "author_id": 908939, "author_profile": "https://Stackoverflow.com/users/908939", "pm_score": 2, "selected": false, "text": "<regex>" } ]
2008/08/04
[ "https://Stackoverflow.com/questions/1041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]