qid
int64 4
22.2M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
4
|
<p>I want to assign the decimal variable "trans" to the double variable "this.Opacity".</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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 594436,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "Opacity"
},
{
"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"
},
{
"answer_id": 7262131,
"author": "ChrisF",
"author_id": 59303,
"author_profile": "https://Stackoverflow.com/users/59303",
"pm_score": 6,
"selected": false,
"text": "Form.Opacity"
},
{
"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"
},
{
"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"
},
{
"answer_id": 72996737,
"author": "David Rodrigues",
"author_id": 5768360,
"author_profile": "https://Stackoverflow.com/users/5768360",
"pm_score": 1,
"selected": false,
"text": "Double"
}
] |
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"
},
{
"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}"
},
{
"answer_id": 43377,
"author": "Evil Andy",
"author_id": 4431,
"author_profile": "https://Stackoverflow.com/users/4431",
"pm_score": 5,
"selected": false,
"text": "div"
},
{
"answer_id": 856615,
"author": "lock",
"author_id": 24744,
"author_profile": "https://Stackoverflow.com/users/24744",
"pm_score": 5,
"selected": false,
"text": "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"
},
{
"answer_id": 64219066,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<div>"
}
] |
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"
},
{
"answer_id": 11942,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 10,
"selected": false,
"text": "yyyymmdd"
},
{
"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"
},
{
"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"
},
{
"answer_id": 5054317,
"author": "camelCasus",
"author_id": 624612,
"author_profile": "https://Stackoverflow.com/users/624612",
"pm_score": 7,
"selected": false,
"text": "AddYears"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 64220001,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "DateTime"
},
{
"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"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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\""
},
{
"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"
},
{
"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"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 22625076,
"author": "Matt Johnson-Pint",
"author_id": 634824,
"author_profile": "https://Stackoverflow.com/users/634824",
"pm_score": 7,
"selected": false,
"text": "getTimezoneOffset"
},
{
"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();"
},
{
"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"
},
{
"answer_id": 64329945,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "user-agent"
},
{
"answer_id": 67072466,
"author": "Antony",
"author_id": 3897214,
"author_profile": "https://Stackoverflow.com/users/3897214",
"pm_score": 1,
"selected": false,
"text": "@Matt Johnson-Pints"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"answer_id": 6742125,
"author": "Azhar",
"author_id": 228755,
"author_profile": "https://Stackoverflow.com/users/228755",
"pm_score": 6,
"selected": false,
"text": "Math.Floor()"
},
{
"answer_id": 10937469,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "Math.Floor()"
},
{
"answer_id": 18893721,
"author": "Pinky",
"author_id": 2699939,
"author_profile": "https://Stackoverflow.com/users/2699939",
"pm_score": 4,
"selected": false,
"text": "Math.Floor()"
},
{
"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"
},
{
"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"
},
{
"answer_id": 48732884,
"author": "Puddle",
"author_id": 9312988,
"author_profile": "https://Stackoverflow.com/users/9312988",
"pm_score": 6,
"selected": false,
"text": "Math.floor"
},
{
"answer_id": 51375320,
"author": "vidy",
"author_id": 9993935,
"author_profile": "https://Stackoverflow.com/users/9993935",
"pm_score": 3,
"selected": false,
"text": "Math.floor()"
},
{
"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"
}
] |
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 = "...";
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"
},
{
"answer_id": 544169,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "DataContext"
},
{
"answer_id": 49774484,
"author": "Vijay S",
"author_id": 7204125,
"author_profile": "https://Stackoverflow.com/users/7204125",
"pm_score": 3,
"selected": false,
"text": "IEnumerable"
},
{
"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"
},
{
"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"
},
{
"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 <math.h>
#include <stdio.h>
#include <time.h>
#define ITERS 10000000
#define TESTWITH(x) { \
diff = 0.0; \
time1 = clock(); \
for (i = 0; i < ITERS; ++i) \
diff += (x) - M_PI; \
time2 = clock(); \
printf("%s\t=> %e, time => %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__) && (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"
},
{
"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"
},
{
"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"
},
{
"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 += \" \" \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"
},
{
"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"
},
{
"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"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"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"
},
{
"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 "type" 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 <sys/socket.h>
int main()
{
return AF_INET;
}
</code></pre>
<p>Compile/Link Output:</p>
<pre><code>cxx -Wc,xplink -Wl,xplink -o inet_test inet.C
"./inet.C", line 5.16: CCN5274 (S) The name lookup for "AF_INET" 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 "C" {
#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\""
},
{
"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"
},
{
"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"
},
{
"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"
}
] |
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 < 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"
},
{
"answer_id": 60,
"author": "Redbaron",
"author_id": 41,
"author_profile": "https://Stackoverflow.com/users/41",
"pm_score": 4,
"selected": false,
"text": "ByteArray"
},
{
"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(*))"
},
{
"answer_id": 3009,
"author": "caryden",
"author_id": 313,
"author_profile": "https://Stackoverflow.com/users/313",
"pm_score": 4,
"selected": false,
"text": "SQLDependency"
},
{
"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(*))"
}
] |
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"
},
{
"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"
}
] |
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><form>
<!-- Put your cursor in this field and press Enter -->
<input type="text" name="field1" />
<!-- This is the button that will submit -->
<input type="submit" name="prev" value="Previous Page" />
<!-- But this is the button that I WANT to submit -->
<input type="submit" name="next" value="Next Page" />
</form></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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 31910,
"author": "palotasb",
"author_id": 3063,
"author_profile": "https://Stackoverflow.com/users/3063",
"pm_score": 8,
"selected": true,
"text": "float"
},
{
"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"
},
{
"answer_id": 71629,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": 4,
"selected": false,
"text": "Next"
},
{
"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"
},
{
"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"
},
{
"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});"
},
{
"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"
},
{
"answer_id": 36206414,
"author": "Barry Franklin",
"author_id": 680563,
"author_profile": "https://Stackoverflow.com/users/680563",
"pm_score": 3,
"selected": false,
"text": "UseSubmitBehavior"
},
{
"answer_id": 48171459,
"author": "riskop",
"author_id": 3760049,
"author_profile": "https://Stackoverflow.com/users/3760049",
"pm_score": 2,
"selected": false,
"text": "textfield"
},
{
"answer_id": 50015400,
"author": "Jyoti mishra",
"author_id": 4890885,
"author_profile": "https://Stackoverflow.com/users/4890885",
"pm_score": 1,
"selected": false,
"text": "Tabindex"
},
{
"answer_id": 65239408,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "input type=\"submit\""
},
{
"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"
},
{
"answer_id": 68941820,
"author": "Stoppeye",
"author_id": 14989607,
"author_profile": "https://Stackoverflow.com/users/14989607",
"pm_score": 1,
"selected": false,
"text": "order"
},
{
"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});"
}
] |
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"
},
{
"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"
},
{
"answer_id": 4521,
"author": "Mike Minutillo",
"author_id": 358,
"author_profile": "https://Stackoverflow.com/users/358",
"pm_score": 7,
"selected": true,
"text": "IQueryable<T>"
},
{
"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"
},
{
"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"
}
] |
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:"
}
] |
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"
}
] |
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"
},
{
"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"
},
{
"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()"
},
{
"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 <cubegames@gmail.com>\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"
},
{
"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(&currentTimeVal, NULL);
performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec);
performanceCount->QuadPart *= (1000 * 1000);
performanceCount->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()"
},
{
"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"
},
{
"answer_id": 522,
"author": "Joe Shaw",
"author_id": 156,
"author_profile": "https://Stackoverflow.com/users/156",
"pm_score": 3,
"selected": false,
"text": "gettimeofday()"
},
{
"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)"
},
{
"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>"
}
] |
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"
},
{
"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"
}
] |
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 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 < 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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 161058,
"author": "abarax",
"author_id": 24390,
"author_profile": "https://Stackoverflow.com/users/24390",
"pm_score": 4,
"selected": false,
"text": "contacts.xml"
},
{
"answer_id": 29953381,
"author": "StaxMan",
"author_id": 59501,
"author_profile": "https://Stackoverflow.com/users/59501",
"pm_score": 2,
"selected": false,
"text": "String"
}
] |
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->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->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"
},
{
"answer_id": 22111,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "get_property()"
},
{
"answer_id": 98244,
"author": "moffdub",
"author_id": 10759,
"author_profile": "https://Stackoverflow.com/users/10759",
"pm_score": 5,
"selected": false,
"text": "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"
},
{
"answer_id": 128488,
"author": "Unlabeled Meat",
"author_id": 20291,
"author_profile": "https://Stackoverflow.com/users/20291",
"pm_score": 4,
"selected": false,
"text": "__get"
}
] |
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"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"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><video></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"
},
{
"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"
},
{
"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"
},
{
"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"
}
] |
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"
}
] |
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 & 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\""
},
{
"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><Location></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"
},
{
"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 webmaster@dummy-host.example.com\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"
},
{
"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"
},
{
"answer_id": 2569128,
"author": "rkulla",
"author_id": 308062,
"author_profile": "https://Stackoverflow.com/users/308062",
"pm_score": 3,
"selected": false,
"text": "error_log"
},
{
"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"
},
{
"answer_id": 50618440,
"author": "Parveen Chauhan",
"author_id": 7013481,
"author_profile": "https://Stackoverflow.com/users/7013481",
"pm_score": 2,
"selected": false,
"text": "thecontrolist.localhost"
}
] |
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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 3249162,
"author": "danieli",
"author_id": 83382,
"author_profile": "https://Stackoverflow.com/users/83382",
"pm_score": 2,
"selected": false,
"text": "SQL/PostgreSQL"
},
{
"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 "set as default email client".</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]"
},
{
"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:user@example.com\">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"
},
{
"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"
}
] |
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(&gtkArgc, &gtkArgv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL);
g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL);
// gcallback calls gtk_main_quit()
gtk_init_add((GtkFunction)gcallback, NULL);
if (type & 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 & 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"
},
{
"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"
},
{
"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 & 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"
},
{
"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"
},
{
"answer_id": 2569558,
"author": "Alex Ruiz",
"author_id": 308018,
"author_profile": "https://Stackoverflow.com/users/308018",
"pm_score": 2,
"selected": false,
"text": "SortedDictionary"
},
{
"answer_id": 2697521,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 3,
"selected": false,
"text": "SortedDictionary"
},
{
"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"
},
{
"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"
},
{
"answer_id": 54885808,
"author": "Ashish Kamble",
"author_id": 6440372,
"author_profile": "https://Stackoverflow.com/users/6440372",
"pm_score": 3,
"selected": false,
"text": "OrderBy()"
},
{
"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;"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
}
] |
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 < 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"
},
{
"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"
},
{
"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"
},
{
"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: <spam&egg>.</p>\n </body>\n</html>\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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 6922856,
"author": "orion elenzil",
"author_id": 230851,
"author_profile": "https://Stackoverflow.com/users/230851",
"pm_score": 3,
"selected": false,
"text": "out"
},
{
"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)"
},
{
"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"
},
{
"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']"
},
{
"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()"
},
{
"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\" <john@blacksmiths-international.com>"
},
{
"answer_id": 2579555,
"author": "Pekka",
"author_id": 187606,
"author_profile": "https://Stackoverflow.com/users/187606",
"pm_score": 5,
"selected": false,
"text": "xxx@gmail.com"
},
{
"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"
},
{
"answer_id": 57564315,
"author": "Mike",
"author_id": 811240,
"author_profile": "https://Stackoverflow.com/users/811240",
"pm_score": 1,
"selected": false,
"text": "-f"
},
{
"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()"
}
] |
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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 4290617,
"author": "Arlen Anderson",
"author_id": 247151,
"author_profile": "https://Stackoverflow.com/users/247151",
"pm_score": 3,
"selected": false,
"text": "shouldAutorotateToInterfaceOrientation"
},
{
"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"
},
{
"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<string> myitems = new List<string>
{
"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"
},
{
"answer_id": 20142,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 5,
"selected": false,
"text": "BindingSource"
}
] |
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"
},
{
"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"
}
] |
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 "historical lock" 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 "wiki answer" 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. "Form based authentication for websites" 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>"Remember me" 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>"
},
{
"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"
}
] |
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"
},
{
"answer_id": 583,
"author": "huseyint",
"author_id": 39,
"author_profile": "https://Stackoverflow.com/users/39",
"pm_score": 4,
"selected": false,
"text": "System.Int32"
},
{
"answer_id": 608,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": false,
"text": "int"
},
{
"answer_id": 1266,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 5,
"selected": false,
"text": "int"
},
{
"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"
},
{
"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"
},
{
"answer_id": 498102,
"author": "mP.",
"author_id": 56524,
"author_profile": "https://Stackoverflow.com/users/56524",
"pm_score": 3,
"selected": false,
"text": "int"
},
{
"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"
},
{
"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"
},
{
"answer_id": 24795920,
"author": "Bindumalini KK",
"author_id": 3790709,
"author_profile": "https://Stackoverflow.com/users/3790709",
"pm_score": 2,
"selected": false,
"text": "int"
},
{
"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"
},
{
"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"
},
{
"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()"
},
{
"answer_id": 42617947,
"author": "Mausam Sinha",
"author_id": 6201874,
"author_profile": "https://Stackoverflow.com/users/6201874",
"pm_score": 1,
"selected": false,
"text": "int"
},
{
"answer_id": 43651213,
"author": "thamashi97",
"author_id": 7859659,
"author_profile": "https://Stackoverflow.com/users/7859659",
"pm_score": 2,
"selected": false,
"text": "int"
},
{
"answer_id": 48816251,
"author": "Rishabh Agarwal",
"author_id": 3878948,
"author_profile": "https://Stackoverflow.com/users/3878948",
"pm_score": 0,
"selected": false,
"text": "int"
},
{
"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"
}
] |
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"
},
{
"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"
}
] |
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"
}
] |
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"
},
{
"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"
},
{
"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"
},
{
"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)"
},
{
"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"
},
{
"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()"
},
{
"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"
},
{
"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"
},
{
"answer_id": 36725003,
"author": "DarthGizka",
"author_id": 4156577,
"author_profile": "https://Stackoverflow.com/users/4156577",
"pm_score": 2,
"selected": false,
"text": "List<int>"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 723,
"author": "Joey deVilla",
"author_id": 216,
"author_profile": "https://Stackoverflow.com/users/216",
"pm_score": 10,
"selected": true,
"text": "lambda"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 29920634,
"author": "Aleksei Matiushkin",
"author_id": 2035262,
"author_profile": "https://Stackoverflow.com/users/2035262",
"pm_score": 2,
"selected": false,
"text": "Proc.new"
},
{
"answer_id": 53316814,
"author": "ComDubh",
"author_id": 1445986,
"author_profile": "https://Stackoverflow.com/users/1445986",
"pm_score": 2,
"selected": false,
"text": "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"
},
{
"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"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"answer_id": 67165881,
"author": "GrahamS",
"author_id": 79591,
"author_profile": "https://Stackoverflow.com/users/79591",
"pm_score": 0,
"selected": false,
"text": "AssemblyVersion"
}
] |
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"
}
] |
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"
},
{
"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 ] )"
},
{
"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"
},
{
"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')"
},
{
"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"
},
{
"answer_id": 4905822,
"author": "shang",
"author_id": 572606,
"author_profile": "https://Stackoverflow.com/users/572606",
"pm_score": 3,
"selected": false,
"text": "operator.attrgettter"
}
] |
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"
},
{
"answer_id": 877,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 3,
"selected": false,
"text": "CPU"
},
{
"answer_id": 4074,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 1,
"selected": false,
"text": "Sybase Anywhere"
}
] |
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"
}
] |
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"
},
{
"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"
},
{
"answer_id": 26031,
"author": "Tom Mayfield",
"author_id": 2314,
"author_profile": "https://Stackoverflow.com/users/2314",
"pm_score": 4,
"selected": false,
"text": "ConstructorInfo.Invoke()"
},
{
"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"
},
{
"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"
},
{
"answer_id": 26708746,
"author": "Sarath Subramanian",
"author_id": 3312636,
"author_profile": "https://Stackoverflow.com/users/3312636",
"pm_score": 5,
"selected": false,
"text": "Car"
},
{
"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"
},
{
"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"
},
{
"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"
}
] |
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"
},
{
"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 "prerequisite" 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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 68091577,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 3,
"selected": false,
"text": "itertools.groupby()"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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<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"
},
{
"answer_id": 80296,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 0,
"selected": false,
"text": "join into"
},
{
"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"
},
{
"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"
}
] |
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><buildArgs>
/noconsolelogger /p:OutputPath=$(CCNetArtifactDirectory)\test
</buildArgs>
</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"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"answer_id": 8741592,
"author": "PaulnOZ",
"author_id": 1131991,
"author_profile": "https://Stackoverflow.com/users/1131991",
"pm_score": 3,
"selected": false,
"text": "@font-face"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"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 & 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": "&"
},
{
"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()"
},
{
"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()"
},
{
"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()"
},
{
"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"
},
{
"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"
},
{
"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"
}
] |
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"
}
] |
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><div>
12333-2333-233-23339392-332332323
</div></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": "­\n"
},
{
"answer_id": 67878,
"author": "Dave Rutledge",
"author_id": 2486915,
"author_profile": "https://Stackoverflow.com/users/2486915",
"pm_score": 3,
"selected": false,
"text": "­"
},
{
"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"
},
{
"answer_id": 9060345,
"author": "aeskr",
"author_id": 1125471,
"author_profile": "https://Stackoverflow.com/users/1125471",
"pm_score": 5,
"selected": false,
"text": "<wbr>"
},
{
"answer_id": 22570418,
"author": "ImaJedi4ever",
"author_id": 3329778,
"author_profile": "https://Stackoverflow.com/users/3329778",
"pm_score": 0,
"selected": false,
"text": "‑\n"
},
{
"answer_id": 30229247,
"author": "TObject",
"author_id": 4736743,
"author_profile": "https://Stackoverflow.com/users/4736743",
"pm_score": 0,
"selected": false,
"text": "-"
},
{
"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"
},
{
"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}"
}
] |
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"
}
] |
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"
},
{
"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"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 4600,
"author": "HS.",
"author_id": 618,
"author_profile": "https://Stackoverflow.com/users/618",
"pm_score": 4,
"selected": false,
"text": "setattr"
},
{
"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()"
},
{
"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"
},
{
"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"
},
{
"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"
},
{
"answer_id": 24748849,
"author": "ChristopherC",
"author_id": 1640404,
"author_profile": "https://Stackoverflow.com/users/1640404",
"pm_score": 2,
"selected": false,
"text": "needle()"
},
{
"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"
},
{
"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"
},
{
"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__"
},
{
"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"
}
] |
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"
},
{
"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"
},
{
"answer_id": 37042,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "%"
},
{
"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"
}
] |
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><input type="hidden" name="__VIEWSTATE"
id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" />
</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"
}
] |
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"
},
{
"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"
},
{
"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)"
},
{
"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"
},
{
"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>"
}
] |
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"
},
{
"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/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.