qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
26,020
<p>I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?</p>
[ { "answer_id": 26035, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 7, "selected": true, "text": "using (var connection = new SqliteConnection(\"Data Source=hello.db\"))\n{\n connection.Open();\n\n var command = connection.CreateCommand();\n command.CommandText =\n @\"\n SELECT name\n FROM user\n WHERE id = $id\n \";\n command.Parameters.AddWithValue(\"$id\", id);\n\n using (var reader = command.ExecuteReader())\n {\n while (reader.Read())\n {\n var name = reader.GetString(0);\n\n Console.WriteLine($\"Hello, {name}!\");\n }\n }\n}\n" }, { "answer_id": 1253002, "author": "DA.", "author_id": 153494, "author_profile": "https://Stackoverflow.com/users/153494", "pm_score": 6, "selected": false, "text": "using System;\nusing System.Text;\nusing System.Data;\nusing System.Data.SQLite;\n\nnamespace MySqlLite\n{\n class DataClass\n {\n private SQLiteConnection sqlite;\n\n public DataClass()\n {\n //This part killed me in the beginning. I was specifying \"DataSource\"\n //instead of \"Data Source\"\n sqlite = new SQLiteConnection(\"Data Source=/path/to/file.db\");\n\n }\n\n public DataTable selectQuery(string query)\n {\n SQLiteDataAdapter ad;\n DataTable dt = new DataTable();\n\n try\n {\n SQLiteCommand cmd;\n sqlite.Open(); //Initiate connection to the db\n cmd = sqlite.CreateCommand();\n cmd.CommandText = query; //set the passed query\n ad = new SQLiteDataAdapter(cmd);\n ad.Fill(dt); //fill the datasource\n }\n catch(SQLiteException ex)\n {\n //Add your exception code here.\n }\n sqlite.Close();\n return dt;\n }\n}\n" }, { "answer_id": 64220839, "author": "floyd70s", "author_id": 12537320, "author_profile": "https://Stackoverflow.com/users/12537320", "pm_score": 0, "selected": false, "text": "Microsoft.Data.Sqlite; public static DataTable GetData(string connectionString, string query)\n {\n DataTable dt = new DataTable();\n Microsoft.Data.Sqlite.SqliteConnection connection;\n Microsoft.Data.Sqlite.SqliteCommand command;\n\n connection = new Microsoft.Data.Sqlite.SqliteConnection(\"Data Source= YOU_PATH_BD.sqlite\");\n try\n {\n connection.Open();\n command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);\n dt.Load(command.ExecuteReader());\n connection.Close();\n }\n catch\n {\n }\n\n return dt;\n }\n" }, { "answer_id": 65482510, "author": "ali asghar tofighian", "author_id": 6078802, "author_profile": "https://Stackoverflow.com/users/6078802", "pm_score": 1, "selected": false, "text": "string connectionString = @\"URI=file:{the location of your sqlite database}\"; SQLiteConnection theConnection = new SQLiteConnection(connectionString ); theConnection.Open(); SQLiteCommand cmd = new SQLiteCommand(theConnection); cmd.CommandText = \"INSERT INTO table_name(col1, col2) VALUES(val1, val2)\"; cmd.ExecuteNonQuery();" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2674/" ]
26,025
<p>I'm about to deploy a mediumsized site powered by Django. I have a dedicated Ubuntu Server. </p> <p>I'm really confused over which serversoftware to use. So i thought to myself: why not ask stackoverflow.</p> <p>What i'm looking for is:</p> <ul> <li>Easy to set up</li> <li>Fast and easy on resources</li> <li>Can serve mediafiles</li> <li>Able to serve multiple djangosites on same server</li> <li>I would rather not install PHP or anything else that sucks resources, and for which I have no use for.</li> </ul> <p>I have heard of mod_wsgi and mod_python on Apache, nginx and lighty. Which are the pros and cons of these and have i missed someone?</p> <p><strong>@Barry</strong>: Somehow i feel like Apache is to bloated for me. What about the alternatives?</p> <p><strong>@BrianLy</strong>: Ok I'll check out mod_wsgi some more. But why do i need Apache if i serve static files with lighty? I have also managed to serve the django app itself with lighty. Is that bad in anyway? Sorry for beeing so stupid :-)</p> <p><strong>UPDATE</strong>: What about lighty and nginx - which are the uses-cases when these are the perfect choice?</p>
[ { "answer_id": 126698, "author": "Roman Odaisky", "author_id": 21055, "author_profile": "https://Stackoverflow.com/users/21055", "pm_score": 2, "selected": false, "text": "mod_wsgi SCRIPT_NAME error_page 404 = @django" }, { "answer_id": 353517, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "cherokee-admin" }, { "answer_id": 14844120, "author": "Alex Stewart", "author_id": 1725981, "author_profile": "https://Stackoverflow.com/users/1725981", "pm_score": 1, "selected": false, "text": "sudo /etc/init.d/apache2 restart\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2639/" ]
26,094
<p>When doing calculations on very large numbers where integral data types such as double or int64 falls short, a separate class to handle such large numbers may be needed. </p> <p>Does anyone care to offer an efficient algorithm on how best to do this?</p>
[ { "answer_id": 26116, "author": "jjnguy", "author_id": 2598, "author_profile": "https://Stackoverflow.com/users/2598", "pm_score": 2, "selected": false, "text": "BigInteger BigDecimal integer" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224/" ]
26,098
<p>I'm writing a C/C++ DLL and want to export certain functions which I've done before using a .def file like this</p> <pre><code>LIBRARY "MyLib" EXPORTS Foo Bar </code></pre> <p>with the code defined as this, for example:</p> <pre><code>int Foo(int a); void Bar(int foo); </code></pre> <p>However, what if I want to declare an overloaded method of Foo() like:</p> <pre><code>int Foo(int a, int b); </code></pre> <p>As the def file only has the function name and not the full prototype I can't see how it would handle the overloaded functions. Do you just use the one entry and then specify which overloaded version you want when passing in the properly prototyped function pointer to LoadLibrary() ?</p> <p>Edit: To be clear, this is on Windows using Visual Studio 2005</p> <p>Edit: Marked the non-def (__declspec) method as the answer...I know this doesn't actually solve the problem using def files as I wanted, but it seems that there is likely no (official) solution using def files. Will leave the question open, however, in case someone knows something we don't have overloaded functions and def files.</p>
[ { "answer_id": 26121, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 4, "selected": true, "text": "#define DllExport __declspec(dllexport)\n\nint DllExport Foo( int a ) {\n // implementation\n}\nint DllExport Foo( int a, int b ) {\n // implementation\n}\n int Foo( int a, int b = -1 )\n" }, { "answer_id": 26142, "author": "Timbo", "author_id": 1810, "author_profile": "https://Stackoverflow.com/users/1810", "pm_score": 4, "selected": false, "text": "LIBRARY \"TestDLL\"\nEXPORTS\n ?Foo@@YAXH@Z\n ?Foo@@YAXHH@Z\n void Foo( int x );\nvoid Foo( int x, int y );\n" }, { "answer_id": 342055, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "extern \"C\" __declspec(dllexport) void Foo();\n extern \"C\" __declspec(dllexport) void __stdcall Foo();\n ----\nEXPORTS\n ; Explicit exports can go here\n\n Foo\n-----\n ----\nEXPORTS\n ; Explicit exports can go here\n\n Foo=_Foo@4\n-----\n #pragma comment(linker, \"/export:Foo=_Foo@4\")\n" }, { "answer_id": 15540686, "author": "null", "author_id": 1999454, "author_profile": "https://Stackoverflow.com/users/1999454", "pm_score": 2, "selected": false, "text": "entryname[=internalname] [@ordinal [NONAME]] [PRIVATE] [DATA]\n EXPORTS\nfunc2=func1\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
26,113
<p>I'm not talking about tools that let one view a page in combinations of operating systems and browsers like crossbrowsertesting.com but in creating or figuring out the actual CSS.</p>
[ { "answer_id": 26131, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "/* All browsers read: */\nhtml body {\n margin: 10px;\n}\n\n/* FF, IE7, Op etc. read: */\nhtml > body {\n margin: 0;\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702/" ]
26,123
<p>I want to use Powershell to write some utilities, leveraging our own .NET components to handle the actual work. This is in place of writing a small console app to tie the calls together. My question is where I would find a good source of documentation or tutorial material to help me fast track this?</p>
[ { "answer_id": 26135, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 5, "selected": true, "text": "[void][System.Reflection.Assembly]::LoadFrom(PathToYourAssembly)\n" }, { "answer_id": 40611548, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "[] add-type -AssemblyName \"System.example\" [system.drawing]::class ...\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1535/" ]
26,137
<p>I have a couple of questions regarding VBScript and ASP Classic:</p> <ol> <li><p>What is the preferred way to access an MS SQL Server database in VBScript/ASP?</p></li> <li><p>What are best practices in regards to separating model from view from controller?</p></li> <li><p>Any other things I should know about either VBScript or ASP?</p></li> </ol> <p>If you haven't noticed, I'm new at VBScript coding. I realize numbers 2 &amp; 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.</p>
[ { "answer_id": 26181, "author": "Michael Pryor", "author_id": 245, "author_profile": "https://Stackoverflow.com/users/245", "pm_score": 5, "selected": true, "text": "Dim db: Set db = Server.CreateObject(\"ADODB.Connection\")\ndb.Open \"yourconnectionstring -> see connectionstrings.com\"\nDim rs: Set rs = db.Execute(\"SELECT firstName from Employees\")\nWhile Not rs.EOF\n Response.Write rs(\"firstName\")\n rs.MoveNext\nWend\nrs.Close\n" }, { "answer_id": 91504, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 3, "selected": false, "text": "Class Dog\n Private Parent\n\n Private Sub Class_Initialize()\n Set Parent = New Animal\n End Sub\n\n Public Function Walk()\n Walk = Parent.Walk\n End Function\n\n Public Function Bark()\n Response.Write(\"Woof! Woof!\")\n End Function\nEnd Class\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
26,145
<p>I'm making a simple extra java app launcher for Eclipse 3.2 (JBuilder 2007-8) for internal use.</p> <p>So I looked up all the documentations related, including this one <a href="http://www.eclipse.org/articles/Article-Launch-Framework/launch.html" rel="nofollow noreferrer" title="The Launching Framework">The Launching Framework from eclipse.org</a> and have managed to make everything else working with the exception of the launch shortcut. </p> <p><img src="https://i.stack.imgur.com/8I8zw.jpg" alt="alt text"></p> <p>This is the part of my plugin.xml. </p> <pre><code> &lt;extension point="org.eclipse.debug.ui.launchShortcuts"&gt; &lt;shortcut category="mycompany.javalaunchext.launchConfig" class="mycompany.javalaunchext.LaunchShortcut" description="launchshortcutsdescription" icon="icons/k2mountain.png" id="mycompany.javalaunchext.launchShortcut" label="Java Application Ext." modes="run, debug"&gt; &lt;perspective id="org.eclipse.jdt.ui.JavaPerspective"&gt; &lt;/perspective&gt; &lt;perspective id="org.eclipse.jdt.ui.JavaHierarchyPerspective"&gt; &lt;/perspective&gt; &lt;perspective id="org.eclipse.jdt.ui.JavaBrowsingPerspective"&gt; &lt;/perspective&gt; &lt;perspective id="org.eclipse.debug.ui.DebugPerspective"&gt; &lt;/perspective&gt; &lt;/shortcut&gt; </code></pre> <p></p> <p>The configuration name in the category section is correct and the class in the class section, i believe, is correctly implemented. (basically copied from org.eclipse.jdt.debug.ui.launchConfigurations.JavaApplicationLaunchShortcut)</p> <hr> <p>I'm really not sure if I'm supposed to write a follow-up here but let me clarify my question more. I've extended org.eclipse.jdt.debug.ui.launchConfigurations.JavaLaunchShortcut. Plus, I've added my own logger to constructors and methods, but the class seems like it's never even instantiating.</p>
[ { "answer_id": 40209, "author": "wbkang", "author_id": 2710, "author_profile": "https://Stackoverflow.com/users/2710", "pm_score": 3, "selected": true, "text": "contextualLaunch org.eclipse.debug.ui.launchShortcuts org.eclipse.ui.commands" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2710/" ]
26,151
<p>C++ 0x has template aliases (sometimes referred to as template typedefs). See <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates" rel="noreferrer">here</a>. Current spec of C++ does not. </p> <p>What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?</p>
[ { "answer_id": 26162, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "template <typename T>\nstruct my_string_map {\n typedef std::map<std::string, T> type;\n};\n\n// Invoke:\n\nmy_string_map<int>::type my_str_int_map;\n allocator::rebind<U>" }, { "answer_id": 2089853, "author": "xghost", "author_id": 253585, "author_profile": "https://Stackoverflow.com/users/253585", "pm_score": 4, "selected": false, "text": "template <typename T>\nstruct my_string_map : public std::map<std::string,T> \n{\n};\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759/" ]
26,158
<p>How does a stack overflow occur and what are the best ways to make sure it doesn't happen, or ways to prevent one, particularly on web servers, but other examples would be interesting as well?</p>
[ { "answer_id": 26169, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 3, "selected": false, "text": "char hugeArray[100000000];\n" }, { "answer_id": 16691034, "author": "the_mandrill", "author_id": 188414, "author_profile": "https://Stackoverflow.com/users/188414", "pm_score": 3, "selected": false, "text": "Fibonacci(1000000) void WindowSizeChanged(Size& newsize) {\n // override window size to constrain width\n newSize.width=200;\n ResizeWindow(newSize);\n}\n ResizeWindow WindowSizeChanged() ResizeWindow" }, { "answer_id": 60846108, "author": "atul sachan", "author_id": 11711605, "author_profile": "https://Stackoverflow.com/users/11711605", "pm_score": 2, "selected": false, "text": "package com.company.dynamicProgramming;\n\nimport java.math.BigInteger;\n\npublic class FibonacciByBigDecimal {\n\n public static void main(String ...args) {\n\n int n = 100000;\n BigInteger[] fibOfnS = new BigInteger[n + 1];\n\n System.out.println(\"fibonacci of \"+ n + \" is : \" + fibByLoop(n));\n }\n\n\n static BigInteger fibByLoop(int n){\n\n if(n==1 || n==2 ){\n return BigInteger.ONE;\n }\n\n BigInteger fib = BigInteger.ONE;\n BigInteger fip = BigInteger.ONE;\n\n\n for (int i = 3; i <= n; i++){\n\n BigInteger p = fib;\n fib = fib.add(fip);\n fip = p;\n }\n\n return fib;\n }\n\n}\n fibonacci of 100000 is : 2597406934722172416615503402127591541488048538651769658472477070395253454351127368626555677283671674475463758722307443211163839947387509103096569738218830449305228763853133492135302679278956701051276578271635608073050532200243233114383986516137827238124777453778337299916214634050054669860390862750996639366409211890125271960172105060300350586894028558103675117658251368377438684936413457338834365158775425371912410500332195991330062204363035213756525421823998690848556374080179251761629391754963458558616300762819916081109836526352995440694284206571046044903805647136346033000520852277707554446794723709030979019014860432846819857961015951001850608264919234587313399150133919932363102301864172536477136266475080133982431231703431452964181790051187957316766834979901682011849907756686456845066287392485603914047605199550066288826345877189410680370091879365001733011710028310473947456256091444932821374855573864080579813028266640270354294412104919995803131876805899186513425175959911520563155337703996941035518275274919959802257507902037798103089922984996304496255814045517000250299764322193462165366210841876745428298261398234478366581588040819003307382939500082132009374715485131027220817305432264866949630987914714362925554252624043999615326979876807510646819068792118299167964409178271868561702918102212679267401362650499784968843680975254700131004574186406448299485872551744746695651879126916993244564817673322257149314967763345846623830333820239702436859478287641875788572910710133700300094229333597292779191409212804901545976262791057055248158884051779418192905216769576608748815567860128818354354292307397810154785701328438612728620176653953444993001980062953893698550072328665131718113588661353747268458543254898113717660519461693791688442534259478126310388952047956594380715301911253964847112638900713362856910155145342332944128435722099628674611942095166100230974070996553190050815866991144544264788287264284501725332048648319457892039984893823636745618220375097348566847433887249049337031633826571760729778891798913667325190623247118037280173921572390822769228077292456662750538337500692607721059361942126892030256744356537800831830637593334502350256972906515285327194367756015666039916404882563967693079290502951488693413799125174856667074717514938979038653338139534684837808612673755438382110844897653836848318258836339917310455850905663846202501463131183108742907729262215943020429159474030610183981685506695026197376150857176119947587572212987205312060791864980361596092339594104118635168854883911918517906151156275293615849000872150192226511785315089251027528045151238603792184692121533829287136924321527332714157478829590260157195485316444794546750285840236000238344790520345108033282013803880708980734832620122795263360677366987578332625485944906021917368867786241120562109836985019729017715780112040458649153935115783499546100636635745448508241888279067531359950519206222976015376529797308588164873117308237059828489404487403932053592935976454165560795472477862029969232956138971989467942218727360512336559521133108778758228879597580320459608479024506385194174312616377510459921102486879496341706862092908893068525234805692599833377510390101316617812305114571932706629167125446512151746802548190358351688971707570677865618800822034683632101813026232996027599403579997774046244952114531588370357904483293150007246173417355805567832153454341170020258560809166294198637401514569572272836921963229511187762530753402594781448204657460288485500062806934811398276016855584079542162057543557291510641537592939022884356120792643705560062367986544382464373946972471945996555795505838034825597839682776084731530251788951718630722761103630509360074262261717363058613291544024695432904616258691774630578507674937487992329181750163484068813465534370997589353607405172909412697657593295156818624747127636468836551757018353417274662607306510451195762866349922848678780591085118985653555434958761664016447588028633629704046289097067736256584300235314749461233912068632146637087844699210427541569410912246568571204717241133378489816764096924981633421176857150311671040068175303192115415611958042570658693127276213710697472226029655524611053715554532499750843275200199214301910505362996007042963297805103066650638786268157658772683745128976850796366371059380911225428835839194121154773759981301921650952140133306070987313732926518169226845063443954056729812031546392324981793780469103793422169495229100793029949237507299325063050942813902793084134473061411643355614764093104425918481363930542369378976520526456347648318272633371512112030629233889286487949209737847861884868260804647319539200840398308008803869049557419756219293922110825766397681361044490024720948340326796768837621396744075713887292863079821849314343879778088737958896840946143415927131757836511457828935581859902923534388888846587452130838137779443636119762839036894595760120316502279857901545344747352706972851454599861422902737291131463782045516225447535356773622793648545035710208644541208984235038908770223039849380214734809687433336225449150117411751570704561050895274000206380497967960402617818664481248547269630823473377245543390519841308769781276565916764229022948181763075710255793365008152286383634493138089971785087070863632205869018938377766063006066757732427272929247421295265000706646722730009956124191409138984675224955790729398495608750456694217771551107346630456603944136235888443676215273928597072287937355966723924613827468703217858459948257514745406436460997059316120596841560473234396652457231650317792833860590388360417691428732735703986803342604670071717363573091122981306903286137122597937096605775172964528263757434075792282180744352908669606854021718597891166333863858589736209114248432178645039479195424208191626088571069110433994801473013100869848866430721216762473119618190737820766582968280796079482259549036328266578006994856825300536436674822534603705134503603152154296943991866236857638062351209884448741138600171173647632126029961408561925599707566827866778732377419444462275399909291044697716476151118672327238679208133367306181944849396607123345271856520253643621964198782752978813060080313141817069314468221189275784978281094367751540710106350553798003842219045508482239386993296926659221112742698133062300073465628498093636693049446801628553712633412620378491919498600097200836727876650786886306933418995225768314390832484886340318940194161036979843833346608676709431643653538430912157815543512852077720858098902099586449602479491970687230765687109234380719509824814473157813780080639358418756655098501321882852840184981407690738507369535377711880388528935347600930338598691608289335421147722936561907276264603726027239320991187820407067412272258120766729040071924237930330972132364184093956102995971291799828290009539147382437802779051112030954582532888721146170133440385939654047806199333224547317803407340902512130217279595753863158148810392952475410943880555098382627633127606718126171022011356181800775400227516734144169216424973175621363128588281978005788832454534581522434937268133433997710512532081478345067139835038332901313945986481820272322043341930929011907832896569222878337497354301561722829115627329468814853281922100752373626827643152685735493223028018101449649009015529248638338885664893002250974343601200814365153625369199446709711126951966725780061891215440222487564601554632812091945824653557432047644212650790655208208337976071465127508320487165271577472325887275761128357592132553934446289433258105028633583669291828566894736223508250294964065798630809614341696830467595174355313224362664207197608459024263017473392225291248366316428006552870975051997504913009859468071013602336440164400179188610853230764991714372054467823597211760465153200163085336319351589645890681722372812310320271897917951272799656053694032111242846590994556380215461316106267521633805664394318881268199494005537068697621855231858921100963441012933535733918459668197539834284696822889460076352031688922002021931318369757556962061115774305826305535862015637891246031220672933992617378379625150999935403648731423208873977968908908369996292995391977217796533421249291978383751460062054967341662833487341011097770535898066498136011395571584328308713940582535274056081011503907941688079197212933148303072638678631411038443128215994936824342998188719768637604496342597524256886188688978980888315865076262604856465004322896856149255063968811404400429503894245872382233543101078691517328333604779262727765686076177705616874050257743749983775830143856135427273838589774133526949165483929721519554793578923866762502745370104660909382449626626935321303744538892479216161188889702077910448563199514826630802879549546453583866307344423753319712279158861707289652090149848305435983200771326653407290662016775706409690183771201306823245333477966660525325490873601961480378241566071271650383582257289215708209369510995890132859490724306183325755201208090007175022022949742801823445413711916298449914722254196594682221468260644961839254249670903104007581488857971672246322887016438403908463856731164308169537326790303114583680575021119639905615169154708510459700542098571797318015564741406172334145847111268547929892443001391468289103679179216978616582489007322033591376706527676521307143985302760988478056216994659655461379174985659739227379416726495377801992098355427866179123126699374730777730569324430166839333011554515542656864937492128687049121754245967831132969248492466744261999033972825674873460201150442228780466124320183016108232183908654771042398228531316559685688005226571474428823317539456543881928624432662503345388199590085105211383124491861802624432195540433985722841341254409411771722156867086291742124053110620522842986199273629406208834754853645128123279609097213953775360023076765694208219943034648783348544492713539450224591334374664937701655605763384697062918725745426505879414630176639760457474311081556747091652708748125267159913793240527304613693961169892589808311906322510777928562071999459487700611801002296132304588294558440952496611158342804908643860880796440557763691857743754025896855927252514563404385217825890599553954627451385454452916761042969267970893580056234501918571489030418495767400819359973218711957496357095967825171096264752068890806407651445893132870767454169607107931692704285168093413311046353506242209810363216771910420786162184213763938194625697286781413636389620123976910465418956806197323148414224550071617215851321302030684176087215892702098879108938081045903397276547326416916845445627600759561367103584575649094430692452532085003091068783157561519847567569191284784654692558665111557913461272425336083635131342183905177154511228464455136016013513228948543271504760839307556100908786096663870612278690274831819331606701484957163004705262228238406266818448788374548131994380387613830128859885264201992286188208499588640888521352501457615396482647451025902530743172956899636499615707551855837165935367125448515089362904567736630035562457374779100987992499146967224041481601289530944015488942613783140087804311431741858071826185149051138744831358439067228949408258286021650288927228387426432786168690381960530155894459451808735197246008221529343980828254126128257157209350985382800738560472910941184006084485235377833503306861977724501886364070344973366473100602018128792886991861824418453968994777259482169137133647470453172979809245844361129618997595696240971845564020511432589591844724920942930301651488713079802102379065536525154780298059407529440513145807551537794861635879901158192019808879694967187448224156836463534326160242632934761634458163890163805123894184523973421841496889262398489648642093409816681494771155177009562669029850101513537599801272501241971119871526593747484778935488777815192931171431167444773882941064615028751327709474504763922874890662989841540259350834035142035136168819248238998027706666916342133424312054507359388616687691188185776118135771332483965209882085982391298606386822804754362408956522921410859852037330544625953261340234864689275060526893755148403298542086991221052597005628576707702567695300978970046408920009852106980295419699802138053295798159478289934443245491565327845223840551240445208226435420656313310702940722371552770504263482073984454889589248861397657079145414427653584572951329719091947694411910966797474262675590953832039169673494261360032263077428684105040061351052194413778158095005714526846009810352109249040027958050736436961021241137739717164869525493114805040126568351268829598413983222676377804500626507241731757395219796890754825199329259649801627068665658030178877405615167159731927320479376247375505855052839660294566992522173600874081212014209071041937598571721431338017425141582491824710905084715977249417049320254165239323233258851588893337097136310892571531417761978326033750109026284066415801371359356529278088456305951770081443994114674291850360748852366654744869928083230516815711602911836374147958492100860528981469547750812338896943152861021202736747049903930417035171342126923486700566627506229058636911882228903170510305406882096970875545329369434063981297696478031825451642178347347716471058423238594580183052756213910186997604305844068665712346869679456044155742100039179758348979935882751881524675930878928159243492197545387668305684668420775409821781247053354523194797398953320175988640281058825557698004397120538312459428957377696001857497335249965013509368925958021863811725906506436882127156815751021712900765992750370228283963962915973251173418586721023497317765969454283625519371556009143680329311962842546628403142444370648432390374906410811300792848955767243481200090309888457270907750873638873299642555050473812528975962934822878917619920725138309388288292510416837622758204081918933603653875284116785703720989718832986921927816629675844580174911809119663048187434155067790863948831489241504300476704527971283482211522202837062857314244107823792513645086677566622804977211397140621664116324756784216612961477109018826094677377686406176721484293894976671380122788941309026553511096118347012565197540807095384060916863936906673786627209429434264260402902158317345003727462588992622049877121178405563348492490326003508569099382392777297498413565614830788262363322368380709822346012274241379036473451735925215754757160934270935192901723954921426490691115271523338109124042812102893738488167358953934508930697715522989199698903885883275409044300321986834003470271220020159699371690650330547577095398748580670024491045504890061727189168031394528036165633941571334637222550477547460756055024108764382121688848916940371258901948490685379722244562009483819491532724502276218589169507405794983759821006604481996519360110261576947176202571702048684914616894068404140833587562118319210838005632144562018941505945780025318747471911604840677997765414830622179069330853875129298983009580277554145435058768984944179136535891620098725222049055183554603706533183176716110738009786625247488691476077664470147193074476302411660335671765564874440577990531996271632972009109449249216456030618827772947750764777446452586328919159107444252320082918209518021083700353881330983215894608680127954224752071924134648334963915094813097541433244209299930751481077919002346128122330161799429930618800533414550633932139339646861616416955220216447995417243171165744471364197733204899365074767844149929548073025856442942381787641506492878361767978677158510784235702640213388018875601989234056868423215585628508645525258377010620532224244987990625263484010774322488172558602233302076399933854152015343847725442917895130637050320444917797752370871958277976799686113626532291118629631164685159934660693460557545956063155830033697634000276685151293843638886090828376141157732003527565158745906567025439437931104838571313294490604926582363108949535090082673154497226396648088618041573977888472892174618974189721700770009862449653759012727015227634510874906948012210684952063002519011655963580552429180205586904259685261047412834518466736938580027700252965356366721619883672428226933950325930390994583168665542234654857020875504617520521853721567282679903418135520602999895366470106557900532129541336924472492212436324523042895188461779122338069674233980694887270587503389228395095135209123109258159006960395156367736067109050566299603571876423247920752836160805597697778756476767210521222327184821484446631261487584226092608875764331731023263768864822594691211032367737558122133470556805958008310127481673962019583598023967414489867276845869819376783757167936723213081586191045995058970991064686919463448038574143829629547131372173669836184558144505748676124322451519943362182916191468026091121793001864788050061351603144350076189213441602488091741051232290357179205497927970924502479940842696158818442616163780044759478212240873204124421169199805572649118243661921835714762891425805771871743688000324113008704819373962295017143090098476927237498875938639942530595331607891618810863505982444578942799346514915952884869757488025823353571677864826828051140885429732788197765736966005727700162592404301688659946862983717270595809808730901820120931003430058796552694788049809205484305467611034654748067290674399763612592434637719995843862812391985470202414880076880818848087892391591369463293113276849329777201646641727587259122354784480813433328050087758855264686119576962172239308693795757165821852416204341972383989932734803429262340722338155102209101262949249742423271698842023297303260161790575673111235465890298298313115123607606773968998153812286999642014609852579793691246016346088762321286205634215901479188632194659637483482564291616278532948239313229440231043277288768139550213348266388687453259281587854503890991561949632478855035090289390973718988003999026132015872678637873095678109625311008054489418857983565902063680699643165033912029944327726770869305240718416592070096139286401966725750087012218149733133695809600369751764951350040285926249203398111014953227533621844500744331562434532484217986108346261345897591234839970751854223281677187215956827243245910829019886390369784542622566912542747056097567984857136623679023878478161201477982939080513150258174523773529510165296934562786122241150783587755373348372764439838082000667214740034466322776918936967612878983488942094688102308427036452854504966759697318836044496702853190637396916357980928865719935397723495486787180416401415281489443785036291071517805285857583987711145474240156416477194116391354935466755593592608849200546384685403028080936417250583653368093407225310820844723570226809826951426162451204040711501448747856199922814664565893938488028643822313849852328452360667045805113679663751039248163336173274547275775636810977344539275827560597425160705468689657794530521602315939865780974801515414987097778078705357058008472376892422189750312758527140173117621279898744958406199843913365680297721208751934988504499713914285158032324823021340630312586072624541637765234505522051086318285359658520708173392709566445011404055106579055037417780393351658360904543047721422281816832539613634982525215232257690920254216409657452618066051777901592902884240599998882753691957540116954696152270401280857579766154722192925655963991820948894642657512288766330302133746367449217449351637104725732980832812726468187759356584218383594702792013663907689741738962252575782663990809792647011407580367850599381887184560094695833270775126181282015391041773950918244137561999937819240362469558235924171478702779448443108751901807414110290370706052085162975798361754251041642244867577350756338018895379263183389855955956527857227926155524494739363665533904528656215464288343162282921123290451842212532888101415884061619939195042230059898349966569463580186816717074818823215848647734386780911564660755175385552224428524049468033692299989300783900020690121517740696428573930196910500988278523053797637940257968953295112436166778910585557213381789089945453947915927374958600268237844486872037243488834616856290097850532497036933361942439802882364323553808208003875741710969289725499878566253048867033095150518452126944989251596392079421452606508516052325614861938282489838000815085351564642761700832096483117944401971780149213345335903336672376719229722069970766055482452247416927774637522135201716231722137632445699154022395494158227418930589911746931773776518735850032318014432883916374243795854695691221774098948611515564046609565094538115520921863711518684562543275047870530006998423140180169421109105925493596116719457630962328831271268328501760321771680400249657674186927113215573270049935709942324416387089242427584407651215572676037924765341808984312676941110313165951429479377670698881249643421933287404390485538222160837088907598277390184204138197811025854537088586701450623578513960109987476052535450100439353062072439709976445146790993381448994644609780957731953604938734950026860564555693224229691815630293922487606470873431166384205442489628760213650246991893040112513103835085621908060270866604873585849001704200923929789193938125116798421788115209259130435572321635660895603514383883939018953166274355609970015699780289236362349895374653428746875\n\n package com.company.dynamicProgramming;\n\nimport java.math.BigInteger;\n\npublic class FibonacciByBigDecimal {\n\n public static void main(String ...args) {\n\n int n = 100000;\n BigInteger[] fibOfnS = new BigInteger[n + 1];\n\n System.out.println(\"fibonacci of \"+ n + \" is : \" + fibByDivCon(n, fibOfnS));\n\n }\n\n\n static BigInteger fibByDivCon(int n, BigInteger[] fibOfnS){\n\n if(fibOfnS[n]!=null){\n return fibOfnS[n];\n }\n\n if (n == 1 || n== 2){\n fibOfnS[n] = BigInteger.ONE;\n return BigInteger.ONE;\n }\n\n // creates 2 further entries in stack\n BigInteger fibOfn = fibByDivCon(n-1, fibOfnS).add( fibByDivCon(n-2, fibOfnS)) ;\n\n fibOfnS[n] = fibOfn;\n\n return fibOfn;\n\n }\n\n}\n Exception in thread \"main\" java.lang.StackOverflowError\n at com.company.dynamicProgramming.FibonacciByBigDecimal.fibByDivCon(FibonacciByBigDecimal.java:29)\n at com.company.dynamicProgramming.FibonacciByBigDecimal.fibByDivCon(FibonacciByBigDecimal.java:29)\n at com.company.dynamicProgramming.FibonacciByBigDecimal.fibByDivCon(FibonacciByBigDecimal.java:29)\n\n // creates 2 further entries in stack\n BigInteger fibOfn = fibByDivCon(n-1, fibOfnS).add( fibByDivCon(n-2, fibOfnS)) ;\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1935/" ]
26,173
<p>I am looking for some JavaScript based component to be used as a course scheduler which would be a cross between Google Calendar and the login time. I do not know if the right term for this is <i>Course Scheduler</i> but I shall describe this in more detail here.</p> <p><b>Course Scheduler</b><br> The widget would be used to enter date and times of a course, as an example if I run a programming course 3 days a week on Mon, Tue and Wed every 7:00 am to 9:00am, 2 hours every day from 1st September to 30th November. I could answer various questions and the course data would be displayed in the calendar. It would also allow for non pattern based timings where each week is different from the other week etc. </p> <p><b>Question</b><br> So would I end up creating something from scratch? Would it be sensible to use Google Calendar API for this? I did a Google search for some widgets, but I believe I need better keywords, as I could not find anything close to what I am looking for. Any tips? Commercial libraries would also work for me. Thanks.</p>
[ { "answer_id": 5494743, "author": "bobo", "author_id": 684997, "author_profile": "https://Stackoverflow.com/users/684997", "pm_score": 3, "selected": false, "text": "* Day/week/month view provided.\n* create/update/remove events by drag & drop.\n* Easy way to integrate with database.\n* All day event/more days event provided.\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370899/" ]
26,195
<p>I've always wanted to be able to get a reasonably elegant way of getting vimdiff to work with a CVS controlled file. I've found numerous (somewhat hacky) scripts around the internet (best example <a href="http://www.vim.org/tips/tip.php?tip_id=390" rel="noreferrer">here</a>) that basically check out the file you are editing from CVS to a temp file, and vimdiff the two. None of these take into account branches, and always assume you're working from MAIN, which for me is completely useless. </p> <p>So, my question is this: has anyone out there found a decent solution for this that does more than this script?</p> <p>Or failing that, does anyone have any ideas of how they would implement this, or suggestions for what features you would consider vital for something that does this? My intention is that, if no one can suggest an already built solution to either use or build from, we start building one from here. </p>
[ { "answer_id": 26649, "author": "Peter Stuifzand", "author_id": 1633, "author_profile": "https://Stackoverflow.com/users/1633", "pm_score": 0, "selected": false, "text": "cvs" }, { "answer_id": 28889, "author": "sanmiguel", "author_id": 24, "author_profile": "https://Stackoverflow.com/users/24", "pm_score": 1, "selected": false, "text": "< map <silent> <C-d> :call <SID>scmToggle()<CR>\n--\n> map <silent> <C-h> :call <SID>scmToggle()<CR>\n < let cmd = 'cd ' . g:scmBufPath . ' && ' . g:scmDiffCommand . ' diff ' . g:scmDiffRev . ' ' . expand('%:p') . ' > ' . tmpdiff\n--\n> if g:scmDiffUseAbsPaths \n> let cmd = 'cd ' . g:scmBufPath . ' && ' . g:scmDiffCommand . ' diff ' . g:scmDiffRev . ' ' . expand('%:p') . ' > ' . tmpdiff\n> else\n> let cmd = g:scmDiffCommand . ' diff ' . g:scmDiffRev . ' ' . bufname('%') . ' > ' . tmpdiff\n> endif\n" }, { "answer_id": 1975434, "author": "0x89", "author_id": 147058, "author_profile": "https://Stackoverflow.com/users/147058", "pm_score": 0, "selected": false, "text": "mapleader" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24/" ]
26,196
<p>I am looking for a very fast way to filter down a collection in C#. I am currently using generic <code>List&lt;object&gt;</code> collections, but am open to using other structures if they perform better.</p> <p>Currently, I am just creating a new <code>List&lt;object&gt;</code> and looping thru the original list. If the filtering criteria matches, I put a copy into the new list.</p> <p>Is there a better way to do this? Is there a way to filter in place so there is no temporary list required?</p>
[ { "answer_id": 26203, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 9, "selected": true, "text": "List<int> myList = GetListOfIntsFromSomewhere();\n\n// This will filter ints that are not > 7 out of the list; Where returns an\n// IEnumerable<T>, so call ToList to convert back to a List<T>.\nList<int> filteredList = myList.Where(x => x > 7).ToList();\n .Where using System.Linq;" }, { "answer_id": 26206, "author": "Mykroft", "author_id": 2191, "author_profile": "https://Stackoverflow.com/users/2191", "pm_score": 4, "selected": false, "text": "List<T> FindAll Where() FindAll" }, { "answer_id": 26210, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 3, "selected": false, "text": "public IEnumerable<T> GetFilteredItems(IEnumerable<T> collection)\n{\n foreach (T item in collection)\n if (Matches<T>(item))\n {\n yield return item;\n }\n}\n IEnumerable<MyType> filteredItems = GetFilteredItems(myList);\nforeach (MyType item in filteredItems)\n{\n // do sth with your filtered items\n}\n" }, { "answer_id": 26232, "author": "Tom Lokhorst", "author_id": 2597, "author_profile": "https://Stackoverflow.com/users/2597", "pm_score": 2, "selected": false, "text": "var filteredList = from x in myList\n where x > 7\n select x;\n" }, { "answer_id": 26273, "author": "Jon Erickson", "author_id": 1950, "author_profile": "https://Stackoverflow.com/users/1950", "pm_score": 4, "selected": false, "text": "#region List Filtering\n\nstatic void Main(string[] args)\n{\n ListFiltering();\n Console.ReadLine();\n}\n\nprivate static void ListFiltering()\n{\n var PersonList = new List<Person>();\n\n PersonList.Add(new Person() { Age = 23, Name = \"Jon\", Gender = \"M\" }); //Non-Constructor Object Property Initialization\n PersonList.Add(new Person() { Age = 24, Name = \"Jack\", Gender = \"M\" });\n PersonList.Add(new Person() { Age = 29, Name = \"Billy\", Gender = \"M\" });\n\n PersonList.Add(new Person() { Age = 33, Name = \"Bob\", Gender = \"M\" });\n PersonList.Add(new Person() { Age = 45, Name = \"Frank\", Gender = \"M\" });\n\n PersonList.Add(new Person() { Age = 24, Name = \"Anna\", Gender = \"F\" });\n PersonList.Add(new Person() { Age = 29, Name = \"Sue\", Gender = \"F\" });\n PersonList.Add(new Person() { Age = 35, Name = \"Sally\", Gender = \"F\" });\n PersonList.Add(new Person() { Age = 36, Name = \"Jane\", Gender = \"F\" });\n PersonList.Add(new Person() { Age = 42, Name = \"Jill\", Gender = \"F\" });\n\n //Logic: Show me all males that are less than 30 years old.\n\n Console.WriteLine(\"\");\n //Iterative Method\n Console.WriteLine(\"List Filter Normal Way:\");\n foreach (var p in PersonList)\n if (p.Gender == \"M\" && p.Age < 30)\n Console.WriteLine(p.Name + \" is \" + p.Age);\n\n Console.WriteLine(\"\");\n //Lambda Filter Method\n Console.WriteLine(\"List Filter Lambda Way\");\n foreach (var p in PersonList.Where(p => (p.Gender == \"M\" && p.Age < 30))) //.Where is an extension method\n Console.WriteLine(p.Name + \" is \" + p.Age);\n\n Console.WriteLine(\"\");\n //LINQ Query Method\n Console.WriteLine(\"List Filter LINQ Way:\");\n foreach (var v in from p in PersonList\n where p.Gender == \"M\" && p.Age < 30\n select new { p.Name, p.Age })\n Console.WriteLine(v.Name + \" is \" + v.Age);\n}\n\nprivate class Person\n{\n public Person() { }\n public int Age { get; set; }\n public string Name { get; set; }\n public string Gender { get; set; }\n}\n\n#endregion\n" }, { "answer_id": 3916043, "author": "gouldos", "author_id": 449696, "author_profile": "https://Stackoverflow.com/users/449696", "pm_score": 2, "selected": false, "text": "FindAll list" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2470/" ]
26,230
<p>Over the last few months/years, I have shared a folder or two with numerous people on my domain. How do I easily revoke those shares to keep access to my system nice and tidy?</p>
[ { "answer_id": 26235, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 1, "selected": false, "text": "Administrative Tools > Computer Management > System Tools > Shared Folders > Shares\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29/" ]
26,233
<p>Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.</p>
[ { "answer_id": 26237, "author": "Chris", "author_id": 2134, "author_profile": "https://Stackoverflow.com/users/2134", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Net;\nusing System.IO;\n\npublic class Test\n{\n public static void Main (string[] args)\n {\n if (args == null || args.Length == 0)\n {\n throw new ApplicationException (\"Specify the URI of the resource to retrieve.\");\n }\n WebClient client = new WebClient ();\n\n // Add a user agent header in case the \n // requested URI contains a query.\n\n client.Headers.Add (\"user-agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)\");\n\n Stream data = client.OpenRead (args[0]);\n StreamReader reader = new StreamReader (data);\n string s = reader.ReadToEnd ();\n Console.WriteLine (s);\n data.Close ();\n reader.Close ();\n }\n}\n" }, { "answer_id": 26238, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 7, "selected": true, "text": "public static void DownloadFile(string remoteFilename, string localFilename)\n{\n WebClient client = new WebClient();\n client.DownloadFile(remoteFilename, localFilename);\n}\n" }, { "answer_id": 26242, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 5, "selected": false, "text": "WebClient Client = new WebClient ();\nClient.DownloadFile(\"http://mysite.com/myfile.txt\", \" C:\\myfile.txt\");\n" }, { "answer_id": 25605187, "author": "EKanadily", "author_id": 365867, "author_profile": "https://Stackoverflow.com/users/365867", "pm_score": 3, "selected": false, "text": "public static string downloadWebPage(string theURL)\n {\n //### download a web page to a string\n WebClient client = new WebClient();\n\n client.Headers.Add(\"user-agent\", \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)\");\n\n Stream data = client.OpenRead(theURL);\n StreamReader reader = new StreamReader(data);\n string s = reader.ReadToEnd();\n return s;\n }\n" }, { "answer_id": 27552526, "author": "liang", "author_id": 802589, "author_profile": "https://Stackoverflow.com/users/802589", "pm_score": 3, "selected": false, "text": "public static void DownloadString (string address)\n{\n WebClient client = new WebClient ();\n string reply = client.DownloadString (address);\n\n Console.WriteLine (reply);\n}\n" }, { "answer_id": 54502464, "author": "Amir Astaneh", "author_id": 577543, "author_profile": "https://Stackoverflow.com/users/577543", "pm_score": 2, "selected": false, "text": "// WebClient vs HttpClient vs HttpWebRequest vs RestSharp\n// در نهایت به نظرم روش زیر سریعترین روشه\nHttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);\nRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;\nRequest.Proxy = null;\nRequest.Method = \"GET\";\nusing (WebResponse Response = Request.GetResponse())\n{\n using (StreamReader Reader = new StreamReader(Response.GetResponseStream()))\n {\n return Reader.ReadToEnd();\n }\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2141/" ]
26,255
<p>What JavaScript keywords (function names, variables, etc) are reserved?</p>
[ { "answer_id": 147776, "author": "Joseph Holsten", "author_id": 16981, "author_profile": "https://Stackoverflow.com/users/16981", "pm_score": 6, "selected": false, "text": "break do instanceof typeof\ncase else new var\ncatch finally return void\ncontinue for switch while\ndebugger function this with\ndefault if throw\ndelete in try\n abstract export interface static\nboolean extends long super\nbyte final native synchronized\nchar float package throws\nclass goto private transient\nconst implements protected volatile\ndouble import public \nenum int short\n null\n true\nfalse\n" }, { "answer_id": 12114140, "author": "art4theSould", "author_id": 1623324, "author_profile": "https://Stackoverflow.com/users/1623324", "pm_score": 11, "selected": false, "text": "Let this long package float, \nGoto private class if short.\nWhile protected with debugger case, \nContinue volatile interface.\nInstanceof super synchronized throw, \nExtends final export throws. \n\nTry import double enum? \n- False, boolean, abstract function, \nImplements typeof transient break!\nVoid static, default do, \nSwitch int native new. \nElse, delete null public var \nIn return for const, true, char\n…Finally catch byte.\n" }, { "answer_id": 16651703, "author": "its_me", "author_id": 1071413, "author_profile": "https://Stackoverflow.com/users/1071413", "pm_score": 4, "selected": false, "text": "break, case, catch, continue, debugger, default, delete, do, else, false, finally, for, function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof, var, void, while, with abstract, boolean, byte, char, class, const, double, enum, export, extends, final, float, goto, implements, import, int, interface, let, long, native, package, private, protected, public, short, static, super, synchronized, throws, transient, volatile, yield alert, blur, closed, document, focus, frames, history, innerHeight, innerWidth, length, location, navigator, open, outerHeight, outerWidth, parent, screen, screenX, screenY, statusbar, window" }, { "answer_id": 29122006, "author": "GOTO 0", "author_id": 1083663, "author_profile": "https://Stackoverflow.com/users/1083663", "pm_score": 3, "selected": false, "text": "function isReservedKeyword(wordToCheck) {\n var reservedWord = false;\n if (/^[a-z]+$/.test(wordToCheck)) {\n try {\n eval('var ' + wordToCheck + ' = 1');\n } catch (error) {\n reservedWord = true;\n }\n }\n return reservedWord;\n}\n" }, { "answer_id": 30130726, "author": "GitaarLAB", "author_id": 588079, "author_profile": "https://Stackoverflow.com/users/588079", "pm_score": 2, "selected": false, "text": "addFilter removeFilter" }, { "answer_id": 36193643, "author": "Reikim", "author_id": 4271595, "author_profile": "https://Stackoverflow.com/users/4271595", "pm_score": 0, "selected": false, "text": "alert" }, { "answer_id": 47374050, "author": "starhopperx", "author_id": 8142866, "author_profile": "https://Stackoverflow.com/users/8142866", "pm_score": 2, "selected": false, "text": "break case catch class const continue debugger default delete do else enum export extend false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/399/" ]
26,301
<p>What algorithm taught you the most about programming or a specific language feature?</p> <p>We have all had those moments where all of a sudden we know, just know, we have learned an important lesson for the future based on finally understanding an algorithm written by a programmer a couple of steps up the evolutionary ladder. Whose ideas and code had the magic touch on you?</p>
[ { "answer_id": 26342, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 2, "selected": false, "text": "void InPlaceSwap (int& a, int &b) {\n a ^= b;\n b ^= a;\n a ^= b;\n}\n" }, { "answer_id": 26374, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 0, "selected": false, "text": "void swap(int *p, int *q)\n{\n int temp;\n\n temp = *p;\n *p = *q;\n *q = temp;\n}\n" }, { "answer_id": 28138, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 2, "selected": false, "text": "@sorted = map { $_->[0] }\n sort { $a->[1] cmp $b->[1] }\n map { [$_, foo($_)] }\n @unsorted;\n" }, { "answer_id": 28145, "author": "Alexander Stolz", "author_id": 2450, "author_profile": "https://Stackoverflow.com/users/2450", "pm_score": 2, "selected": false, "text": "qsort [] = []\nqsort (x:xs) = qsort (filter (< x) xs) ++ [x] ++ qsort (filter (>= x) xs)\n" }, { "answer_id": 2383873, "author": "polygenelubricants", "author_id": 276101, "author_profile": "https://Stackoverflow.com/users/276101", "pm_score": 4, "selected": false, "text": "procedure FloydWarshall ()\n for k := 1 to n\n for i := 1 to n\n for j := 1 to n\n path[i][j] = min ( path[i][j], path[i][k]+path[k][j] );\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/269/" ]
26,305
<p>I want to be able to play sound files in my program. Where should I look?</p>
[ { "answer_id": 26311, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 4, "selected": false, "text": "import sun.audio.*; //import the sun.audio package\nimport java.io.*;\n\n//** add this into your application code as appropriate\n// Open an input stream to the audio file.\nInputStream in = new FileInputStream(Filename);\n\n// Create an AudioStream object from the input stream.\nAudioStream as = new AudioStream(in); \n\n// Use the static class member \"player\" from class AudioPlayer to play\n// clip.\nAudioPlayer.player.start(as); \n\n// Similarly, to stop the audio.\nAudioPlayer.player.stop(as); \n" }, { "answer_id": 26318, "author": "pek", "author_id": 2644, "author_profile": "https://Stackoverflow.com/users/2644", "pm_score": 8, "selected": true, "text": ".wav public static synchronized void playSound(final String url) {\n new Thread(new Runnable() {\n // The wrapper thread is unnecessary, unless it blocks on the\n // Clip finishing; see comments.\n public void run() {\n try {\n Clip clip = AudioSystem.getClip();\n AudioInputStream inputStream = AudioSystem.getAudioInputStream(\n Main.class.getResourceAsStream(\"/path/to/sounds/\" + url));\n clip.open(inputStream);\n clip.start(); \n } catch (Exception e) {\n System.err.println(e.getMessage());\n }\n }\n }).start();\n}\n" }, { "answer_id": 15694770, "author": "hamilton.lima", "author_id": 1953431, "author_profile": "https://Stackoverflow.com/users/1953431", "pm_score": 2, "selected": false, "text": "package com.athanazio.jaga.desktop.sound;\n\nimport java.io.BufferedInputStream;\nimport java.io.IOException;\nimport java.io.InputStream;\n\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.AudioInputStream;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.DataLine;\nimport javax.sound.sampled.LineUnavailableException;\nimport javax.sound.sampled.SourceDataLine;\nimport javax.sound.sampled.UnsupportedAudioFileException;\n\npublic class Sound {\n\n AudioInputStream in;\n\n AudioFormat decodedFormat;\n\n AudioInputStream din;\n\n AudioFormat baseFormat;\n\n SourceDataLine line;\n\n private boolean loop;\n\n private BufferedInputStream stream;\n\n // private ByteArrayInputStream stream;\n\n /**\n * recreate the stream\n * \n */\n public void reset() {\n try {\n stream.reset();\n in = AudioSystem.getAudioInputStream(stream);\n din = AudioSystem.getAudioInputStream(decodedFormat, in);\n line = getLine(decodedFormat);\n\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void close() {\n try {\n line.close();\n din.close();\n in.close();\n } catch (IOException e) {\n }\n }\n\n Sound(String filename, boolean loop) {\n this(filename);\n this.loop = loop;\n }\n\n Sound(String filename) {\n this.loop = false;\n try {\n InputStream raw = Object.class.getResourceAsStream(filename);\n stream = new BufferedInputStream(raw);\n\n // ByteArrayOutputStream out = new ByteArrayOutputStream();\n // byte[] buffer = new byte[1024];\n // int read = raw.read(buffer);\n // while( read > 0 ) {\n // out.write(buffer, 0, read);\n // read = raw.read(buffer);\n // }\n // stream = new ByteArrayInputStream(out.toByteArray());\n\n in = AudioSystem.getAudioInputStream(stream);\n din = null;\n\n if (in != null) {\n baseFormat = in.getFormat();\n\n decodedFormat = new AudioFormat(\n AudioFormat.Encoding.PCM_SIGNED, baseFormat\n .getSampleRate(), 16, baseFormat.getChannels(),\n baseFormat.getChannels() * 2, baseFormat\n .getSampleRate(), false);\n\n din = AudioSystem.getAudioInputStream(decodedFormat, in);\n line = getLine(decodedFormat);\n }\n } catch (UnsupportedAudioFileException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (LineUnavailableException e) {\n e.printStackTrace();\n }\n }\n\n private SourceDataLine getLine(AudioFormat audioFormat)\n throws LineUnavailableException {\n SourceDataLine res = null;\n DataLine.Info info = new DataLine.Info(SourceDataLine.class,\n audioFormat);\n res = (SourceDataLine) AudioSystem.getLine(info);\n res.open(audioFormat);\n return res;\n }\n\n public void play() {\n\n try {\n boolean firstTime = true;\n while (firstTime || loop) {\n\n firstTime = false;\n byte[] data = new byte[4096];\n\n if (line != null) {\n\n line.start();\n int nBytesRead = 0;\n\n while (nBytesRead != -1) {\n nBytesRead = din.read(data, 0, data.length);\n if (nBytesRead != -1)\n line.write(data, 0, nBytesRead);\n }\n\n line.drain();\n line.stop();\n line.close();\n\n reset();\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n}\n" }, { "answer_id": 20514020, "author": "Ishwor", "author_id": 2118080, "author_profile": "https://Stackoverflow.com/users/2118080", "pm_score": 3, "selected": false, "text": "import java.io.*;\nimport java.net.URL;\nimport javax.sound.sampled.*;\nimport javax.swing.*;\n\n// To play sound using Clip, the process need to be alive.\n// Hence, we use a Swing application.\npublic class SoundClipTest extends JFrame {\n\n public SoundClipTest() {\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n this.setTitle(\"Test Sound Clip\");\n this.setSize(300, 200);\n this.setVisible(true);\n\n try {\n // Open an audio input stream.\n URL url = this.getClass().getClassLoader().getResource(\"gameover.wav\");\n AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);\n // Get a sound clip resource.\n Clip clip = AudioSystem.getClip();\n // Open audio clip and load samples from the audio input stream.\n clip.open(audioIn);\n clip.start();\n } catch (UnsupportedAudioFileException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (LineUnavailableException e) {\n e.printStackTrace();\n }\n }\n\n public static void main(String[] args) {\n new SoundClipTest();\n }\n}\n" }, { "answer_id": 35162134, "author": "Cyril Duchon-Doris", "author_id": 2832282, "author_profile": "https://Stackoverflow.com/users/2832282", "pm_score": 4, "selected": false, "text": "private static void playSound(String sound){\n // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();\n URL file = cl.getResource(sound);\n final Media media = new Media(file.toString());\n final MediaPlayer mediaPlayer = new MediaPlayer(media);\n mediaPlayer.play();\n}\n static{\n JFXPanel fxPanel = new JFXPanel();\n}\n" }, { "answer_id": 37693420, "author": "Andrew Jenkins", "author_id": 2657020, "author_profile": "https://Stackoverflow.com/users/2657020", "pm_score": 3, "selected": false, "text": "void playSound(String soundFile) {\n File f = new File(\"./\" + soundFile);\n AudioInputStream audioIn = AudioSystem.getAudioInputStream(f.toURI().toURL()); \n Clip clip = AudioSystem.getClip();\n clip.open(audioIn);\n clip.start();\n}\n playSound(\"sounds/effects/sheep1.wav\");\n" }, { "answer_id": 39965540, "author": "Galen Nare", "author_id": 2737479, "author_profile": "https://Stackoverflow.com/users/2737479", "pm_score": 0, "selected": false, "text": "AudioStream String command = \"\\\"C:/Program Files (x86)/Windows Media Player/wmplayer.exe\\\" \\\"C:/song.mp3\\\"\";\ntry {\n Process p = Runtime.getRuntime().exec(command);\ncatch (IOException e) {\n e.printStackTrace();\n}\n p.destroy();\n" }, { "answer_id": 54341775, "author": "Nav", "author_id": 453673, "author_profile": "https://Stackoverflow.com/users/453673", "pm_score": 2, "selected": false, "text": "Applet wav package javaapplication2;\n\nimport java.applet.Applet;\nimport java.applet.AudioClip;\nimport java.io.File;\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\npublic class JavaApplication2 {\n\n public static void main(String[] args) throws MalformedURLException {\n File file = new File(\"/path/to/your/sounds/beep3.wav\");\n URL url = null;\n if (file.canRead()) {url = file.toURI().toURL();}\n System.out.println(url);\n AudioClip clip = Applet.newAudioClip(url);\n clip.play();\n System.out.println(\"should've played by now\");\n }\n}\n//beep3.wav was available from: http://www.pacdv.com/sounds/interface_sound_effects/beep-3.wav\n" }, { "answer_id": 63436083, "author": "Arsen Tagaev", "author_id": 12102080, "author_profile": "https://Stackoverflow.com/users/12102080", "pm_score": 2, "selected": false, "text": "public void makeSound(){\n File lol = new File(\"somesound.wav\");\n \n\n try{\n Clip clip = AudioSystem.getClip();\n clip.open(AudioSystem.getAudioInputStream(lol));\n clip.start();\n } catch (Exception e){\n e.printStackTrace();\n }\n}\n" }, { "answer_id": 67658292, "author": "Adir D", "author_id": 6130501, "author_profile": "https://Stackoverflow.com/users/6130501", "pm_score": 0, "selected": false, "text": "try\n{\n Clip clip = AudioSystem.getClip();\n clip.open(AudioSystem.getAudioInputStream(GuiUtils.class.getResource(\"/sounds/success.wav\")));\n clip.start();\n}\ncatch (Exception e)\n{\n LogUtils.logError(e);\n}\n" }, { "answer_id": 68312041, "author": "devp", "author_id": 8234870, "author_profile": "https://Stackoverflow.com/users/8234870", "pm_score": 1, "selected": false, "text": "import java.net.URL;\nimport java.net.MalformedURLException;\nimport javax.sound.sampled.AudioInputStream;\nimport javax.sound.sampled.AudioSystem;\nimport javax.sound.sampled.AudioFormat;\nimport javax.sound.sampled.Clip;\nimport javax.sound.sampled.LineUnavailableException;\nimport javax.sound.sampled.UnsupportedAudioFileException;\nimport java.io.IOException;\nimport java.io.File;\npublic class SoundClipTest{\n //plays the sound\n public static void playSound(final String path){\n try{\n final File audioFile=new File(path);\n AudioInputStream audioIn=AudioSystem.getAudioInputStream(audioFile);\n Clip clip=AudioSystem.getClip();\n clip.open(audioIn);\n clip.start();\n long duration=getDurationInSec(audioIn);\n //System.out.println(duration);\n //We need to delay it otherwise function will return\n //duration is in seconds we are converting it to milliseconds\n Thread.sleep(duration*1000);\n }catch(LineUnavailableException | UnsupportedAudioFileException | MalformedURLException | InterruptedException exception){\n exception.printStackTrace();\n }\n catch(IOException ioException){\n ioException.printStackTrace();\n }\n }\n //Gives duration in seconds for audio files\n public static long getDurationInSec(final AudioInputStream audioIn){\n final AudioFormat format=audioIn.getFormat();\n double frameRate=format.getFrameRate();\n return (long)(audioIn.getFrameLength()/frameRate);\n }\n ////////main//////\n public static void main(String $[]){\n //SoundClipTest test=new SoundClipTest();\n SoundClipTest.playSound(\"/home/dev/Downloads/mixkit-sad-game-over-trombone-471.wav\");\n }\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
26,323
<p>C#: What is a good Regex to parse hyperlinks and their description?</p> <p>Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag.</p> <p>Please also consider obtaining hyperlinks which have other tags within the <code>&lt;a&gt;</code> tags such as <code>&lt;b&gt;</code> and <code>&lt;i&gt;</code>. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 26328, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 1, "selected": false, "text": "<a href=\"pages/index.php\" title=\"the title\">Text</a>\n\narray(3) { [0]=> string(52) \"Text\" [1]=> string(15) \"pages/index.php\" [2]=> string(4) \"Text\" } \n" }, { "answer_id": 26339, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": true, "text": "<a\\s+href=(?:\"([^\"]+)\"|'([^']+)').*?>(.*?)</a>\n (?:<a.*?href=[\"\"'](?<url>.*?)[\"\"'].*?>)(?<name>(?><a[^<]*>(?<DEPTH>)|</a>(?<-DEPTH>)|.)+)(?(DEPTH)(?!))(?:</a>) \n" }, { "answer_id": 1720232, "author": "James Shaw", "author_id": 189626, "author_profile": "https://Stackoverflow.com/users/189626", "pm_score": 0, "selected": false, "text": "static Regex rHref = new Regex(@\"<a.*?href=[\"\"'](?<url>[^\"\"^']+[.]*?)[\"\"'].*?>(?<keywords>[^<]+[.]*?)</a>\", RegexOptions.IgnoreCase | RegexOptions.Compiled);\npublic void ParseHyperlinks(string html)\n{\n MatchCollection mcHref = rHref.Matches(html);\n\n foreach (Match m in mcHref)\n AddKeywordLink(m.Groups[\"keywords\"].Value, m.Groups[\"url\"].Value);\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2141/" ]
26,354
<p>Does anyone know how to print a barcode to the Intermec PB20 bluetooth printer from a Windows Compact Framework application? We are currently using the Intermec LinePrinter API but have been unable to find a way to print a barcode. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 28168, "author": "Steve", "author_id": 620435, "author_profile": "https://Stackoverflow.com/users/620435", "pm_score": 2, "selected": true, "text": "Intermec.Print.LinePrinter lp;\n\nint escapeCharacter = int.Parse(\"1b\", NumberStyles.HexNumber);\nchar[] toEzPrintMode = new char[] { Convert.ToChar(num2), 'E', 'Z' };\n\nlp = new Intermec.Print.LinePrinter(\"Printer_Config.XML\", \"PrinterPB20_40COL\");\nlp.Open();\n\nlp.Write(charArray2); //switch to ez print mode\n\nstring testBarcode = \"{PRINT:@75,10:PD417,YDIM 6,XDIM 2,COLUMNS 2, SECURITY 3|ABCDEFGHIJKL|}\";\nlp.Write(testBarcode);\n\nlp.Write(\"{LP}\"); //switch from ez print mode back to line printer mode\n\nlp.NewLine();\nlp.Write(\"Test\"); //verify line printer mode is working\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/620435/" ]
26,362
<p>Has anyone managed to use <code>ItemizedOverlays</code> in Android Beta 0.9? I can't get it to work, but I'm not sure if I've done something wrong or if this functionality isn't yet available. </p> <p>I've been trying to use the <code>ItemizedOverlay</code> and <code>OverlayItem</code> classes. Their intended purpose is to simulate map markers (as seen in Google Maps Mashups) but I've had problems getting them to appear on the map.</p> <p>I can add my own custom overlays using a similar technique, it's just the <code>ItemizedOverlays</code> that don't work.</p> <p>Once I've implemented my own <code>ItemizedOverlay</code> (and overridden <code>createItem</code>), creating a new instance of my class seems to work (I can extract <code>OverlayItems</code> from it) but adding it to a map's <code>Overlay</code> list doesn't make it appear as it should.</p> <p>This is the code I use to add the <code>ItemizedOverlay</code> class as an <code>Overlay</code> on to my <code>MapView</code>.</p> <pre><code>// Add the ItemizedOverlay to the Map private void addItemizedOverlay() { Resources r = getResources(); MapView mapView = (MapView)findViewById(R.id.mymapview); List&lt;Overlay&gt; overlays = mapView.getOverlays(); MyItemizedOverlay markers = new MyItemizedOverlay(r.getDrawable(R.drawable.icon)); overlays.add(markers); OverlayItem oi = markers.getItem(0); markers.setFocus(oi); mapView.postInvalidate(); } </code></pre> <p>Where <code>MyItemizedOverlay</code> is defined as:</p> <pre><code>public class MyItemizedOverlay extends ItemizedOverlay&lt;OverlayItem&gt; { public MyItemizedOverlay(Drawable defaultMarker) { super(defaultMarker); populate(); } @Override protected OverlayItem createItem(int index) { Double lat = (index+37.422006)*1E6; Double lng = -122.084095*1E6; GeoPoint point = new GeoPoint(lat.intValue(), lng.intValue()); OverlayItem oi = new OverlayItem(point, "Marker", "Marker Text"); return oi; } @Override public int size() { return 5; } } </code></pre>
[ { "answer_id": 46766, "author": "eon", "author_id": 2000, "author_profile": "https://Stackoverflow.com/users/2000", "pm_score": 7, "selected": true, "text": "Drawable defaultMarker = r.getDrawable(R.drawable.icon);\n\n// You HAVE to specify the bounds! It seems like the markers are drawn\n// through Drawable.draw(Canvas) and therefore must have its bounds set\n// before drawing.\ndefaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),\n defaultMarker.getIntrinsicHeight());\n\nMyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);\noverlays.add(markers);\n" }, { "answer_id": 58889919, "author": "zahra salmaninejad", "author_id": 11372789, "author_profile": "https://Stackoverflow.com/users/11372789", "pm_score": 1, "selected": false, "text": "Drawable defaultMarker = r.getDrawable(R.drawable.icon);\n\ndefaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),\n defaultMarker.getIntrinsicHeight());\n\nMyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);\noverlays.add(markers);\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/822/" ]
26,366
<p>For the past 10 years or so there have been a smattering of articles and papers referencing Christopher Alexander's newer work "The Nature of Order" and how it can be applied to software.</p> <p>Unfortunately, the only works I can find are from James Coplien and Richard Gabriel; there is nothing beyond that, at least from my attempts to find such things through google.</p> <p>Is this kind of discussion happening anywhere?</p> <p>MSN</p> <hr> <p>@Georgia</p> <p>My question isn't about design patterns or pattern languages; it's about trying to see if more of Christopher Alexander's work can be applied to software (which it probably can, since it has even less physical constraints than architecture and building).</p> <p>Design patterns and pattern languages seem to have embraced the structure of Alexander's design patterns, but not many capture the essence. The essence being something beyond solving a problem in a particular context.</p> <p>It's difficult to explain without using some of Alexander's later works as a reference point.</p> <p>Edit: No, I take that back.</p> <p>For example, there's an architectural design pattern that is called Alcoves. The pattern has a context that isn't just rooted in the circumstances of the situation but also rooted in fundamentals about the purpose of buildings: that they are structures to be lived in and must promote living in them. In the case of the Alcove pattern, the context is that you want an area that allows for multiple people to be in the same area doing different things, because it is important for family members to be physically together as well as to be able to do things that tend to distract other family members.</p> <p>Most software design patterns describe a problem in a context, but they make no deeper statement about why the problem is important, or why the problem is something that is fundamental to software. It makes it very easy to apply design patterns inappropriately or blithely, which is the exact opposite of the intent of design patterns to began with.</p> <p>MSN ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 46766, "author": "eon", "author_id": 2000, "author_profile": "https://Stackoverflow.com/users/2000", "pm_score": 7, "selected": true, "text": "Drawable defaultMarker = r.getDrawable(R.drawable.icon);\n\n// You HAVE to specify the bounds! It seems like the markers are drawn\n// through Drawable.draw(Canvas) and therefore must have its bounds set\n// before drawing.\ndefaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),\n defaultMarker.getIntrinsicHeight());\n\nMyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);\noverlays.add(markers);\n" }, { "answer_id": 58889919, "author": "zahra salmaninejad", "author_id": 11372789, "author_profile": "https://Stackoverflow.com/users/11372789", "pm_score": 1, "selected": false, "text": "Drawable defaultMarker = r.getDrawable(R.drawable.icon);\n\ndefaultMarker.setBounds(0, 0, defaultMarker.getIntrinsicWidth(),\n defaultMarker.getIntrinsicHeight());\n\nMyItemizedOverlay markers = new MyItemizedOverlay(defaultMarker);\noverlays.add(markers);\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1799/" ]
26,369
<p>I have a .NET 2.0 Windows Forms application. Where is the best place the store user settings (considering Windows guidelines)?</p> <p>Some people pointed to <code>Application.LocalUserAppDataPath</code>. However, that creates a folder structure like:</p> <blockquote> <p>C:\Documents and Settings\user_name\Local Settings\Application Data\company_name\product_name\product_version\</p> </blockquote> <p>If I release version 1 of my application and store an XML file there, then release version 2, that would change to a different folder, right? I'd prefer to have a single folder, per user, to store settings, regardless of the application version. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 26394, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 7, "selected": true, "text": "// read setting\nstring setting1 = (string)Settings.Default[\"MySetting1\"];\n// save setting\nSettings.Default[\"MySetting2\"] = \"My Setting Value\";\n\n// you can force a save with\nProperties.Settings.Default.Save();\n Properties.Settings.Default.Upgrade(); \n" }, { "answer_id": 31044553, "author": "vitalinvent", "author_id": 2409677, "author_profile": "https://Stackoverflow.com/users/2409677", "pm_score": 1, "selected": false, "text": "Settings.Get(\"name\", \"Ivan\");\n Settings.Set(\"name\", \"John\");\n using System;\nusing System.Collections.Generic;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Windows.Forms;\n public static class Settings\n{\n private static string SECTION = typeof(Settings).Namespace;//\"SETTINGS\";\n private static string settingsPath = Application.StartupPath.ToString() + \"\\\\settings.txt\";\n [DllImport(\"kernel32\")]\n private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);\n [DllImport(\"kernel32\")]\n private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);\n public static String GetString(String name)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(SECTION,name,\"\",temp,255,settingsPath);\n return temp.ToString();\n }\n public static String Get(String name, String defVal)\n {\n return Get(SECTION,name,defVal);\n }\n public static String Get(string _SECTION, String name, String defVal)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(_SECTION, name, \"\", temp, 255, settingsPath);\n return temp.ToString();\n }\n public static Boolean Get(String name, Boolean defVal)\n {\n return Get(SECTION, name, defVal);\n }\n public static Boolean Get(string _SECTION, String name, Boolean defVal)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(_SECTION,name,\"\",temp,255,settingsPath);\n bool retval=false;\n if (bool.TryParse(temp.ToString(),out retval))\n {\n return retval;\n } else\n {\n return retval;\n }\n }\n public static int Get(String name, int defVal)\n {\n return Get(SECTION, name, defVal);\n }\n public static int Get(string _SECTION, String name, int defVal)\n {\n StringBuilder temp = new StringBuilder(255);\n int i = GetPrivateProfileString(SECTION,name,\"\",temp,255,settingsPath);\n int retval=0;\n if (int.TryParse(temp.ToString(),out retval))\n {\n return retval;\n } else\n {\n return retval;\n }\n }\n public static void Set(String name, String val)\n {\n Set(SECTION, name,val);\n }\n public static void Set(string _SECTION, String name, String val)\n {\n WritePrivateProfileString(_SECTION, name, val, settingsPath);\n }\n public static void Set(String name, Boolean val)\n {\n Set(SECTION, name, val);\n }\n public static void Set(string _SECTION, String name, Boolean val)\n {\n WritePrivateProfileString(_SECTION, name, val.ToString(), settingsPath);\n }\n public static void Set(String name, int val)\n {\n Set(SECTION, name, val);\n }\n public static void Set(string _SECTION,String name, int val)\n {\n WritePrivateProfileString(SECTION, name, val.ToString(), settingsPath);\n }\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2868/" ]
26,393
<p>I've seen news of <a href="http://github.com/jeresig/sizzle/tree/master" rel="noreferrer">John Resig's fast new selector engine named Sizzle</a> pop up in quite a few places, but I don't know what a selector engine is, nor have any of the articles given an explanation of what it is. I know Resig is the creator of jQuery, and that Sizzle is something in Javascript, but beyond that I don't know what it is. So, what is a selector engine?</p> <p>Thanks!</p>
[ { "answer_id": 26411, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 7, "selected": true, "text": "$('div')\n" }, { "answer_id": 26418, "author": "dguaraglia", "author_id": 2384, "author_profile": "https://Stackoverflow.com/users/2384", "pm_score": 4, "selected": false, "text": "var paragraphs = selectorengine.select('p.firstParagraph')\n var checkedBoxes = jQuery('form#login input:checked')\n" }, { "answer_id": 26419, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "var foo = document.getElementById('foo');\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
26,433
<p>Say I have three files (template_*.txt):</p> <ul> <li>template_x.txt</li> <li>template_y.txt</li> <li>template_z.txt</li> </ul> <p>I want to copy them to three new files (foo_*.txt). </p> <ul> <li>foo_x.txt </li> <li>foo_y.txt </li> <li>foo_z.txt</li> </ul> <p>Is there some simple way to do that with one command, e.g. </p> <p><code>cp --enableAwesomeness template_*.txt foo_*.txt</code></p>
[ { "answer_id": 26439, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 1, "selected": false, "text": "($op = shift) || die \"Usage: rename perlexpr [filenames]\\n\";\n\nfor (@ARGV) {\n $was = $_;\n eval $op;\n die $@ if $@;\n rename($was,$_) unless $was eq $_;\n}\n rename s/template/foo/ *.txt\n" }, { "answer_id": 26441, "author": "pauldoo", "author_id": 755, "author_profile": "https://Stackoverflow.com/users/755", "pm_score": 1, "selected": false, "text": "for i in template_*.txt; do cp -v \"$i\" \"`echo $i | sed 's%^template_%foo_%'`\"; done\n" }, { "answer_id": 26447, "author": "Chris Bartow", "author_id": 497, "author_profile": "https://Stackoverflow.com/users/497", "pm_score": 2, "selected": false, "text": "for file in template_*.txt ; do cp $file `echo $file | sed 's/template_\\(.*\\)/foo_\\1/'` ; done\n" }, { "answer_id": 26451, "author": "Matt McMinn", "author_id": 1322, "author_profile": "https://Stackoverflow.com/users/1322", "pm_score": 2, "selected": false, "text": "[01:22 PM] matt@Lunchbox:~/tmp/ba$\nls\ntemplate_x.txt template_y.txt template_z.txt\n\n[01:22 PM] matt@Lunchbox:~/tmp/ba$\nfor i in template_*.txt ; do mv $i foo${i:8}; done\n\n[01:22 PM] matt@Lunchbox:~/tmp/ba$\nls\nfoo_x.txt foo_y.txt foo_z.txt\n" }, { "answer_id": 31349, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 0, "selected": false, "text": "$ ls template_*.txt | sed -e 's/^template\\(.*\\)$/cp template\\1 foo\\1/' | ksh -sx\n $ convert rose.jpg rose.png\n $ mogrify -format png *.jpg\n" }, { "answer_id": 63980, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 1, "selected": false, "text": "mmv mmv mcp \"template_*.txt\" \"foo_#1.txt\"\n mmv" }, { "answer_id": 89102, "author": "Roberto Bonvallet", "author_id": 13169, "author_profile": "https://Stackoverflow.com/users/13169", "pm_score": 2, "selected": false, "text": "for f in template_*.txt\ndo\n cp $f ${f/template/foo}\ndone\n for i in x y z\ndo\n cp template_$i foo_$\ndone\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437/" ]
26,450
<p>Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?</p> <ul> <li>Doing <code>session.contains(obj)</code> seems to only return true if the session contains that exact object, not another object with the same ID.</li> <li>Using <code>merge(obj)</code> throws an exception if the object is new</li> </ul>
[ { "answer_id": 26468, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 2, "selected": false, "text": "IPersistable entity = Whatever(); // This is the object we're trying to update\n// (IPersistable has an id field)\nsession.Evict(session.Get(entity.GetType(), entity.Id));\nsession.SaveOrUpdate(entity);\n" }, { "answer_id": 40768, "author": "Georgy Bolyuba", "author_id": 4052, "author_profile": "https://Stackoverflow.com/users/4052", "pm_score": 1, "selected": false, "text": "session.replicate(entity, ReplicationMode.OVERWRITE);\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2875/" ]
26,455
<p>Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach?</p> <p>I came across the <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="noreferrer">Design by Contract</a> approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd.</p>
[ { "answer_id": 26484, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 5, "selected": true, "text": "// @returns null iff x = 0\npublic foo(int x) {\n ...\n}\n public test_foo_returns_null_iff_x_equals_0() {\n assertNull foo(0);\n}\n" }, { "answer_id": 34811, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "null null" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
26,458
<p>Is there any IDE that simplifies creating Swing applications (ideally something along the lines of Visual Studio)</p>
[ { "answer_id": 10298568, "author": "komputisto", "author_id": 629033, "author_profile": "https://Stackoverflow.com/users/629033", "pm_score": 3, "selected": false, "text": "JFrame" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2875/" ]
26,478
<p>I'm having trouble getting the following to work in SQL Server 2k, but it works in 2k5:</p> <pre><code>--works in 2k5, not in 2k create view foo as SELECT usertable.legacyCSVVarcharCol as testvar FROM usertable WHERE rsrcID in ( select val from dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, default) ) --error message: Msg 170, Level 15, State 1, Procedure foo, Line 4 Line 25: Incorrect syntax near '.'. </code></pre> <p>So, legacyCSVVarcharCol is a column containing comma-separated lists of INTs. I realize that this is a huge WTF, but this is legacy code, and there's nothing that can be done about the schema right now. Passing "testvar" as the argument to the function doesn't work in 2k either. In fact, it results in a slightly different (and even weirder error):</p> <pre><code>Msg 155, Level 15, State 1, Line 8 'testvar' is not a recognized OPTIMIZER LOCK HINTS option. </code></pre> <p>Passing a hard-coded string as the argument to fnSplitStringToInt works in both 2k and 2k5.</p> <p>Does anyone know why this doesn't work in 2k? Is this perhaps a known bug in the query planner? Any suggestions for how to make it work? Again, I realize that the real answer is "don't store CSV lists in your DB!", but alas, that's beyond my control.</p> <p>Some sample data, if it helps:</p> <pre><code>INSERT INTO usertable (legacyCSVVarcharCol) values ('1,2,3'); INSERT INTO usertable (legacyCSVVarcharCol) values ('11,13,42'); </code></pre> <p>Note that the data in the table does not seem to matter since this is a syntax error, and it occurs even if usertable is completely empty.</p> <p>EDIT: Realizing that perhaps the initial example was unclear, here are two examples, one of which works and one of which does not, which should highlight the problem that's occurring:</p> <pre><code>--fails in sql2000, works in 2005 SELECT t1.* FROM usertable t1 WHERE 1 in (Select val from fnSplitStringToInt(t1.legacyCSVVarcharCol, ',') ) --works everywhere: SELECT t1.* FROM usertable t1 WHERE 1 in ( Select val from fnSplitStringToInt('1,4,543,56578', ',') ) </code></pre> <p>Note that the only difference is the first argument to fnSplitStringToInt is a column in the case that fails in 2k and a literal string in the case that succeeds in both.</p>
[ { "answer_id": 26577, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 0, "selected": false, "text": "select val \nfrom dbo.fnSplitStringToInt('1,2,3', default)\n" }, { "answer_id": 49638, "author": "MobyDX", "author_id": 3923, "author_profile": "https://Stackoverflow.com/users/3923", "pm_score": 2, "selected": true, "text": "SELECT *, (SELECT TOP 1 val FROM dbo.fnSplitStringToInt(usertable.legacyCSVVarcharCol, ','))\nFROM usertable\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2327/" ]
26,512
<p>I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.</p> <p>How can I do this?</p>
[ { "answer_id": 26553, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 0, "selected": false, "text": "BindingUtils dataProvider BindingUtils.bindSetter(comboBoxDataProviderChanged, comboBox, \"dataProvider\");\n BindingUtils mx.binding.utils BindingUtils" }, { "answer_id": 26563, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 0, "selected": false, "text": "ResultEvent.RESULT" }, { "answer_id": 26695, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "\npublic class FooComboBox extends ComboBox\n{\n private var service:HTTPService = null;\n public function ProjectAutoComplete()\n {\n service = new HTTPService();\n service.url = Application.application.poxmlUrl;\n service.addEventListener(FaultEvent.FAULT,serviceFault);\n service.addEventListener(ResultEvent.RESULT,resultReturned);\n\n\n this.addEventListener(FlexEvent.DATA_CHANGE,dataChange);\n }\n public function init():void\n {\n var postdata:Object = {};\n postdata[\"key\"] = \"ProjectName\";\n postdata[\"accountId\"] = Application.application.accountId\n service.send(postdata);\n }\n private function resultReturned(event:ResultEvent):void\n {\n this.dataProvider = service.lastResult.Array.Element;\n // thought I could do it here...but no luck...\n }\n private function dataChange(e:FlexEvent):void\n {\n // combobox has been databound\n mx.controls.Alert.show(\"databound!\");\n }\n ...\n}\n \nfoo.init();\n" }, { "answer_id": 27467, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 0, "selected": false, "text": "validateNow() resultReturned commitProperties validateNow()" }, { "answer_id": 3366706, "author": "Shashi Penumarthy", "author_id": 367464, "author_profile": "https://Stackoverflow.com/users/367464", "pm_score": 2, "selected": false, "text": "<!-- Assume you have extracted an XMLList out of the result \nand attached it to the collection -->\n<mx:HttpService id=\"svc\" result=\"col.source = event.result.Project\"/>\n<mx:XMLListCollection id=\"col\"/>\n\n<mx:ComboBox id=\"cbProject\" dataProvider=\"{col}\"/>\n // Strategy 1\nChangeWatcher.watch(cbProject, \"dataProvider\", handler) ;\n // Strategy 2\nChangeWatcher.watch(cbProject, [\"dataProvider\", \"source\"], handler) ;\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
26,515
<p>I have a habit of keeping my variable usage to a bare minimum. So I'm wondering if there is any advantage to be gained by the following:</p> <pre><code>$query = $mysqli-&gt;query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30'); // Example 1 $query = $query-&gt;fetch_assoc(); // Example 2 $query_r = $query-&gt;fetch_assoc(); $query-&gt;free(); </code></pre> <p>Now if I'm right Example 1 should be more efficient as <code>$query</code> is <code>unset</code> when I reassign it which should free any memory associated with it. However there is a method (<code>MySQLi_Result::free()</code>) which frees associated memory - is this the same thing?</p> <p>If I don't call <code>::free()</code> to free any memory associated with the result but <code>unset</code> it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas?</p>
[ { "answer_id": 26537, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 4, "selected": true, "text": "free() free() free()" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
26,522
<p>Let's say I have a .NET Array of n number of dimensions. I would like to foreach through the elements and print out something like:</p> <pre><code>[0, 0, 0] = 2 [0, 0, 1] = 32 </code></pre> <p>And so on. I could write a loop using some the Rank and dimension functions to come up with the indices. Is there a built in function instead?</p>
[ { "answer_id": 26582, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": 3, "selected": true, "text": "public static string Format(Array array)\n{\n var builder = new StringBuilder();\n builder.AppendLine(\"Count: \" + array.Length);\n var counter = 0;\n\n var dimensions = new List<int>();\n for (int i = 0; i < array.Rank; i++)\n {\n dimensions.Add(array.GetUpperBound(i) + 1);\n }\n\n foreach (var current in array)\n {\n var index = \"\";\n var remainder = counter;\n foreach (var bound in dimensions)\n {\n index = remainder % bound + \", \" + index;\n remainder = remainder / bound;\n }\n index = index.Substring(0, index.Length - 2);\n\n builder.AppendLine(\" [\" + index + \"] \" + current);\n counter++;\n }\n return builder.ToString();\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632/" ]
26,536
<p>My coworker and I have encountered a nasty situation where we have to use an active X control to manipulate a web camera on a page. </p> <p>Is it possible to assign a javascript event handler to a button in the active x control so that it would fire an action on the page when clicked, or do we have to create a button on the html page itself that manipulates the Active X Control and then can fire any necessary actions on the page?</p>
[ { "answer_id": 26679, "author": "Jared Updike", "author_id": 2543, "author_profile": "https://Stackoverflow.com/users/2543", "pm_score": 2, "selected": false, "text": "function Uploader::MyUpdate()\n{\n // ... code to fetch the current state of various\n // properties from the Uploader object and do something with it\n // for example check Uploader.IsActive and show or hide an HTML div\n}\n" }, { "answer_id": 26684, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 4, "selected": true, "text": "IDispatch" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1942/" ]
26,547
<p>Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it?</p> <p>Basic detection can be done with the URL itself, such as “<a href="http://myblog.blogger.com" rel="nofollow noreferrer">http://myblog.blogger.com</a>” etc. But what if it's self hosted?</p> <p>I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.</p>
[ { "answer_id": 26579, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 1, "selected": false, "text": "<meta content='blogger' name='generator'/>\n" }, { "answer_id": 26589, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 3, "selected": true, "text": "<meta name=\"generator\" content=\"Blogger\" /> \n <meta name=\"Generator\" content=\"Subtext Version 1.9.5.177\" /> \n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
26,551
<p>I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.</p> <p>Here's what the command line looks like:</p> <pre><code>test.cmd admin P@55w0rd &gt; test-log.txt </code></pre>
[ { "answer_id": 26556, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 6, "selected": false, "text": "%%1 if for %" }, { "answer_id": 26702, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 10, "selected": false, "text": "%* echo off\nset arg1=%1\nset arg2=%2\nshift\nshift\nfake-command /u %arg1% /p %arg2% %*\n test-command admin password foo bar\n fake-command /u admin /p password admin password foo bar\n" }, { "answer_id": 26742, "author": "thelsdj", "author_id": 163, "author_profile": "https://Stackoverflow.com/users/163", "pm_score": 7, "selected": false, "text": "IF %1.==. GOTO No1\nIF %2.==. GOTO No2\n... do stuff...\nGOTO End1\n\n:No1\n ECHO No param 1\nGOTO End1\n:No2\n ECHO No param 2\nGOTO End1\n\n:End1\n" }, { "answer_id": 92057, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 9, "selected": true, "text": "@fake-command /u %1 /p %2\n test.cmd admin P@55w0rd > test-log.txt\n %1 %2" }, { "answer_id": 4913598, "author": "SvenVP", "author_id": 605296, "author_profile": "https://Stackoverflow.com/users/605296", "pm_score": 2, "selected": false, "text": "java %~n1\n" }, { "answer_id": 5493124, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 7, "selected": false, "text": "\"&\"^& set var=%1\nset \"var=%1\"\nset var=%~1\nset \"var=%~1\"\n set var=\"&\"&\nset \"var=\"&\"&\"\nset var=\"&\"&\nset \"var=\"&\"&\"\n & @echo off\nSETLOCAL DisableDelayedExpansion\n\nSETLOCAL\nfor %%a in (1) do (\n set \"prompt=\"\n echo on\n for %%b in (1) do rem * #%1#\n @echo off\n) > param.txt\nENDLOCAL\n\nfor /F \"delims=\" %%L in (param.txt) do (\n set \"param1=%%L\"\n)\nSETLOCAL EnableDelayedExpansion\nset \"param1=!param1:*#=!\"\nset \"param1=!param1:~0,-2!\"\necho %%1 is '!param1!'\n echo on rem %2 .. %* \"&\"& echo on * # /? REM rem param1 param1" }, { "answer_id": 10219730, "author": "DearWebby", "author_id": 1342715, "author_profile": "https://Stackoverflow.com/users/1342715", "pm_score": 6, "selected": false, "text": "@echo off\n\nxcopy %1 %2 /D /E /C /Q /H /R /K /Y /Z\n\necho copied %1 to %2\n\npause\n xx c:\\f\\30\\*.* f:\\sites\\30\n Q" }, { "answer_id": 19985230, "author": "CMS_95", "author_id": 2358955, "author_profile": "https://Stackoverflow.com/users/2358955", "pm_score": 3, "selected": false, "text": "%a% set a=100 \necho %a% \nrem output = 100 \n" }, { "answer_id": 22397352, "author": "rightcodeatrighttime", "author_id": 3414206, "author_profile": "https://Stackoverflow.com/users/3414206", "pm_score": 5, "selected": false, "text": "@ECHO OFF\n:Loop\nIF \"%1\"==\"\" GOTO Continue\nSHIFT\nGOTO Loop\n:Continue\n \"%1\"==\"\" %1 IF [%1]==[] IF \"%~1\"==\"\"" }, { "answer_id": 27118914, "author": "Amr Ali", "author_id": 4208440, "author_profile": "https://Stackoverflow.com/users/4208440", "pm_score": 5, "selected": false, "text": "FOR %%A IN (%*) DO (\n REM Now your batch file handles %%A instead of %1\n REM No need to use SHIFT anymore.\n ECHO %%A\n)\n" }, { "answer_id": 34550007, "author": "Love and peace - Joe Codeswell", "author_id": 601770, "author_profile": "https://Stackoverflow.com/users/601770", "pm_score": 5, "selected": false, "text": "@echo off\nrem this file is named echo_3params.cmd\necho %1\necho %2\necho %3\nset v1=%1\nset v2=%2\nset v3=%3\necho v1 equals %v1%\necho v2 equals %v2%\necho v3 equals %v3%\n C:\\Users\\joeco>echo_3params 1abc 2 def 3 ghi\n1abc\n2\ndef\nv1 equals 1abc\nv2 equals 2\nv3 equals def\n\nC:\\Users\\joeco>echo_3params 1abc \"2 def\" \"3 ghi\"\n1abc\n\"2 def\"\n\"3 ghi\"\nv1 equals 1abc\nv2 equals \"2 def\"\nv3 equals \"3 ghi\"\n\nC:\\Users\\joeco>echo_3params 1abc '2 def' \"3 ghi\"\n1abc\n'2\ndef'\nv1 equals 1abc\nv2 equals '2\nv3 equals def'\n\nC:\\Users\\joeco>\n" }, { "answer_id": 35445653, "author": "Evan Kennedy", "author_id": 1572938, "author_profile": "https://Stackoverflow.com/users/1572938", "pm_score": 4, "selected": false, "text": ".bat call myscript.bat some -random=43 extra -greeting=\"hello world\" fluff\n myscript.bat call :read_params %*\n\necho %random%\necho %greeting%\n :read_params\nif not %1/==/ (\n if not \"%__var%\"==\"\" (\n if not \"%__var:~0,1%\"==\"-\" (\n endlocal\n goto read_params\n )\n endlocal & set %__var:~1%=%~1\n ) else (\n setlocal & set __var=%~1\n )\n shift\n goto read_params\n)\nexit /B\n -force -force=true -" }, { "answer_id": 45070967, "author": "kodybrown", "author_id": 139793, "author_profile": "https://Stackoverflow.com/users/139793", "pm_score": 6, "selected": false, "text": ">template.bat [-f] [--flag] [--namedvalue value] arg1 [arg2][arg3][...]\n :init :parse :main >template.bat /?\ntest v1.23\nThis is a sample batch file template,\nproviding command-line arguments and flags.\n\nUSAGE:\ntest.bat [flags] \"required argument\" \"optional argument\"\n\n/?, --help shows this help\n/v, --version shows the version\n/e, --verbose shows detailed output\n-f, --flag value specifies a named parameter value\n\n>template.bat <- throws missing argument error\n(same as /?, plus..)\n**** ****\n**** MISSING \"REQUIRED ARGUMENT\" ****\n**** ****\n\n>template.bat -v\n1.23\n\n>template.bat --version\ntest v1.23\nThis is a sample batch file template,\nproviding command-line arguments and flags.\n\n>template.bat -e arg1\n**** DEBUG IS ON\nUnNamedArgument: \"arg1\"\nUnNamedOptionalArg: not provided\nNamedFlag: not provided\n\n>template.bat --flag \"my flag\" arg1 arg2\nUnNamedArgument: \"arg1\"\nUnNamedOptionalArg: \"arg2\"\nNamedFlag: \"my flag\"\n\n>template.bat --verbose \"argument #1\" --flag \"my flag\" second\n**** DEBUG IS ON\nUnNamedArgument: \"argument #1\"\nUnNamedOptionalArg: \"second\"\nNamedFlag: \"my flag\"\n @::!/dos/rocks\n@echo off\ngoto :init\n\n:header\n echo %__NAME% v%__VERSION%\n echo This is a sample batch file template,\n echo providing command-line arguments and flags.\n echo.\n goto :eof\n\n:usage\n echo USAGE:\n echo %__BAT_NAME% [flags] \"required argument\" \"optional argument\" \n echo.\n echo. /?, --help shows this help\n echo. /v, --version shows the version\n echo. /e, --verbose shows detailed output\n echo. -f, --flag value specifies a named parameter value\n goto :eof\n\n:version\n if \"%~1\"==\"full\" call :header & goto :eof\n echo %__VERSION%\n goto :eof\n\n:missing_argument\n call :header\n call :usage\n echo.\n echo **** ****\n echo **** MISSING \"REQUIRED ARGUMENT\" ****\n echo **** ****\n echo.\n goto :eof\n\n:init\n set \"__NAME=%~n0\"\n set \"__VERSION=1.23\"\n set \"__YEAR=2017\"\n\n set \"__BAT_FILE=%~0\"\n set \"__BAT_PATH=%~dp0\"\n set \"__BAT_NAME=%~nx0\"\n\n set \"OptHelp=\"\n set \"OptVersion=\"\n set \"OptVerbose=\"\n\n set \"UnNamedArgument=\"\n set \"UnNamedOptionalArg=\"\n set \"NamedFlag=\"\n\n:parse\n if \"%~1\"==\"\" goto :validate\n\n if /i \"%~1\"==\"/?\" call :header & call :usage \"%~2\" & goto :end\n if /i \"%~1\"==\"-?\" call :header & call :usage \"%~2\" & goto :end\n if /i \"%~1\"==\"--help\" call :header & call :usage \"%~2\" & goto :end\n\n if /i \"%~1\"==\"/v\" call :version & goto :end\n if /i \"%~1\"==\"-v\" call :version & goto :end\n if /i \"%~1\"==\"--version\" call :version full & goto :end\n\n if /i \"%~1\"==\"/e\" set \"OptVerbose=yes\" & shift & goto :parse\n if /i \"%~1\"==\"-e\" set \"OptVerbose=yes\" & shift & goto :parse\n if /i \"%~1\"==\"--verbose\" set \"OptVerbose=yes\" & shift & goto :parse\n\n if /i \"%~1\"==\"--flag\" set \"NamedFlag=%~2\" & shift & shift & goto :parse\n if /i \"%~1\"==\"-f\" set \"NamedFlag=%~2\" & shift & shift & goto :parse\n\n if not defined UnNamedArgument set \"UnNamedArgument=%~1\" & shift & goto :parse\n if not defined UnNamedOptionalArg set \"UnNamedOptionalArg=%~1\" & shift & goto :parse\n\n shift\n goto :parse\n\n:validate\n if not defined UnNamedArgument call :missing_argument & goto :end\n\n:main\n if defined OptVerbose (\n echo **** DEBUG IS ON\n )\n\n echo UnNamedArgument: \"%UnNamedArgument%\"\n\n if defined UnNamedOptionalArg echo UnNamedOptionalArg: \"%UnNamedOptionalArg%\"\n if not defined UnNamedOptionalArg echo UnNamedOptionalArg: not provided\n\n if defined NamedFlag echo NamedFlag: \"%NamedFlag%\"\n if not defined NamedFlag echo NamedFlag: not provided\n\n:end\n call :cleanup\n exit /B\n\n:cleanup\n REM The cleanup function is only really necessary if you\n REM are _not_ using SETLOCAL.\n set \"__NAME=\"\n set \"__VERSION=\"\n set \"__YEAR=\"\n\n set \"__BAT_FILE=\"\n set \"__BAT_PATH=\"\n set \"__BAT_NAME=\"\n\n set \"OptHelp=\"\n set \"OptVersion=\"\n set \"OptVerbose=\"\n\n set \"UnNamedArgument=\"\n set \"UnNamedArgument2=\"\n set \"NamedFlag=\"\n\n goto :eof\n" }, { "answer_id": 50653047, "author": "Garret Wilson", "author_id": 421049, "author_profile": "https://Stackoverflow.com/users/421049", "pm_score": 4, "selected": false, "text": "foobar --foo default --bar --baz foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]\n @ECHO OFF\nSETLOCAL\nREM FooBar parameter demo\nREM By Garret Wilson\n\nSET CMD=%~1\n\nIF \"%CMD%\" == \"\" (\n GOTO usage\n)\nSET FOO=\nSET DEFAULT_FOO=default\nSET BAR=\nSET BAZ=\n\nSHIFT\n:args\nSET PARAM=%~1\nSET ARG=%~2\nIF \"%PARAM%\" == \"--foo\" (\n SHIFT\n IF NOT \"%ARG%\" == \"\" (\n IF NOT \"%ARG:~0,2%\" == \"--\" (\n SET FOO=%ARG%\n SHIFT\n ) ELSE (\n SET FOO=%DEFAULT_FOO%\n )\n ) ELSE (\n SET FOO=%DEFAULT_FOO%\n )\n) ELSE IF \"%PARAM%\" == \"--bar\" (\n SHIFT\n IF NOT \"%ARG%\" == \"\" (\n SET BAR=%ARG%\n SHIFT\n ) ELSE (\n ECHO Missing bar value. 1>&2\n ECHO:\n GOTO usage\n )\n) ELSE IF \"%PARAM%\" == \"--baz\" (\n SHIFT\n SET BAZ=true\n) ELSE IF \"%PARAM%\" == \"\" (\n GOTO endargs\n) ELSE (\n ECHO Unrecognized option %1. 1>&2\n ECHO:\n GOTO usage\n)\nGOTO args\n:endargs\n\nECHO Command: %CMD%\nIF NOT \"%FOO%\" == \"\" (\n ECHO Foo: %FOO%\n)\nIF NOT \"%BAR%\" == \"\" (\n ECHO Bar: %BAR%\n)\nIF \"%BAZ%\" == \"true\" (\n ECHO Baz\n)\n\nREM TODO do something with FOO, BAR, and/or BAZ\nGOTO :eof\n\n:usage\nECHO FooBar\nECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]\nEXIT /B 1\n SETLOCAL SET FOO= %~1 IF \"%ARG%\" == \"\" IF [%ARG%] == [] [ ] SHIFT IF %~1 IF %~1 %~2 IF SHIFT SHIFT %~1 %~1 IF NOT \"%ARG:~0,2%\" == \"--\" SHIFT SET FOO=%DEFAULT_FOO% IF \"%FOO%\" == \"\" SET FOO=%DEFAULT_FOO% IF NOT \"%ARG%\" == \"\" IF \"%PARAM%\" == \"--foo\" %FOO% --foo %FOO% ECHO Missing bar value. 1>&2 ECHO:" }, { "answer_id": 51156281, "author": "Amol Patil", "author_id": 1811749, "author_profile": "https://Stackoverflow.com/users/1811749", "pm_score": 2, "selected": false, "text": "echo off\necho \"Batch started\"\nset arg1=%1\necho \"arg1 is %arg1%\"\necho on\npause\n call \"C:\\Temp\\Test1.bat\" pass123\n YourLocalPath>call \"C:\\Temp\\test.bat\" pass123\n\nYourLocalPath>echo off\n\"Batch started\"\n\"arg1 is pass123\"\n\nYourLocalPath>pause\nPress any key to continue . . .\n" }, { "answer_id": 54635244, "author": "Io-oI", "author_id": 8177207, "author_profile": "https://Stackoverflow.com/users/8177207", "pm_score": 3, "selected": false, "text": "?*&|<> @echo off && setlocal EnableDelayedExpansion\n\n for %%Z in (%*)do set \"_arg_=%%Z\" && set/a \"_cnt+=1+0\" && (\n call set \"_arg_[!_cnt!]=!_arg_!\" && for /l %%l in (!_cnt! 1 !_cnt!\n )do echo/ The argument n:%%l is: !_arg_[%%l]!\n )\n\ngoto :eof \n @echo off && setlocal EnableDelayedExpansion\n\n for %%Z in (%*)do set \"_arg_=%%Z\" && set/a \"_cnt+=1+0\" && call set \"_arg_[!_cnt!]=!_arg_!\"\n \n fake-command /u !_arg_[1]! /p !_arg_[2]! > test-log.txt\n \n" }, { "answer_id": 58447844, "author": "The Godfather", "author_id": 2261656, "author_profile": "https://Stackoverflow.com/users/2261656", "pm_score": 5, "selected": false, "text": "set argument1=%1\nset argument2=%2\necho %argument1%\necho %argument2%\n %1 %2 Directory> batchFileName admin P@55w0rd \n admin\nP@55w0rd\n" }, { "answer_id": 64749745, "author": "npocmaka", "author_id": 388389, "author_profile": "https://Stackoverflow.com/users/388389", "pm_score": 2, "selected": false, "text": "@echo off\n\nsetlocal enableDelayedExpansion\n\n::::: asigning arguments as a key-value pairs:::::::::::::\nset counter=0\nfor %%# in (%*) do ( \n set /a counter=counter+1\n set /a even=counter%%2\n \n if !even! == 0 (\n echo setting !prev! to %%#\n set \"!prev!=%%~#\"\n )\n set \"prev=%%~#\"\n)\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n:: showing the assignments\necho %one% %two% %three% %four% %five%\n\nendlocal\n c:>argumentsDemo.bat one 1 \"two\" 2 three 3 four 4 \"five\" 5\n1 2 3 4 5\n @echo off\n\nif defined variable1 (\n echo %variable1%\n)\n\nif defined variable2 (\n echo %variable2%\n)\n c:\\>set variable1=1\n\nc:\\>set variable2=2\n\nc:\\>argumentsTest.bat\n1\n2\n @echo off\n\nsetlocal\n::::::::::\nset \"VALUES_FILE=E:\\scripts\\values.txt\"\n:::::::::::\n\n\nfor /f \"usebackq eol=: tokens=* delims=\" %%# in (\"%VALUES_FILE%\") do set \"%%#\"\n\necho %key1% %key2% %some_other_key%\n\nendlocal\n :::: use EOL=: in the FOR loop to use it as a comment\n\nkey1=value1\n\nkey2=value2\n\n:::: do not left spaces arround the =\n:::: or at the begining of the line\n\nsome_other_key=something else\n\nand_one_more=more\n" }, { "answer_id": 67860255, "author": "i Mr Oli i", "author_id": 11199164, "author_profile": "https://Stackoverflow.com/users/11199164", "pm_score": 5, "selected": false, "text": "%1 %2 %3 %1 %2 @echo off\necho %1\n C:> script.bat Hello\n Hello\n @echo off\necho Your name is: %1\necho Your age is: %2\n C:> script.bat Oliver 1000\n Your name is: Oliver\nYour age is: 1000\n" }, { "answer_id": 69130861, "author": "Zimba", "author_id": 5958708, "author_profile": "https://Stackoverflow.com/users/5958708", "pm_score": 0, "selected": false, "text": "set /p" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
26,552
<p>What are the advantages and disadvantages of turning <strong><code>NOCOUNT</code></strong> off in SQL server queries? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 26588, "author": "jerhinesmith", "author_id": 1108, "author_profile": "https://Stackoverflow.com/users/1108", "pm_score": 0, "selected": false, "text": "Print" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2141/" ]
26,559
<p>I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems. But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much. </p>
[ { "answer_id": 26597, "author": "Ryan Doherty", "author_id": 956, "author_profile": "https://Stackoverflow.com/users/956", "pm_score": 6, "selected": true, "text": ".htaccess .htaccess .htaccess" }, { "answer_id": 26770, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 3, "selected": false, "text": ".htaccess" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2687/" ]
26,567
<p>I have a report with many fields that I'm trying to get down to 1 page horizontally (I don't care whether it's 2 or 200 pages vertically... just don't want to have to deal with 2 pages wide by x pages long train-wreck). That said, it deals with contact information.</p> <p>My idea was to do:</p> <pre><code>Name: Address: City: State: ... Jon Doe Addr1 ThisTown XX ... Addr2 Addr3 ----------------------------------------------- Jane Doe Addr1 ThisTown XX ... Addr2 Addr3 ----------------------------------------------- </code></pre> <p>Is there some way to set a <code>textbox</code> to be multi-line (or the SQL result)? Have I missed something bloody obvious?</p> <hr> <p>The CanGrow Property is on by default, and I've double checked that this is true. My problem is that I don't know how to force a line-break. I get the 3 address fields that just fills a line, then wraps to another. I've tried <code>/n</code>, <code>\n</code> (since I can never remember which is the correct slash to put), <code>&lt;br&gt;</code>, <code>&lt;br /&gt;</code> (since the report will be viewed in a ReportViewer control in an ASP.NET website). I can't think of any other ways to wrap the text. </p> <p>Is there some way to get the results from the database as 3 lines of text/characters? ­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 30409, "author": "Pulsehead", "author_id": 2156, "author_profile": "https://Stackoverflow.com/users/2156", "pm_score": 6, "selected": true, "text": "= Fields!Addr1.Value + VbCrLf + \n Fields!Addr2.Value + VbCrLf + \n Fields!Addr3.Value\n" }, { "answer_id": 3582842, "author": "Sam", "author_id": 432755, "author_profile": "https://Stackoverflow.com/users/432755", "pm_score": 3, "selected": false, "text": "chr(10) =REPLACE(Fields!Addr1.Value, CHR(10), vbCrLf)\n" }, { "answer_id": 16785761, "author": "Adriaan Davel", "author_id": 776271, "author_profile": "https://Stackoverflow.com/users/776271", "pm_score": 3, "selected": false, "text": "=REPLACE(Fields!Text.Value, CHR(13), vbCrLf)\n" }, { "answer_id": 41986590, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "= Fields!Field1.Value + System.Environment.NewLine + Fields!Field2.Value\n" }, { "answer_id": 45657284, "author": "Hemal", "author_id": 2270492, "author_profile": "https://Stackoverflow.com/users/2270492", "pm_score": 0, "selected": false, "text": "<br/>" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156/" ]
26,570
<p>I'm looking for a way to get the size of an instance of a reference type. sizeof is only for value types. Is this possible?</p>
[ { "answer_id": 6580593, "author": "serhio", "author_id": 185593, "author_profile": "https://Stackoverflow.com/users/185593", "pm_score": 1, "selected": false, "text": "Dim myObjectSize As Long\n\nDim ms As New IO.MemoryStream\nDim bf As New Runtime.Serialization.Formatters.Binary.BinaryFormatter()\nbf.Serialize(ms, myObject)\nmyObjectSize = ms.Position\n" }, { "answer_id": 6668193, "author": "GrantJ", "author_id": 232571, "author_profile": "https://Stackoverflow.com/users/232571", "pm_score": 2, "selected": false, "text": "Measuring Object:\niter working set size estimate\n-1 11190272\n1000000 85995520 74.805248\n2000000 159186944 73.998336\n3000000 231473152 73.4276266666667\n4000000 306401280 73.802752\n5000000 379092992 73.580544\n6000000 451387392 73.3661866666667\n7000000 524378112 73.3125485714286\n8000000 600096768 73.613312\n9000000 676405248 73.9127751111111\nAverage size: 73.7577032239859\nMeasuring LinkedListNode<Object>:\niter working set size estimate\n-1 34168832\n1000000 147959808 113.790976\n2000000 268963840 117.397504\n3000000 387796992 117.876053333333\n4000000 507973632 118.4512\n5000000 628379648 118.8421632\n6000000 748834816 119.110997333333\n7000000 869265408 119.299510857143\n8000000 993509376 119.917568\n9000000 1114038272 119.985493333333\nAverage size: 118.296829561905\nEstimated Object size: 29.218576886067\nEstimated LinkedListNode<reference type> size: 44.5391263379189\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
26,594
<p>What libraries/methods do you know of that can do some basic HTML representation in Swing? Can you comment on your experience?</p>
[ { "answer_id": 24264560, "author": "Paolo Fulgoni", "author_id": 323447, "author_profile": "https://Stackoverflow.com/users/323447", "pm_score": 1, "selected": false, "text": "BrowserPane JEditorPane JScrollPane BrowserPane browserPane = new BrowserPane();\nJScrollPane scrollPane = new JScrollPane(browserPane);\nsomeContainer.add(scrollPane);\n\nbrowserPane.setText(\"<html><b>Some HTML here</b></html>\");\n// or...\nbrowserPane.setPage(new URL(\"http://en.wikipedia.org\"));\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
26,595
<p>Is there any difference between:</p> <pre><code>if foo is None: pass </code></pre> <p>and</p> <pre><code>if foo == None: pass </code></pre> <p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p>
[ { "answer_id": 26611, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 9, "selected": true, "text": "is True == __eq__() \n>>> class Foo(object):\n def __eq__(self, other):\n return True\n\n>>> f = Foo()\n>>> f == None\nTrue\n>>> f is None\nFalse\n" }, { "answer_id": 26654, "author": "Stephen Pellicer", "author_id": 360, "author_profile": "https://Stackoverflow.com/users/360", "pm_score": 3, "selected": false, "text": "list1 = [1, 2, 3]\nlist2 = [1, 2, 3]\nif list1==list2: print \"Equal\"\nif list1 is list2: print \"Same\"\n" }, { "answer_id": 26963, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 3, "selected": false, "text": "if foo:\n #foo isn't None\nelse:\n #foo is None\n" }, { "answer_id": 28067, "author": "Tendayi Mawushe", "author_id": 2979, "author_profile": "https://Stackoverflow.com/users/2979", "pm_score": 5, "selected": false, "text": "if foo:\n # do something\n if x is not None:\n # do something\n" }, { "answer_id": 585491, "author": "Mykola Kharechko", "author_id": 69885, "author_profile": "https://Stackoverflow.com/users/69885", "pm_score": 4, "selected": false, "text": "(ob1 is ob2) (id(ob1) == id(ob2))" }, { "answer_id": 2932590, "author": "mthurlin", "author_id": 39991, "author_profile": "https://Stackoverflow.com/users/39991", "pm_score": 4, "selected": false, "text": "foo is None __eq__ foo is None None" }, { "answer_id": 5451786, "author": "ncmathsadist", "author_id": 467379, "author_profile": "https://Stackoverflow.com/users/467379", "pm_score": 1, "selected": false, "text": "None >>> x = None\n>>> y = None\n>>> x == y\nTrue\n>>> x is y\nTrue\n>>> \n None x == None x is None x == None" }, { "answer_id": 16636124, "author": "Bleeding Fingers", "author_id": 1309352, "author_profile": "https://Stackoverflow.com/users/1309352", "pm_score": 2, "selected": false, "text": "is object id is object bool int string NoneType >>> int(1) is int(1)\nTrue\n>>> str(\"abcd\") is str(\"abcd\")\nTrue\n>>> bool(1) is bool(2)\nTrue\n>>> bool(0) is bool(0)\nTrue\n>>> bool(0)\nFalse\n>>> bool(1)\nTrue\n NoneType" }, { "answer_id": 16636358, "author": "Thijs van Dien", "author_id": 1163893, "author_profile": "https://Stackoverflow.com/users/1163893", "pm_score": 3, "selected": false, "text": "is" }, { "answer_id": 27559554, "author": "Chillar Anand", "author_id": 2698552, "author_profile": "https://Stackoverflow.com/users/2698552", "pm_score": 3, "selected": false, "text": "is foo is none == __eq__() In [102]: x, y, z = 2, 2, 2.0\n\nIn [103]: id(x), id(y), id(z)\nOut[103]: (38641984, 38641984, 48420880)\n\nIn [104]: x is y\nOut[104]: True\n\nIn [105]: x == y\nOut[105]: True\n\nIn [106]: x is z\nOut[106]: False\n\nIn [107]: x == z\nOut[107]: True\n None None is None In [101]: None is None\nOut[101]: True\n" }, { "answer_id": 55489100, "author": "Aks", "author_id": 4417090, "author_profile": "https://Stackoverflow.com/users/4417090", "pm_score": 0, "selected": false, "text": "a is b # returns true if they a and b are true alias\na == b # returns true if they are true alias or they have values that are deemed equivalence \n\n\na = [1,3,4]\nb = a[:] #creating copy of list\na is b # if gives false\nFalse\na == b # gives true\nTrue\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/156/" ]
26,620
<p>In my web app, I submit some form fields with jQuery's <code>$.getJSON()</code> method. I am having some problems with the encoding. The character-set of my app is <code>charset=ISO-8859-1</code>, but I think these fields are submitted with <code>UTF-8</code>. </p> <p>How I can set encoding used in <code>$.getJSON</code> calls? </p>
[ { "answer_id": 26681, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 6, "selected": true, "text": "$.ajax() contentType success error <div id=\"success\"></div> <div id=\"error\"></div> $.ajax({\n type: \"POST\",\n url: \"SomePage.aspx/GetSomeObjects\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n data: \"{id: '\" + someId + \"'}\",\n success: function(json) {\n $(\"#success\").html(\"json.length=\" + json.length);\n itemAddCallback(json);\n },\n error: function (xhr, textStatus, errorThrown) {\n $(\"#error\").html(xhr.responseText);\n }\n});\n" }, { "answer_id": 27023, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 6, "selected": false, "text": "$.getJSON() $.ajaxSetup({\n scriptCharset: \"utf-8\",\n contentType: \"application/json; charset=utf-8\"\n});\n utf-8 contentType : content-type application/x-www-form-urlencoded scriptCharset : jsonp script" }, { "answer_id": 8707420, "author": "Anderson Mao", "author_id": 818400, "author_profile": "https://Stackoverflow.com/users/818400", "pm_score": 1, "selected": false, "text": "encodeURI() URLDecoder.decode() $.getJSON(\n url,\n {\n \"user\": encodeURI(JSON.stringify(user))\n },\n onSuccess\n);\n java.net.URLDecoder.decode(params.user, \"UTF-8\");" }, { "answer_id": 26887335, "author": "Vipin Kohli", "author_id": 3167919, "author_profile": "https://Stackoverflow.com/users/3167919", "pm_score": 0, "selected": false, "text": "function decode_utf8(s) { \n return decodeURIComponent(escape(s)); \n}\n" }, { "answer_id": 58890056, "author": "zahra salmaninejad", "author_id": 11372789, "author_profile": "https://Stackoverflow.com/users/11372789", "pm_score": 0, "selected": false, "text": "$.ajaxSetup({\n scriptCharset: \"utf-8\",\n contentType: \"application/json; charset=utf-8\"\n});\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
26,652
<p>Is there a way to make a TSQL variable constant?</p>
[ { "answer_id": 26655, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 0, "selected": false, "text": "DECLARE @two INT\nSET @two = 2\n" }, { "answer_id": 26656, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 7, "selected": true, "text": "CREATE FUNCTION fnConstant()\nRETURNS INT\nAS\nBEGIN\n RETURN 2\nEND\nGO\n\nSELECT dbo.fnConstant()\n" }, { "answer_id": 26673, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 3, "selected": false, "text": "declare @MY_VALUE as int\n" }, { "answer_id": 26675, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "declare @myvalue as int\nset @myvalue = 5\nset @myvalue = 10--oops we just changed it\n" }, { "answer_id": 26676, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "ConstantValue" }, { "answer_id": 12723310, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 5, "selected": false, "text": "DECLARE @Constant INT = 123;\n\nSELECT * \nFROM [some_relation] \nWHERE [some_attribute] = @Constant\nOPTION( OPTIMIZE FOR (@Constant = 123))\n" }, { "answer_id": 13685800, "author": "Tony Wall", "author_id": 1080914, "author_profile": "https://Stackoverflow.com/users/1080914", "pm_score": -1, "selected": false, "text": "use tempdb\ngo\ncreate function dbo.MySchemaVersion()\nreturns int\nas\nbegin\n return 123\nend\ngo\n\nuse master\ngo\n\n-- Big long database create script with multiple batches...\nprint 'Creating database schema version ' + CAST(tempdb.dbo.MySchemaVersion() as NVARCHAR) + '...'\ngo\n-- ...\ngo\n-- ...\ngo\nuse MyDatabase\ngo\n\n-- Update schema version with constant at end (not normally possible as GO puts\n-- local @variables out of scope)\ninsert MyConfigTable values ('SchemaVersion', tempdb.dbo.MySchemaVersion())\ngo\n\n-- Clean-up\nuse tempdb\ndrop function MySchemaVersion\ngo\n" }, { "answer_id": 14096239, "author": "Robert", "author_id": 1938754, "author_profile": "https://Stackoverflow.com/users/1938754", "pm_score": 3, "selected": false, "text": "IF OBJECT_ID('fnFalse') IS NOT NULL\nDROP FUNCTION fnFalse\nGO\n\nIF OBJECT_ID('fnTrue') IS NOT NULL\nDROP FUNCTION fnTrue\nGO\n\nCREATE FUNCTION fnTrue() RETURNS INT WITH SCHEMABINDING\nAS\nBEGIN\nRETURN 1\nEND\nGO\n\nCREATE FUNCTION fnFalse() RETURNS INT WITH SCHEMABINDING\nAS\nBEGIN\nRETURN ~ dbo.fnTrue()\nEND\nGO\n\nDECLARE @TimeStart DATETIME = GETDATE()\nDECLARE @Count INT = 100000\nWHILE @Count > 0 BEGIN\nSET @Count -= 1\n\nDECLARE @Value BIT\nSELECT @Value = dbo.fnTrue()\nIF @Value = 1\n SELECT @Value = dbo.fnFalse()\nEND\nDECLARE @TimeEnd DATETIME = GETDATE()\nPRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using function'\nGO\n\nDECLARE @TimeStart DATETIME = GETDATE()\nDECLARE @Count INT = 100000\nDECLARE @FALSE AS BIT = 0\nDECLARE @TRUE AS BIT = ~ @FALSE\n\nWHILE @Count > 0 BEGIN\nSET @Count -= 1\n\nDECLARE @Value BIT\nSELECT @Value = @TRUE\nIF @Value = 1\n SELECT @Value = @FALSE\nEND\nDECLARE @TimeEnd DATETIME = GETDATE()\nPRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using local variable'\nGO\n\nDECLARE @TimeStart DATETIME = GETDATE()\nDECLARE @Count INT = 100000\n\nWHILE @Count > 0 BEGIN\nSET @Count -= 1\n\nDECLARE @Value BIT\nSELECT @Value = 1\nIF @Value = 1\n SELECT @Value = 0\nEND\nDECLARE @TimeEnd DATETIME = GETDATE()\nPRINT CAST(DATEDIFF(ms, @TimeStart, @TimeEnd) AS VARCHAR) + ' elapsed, using hard coded values'\nGO\n" }, { "answer_id": 32373858, "author": "mbobka", "author_id": 2201119, "author_profile": "https://Stackoverflow.com/users/2201119", "pm_score": 5, "selected": false, "text": "CREATE SCHEMA ShipMethod\nGO\n-- Each view can only have one row.\n-- Create one column for each desired constant.\n-- Each column is restricted to a single value.\nCREATE VIEW ShipMethod.ShipMethodID AS\nSELECT CAST(1 AS INT) AS [XRQ - TRUCK GROUND]\n ,CAST(2 AS INT) AS [ZY - EXPRESS]\n ,CAST(3 AS INT) AS [OVERSEAS - DELUXE]\n ,CAST(4 AS INT) AS [OVERNIGHT J-FAST]\n ,CAST(5 AS INT) AS [CARGO TRANSPORT 5]\n SELECT h.*\nFROM Sales.SalesOrderHeader h\nJOIN ShipMethod.ShipMethodID const\n ON h.ShipMethodID = const.[OVERNIGHT J-FAST]\n SELECT h.*\nFROM Sales.SalesOrderHeader h\nWHERE h.ShipMethodID = (SELECT TOP 1 [OVERNIGHT J-FAST] FROM ShipMethod.ShipMethodID)\n" }, { "answer_id": 39659808, "author": "Michal D.", "author_id": 2150054, "author_profile": "https://Stackoverflow.com/users/2150054", "pm_score": 3, "selected": false, "text": "DECLARE @var varchar(100) = 'some text'\nDECLARE @sql varchar(MAX)\nSET @sql = 'SELECT * FROM table WHERE col = '''+@var+''''\nEXEC (@sql)\n" }, { "answer_id": 48013270, "author": "monkeyhouse", "author_id": 1778606, "author_profile": "https://Stackoverflow.com/users/1778606", "pm_score": 3, "selected": false, "text": " CREATE VIEW ShipMethods AS\n SELECT CAST(1 AS INT) AS [XRQ - TRUCK GROUND]\n ,CAST(2 AS INT) AS [ZY - EXPRESS]\n ,CAST(3 AS INT) AS [OVERSEAS - DELUXE]\n , CAST(4 AS INT) AS [OVERNIGHT J-FAST]\n ,CAST(5 AS INT) AS [CARGO TRANSPORT 5]\n SELECT h.*\nFROM Sales.SalesOrderHeader \nWHERE ShipMethodID = ( select [OVERNIGHT J-FAST] from ShipMethods )\n" }, { "answer_id": 48025646, "author": "Gert-Jan", "author_id": 8992916, "author_profile": "https://Stackoverflow.com/users/8992916", "pm_score": 1, "selected": false, "text": "Declare Constant @supplement int = 240\nSELECT price + @supplement\nFROM what_does_it_cost\n SELECT price + 240/*CONSTANT:supplement*/\nFROM what_does_it_cost\n" }, { "answer_id": 74219496, "author": "JensG", "author_id": 19150755, "author_profile": "https://Stackoverflow.com/users/19150755", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION fnConstant() RETURNS INT AS BEGIN RETURN 2 END GO SELECT is_inlineable FROM sys.sql_modules WHERE [object_id]=OBJECT_ID('dbo.fnConstant'); SELECT dbo.fnConstant() CREATE FUNCTION fnConstant1()\nRETURNS INT\nAS\nBEGIN\n RETURN 1\nEND\nGO\n DROP TABLE IF EXISTS #temp ; \ncreate table #temp (value_int INT) \nDECLARE @counter INT; \nSET @counter = 0 \nWHILE @counter <= 500000 \nBEGIN \n INSERT INTO #temp VALUES (1); \n SET @counter = @counter +1 \nEND \nSET @counter = 0\n \nWHILE @counter <= 3 \nBEGIN \n INSERT INTO #temp VALUES (2);\n SET @counter = @counter +1\nEND\ncreate index i_temp on #temp (value_int);\n select * from #temp where value_int = dbo.fnConstant1(); --Returns 500001 rows select * from #temp where value_int = dbo.fnConstant(); --Returns 4rows" }, { "answer_id": 74360479, "author": "pricerc", "author_id": 2258866, "author_profile": "https://Stackoverflow.com/users/2258866", "pm_score": 0, "selected": false, "text": "create table #testTable (id int identity(1, 1) primary key, value tinyint);\n insert @testTable(value)\nselect case when value > 127\n then @FALSE\n else @TRUE\nend\nfrom #testTable with(nolock)\n set nocount on;\ngo\n\n-- create test data table\ndrop table if exists #testTable;\ncreate table #testTable (id int identity(1, 1) primary key, value tinyint);\n\n-- populate test data\ninsert #testTable (value)\nselect top (1000000) convert(binary (1), newid()) \nfrom sys.all_objects a\n , sys.all_objects b\ngo\n\n-- scalar function for True\ndrop function if exists fnTrue;\ngo\ncreate function dbo.fnTrue() returns bit with schemabinding as\nbegin\n return 1\nend\ngo\n\n-- scalar function for False\ndrop function if exists fnFalse;\ngo\ncreate function dbo.fnFalse () returns bit with schemabinding as\nbegin\n return 0\nend\ngo\n\n-- table-valued function for booleans\ndrop function if exists dbo.tvfBoolean;\ngo\ncreate function tvfBoolean() returns table with schemabinding as\nreturn\n select convert(bit, 1) as true, convert(bit, 0) as false\ngo\n\n-- view for booleans\ndrop view if exists dbo.viewBoolean;\ngo\ncreate view dbo.viewBoolean with schemabinding as\n select convert(bit, 1) as true, convert(bit, 0) as false\ngo\n\n-- create table for results\ndrop table if exists #testResults\ncreate table #testResults (id int identity(1,1), test int, elapsed bigint, message varchar(1000));\n\n-- define tests\ndeclare @tests table(testNumber int, description nvarchar(100), sql nvarchar(max))\ninsert @tests values \n (1, N'hard-coded values', N'\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when t.value > 127 \n then 0 \n else 1\nend\nfrom #testTable t')\n, (2, N'local variables', N'\ndeclare @FALSE as bit = 0\ndeclare @TRUE as bit = 1\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when t.value > 127 \n then @FALSE\n else @TRUE\nend\nfrom #testTable t'), \n(3, N'scalar functions', N'\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when t.value > 127 \n then dbo.fnFalse()\n else dbo.fnTrue()\nend\nfrom #testTable t'), \n(4, N'view', N'\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when value > 127\n then b.false\n else b.true\nend\nfrom #testTable t with(nolock), viewBoolean b'),\n(5, N'table-valued function', N'\ndeclare @testTable table (id int, value bit);\ninsert @testTable(id, value)\nselect id, case when value > 127\n then b.false\n else b.true\nend\nfrom #testTable with(nolock), dbo.tvfBoolean() b')\n;\n\ndeclare @testNumber int, @description varchar(100), @sql nvarchar(max)\n\ndeclare @testRuns int = 10;\n\n-- execute tests\nwhile @testRuns > 0 begin\n set @testRuns -= 1\n\n declare testCursor cursor for select testNumber, description, sql from @tests;\n open testCursor\n\n fetch next from testCursor into @testNumber, @description, @sql\n while @@FETCH_STATUS = 0 begin\n \n declare @TimeStart datetime2(7) = sysdatetime();\n\n execute sp_executesql @sql;\n\n declare @TimeEnd datetime2(7) = sysdatetime()\n\n insert #testResults(test, elapsed, message) \n select @testNumber, datediff_big(ms, @TimeStart, @TimeEnd), @description\n\n fetch next from testCursor into @testNumber, @description, @sql\n end \n close testCursor\n deallocate testCursor\nend\n\n\n-- display results\nselect test, message, count(*) runs, min(elapsed) as min, max(elapsed) as max, avg(elapsed) as avg\nfrom #testResults\ngroup by test, message\norder by avg(elapsed);\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874/" ]
26,663
<p>So far, I've only used Rational Quantify. I've heard great things about Intel's VTune, but have never tried it!</p> <p>Edit: I'm mostly looking for software that will instrument the code, as I guess that's about the only way to get very fine results.</p> <hr /> <h3>See also:</h3> <p><a href="https://stackoverflow.com/questions/153559/what-are-some-good-profilers-for-native-c-on-windows">What are some good profilers for native C++ on Windows?</a></p>
[ { "answer_id": 4233209, "author": "Moberg", "author_id": 393010, "author_profile": "https://Stackoverflow.com/users/393010", "pm_score": 3, "selected": false, "text": "ProfilingTimer::ProfilingTimer(std::string name)\n : mLocalName(name)\n{\n sNestedName += mLocalName;\n sNestedName += \" > \";\n\n if(sTimetable.find(sNestedName) == sTimetable.end())\n sTimetable[sNestedName] = 0;\n\n mStartTick = Platform::GetTimerTicks();\n}\n\nProfilingTimer::~ProfilingTimer()\n{\n long long totalTicks = Platform::GetTimerTicks() - mStartTick;\n\n sTimetable[sNestedName] += totalTicks;\n\n sNestedName.erase(sNestedName.length() - mLocalName.length() - 3);\n}\n ProfilingTimer _ProfilingTimer(\"identifier\");\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2638/" ]
26,719
<p>I have a set of multiple assemblies (one assembly is to be used as an API and it depends on other assemblies). I would like to merge all assemblies into one single assembly but prevent all assemblies except the API one to be visible from the outside.</p> <p>I will then obfuscate this assembly with Xenocode. From what I have seen, it is impossible to internalize assembly with Xenocode.</p> <p>I have seen ILMerge from Microsoft, but was unable to figure if it can do what I want. <a href="http://research.microsoft.com/~mbarnett/ILMerge.aspx" rel="nofollow noreferrer">http://research.microsoft.com/~mbarnett/ILMerge.aspx</a></p>
[ { "answer_id": 177982, "author": "Ant", "author_id": 11529, "author_profile": "https://Stackoverflow.com/users/11529", "pm_score": 1, "selected": false, "text": "InternalsVisibleTo internal public" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
26,721
<p>When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed. Ideally the content would shrink just a bit to make room for the vertical scrollbar.</p> <p>My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up. Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all. But then at least the user doesn't actually need to <strong>use</strong> the horizontal scrollbar that comes up.</p> <p>Is there a better way to make this all work? Some way to keep the unneeded and unwanted scrollbars from showing up at all?</p>
[ { "answer_id": 26782, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 0, "selected": false, "text": "myPanel.AutoScroll = False\n" }, { "answer_id": 27032, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "#region Windows Form Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent() {\n this.textBox1 = new System.Windows.Forms.TextBox();\n this.label1 = new System.Windows.Forms.Label();\n this.panel1 = new System.Windows.Forms.Panel();\n this.panel2 = new System.Windows.Forms.Panel();\n this.textBox2 = new System.Windows.Forms.TextBox();\n this.label2 = new System.Windows.Forms.Label();\n this.panel1.SuspendLayout();\n this.panel2.SuspendLayout();\n this.SuspendLayout();\n // \n // textBox1\n // \n this.textBox1.Dock = System.Windows.Forms.DockStyle.Top;\n this.textBox1.Location = new System.Drawing.Point(32, 0);\n this.textBox1.MaximumSize = new System.Drawing.Size(250, 0);\n this.textBox1.Name = \"textBox1\";\n this.textBox1.Size = new System.Drawing.Size(250, 20);\n this.textBox1.TabIndex = 0;\n // \n // label1\n // \n this.label1.AutoSize = true;\n this.label1.Dock = System.Windows.Forms.DockStyle.Left;\n this.label1.Location = new System.Drawing.Point(0, 0);\n this.label1.Name = \"label1\";\n this.label1.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);\n this.label1.Size = new System.Drawing.Size(32, 16);\n this.label1.TabIndex = 0;\n this.label1.Text = \"Field:\";\n // \n // panel1\n // \n this.panel1.Controls.Add(this.textBox1);\n this.panel1.Controls.Add(this.label1);\n this.panel1.Dock = System.Windows.Forms.DockStyle.Top;\n this.panel1.Location = new System.Drawing.Point(0, 0);\n this.panel1.Name = \"panel1\";\n this.panel1.Size = new System.Drawing.Size(392, 37);\n this.panel1.TabIndex = 2;\n // \n // panel2\n // \n this.panel2.Controls.Add(this.textBox2);\n this.panel2.Controls.Add(this.label2);\n this.panel2.Dock = System.Windows.Forms.DockStyle.Top;\n this.panel2.Location = new System.Drawing.Point(0, 37);\n this.panel2.Name = \"panel2\";\n this.panel2.Size = new System.Drawing.Size(392, 37);\n this.panel2.TabIndex = 3;\n // \n // textBox2\n // \n this.textBox2.Dock = System.Windows.Forms.DockStyle.Top;\n this.textBox2.Location = new System.Drawing.Point(32, 0);\n this.textBox2.MaximumSize = new System.Drawing.Size(250, 0);\n this.textBox2.Name = \"textBox2\";\n this.textBox2.Size = new System.Drawing.Size(250, 20);\n this.textBox2.TabIndex = 0;\n // \n // label2\n // \n this.label2.AutoSize = true;\n this.label2.Dock = System.Windows.Forms.DockStyle.Left;\n this.label2.Location = new System.Drawing.Point(0, 0);\n this.label2.Name = \"label2\";\n this.label2.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0);\n this.label2.Size = new System.Drawing.Size(32, 16);\n this.label2.TabIndex = 0;\n this.label2.Text = \"Field:\";\n // \n // Form1\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.AutoScroll = true;\n this.ClientSize = new System.Drawing.Size(392, 116);\n this.Controls.Add(this.panel2);\n this.Controls.Add(this.panel1);\n this.Name = \"Form1\";\n this.Text = \"Form1\";\n this.panel1.ResumeLayout(false);\n this.panel1.PerformLayout();\n this.panel2.ResumeLayout(false);\n this.panel2.PerformLayout();\n this.ResumeLayout(false);\n\n }\n\n #endregion\n\n private System.Windows.Forms.TextBox textBox1;\n private System.Windows.Forms.Label label1;\n private System.Windows.Forms.Panel panel1;\n private System.Windows.Forms.Panel panel2;\n private System.Windows.Forms.TextBox textBox2;\n private System.Windows.Forms.Label label2;\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2729/" ]
26,732
<pre><code>&lt;servlet&gt; &lt;servlet-name&gt;myservlet&lt;/servlet-name&gt; &lt;servlet-class&gt;workflow.WDispatcher&lt;/servlet-class&gt; &lt;load-on-startup&gt;2&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;myservlet&lt;/servlet-name&gt; &lt;url-pattern&gt;*NEXTEVENT*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; </code></pre> <p>Above is the snippet from Tomcat's <code>web.xml</code>. The URL pattern <code>*NEXTEVENT*</code> on start up throws</p> <blockquote> <p>java.lang.IllegalArgumentException: Invalid &lt;url-pattern> in servlet mapping</p> </blockquote> <p>It will be greatly appreciated if someone can hint at the error. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 26744, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 8, "selected": true, "text": "<url-pattern>*NEXTEVENT*</url-pattern>\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
26,733
<p>Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?</p> <p>This is what I want to re-write:</p> <pre><code>foreach (Type t in this.GetType().Assembly.GetTypes()) if (t is IMyInterface) ; //do stuff </code></pre>
[ { "answer_id": 26745, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": false, "text": "Type ti = typeof(IYourInterface);\nforeach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {\n foreach (Type t in asm.GetTypes()) {\n if (ti.IsAssignableFrom(t)) {\n // here's your type in t\n }\n }\n}\n" }, { "answer_id": 26750, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 11, "selected": true, "text": "var type = typeof(IMyInterface);\nvar types = AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .Where(p => type.IsAssignableFrom(p));\n loop assemblies \n loop types \n see if implemented.\n" }, { "answer_id": 26752, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 2, "selected": false, "text": "public static List<Type> GetSubclassesOf(this Type type, bool excludeSystemTypes) {\n List<Type> list = new List<Type>();\n IEnumerator enumerator = Thread.GetDomain().GetAssemblies().GetEnumerator();\n while (enumerator.MoveNext()) {\n try {\n Type[] types = ((Assembly) enumerator.Current).GetTypes();\n if (!excludeSystemTypes || (excludeSystemTypes && !((Assembly) enumerator.Current).FullName.StartsWith(\"System.\"))) {\n IEnumerator enumerator2 = types.GetEnumerator();\n while (enumerator2.MoveNext()) {\n Type current = (Type) enumerator2.Current;\n if (type.IsInterface) {\n if (current.GetInterface(type.FullName) != null) {\n list.Add(current);\n }\n } else if (current.IsSubclassOf(type)) {\n list.Add(current);\n }\n }\n }\n } catch {\n }\n }\n return list;\n}\n" }, { "answer_id": 26754, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 2, "selected": false, "text": "Assembly asm = Assembly.Load(\"MyAssembly\");\nType[] types = asm.GetTypes();\nType[] result = types.where(x => x.GetInterface(\"IMyInterface\") != null);\n" }, { "answer_id": 26766, "author": "Ryan Rinaldi", "author_id": 2278, "author_profile": "https://Stackoverflow.com/users/2278", "pm_score": -1, "selected": false, "text": "var types = from type in this.GetType().Assembly.GetTypes()\n where type is ISomeInterface\n select type;\n" }, { "answer_id": 26768, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 6, "selected": false, "text": "var results = from type in someAssembly.GetTypes()\n where typeof(IFoo).IsAssignableFrom(type)\n select type;\n where type is IFoo\n" }, { "answer_id": 4165635, "author": "Carl Nayak", "author_id": 505851, "author_profile": "https://Stackoverflow.com/users/505851", "pm_score": 4, "selected": false, "text": "Type lookupType = typeof (IMenuItem);\nIEnumerable<Type> lookupTypes = GetType().Assembly.GetTypes().Where(\n t => lookupType.IsAssignableFrom(t) && !t.IsInterface); \n" }, { "answer_id": 10947832, "author": "hillstuk", "author_id": 1298296, "author_profile": "https://Stackoverflow.com/users/1298296", "pm_score": 5, "selected": false, "text": "IsAssignableFrom FindInterfaces System static void Main() {\n const string qualifiedInterfaceName = \"Interfaces.IMyInterface\";\n var interfaceFilter = new TypeFilter(InterfaceFilter);\n var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);\n var di = new DirectoryInfo(path);\n foreach (var file in di.GetFiles(\"*.dll\")) {\n try {\n var nextAssembly = Assembly.ReflectionOnlyLoadFrom(file.FullName);\n foreach (var type in nextAssembly.GetTypes()) {\n var myInterfaces = type.FindInterfaces(interfaceFilter, qualifiedInterfaceName);\n if (myInterfaces.Length > 0) {\n // This class implements the interface\n }\n }\n } catch (BadImageFormatException) {\n // Not a .net assembly - ignore\n }\n }\n}\n\npublic static bool InterfaceFilter(Type typeObj, Object criteriaObj) {\n return typeObj.ToString() == criteriaObj.ToString();\n}\n" }, { "answer_id": 12602220, "author": "Ben Watkins", "author_id": 1700301, "author_profile": "https://Stackoverflow.com/users/1700301", "pm_score": 6, "selected": false, "text": " foreach (Type mytype in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()\n .Where(mytype => mytype .GetInterfaces().Contains(typeof(myInterface)))) {\n //do stuff\n }\n" }, { "answer_id": 29379834, "author": "rism", "author_id": 70149, "author_profile": "https://Stackoverflow.com/users/70149", "pm_score": 6, "selected": false, "text": "Assembly.GetTypes ReflectionTypeLoadException derived base base derived Class A // in AssemblyA\nClass B : Class A, IMyInterface // in AssemblyB\nClass C // in AssemblyC which references AssemblyB but not AssemblyA\n ClassC AssemblyC var type = typeof(IMyInterface);\nvar types = AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .Where(p => type.IsAssignableFrom(p));\n ReflectionTypeLoadException AssemblyA AssemblyC var bType = typeof(ClassB);\nvar bClass = (ClassB)Activator.CreateInstance(bType);\n ClassB public static class TypeLoaderExtensions {\n public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) {\n if (assembly == null) throw new ArgumentNullException(\"assembly\");\n try {\n return assembly.GetTypes();\n } catch (ReflectionTypeLoadException e) {\n return e.Types.Where(t => t != null);\n }\n }\n}\n private IEnumerable<Type> GetTypesWithInterface(Assembly asm) {\n var it = typeof (IMyInterface);\n return asm.GetLoadableTypes().Where(it.IsAssignableFrom).ToList();\n}\n" }, { "answer_id": 49006805, "author": "akop", "author_id": 6537157, "author_profile": "https://Stackoverflow.com/users/6537157", "pm_score": 0, "selected": false, "text": "private static IList<Type> loadAllImplementingTypes(Type[] interfaces)\n{\n IList<Type> implementingTypes = new List<Type>();\n\n // find all types\n foreach (var interfaceType in interfaces)\n foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())\n try\n {\n foreach (var currentType in currentAsm.GetTypes())\n if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)\n implementingTypes.Add(currentType);\n }\n catch { }\n\n return implementingTypes;\n}\n" }, { "answer_id": 52411210, "author": "Antonin GAVREL", "author_id": 3161139, "author_profile": "https://Stackoverflow.com/users/3161139", "pm_score": 3, "selected": false, "text": "List<string> types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())\n .Where(x => typeof(ISomeInterface).IsAssignableFrom(x) && !x.IsInterface && !x.IsAbstract)\n .Select(x => x.Name).ToList();\n AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes())\n !x.IsInterface && !x.IsAbstract\n .Select(x => x.Name).ToList();\n" }, { "answer_id": 54297288, "author": "user489566", "author_id": 10558750, "author_profile": "https://Stackoverflow.com/users/10558750", "pm_score": 2, "selected": false, "text": "// We get the assembly through the base class\nvar baseAssembly = typeof(baseClass).GetTypeInfo().Assembly;\n\n// we filter the defined classes according to the interfaces they implement\nvar typeList = baseAssembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(IMyInterface))).ToList();\n" }, { "answer_id": 57359586, "author": "Jonathan Santiago", "author_id": 4457506, "author_profile": "https://Stackoverflow.com/users/4457506", "pm_score": -1, "selected": false, "text": " public IList<T> GetClassByType<T>()\n {\n return AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(s => s.GetTypes())\n .ToList(p => typeof(T)\n .IsAssignableFrom(p) && !p.IsAbstract && !p.IsInterface)\n .SelectList(c => (T)Activator.CreateInstance(c));\n }\n" }, { "answer_id": 60949971, "author": "diegosasw", "author_id": 2948212, "author_profile": "https://Stackoverflow.com/users/2948212", "pm_score": 1, "selected": false, "text": "public static class TypeExtensions\n{\n public static IEnumerable<Type> GetAllTypes(this Type type)\n {\n var typeInfo = type.GetTypeInfo();\n var allTypes = GetAllImplementedTypes(type).Concat(typeInfo.ImplementedInterfaces);\n return allTypes;\n }\n\n private static IEnumerable<Type> GetAllImplementedTypes(Type type)\n {\n yield return type;\n var typeInfo = type.GetTypeInfo();\n var baseType = typeInfo.BaseType;\n if (baseType != null)\n {\n foreach (var foundType in GetAllImplementedTypes(baseType))\n {\n yield return foundType;\n }\n }\n }\n}\n public static class GetAllTypesTests\n{\n public class Given_A_Sample_Standalone_Class_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(SampleStandalone);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(SampleStandalone),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Abstract_Base_Class_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(SampleBase);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(SampleBase),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Child_Class_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(SampleChild);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(SampleChild),\n typeof(SampleBase),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Base_Interface_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(ISampleBase);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(ISampleBase)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Child_Interface_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(ISampleChild);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(ISampleBase),\n typeof(ISampleChild)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Implementation_Class_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n protected override void Given()\n {\n _sut = typeof(SampleImplementation);\n\n _expectedTypes =\n new List<Type>\n {\n typeof(SampleImplementation),\n typeof(SampleChild),\n typeof(SampleBase),\n typeof(ISampleChild),\n typeof(ISampleBase),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n public class Given_A_Sample_Interface_Instance_Type_When_Getting_All_Types\n : Given_When_Then_Test\n {\n private Type _sut;\n private IEnumerable<Type> _expectedTypes;\n private IEnumerable<Type> _result;\n\n class Foo : ISampleChild { }\n\n protected override void Given()\n {\n var foo = new Foo();\n _sut = foo.GetType();\n\n _expectedTypes =\n new List<Type>\n {\n typeof(Foo),\n typeof(ISampleChild),\n typeof(ISampleBase),\n typeof(object)\n };\n }\n\n protected override void When()\n {\n _result = _sut.GetAllTypes();\n }\n\n [Fact]\n public void Then_It_Should_Return_The_Right_Type()\n {\n _result.Should().BeEquivalentTo(_expectedTypes);\n }\n }\n\n sealed class SampleStandalone { }\n abstract class SampleBase { }\n class SampleChild : SampleBase { }\n interface ISampleBase { }\n interface ISampleChild : ISampleBase { }\n class SampleImplementation : SampleChild, ISampleChild { }\n}\n" }, { "answer_id": 63209158, "author": "rvnlord", "author_id": 3783852, "author_profile": "https://Stackoverflow.com/users/3783852", "pm_score": 3, "selected": false, "text": "IsAssignableFrom public static IEnumerable<Type> GetImplementingTypes(this Type itype) \n => AppDomain.CurrentDomain.GetAssemblies().SelectMany(s => s.GetTypes())\n .Where(t => t.GetInterfaces().Contains(itype));\n" }, { "answer_id": 66900943, "author": "chtenb", "author_id": 1546844, "author_profile": "https://Stackoverflow.com/users/1546844", "pm_score": 3, "selected": false, "text": "public static class ReflectionUtils\n{\n public static bool DoesTypeSupportInterface(Type type, Type inter)\n {\n if (inter.IsAssignableFrom(type))\n return true;\n if (type.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == inter))\n return true;\n return false;\n }\n\n public static IEnumerable<Assembly> GetReferencingAssemblies(Assembly assembly)\n {\n return AppDomain\n .CurrentDomain\n .GetAssemblies().Where(asm => asm.GetReferencedAssemblies().Any(asmName => AssemblyName.ReferenceMatchesDefinition(asmName, assembly.GetName())));\n }\n\n public static IEnumerable<Type> TypesImplementingInterface(Type desiredType)\n {\n var assembliesToSearch = new Assembly[] { desiredType.Assembly }\n .Concat(GetReferencingAssemblies(desiredType.Assembly));\n return assembliesToSearch.SelectMany(assembly => assembly.GetTypes())\n .Where(type => DoesTypeSupportInterface(type, desiredType));\n }\n\n public static IEnumerable<Type> NonAbstractTypesImplementingInterface(Type desiredType)\n {\n return TypesImplementingInterface(desiredType).Where(t => !t.IsAbstract);\n }\n}\n" }, { "answer_id": 72022365, "author": "classicSchmosby98", "author_id": 7368872, "author_profile": "https://Stackoverflow.com/users/7368872", "pm_score": 0, "selected": false, "text": "public static Type GetInterfacesImplementation(this Type type)\n{\n return type.Assembly.GetTypes()\n .Where(p => type.IsAssignableFrom(p) && !p.IsInterface)\n .SingleOrDefault();\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
26,743
<p>I use .NET XML technologies quite extensively on my work. One of the things the I like very much is the XSLT engine, more precisely the extensibility of it. However there one little piece which keeps being a source of annoyance. Nothing major or something we can't live with but it is preventing us from producing the beautiful XML we would like to produce. </p> <p>One of the things we do is transform nodes inline and importing nodes from one XML document to another. </p> <p>Sadly , when you save nodes to an <code>XmlTextWriter</code> (actually whatever <code>XmlWriter.Create(Stream)</code> returns), the namespace definitions get all thrown in there, regardless of it is necessary (previously defined) or not. You get kind of the following xml:</p> <pre><code>&lt;root xmlns:abx="http://bladibla"&gt; &lt;abx:child id="A"&gt; &lt;grandchild id="B"&gt; &lt;abx:grandgrandchild xmlns:abx="http://bladibla" /&gt; &lt;/grandchild&gt; &lt;/abx:child&gt; &lt;/root&gt; </code></pre> <p>Does anyone have a suggestion as to how to convince .NET to be efficient about its namespace definitions?</p> <p>PS. As an added bonus I would like to override the default namespace, changing it as I write a node.</p>
[ { "answer_id": 6421794, "author": "Simon Mourier", "author_id": 403671, "author_profile": "https://Stackoverflow.com/users/403671", "pm_score": 1, "selected": false, "text": "myWriter.WriteAttributeString(\"xmlns\", \"abx\", null, \"http://bladibla\");\n" }, { "answer_id": 6482730, "author": "Kirill Polishchuk", "author_id": 787016, "author_profile": "https://Stackoverflow.com/users/787016", "pm_score": 4, "selected": false, "text": "using (var writer = XmlWriter.Create(\"file.xml\"))\n{\n const string Ns = \"http://bladibla\";\n const string Prefix = \"abx\";\n\n writer.WriteStartDocument();\n\n writer.WriteStartElement(\"root\");\n\n // set root namespace\n writer.WriteAttributeString(\"xmlns\", Prefix, null, Ns);\n\n writer.WriteStartElement(Prefix, \"child\", Ns);\n writer.WriteAttributeString(\"id\", \"A\");\n\n writer.WriteStartElement(\"grandchild\");\n writer.WriteAttributeString(\"id\", \"B\");\n\n writer.WriteElementString(Prefix, \"grandgrandchild\", Ns, null);\n\n // grandchild\n writer.WriteEndElement();\n // child\n writer.WriteEndElement();\n // root\n writer.WriteEndElement();\n\n writer.WriteEndDocument();\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root xmlns:abx=\"http://bladibla\">\n <abx:child id=\"A\">\n <grandchild id=\"B\">\n <abx:grandgrandchild />\n </grandchild>\n </abx:child>\n</root>\n" }, { "answer_id": 6493730, "author": "habakuk", "author_id": 254041, "author_profile": "https://Stackoverflow.com/users/254041", "pm_score": 2, "selected": false, "text": "Dim settings = New XmlWriterSettings With {.Indent = True,\n .NamespaceHandling = NamespaceHandling.OmitDuplicates,\n .OmitXmlDeclaration = True}\nDim s As New MemoryStream\nUsing writer = XmlWriter.Create(s, settings)\n ...\nEnd Using\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2892/" ]
26,760
<p>I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?</p>
[ { "answer_id": 26769, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 6, "selected": true, "text": "TimeSpan span;\n\n\nif (TimeSpan.TryParse(\"05h:30m\".Replace(\"m\",\"\").Replace(\"h\",\"\"), out span))\n MessageBox.Show(span.ToString());\n" }, { "answer_id": 26778, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "DateTime.ParseExact DateTime.TryParseExact DateTime DateTime.TimeOfDay TimeSpan TimeSpan.TryParseExact" }, { "answer_id": 26780, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 2, "selected": false, "text": "TimeSpan.Parse(s.Remove(2, 1).Remove(5, 1));\n public static TimeSpan ToTimeSpan(this string s)\n{\n TimeSpan t = TimeSpan.Parse(s.Remove(2, 1).Remove(5, 1));\n return t;\n}\n \"05h:30m\".ToTimeSpan();\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
26,762
<p>Our dev shop currently uses Visual SourceSafe. We all know how that could end up (badly), so we're investigating other systems. First up is Perforce. Does anyone have experience with using it and its integration into Visual Studio (2003/2005/2008)? Is it as good as any other, or is it pretty solid with good features, comparatively?</p>
[ { "answer_id": 96192, "author": "MP24", "author_id": 6206, "author_profile": "https://Stackoverflow.com/users/6206", "pm_score": 0, "selected": false, "text": "p4 edit" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212/" ]
26,795
<p>I have an extender (IExtenderProvider) which extends certain types of controls with additional properties. For one of these properties, I have written a UITypeEditor. So far, all works just fine.</p> <p>The extender also has a couple of properties itself, which I am trying to use as a sort of default for the UITypeEditor. What I want to do is to be able to set a property on the extender itself (not the extended controls), and when I open up the UITypeEditor for one of the additional properties on an extended control, I want to set a value in the UITypeEditor to the value of the property on the extender.</p> <p>A simple example: The ExtenderProvider has a property DefaultExtendedValue. On the form I set the value of this property to "My Value". Extended controls have, through the provider, a property ExtendedValue with a UITypeEditor. When I open the editor for the property ExtendedValue the default (initial) value should be set to "My Value".</p> <p>It seems to me that the best place to do this would be UITypeEditor.EditValue, just before calling IWindowsFormsEditorService.DropDownControl or .ShowDialog.</p> <p>The only problem is that I can't (or I haven't discovered how to) get hold of the extender provider itself in EditValue, to read the value of the property in question and set it in the UITypeEditor. Context gives me the extended control, but that is of no use to me in this case.</p> <p>Is there any way to achieve what I'm trying? Any help appreciated!</p> <p>Thanks Tom</p> <hr> <p>@samjudson: That's not a bad idea, but unfortunately it doesn't quite get me there. I'd really like to be able to set this default value individually for each instance of the extender provider. (I might have more than one on a single form with different values for different groups of extended controls.)</p>
[ { "answer_id": 187256, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "DefaultValueAttribute att = context.\n PropertyDescriptor.Attributes.\n OfType<DefaultValueAttribute>().\n FirstOrDefault();\nobject myDefault = null;\nif ( att != null )\n myDefault = att.Value;\n" }, { "answer_id": 2193027, "author": "Larry", "author_id": 24472, "author_profile": "https://Stackoverflow.com/users/24472", "pm_score": 1, "selected": false, "text": "var Ctl = context.Instance as Control;\n\nType t = Type.GetType(\"System.ComponentModel.ExtendedPropertyDescriptor\");\nLocalizationProvider myProvider = GetValueOnPrivateMember(t, context.PropertyDescriptor, \"provider\") as MyOwnExtenderProvider;\n static object GetValueOnPrivateMember(Type type, object dataobject, string fieldname)\n {\n BindingFlags getFieldBindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField;\n return type.InvokeMember(fieldname,\n getFieldBindingFlags,\n null,\n dataobject,\n null);\n }\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2899/" ]
26,796
<p>What is the best way to use ResolveUrl() in a Shared/static function in Asp.Net? My current solution for VB.Net is:</p> <pre><code>Dim x As New System.Web.UI.Control x.ResolveUrl("~/someUrl") </code></pre> <p>Or C#:</p> <pre><code>System.Web.UI.Control x = new System.Web.UI.Control(); x.ResolveUrl("~/someUrl"); </code></pre> <p>But I realize that isn't the best way of calling it.</p>
[ { "answer_id": 528198, "author": "jdw", "author_id": 64181, "author_profile": "https://Stackoverflow.com/users/64181", "pm_score": 5, "selected": false, "text": "public static string GetUrl(int id)\n{\n string path = VirtualPathUtility.ToAbsolute(\"~/SomePage.aspx\");\n return string.Format(\"{0}?id={1}\", path, id);\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
26,800
<p>I'm using XPath in .NET to parse an XML document, along the lines of:</p> <pre class="lang-cs prettyprint-override"><code>XmlNodeList lotsOStuff = doc.SelectNodes("//stuff"); foreach (XmlNode stuff in lotsOStuff) { XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild"); // ... etc } </code></pre> <p>The issue is that the XPath Query for <code>stuffChild</code> is always returning the child of the first <code>stuff</code> element, never the rest. Can XPath not be used to query against an individual <code>XMLElement</code>?</p>
[ { "answer_id": 26805, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 4, "selected": true, "text": "// XmlNode stuffChild = stuff.SelectSingleNode(\".//stuffChild\");\n xmlNode stuffChild = stuff.SelectSingleNode(\"self::node()/descendant-or-self::stuffChild\");\n xmlNode stuffChild = stuff.SelectSingleNode(\"self::node()/descendant::stuffChild\");\n XmlNode stuffChild = stuff.SelectSingleNode(\"stuffChild\");\n" }, { "answer_id": 26813, "author": "Tom Lokhorst", "author_id": 2597, "author_profile": "https://Stackoverflow.com/users/2597", "pm_score": 2, "selected": false, "text": "// stuffChild stuffChild .// stuff.SelectSingleNode(\".//stuffChild\");\n" }, { "answer_id": 26817, "author": "Rob Thomas", "author_id": 803, "author_profile": "https://Stackoverflow.com/users/803", "pm_score": 1, "selected": false, "text": "XmlNode stuffChild = stuff.SelectSingleNode(\"stuffChild\");\n" }, { "answer_id": 596498, "author": "Azat Razetdinov", "author_id": 9649, "author_profile": "https://Stackoverflow.com/users/9649", "pm_score": -1, "selected": false, "text": "XmlNode stuffChild = stuff.SelectSingleNode(\"descendant::stuffChild[1]\");\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
26,809
<p>I frequently have problems dealing with <code>DataRows</code> returned from <code>SqlDataAdapters</code>. When I try to fill in an object using code like this:</p> <pre><code>DataRow row = ds.Tables[0].Rows[0]; string value = (string)row; </code></pre> <p>What is the best way to deal with <code>DBNull's</code> in this type of situation.</p>
[ { "answer_id": 26832, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 6, "selected": true, "text": "int? value = 5;\n as as null DBNull as DataRow row = ds.Tables[0].Rows[0];\nstring value = row as string;\n row DBNull value null as null" }, { "answer_id": 26853, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "System.Data.DataSetExtensions string value = (\n from row in ds.Tables[0].Rows\n select row.Field<string>(0) ).FirstOrDefault();\n" }, { "answer_id": 27075, "author": "Manu", "author_id": 2133, "author_profile": "https://Stackoverflow.com/users/2133", "pm_score": 1, "selected": false, "text": "ConvertDBNull.ToInt64(object obj) Convert.ToInt64(obj)" }, { "answer_id": 27082, "author": "Daniel Auger", "author_id": 1644, "author_profile": "https://Stackoverflow.com/users/1644", "pm_score": 4, "selected": false, "text": "DataRow row = ds.Tables[0].Rows[0];\nstring value;\n\nif (row[\"fooColumn\"] == DBNull.Value)\n{\n value = string.Empty;\n}\nelse \n{\n value = Convert.ToString(row[\"fooColumn\"]);\n}\n" }, { "answer_id": 27093, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 1, "selected": false, "text": "if (row.IsNull[\"fooColumn\"])\n{\n value = string.Empty();\n}\n{\nelse\n{\n value = row[\"fooColumn\"].ToString;\n}\n" }, { "answer_id": 49006, "author": "Steve Schoon", "author_id": 3881, "author_profile": "https://Stackoverflow.com/users/3881", "pm_score": 3, "selected": false, "text": "SELECT \n ISNULL(name,'') AS name\n ,ISNULL(age, 0) AS age\nFROM \n names\n" }, { "answer_id": 66201, "author": "Meff", "author_id": 9647, "author_profile": "https://Stackoverflow.com/users/9647", "pm_score": 3, "selected": false, "text": "return row[\"MyCol\"] == DBNull.Value ? -99 : Convert.ToInt32(Row[\"MyCol\"]);\n Object.ID = DataReader[\"ID\"] == DBNull.Value ? -99 : Convert.ToInt32(DataReader[\"ID\"]);\nObject.Name = DataReader[\"Name\"] == DBNull.Value ? \"None\" : Convert.ToString(DataReader[\"Name\"]);\nObject.Price = DataReader[\"Price\"] == DBNull.Value ? 0.0 : Convert.ToFloat(DataReader[\"Price\"]);\n" }, { "answer_id": 534305, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 1, "selected": false, "text": "// Or if (row[\"fooColumn\"] == DBNull.Value)\nif (row.IsNull[\"fooColumn\"])\n{\n // use a null for strings and a Nullable for value types \n // if it is a value type and null is invalid throw a \n // InvalidOperationException here with some descriptive text. \n // or dont check for null at all and let the cast exception below bubble \n value = null;\n}\nelse\n{\n // do a direct cast here. dont use \"as\", \"convert\", \"parse\" or \"tostring\"\n // as all of these will swallow the case where is the incorect type.\n // (Unless it is a string in the DB and really do want to convert it)\n value = (string)row[\"fooColumn\"];\n}\n" }, { "answer_id": 675894, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "DataRow row = ds.Tables[0].Rows[0];\nstring value;\n\nif (row[\"fooColumn\"] == DBNull.Value)\n{\n value = string.Empty;\n}\nelse \n{\n value = Convert.ToString(row[\"fooColumn\"]);\n}\n DataRow row = ds.Tables[0].Rows[0];\nstring value = row.ToString()\n" }, { "answer_id": 16580743, "author": "Jürgen Steinblock", "author_id": 98491, "author_profile": "https://Stackoverflow.com/users/98491", "pm_score": 2, "selected": false, "text": "DBNull.Value.ToString() String.Empty DataRow row = ds.Tables[0].Rows[0];\nstring value = row[\"name\"].ToString();\n Convert.ChangeType(...) int value = row.GetValueOrDefault<int>(\"count\");\nint value = row.GetValueOrDefault<int>(\"count\", 15);\n" }, { "answer_id": 18943063, "author": "João Pinho", "author_id": 2606833, "author_profile": "https://Stackoverflow.com/users/2606833", "pm_score": 2, "selected": false, "text": "string myValue = (myDataTable.Rows[i][\"MyDbNullableField\"] as string) ?? string.Empty;\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2191/" ]
26,816
<p>is there a way to abort threads created with QueueUserWorkItem?</p> <p>Or maybe I don't need to? What happens if the main application exits? Are all thread created from it aborted automatically?</p>
[ { "answer_id": 896492, "author": "Lukas Šalkauskas", "author_id": 5369, "author_profile": "https://Stackoverflow.com/users/5369", "pm_score": 0, "selected": false, "text": "bool stop = false;\nvoid doDownloadWork(object s) \n{\n if (!stop)\n {\n DownloadLink((String)s, location);\n }\n}\n" }, { "answer_id": 975941, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "volatile bool stop = false;\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
26,825
<p>I have a CollapsiblePanelExtender that will not collapse. I have "collapsed" set to true and all the ControlID set correctly. I try to collapse and it goes through the animation but then expands almost instantly. This is in an User Control with the following structure.</p> <pre><code>&lt;asp:UpdatePanel ID="UpdatePanel1" runat="server"&gt; &lt;ContentTemplate&gt; &lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="odsPartners" Width="450px" BorderWidth="0" ShowHeader="false" ShowFooter="false" AllowSorting="true" onrowdatabound="GridView1_RowDataBound"&gt; &lt;Columns&gt; &lt;asp:TemplateField HeaderText="Contract Partners" SortExpression="Name"&gt; &lt;ItemTemplate&gt; &lt;asp:Panel id="pnlRow" runat="server"&gt; &lt;table&gt; ...Stuff... &lt;/table&gt; &lt;/asp:Panel&gt; &lt;ajaxToolkit:CollapsiblePanelExtender runat="server" ID="DDE" Collapsed="true" ImageControlID="btnExpander" ExpandedImage="../Images/collapse.jpg" CollapsedImage="../Images/expand.jpg" TargetControlID="DropPanel" CollapseControlID="btnExpander" ExpandControlID="btnExpander" /&gt; &lt;asp:Panel ID="DropPanel" runat="server" CssClass="CollapsedPanel"&gt; &lt;asp:Table ID="tblContracts" runat="server"&gt; &lt;asp:TableRow ID="row" runat="server"&gt; &lt;asp:TableCell ID="spacer" runat="server" Width="30"&gt;&amp;nbsp;&lt;/asp:TableCell&gt; &lt;asp:TableCell ID="cellData" runat="server" Width="400"&gt; &lt;uc1:ContractList ID="ContractList1" runat="server" PartnerID='&lt;%# Bind("ID") %&gt;' /&gt; &lt;/asp:TableCell&gt; &lt;/asp:TableRow&gt; &lt;/asp:Table&gt; &lt;/asp:Panel&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="tbFilter" EventName="TextChanged" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt; </code></pre>
[ { "answer_id": 26918, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 0, "selected": false, "text": "AutoExpand=\"False\"\n" }, { "answer_id": 27026, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 1, "selected": false, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\" > \n" }, { "answer_id": 28340499, "author": "user4532236", "author_id": 4532236, "author_profile": "https://Stackoverflow.com/users/4532236", "pm_score": -1, "selected": false, "text": "CollapsiblePanelExtender CpeForControls = (CollapsiblePanelExtender)tbl_Form.FindControl(\"cpe_controls\");\nCpeForControls.ClientState = \"true\";\nCpeForControls.Collapsed = true;\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2894/" ]
26,834
<p>I have an application, built using MVC, that produces a view which delivers summary information across a number of models. Further to that, some calculations are performed across the different sets of data.</p> <p>There's no clear single model (that maps to a table at least) that seems to make sense as the starting point for this, so the various summaries are pulled from the contributing models in the controller, passed into the view and the calculations are performed there.</p> <p>But that seems, well, <em>dirty</em>. But controllers are supposed to be lightweight, aren't they? And business logic shouldn't be in views, as I have it as present.</p> <p>So where should this information be assembled? A new model, that doesn't map to a table? A library function/module? Or something else?</p> <p>(Although I see this as mostly of an architectural/pattern question, I'm working in Rails, FWIW.)</p> <p><strong>Edit</strong>: Good answers all round, and a lot of consensus, which is reassuring. I "accepted" the answer I did to keep the link to Railscasts at the top. I'm behind in my Railscast viewing - something I shall make strenuous attempts to rectify!</p>
[ { "answer_id": 26848, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 1, "selected": false, "text": "ActiveRecord::Base" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1060/" ]
26,842
<p>I'm attempting to use an existing CAS server to authenticate login for a Perl CGI web script and am using the <a href="http://search.cpan.org/dist/AuthCAS" rel="nofollow noreferrer">AuthCAS</a> Perl module (v 1.3.1). I can connect to the CAS server to get the service ticket but when I try to connect to validate the ticket my script returns with the following error from the <a href="http://search.cpan.org/dist/IO-Socket-SSL" rel="nofollow noreferrer">IO::Socket::SSL</a> module:</p> <pre><code> 500 Can't connect to [CAS Server]:443 (Bad hostname '[CAS Server]') ([CAS Server] substituted for real server name) </code></pre> <p>Symptoms/Tests:</p> <ol> <li>If I type the generated URL for the authentication into the web browser's location bar it returns just fine with the expected XML snippet. So it is not a bad host name.</li> <li>If I generate a script without using the AuthCAS module but using the IO::Socket::SSL module directly to query the CAS server for validation on the generated service ticket the Perl script will run fine from the command line but not in the browser.</li> <li>If I add the AuthCAS module into the script in item 2, the script no longer works on the command line and still doesn't work in the browser.</li> </ol> <p>Here is the bare-bones script that produces the error:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use CGI; use AuthCAS; use CGI::Carp qw( fatalsToBrowser ); my $id = $ENV{QUERY_STRING}; my $q = new CGI; my $target = "http://localhost/cgi-bin/testCAS.cgi"; my $cas = new AuthCAS(casUrl =&gt; 'https://cas_server/cas'); if ($id eq ""){ my $login_url = $cas-&gt;getServerLoginURL($target); printf "Location: $login_url\n\n"; exit 0; } else { print $q-&gt;header(); print "CAS TEST&lt;br&gt;\n"; ## When coming back from the CAS server a ticket is provided in the QUERY_STRING print "QUERY_STRING = " . $id . "&lt;/br&gt;\n"; ## $ST should contain the received Service Ticket my $ST = $q-&gt;param('ticket'); my $user = $cas-&gt;validateST($target, $ST); #### This is what fails printf "Error: %s\n", &amp;AuthCAS::get_errors() unless (defined $user); } </code></pre> <p>Any ideas on where the conflict might be?</p> <hr> <p>The error is coming from the line directly above the snippet Cebjyre quoted namely</p> <pre><code>$ssl_socket = new IO::Socket::SSL(%ssl_options); </code></pre> <p>namely the socket creation. All of the input parameters are correct. I had edited the module to put in debug statements and print out all the parameters just before that call and they are all fine. Looks like I'm going to have to dive deeper into the IO::Socket::SSL module.</p>
[ { "answer_id": 27602, "author": "Cebjyre", "author_id": 1612, "author_profile": "https://Stackoverflow.com/users/1612", "pm_score": -1, "selected": false, "text": "[...]\nunless ($ssl_socket) {\n $errors = sprintf \"error %s unable to connect https://%s:%s/\\n\",&IO::Socket::SSL::errstr,$host,$port;\n return undef;\n}\n[...]\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/171/" ]
26,845
<p>I'd like to hear from people who are using distributed version control (aka distributed revision control, decentralized version control) and how they are finding it. What are you using, Mercurial, Darcs, Git, Bazaar? Are you still using it? If you've used client/server rcs in the past, are you finding it better, worse or just different? What could you tell me that would get me to jump on the bandwagon? Or jump off for that matter, I'd be interested to hear from people with negative experiences as well. </p> <p>I'm currently looking at replacing our current source control system (Subversion) which is the impetus for this question.</p> <p>I'd be especially interested in anyone who's used it with co-workers in other countries, where your machines may not be on at the same time, and your connection is very slow.</p> <p>If you're not sure what distributed version control is, here are a couple articles:</p> <p><a href="http://betterexplained.com/articles/intro-to-distributed-version-control-illustrated/" rel="nofollow noreferrer">Intro to Distributed Version Control</a></p> <p><a href="http://en.wikipedia.org/wiki/Distributed_revision_control" rel="nofollow noreferrer">Wikipedia Entry</a></p>
[ { "answer_id": 30657, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 2, "selected": false, "text": ". git-sh-setup" }, { "answer_id": 738292, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 1, "selected": false, "text": "hg clone" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1329401/" ]
26,855
<p>I'm currently using the module <code>URI::URL</code> to generate a full URL from a relative URL; however, it isn't running as fast as I'd like it to be. Does anyone know another way to do this that may be faster?</p>
[ { "answer_id": 26894, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 0, "selected": false, "text": "$full_url = $base_url . $relative_url" }, { "answer_id": 26960, "author": "Peter Stuifzand", "author_id": 1633, "author_profile": "https://Stackoverflow.com/users/1633", "pm_score": 3, "selected": true, "text": "$uri = URI->new_abs( $str, $base_uri )\n" }, { "answer_id": 27993, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 2, "selected": false, "text": "URI" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2901/" ]
26,857
<p>Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?</p> <p>Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a link/button on my site's page that will fill in those values and submit the info without having to copy/paste them across and click the submit button.</p> <p>Further clarification: How do automated spam bots fill out forms and click the submit button if they were written in C#?</p>
[ { "answer_id": 26881, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 7, "selected": true, "text": "WebRequest req = WebRequest.Create(\"http://mysite/myform.aspx\");\nstring postData = \"item1=11111&item2=22222&Item3=33333\";\n\nbyte[] send = Encoding.Default.GetBytes(postData);\nreq.Method = \"POST\";\nreq.ContentType = \"application/x-www-form-urlencoded\";\nreq.ContentLength = send.Length;\n\nStream sout = req.GetRequestStream();\nsout.Write(send, 0, send.Length);\nsout.Flush();\nsout.Close();\n\nWebResponse res = req.GetResponse();\nStreamReader sr = new StreamReader(res.GetResponseStream());\nstring returnvalue = sr.ReadToEnd();\n" }, { "answer_id": 8378787, "author": "John Kelvie", "author_id": 929047, "author_profile": "https://Stackoverflow.com/users/929047", "pm_score": 2, "selected": false, "text": "var webClient = new WebClient();\nDebug.Info(\"PostingForm: \" + url);\ntry\n{\n byte [] responseArray = webClient.UploadValues(url, nameValueCollection);\n return new Response(responseArray, (int) HttpStatusCode.OK);\n}\ncatch (WebException e)\n{\n var response = (HttpWebResponse)e.Response;\n byte[] responseBytes = IOUtil.StreamToBytes(response.GetResponseStream());\n return new Response(responseBytes, (int) response.StatusCode);\n} \n" }, { "answer_id": 14978752, "author": "John", "author_id": 1252113, "author_profile": "https://Stackoverflow.com/users/1252113", "pm_score": 0, "selected": false, "text": "<br /> Regex.Replace( HttpUtility.HtmlDecode( test ), \"(<br.*?>)\", \"\\r\\n\" ,RegexOptions.IgnoreCase);\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
26,860
<p>I'm a web developer, and I want to make the web sites I develop more accessible to those using screen readers. What limitations do screen readers have that I should be most aware of, and what can I do to avoid hitting these limitations.</p> <p>This question was sparked by reading another question about <a href="https://stackoverflow.com/questions/8472/best-non-image-based-captcha">non-image based captchas</a>. In there, a commenter said that honey pot form fields (form fields hidden with CSS that only a bot would fill in), are a bad idea, because screen readers would still pick them up. </p> <p>Are screen readers really so primitive that they would read text that isn't even displayed on the screen? Ideally, couldn't you make a screen reader that waited until the page was finished loading, applied all css, and even ran Javascript onload functions before it figured out what was actually displayed, and then read that off to the user? You could probably even identify parts of the page that are menus or table of contents, and give some sort of easy way for those parts to be read exclusively or skipped over. I would think that the programming community could come up with a better solution to this problem. </p>
[ { "answer_id": 26917, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<label for=\"Requestor\" accesskey=\"9\"><span class=\"required\">&nbsp;Requestor&nbsp;*&nbsp;</span><span class=\"hidden\">required.</span></label>\n #hidden {\n position:absolute;\n left:0px;\n top:-500px;\n width:1px;\n height:1px;\n overflow:hidden;\n}\n .hidden {\n position:absolute;\n left:0px;\n top:-500px;\n width:1px;\n height:1px;\n overflow:hidden;\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1862/" ]
26,863
<p>I had a plugin installed in Visual Studio 2008, and it created some extra dockable windows. I have uninstalled it, and I can't get rid of the windows it created - I close them, but they always come back. They're just empty windows now, since the plugin is no longer present, but nothing I've tried gets rid of them. I've tried:</p> <ul> <li>Window -> Reset Window Layout</li> <li>Deleting the .suo files in my project directories</li> <li>Deleting the Visual Studio 9.0 folder in my Application Settings directory</li> </ul> <p>Any ideas?</p>
[ { "answer_id": 26945, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 4, "selected": false, "text": "Devenv.exe /ResetSettings\n Devenv.exe /ResetSettings \"C:\\My Files\\MySettings.vssettings\"\n" }, { "answer_id": 3345188, "author": "yossharel", "author_id": 184175, "author_profile": "https://Stackoverflow.com/users/184175", "pm_score": 2, "selected": false, "text": "\"C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\devenv.exe\" /resetsettings\n devenv.exe /resetsettings" }, { "answer_id": 71174521, "author": "Geoff Davids", "author_id": 6283495, "author_profile": "https://Stackoverflow.com/users/6283495", "pm_score": 0, "selected": false, "text": "Window -> Reset Window Layout Views: Reset View Locations" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2348/" ]
26,877
<p>In C#, what is the difference (if any) between these two lines of code?</p> <pre><code>tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick); </code></pre> <p>and</p> <pre><code>tmrMain.Elapsed += tmrMain_Tick; </code></pre> <p>Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?</p>
[ { "answer_id": 26884, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 6, "selected": true, "text": "static void Hook1()\n{\n someEvent += new EventHandler( Program_someEvent );\n}\n\nstatic void Hook2()\n{\n someEvent += Program_someEvent;\n}\n someEvent += new EventHandler( Program_someEvent ); EventHandler" }, { "answer_id": 26913, "author": "Timbo", "author_id": 1810, "author_profile": "https://Stackoverflow.com/users/1810", "pm_score": 0, "selected": false, "text": "new XYZEventHandler" }, { "answer_id": 27048, "author": "Andrei Rînea", "author_id": 1796, "author_profile": "https://Stackoverflow.com/users/1796", "pm_score": 2, "selected": false, "text": "(new EventHandler(MethodName))" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
26,879
<p>I have a website that is perfectely centered aligned. The CSS code works fine. The problem doesn't really have to do with CSS. I have headers for each page that perfectely match eachother.</p> <p>However, when the content gets larger, Opera and FireFox show a scrollbar at the left so you can scroll to the content not on the screen. This makes my site jump a few pixels to the left. Thus the headers are not perfectely aligned anymore.</p> <p>IE always has a scrollbar, so the site never jumps around in IE. </p> <p>Does anyone know a JavaScript/CSS/HTML solution for this problem?</p>
[ { "answer_id": 26907, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " #middle \n { \nposition: relative;\nmargin: 0px auto 0px auto; \nwidth: 1000px; \nmax-width: 1000px;\n}\n" }, { "answer_id": 26911, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "position: relative; div 1000px" }, { "answer_id": 26924, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 4, "selected": true, "text": "html { overflow-y: scroll; }\n" }, { "answer_id": 94534, "author": "Carl Camera", "author_id": 12804, "author_profile": "https://Stackoverflow.com/users/12804", "pm_score": 2, "selected": false, "text": "html { height: 101%; }\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
26,882
<p>My asp.net page will render different controls based on which report a user has selected e.g. some reports require 5 drop downs, some two checkboxes and 6 dropdowns).</p> <p>They can select a report using two methods. With <code>SelectedReport=MyReport</code> in the query string, or by selecting it from a dropdown. And it's a common case for them to come to the page with SelectedReport in the query string, and then change the report selected in the drop down.</p> <p>My question is, is there anyway of making the dropdown modify the query string when it's selected. So I'd want <code>SelectedReport=MyNewReport</code> in the query string and the page to post back.</p> <p>At the moment it's just doing a normal postback, which leaves the <code>SelectedReport=MyReport</code> in the query string, even if it's not the currently selected report.</p> <p><strong>Edit:</strong> And I also need to preserve ViewState.</p> <p>I've tried doing <code>Server.Transfer(Request.Path + "?SelectedReport=" + SelectedReport, true)</code> in the event handler for the Dropdown, and this works function wise, unfortunately because it's a Server.Transfer (to preserve ViewState) instead of a Response.Redirect the URL lags behind what's shown.</p> <p>Maybe I'm asking the impossible or going about it completely the wrong way. </p> <p><strong>@Craig</strong> The QueryString collection is read-only and cannot be modified.<br> <strong>@Jason</strong> That would be great, except I'd lose the ViewState wouldn't I? (Sorry I added that after seeing your response).</p>
[ { "answer_id": 26943, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 2, "selected": false, "text": "<script>\n function changeReport(dropDownList) {\n var selectedReport = dropDownList.options[dropDownList.selectedIndex];\n window.location = (\"scratch.htm?SelectedReport=\" + selectedReport.value);\n }\n</script>\n\n<select id=\"SelectedReport\" onchange=\"changeReport(this)\">\n <option value=\"foo\">foo</option>\n <option value=\"bar\">bar</option>\n <option value=\"baz\">baz</option>\n</select>\n" }, { "answer_id": 29605, "author": "Tom", "author_id": 3139, "author_profile": "https://Stackoverflow.com/users/3139", "pm_score": 0, "selected": false, "text": "Form.Action = Request.Path;\n" }, { "answer_id": 16968178, "author": "Rajat Agrawal", "author_id": 2460674, "author_profile": "https://Stackoverflow.com/users/2460674", "pm_score": 0, "selected": false, "text": "var url = updateQueryStringParameter(window.location.href,\n 'Search',\n document.getElementById('txtSearch').value);\nWebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(\"searchbutton\", \"\",\n true, \"aa\", url, false, true));\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
26,903
<p>Is there a way?</p> <p>I need all types that implement a specific interface to have a parameterless constructor, can it be done?</p> <p>I am developing the base code for other developers in my company to use in a specific project.</p> <p>There's a proccess which will create instances of types (in different threads) that perform certain tasks, and I need those types to follow a specific contract (ergo, the interface).</p> <p>The interface will be internal to the assembly</p> <p>If you have a suggestion for this scenario without interfaces, I'll gladly take it into consideration...</p>
[ { "answer_id": 27047, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 3, "selected": false, "text": "interface ITest<T> where T: new()\n{\n //...\n}\n\nclass Test: ITest<Test>\n{\n //...\n}\n" }, { "answer_id": 27049, "author": "Landon Kuhn", "author_id": 1785, "author_profile": "https://Stackoverflow.com/users/1785", "pm_score": 0, "selected": false, "text": "interface FooFactory {\n Foo createInstance();\n}\n" }, { "answer_id": 27454, "author": "Chris Ammerman", "author_id": 2729, "author_profile": "https://Stackoverflow.com/users/2729", "pm_score": 4, "selected": true, "text": "public class Something : ITest<String>\n{\n private Something() { }\n}\n public interface ITest<T>\n where T : ITest<T>, new()\n{\n}\n public class A : ITest<A>\n{\n}\n\npublic class B : ITest<A>\n{\n private B() { }\n}\n" }, { "answer_id": 36919, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 1, "selected": false, "text": "void RegisterType<T>() where T:ITest, new() {\n}\n" }, { "answer_id": 68357, "author": "munificent", "author_id": 9457, "author_profile": "https://Stackoverflow.com/users/9457", "pm_score": 2, "selected": false, "text": "public interface IInterface\n{\n void DoSomething();\n}\n\npublic class Foo : IInterface\n{\n public void DoSomething() { /* whatever */ }\n}\n public IInterface CreateUsingType(Type thingThatCreates)\n{\n ConstructorInfo constructor = thingThatCreates.GetConstructor(Type.EmptyTypes);\n return (IInterface)constructor.Invoke(new object[0]);\n}\n\npublic void Test()\n{\n IInterface thing = CreateUsingType(typeof(Foo));\n}\n public interface IFactory\n{\n IInterface Create();\n}\n\npublic class Factory<T> where T : IInterface, new()\n{\n public IInterface Create() { return new T(); }\n}\n\npublic IInterface CreateUsingFactory(IFactory factory)\n{\n return factory.Create();\n}\n\npublic void Test()\n{\n IInterface thing = CreateUsingFactory(new Factory<Foo>());\n}\n public IInterface CreateUsingDelegate(Func<IInterface> createCallback)\n{\n return createCallback();\n}\n\npublic void Test()\n{\n IInterface thing = CreateUsingDelegate(() => new Foo());\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
26,904
<p>I have a large exiting C++ project involving:</p> <ul> <li>4 applications</li> <li>50+ libraries</li> <li>20+ third party libraries</li> </ul> <p>The project uses QMake (part of Trolltech's Qt) to build the production version on Linux, but I've been playing around at building it on MacOS.</p> <p>I can build in on MacOS using QMake just fine but I'm having trouble producing the final .app. It needs collecting all the third party frameworks and dynamic libraries, all the project's dynamic libraries and making sure the application finds them.</p> <p>I've read online about using install_name_tool but was wondering if there's a process to automate it.</p> <p>(Maybe the answer is to use XCode, see related question, but it would have issues with building uic and moc)</p> <p>Thanks </p>
[ { "answer_id": 82054, "author": "mxcl", "author_id": 6444, "author_profile": "https://Stackoverflow.com/users/6444", "pm_score": 2, "selected": false, "text": " macx*:!macx-xcode:release {\n system( QT=\\'$$QT\\' QMAKE_LIBDIR_QT=\\'$$QMAKE_LIBDIR_QT\\' $$ROOT_DIR/common/dist/mac/Makefile.dmg.pl $$DESTDIR $$VERSION $$LIBS > Makefile.dmg )\n QMAKE_EXTRA_INCLUDES += Makefile.dmg \n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2711/" ]
26,925
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/8127/pre-build-task-deleting-the-working-copy-in-cruisecontrol-net">Pre-build task - deleting the working copy in CruiseControl.NET</a> </p> </blockquote> <p>I would like to delete my working directory during the cruisecontrol build process...I'm sure this is easy, but I have been unable to find an example of it...</p> <p>If you know how to create a directory, that would be useful as well.</p> <p>Thanks.</p>
[ { "answer_id": 26968, "author": "Ian Patrick Hughes", "author_id": 2213, "author_profile": "https://Stackoverflow.com/users/2213", "pm_score": 0, "selected": false, "text": "\nstatic void Main(string[] args) \n\n{\n for (int n = 0; n < args.Length; n++)\n {\n if (Directory.Exists(args[n].ToString()))\n {\n Directory.Delete(args[n].ToString(), true);\n }\n\n }\n\n\n}\n\n\n {\n for (int n = 0; n < args.Length; n++)\n {\n if (Directory.Exists(args[n].ToString()))\n {\n Directory.Delete(args[n].ToString(), true);\n }\n\n }\n\n\n}\n " }, { "answer_id": 27202, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 0, "selected": false, "text": "<msbuild> <msbuild>" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
26,947
<p>What built-in PHP functions are useful for web scraping? What are some good resources (web or print) for getting up to speed on web scraping with PHP?</p>
[ { "answer_id": 26955, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "file_get_contents()" }, { "answer_id": 103554, "author": "tyshock", "author_id": 16448, "author_profile": "https://Stackoverflow.com/users/16448", "pm_score": 6, "selected": false, "text": "\n\n$curl = new Curl();\n$html = $curl->get(\"http://www.google.com\");\n\n// now, do your regex work against $html\n \n\n<?php\n\nclass Curl\n{ \n\n public $cookieJar = \"\";\n\n public function __construct($cookieJarFile = 'cookies.txt') {\n $this->cookieJar = $cookieJarFile;\n }\n\n function setup()\n {\n\n\n $header = array();\n $header[0] = \"Accept: text/xml,application/xml,application/xhtml+xml,\";\n $header[0] .= \"text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\";\n $header[] = \"Cache-Control: max-age=0\";\n $header[] = \"Connection: keep-alive\";\n $header[] = \"Keep-Alive: 300\";\n $header[] = \"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\";\n $header[] = \"Accept-Language: en-us,en;q=0.5\";\n $header[] = \"Pragma: \"; // browsers keep this blank.\n\n\n curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');\n curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);\n curl_setopt($this->curl,CURLOPT_COOKIEJAR, $this->cookieJar); \n curl_setopt($this->curl,CURLOPT_COOKIEFILE, $this->cookieJar);\n curl_setopt($this->curl,CURLOPT_AUTOREFERER, true);\n curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION, true);\n curl_setopt($this->curl,CURLOPT_RETURNTRANSFER, true); \n }\n\n\n function get($url)\n { \n $this->curl = curl_init($url);\n $this->setup();\n\n return $this->request();\n }\n\n function getAll($reg,$str)\n {\n preg_match_all($reg,$str,$matches);\n return $matches[1];\n }\n\n function postForm($url, $fields, $referer='')\n {\n $this->curl = curl_init($url);\n $this->setup();\n curl_setopt($this->curl, CURLOPT_URL, $url);\n curl_setopt($this->curl, CURLOPT_POST, 1);\n curl_setopt($this->curl, CURLOPT_REFERER, $referer);\n curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);\n return $this->request();\n }\n\n function getInfo($info)\n {\n $info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);\n return $info;\n }\n\n function request()\n {\n return curl_exec($this->curl);\n }\n}\n\n?>\n" }, { "answer_id": 1962728, "author": "Sarfraz", "author_id": 139459, "author_profile": "https://Stackoverflow.com/users/139459", "pm_score": 0, "selected": false, "text": "<?php\n\n/*\n Example:\n\n $site = $this->load->cls('scraper', 'http://www.anysite.com');\n $excss = $site->getExternalCSS();\n $incss = $site->getInternalCSS();\n $ids = $site->getIds();\n $classes = $site->getClasses();\n $spans = $site->getSpans(); \n\n print '<pre>';\n print_r($excss);\n print_r($incss);\n print_r($ids);\n print_r($classes);\n print_r($spans); \n\n*/\n\nclass scraper\n{\n private $url = '';\n\n public function __construct($url)\n {\n $this->url = file_get_contents(\"$url\");\n }\n\n public function getInternalCSS()\n {\n $tmp = preg_match_all('/(style=\")(.*?)(\")/is', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n public function getExternalCSS()\n {\n $tmp = preg_match_all('/(href=\")(\\w.*\\.css)\"/i', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n public function getIds()\n {\n $tmp = preg_match_all('/(id=\"(\\w*)\")/is', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n public function getClasses()\n {\n $tmp = preg_match_all('/(class=\"(\\w*)\")/is', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n public function getSpans(){\n $tmp = preg_match_all('/(<span>)(.*)(<\\/span>)/', $this->url, $patterns);\n $result = array();\n array_push($result, $patterns[2]);\n array_push($result, count($patterns[2]));\n return $result;\n }\n\n}\n?>\n" }, { "answer_id": 10763495, "author": "Salman von Abbas", "author_id": 362006, "author_profile": "https://Stackoverflow.com/users/362006", "pm_score": 4, "selected": false, "text": "Symfony\\Component\\BrowserKit\\Client use Goutte\\Client;\n\n$client = new Client();\n request() $crawler = $client->request('GET', 'http://www.symfony-project.org/');\n request Crawler Symfony\\Component\\DomCrawler\\Crawler $link = $crawler->selectLink('Plugins')->link();\n$crawler = $client->click($link);\n $form = $crawler->selectButton('sign in')->form();\n$crawler = $client->submit($form, array('signin[username]' => 'fabien', 'signin[password]' => 'xxxxxx'));\n $nodes = $crawler->filter('.error_list');\n\nif ($nodes->count())\n{\n die(sprintf(\"Authentification error: %s\\n\", $nodes->text()));\n}\n\nprintf(\"Nb tasks: %d\\n\", $crawler->filter('#nb_tasks')->text());\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2052/" ]
26,971
<p>As someone who hasn't used either technology on real-world projects I wonder if anyone knows how these two complement each other and how much their functionalities overlap?</p>
[ { "answer_id": 8580564, "author": "Ali Adravi", "author_id": 586227, "author_profile": "https://Stackoverflow.com/users/586227", "pm_score": 0, "selected": false, "text": "MyDataContext db = new MyDataContext();\nList<CUSTOMER_ORDER_LINEITEMResult> records = db.CUSTOMER_ORDER_LINEITEM(pram1, param2 ...).ToList<CUSTOMER_ORDER_LINEITEMResult>();\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
26,984
<p>I have been in both situations: </p> <ul> <li>Creating too many custom Exceptions</li> <li>Using too many general Exception class</li> </ul> <p>In both cases the project started OK but soon became an overhead to maintain (and refactor).</p> <p>So what is the best practice regarding the creation of your own Exception classes?</p>
[ { "answer_id": 27000, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "NullPointerException IndexOutofBoundsException" }, { "answer_id": 27041, "author": "Landon Kuhn", "author_id": 1785, "author_profile": "https://Stackoverflow.com/users/1785", "pm_score": 3, "selected": false, "text": "try {\n doIt();\n} catch (ExceptionType1 ex1) {\n // do something useful\n} catch (ExceptionType2 ex2) {\n // do the exact same useful thing that was done in the block above\n}\n" }, { "answer_id": 52793202, "author": "Sorter", "author_id": 1097600, "author_profile": "https://Stackoverflow.com/users/1097600", "pm_score": 0, "selected": false, "text": "IllegalStateException\nUnsupportedOperationException\nIllegalArgumentException\nNoSuchElementException\nNullPointerException\n public void validate(MyObject myObjectInstance) {\n if (!myObjectList.contains(myObjectInstance))\n throw new NoSuchElementException(\"object not present in list\");\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
27,009
<p>What are some of the strategies that are used when implementing FxCop / static analysis on existing code bases with existing violations? How can one most effectively reduce the static analysis violations?</p>
[ { "answer_id": 378439, "author": "Patrick from NDepend team", "author_id": 27194, "author_profile": "https://Stackoverflow.com/users/27194", "pm_score": -1, "selected": false, "text": "warnif count > 0 \nfrom m in Methods\nwhere m.CyclomaticComplexity > 20 &&\n m.WasAdded() || m.CodeWasChanged()\nselect new { m, m.CyclomaticComplexity }\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2822/" ]
27,018
<p>When applying the Single Responsibility Principle and looking at a class's reason to change, how do you determine whether that reason too change is too granular, or not granular enough?</p>
[ { "answer_id": 378439, "author": "Patrick from NDepend team", "author_id": 27194, "author_profile": "https://Stackoverflow.com/users/27194", "pm_score": -1, "selected": false, "text": "warnif count > 0 \nfrom m in Methods\nwhere m.CyclomaticComplexity > 20 &&\n m.WasAdded() || m.CodeWasChanged()\nselect new { m, m.CyclomaticComplexity }\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2822/" ]
27,020
<p>I have an Excel Spreadsheet like this</p> <pre> id | data for id | more data for id id | data for id id | data for id | more data for id | even more data for id id | data for id | more data for id id | data for id id | data for id | more data for id </pre> <p>Now I want to group the data of one id by alternating the background color of the rows</p> <pre> var color = white for each row if the first cell is not empty and color is white set color to green if the first cell is not empty and color is green set color to white set background of row to color </pre> <p>Can anyone help me with a macro or some VBA code</p> <p>Thanks</p>
[ { "answer_id": 27139, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 3, "selected": true, "text": "Public Sub HighLightRows()\n Dim i As Integer\n i = 1\n Dim c As Integer\n c = 3 'red\n\n Do While (Cells(i, 2) <> \"\")\n If (Cells(i, 1) <> \"\") Then 'check for new ID\n If c = 3 Then\n c = 4 'green\n Else\n c = 3 'red\n End If\n End If\n\n Rows(Trim(Str(i)) + \":\" + Trim(Str(i))).Interior.ColorIndex = c\n i = i + 1\n Loop\nEnd Sub\n" }, { "answer_id": 6768304, "author": "Adriano P", "author_id": 276311, "author_profile": "https://Stackoverflow.com/users/276311", "pm_score": 5, "selected": false, "text": "=IF(B2=B1,E1,1-E1)) [content of cell E2]\n" }, { "answer_id": 16961839, "author": "Laurent S.", "author_id": 2187273, "author_profile": "https://Stackoverflow.com/users/2187273", "pm_score": 2, "selected": false, "text": "Public Sub HighLightRows()\n Dim i As Integer\n i = 2 'start at 2, cause there's nothing to compare the first row with\n Dim c As Integer\n c = 2 'Color 1. Check http://dmcritchie.mvps.org/excel/colors.htm for color indexes\n\n Do While (Cells(i, 1) <> \"\")\n If (Cells(i, 1) <> Cells(i - 1, 1)) Then 'check for different value in cell A (index=1)\n If c = 2 Then\n c = 34 'color 2\n Else\n c = 2 'color 1\n End If\n End If\n\n Rows(Trim(Str(i)) + \":\" + Trim(Str(i))).Interior.ColorIndex = c\n i = i + 1\n Loop\nEnd Sub\n" }, { "answer_id": 28683156, "author": "KyleF", "author_id": 4598660, "author_profile": "https://Stackoverflow.com/users/4598660", "pm_score": 1, "selected": false, "text": "\nChangeBackgroundColor()\n' ChangeBackgroundColor Macro\n'\n' Keyboard Shortcut: Ctrl+Shift+B\nDim a As Integer\n a = 1\n Dim c As Integer\n c = 15 'gray\n Do While (Cells(a, 2) <> \"\")\n If (Cells(a, 1) <> \"\") Then 'check for new ID\n If c = 15 Then\n c = 2 'white\n Else\n c = 15 'gray\n End If\n End If\n Rows(Trim(Str(a)) + \":\" + Trim(Str(a))).Interior.ColorIndex = c\n a = a + 1\n Loop \n\n End Sub" }, { "answer_id": 30895802, "author": "AjV Jsy", "author_id": 2078245, "author_profile": "https://Stackoverflow.com/users/2078245", "pm_score": 0, "selected": false, "text": "Public Sub HighLightRows(intSheet As Integer)\n Dim intRow As Integer: intRow = 2 ' start at 2, cause there's nothing to compare the first row with\n Dim intCol As Integer: intCol = 1 ' define the column with changing values\n Dim Colr1 As Boolean: Colr1 = True ' Will flip True/False; adding 2 gives 1 or 2\n Dim lngColors(2 + True To 2 + False) As Long ' Indexes : 1 and 2\n ' True = -1, array index 1. False = 0, array index 2.\n lngColors(2 + False) = RGB(235, 235, 235) ' lngColors(2) = light grey\n lngColors(2 + True) = RGB(255, 255, 255) ' lngColors(1) = white\n\n Do While (Sheets(intSheet).Cells(intRow, 1) <> \"\")\n 'check for different value in intCol, flip the boolean if it's different\n If (Sheets(intSheet).Cells(intRow, intCol) <> Sheets(intSheet).Cells(intRow - 1, intCol)) Then Colr1 = Not Colr1\n Sheets(intSheet).Rows(intRow).Interior.Color = lngColors(2 + Colr1) ' one colour or the other\n ' Optional : retain borders (these no longer show through when interior colour is changed) by specifically setting them\n With Sheets(intSheet).Rows(intRow).Borders\n .LineStyle = xlContinuous\n .Weight = xlThin\n .Color = RGB(220, 220, 220)\n End With\n intRow = intRow + 1\n Loop\nEnd Sub\n Public Sub HighLightNULLs(intSheet As Integer)\n Dim intRow As Integer: intRow = 2 ' start at 2 to avoid the headings\n Dim intCol As Integer\n Dim lngColor As Long: lngColor = RGB(255, 255, 225) ' pale yellow\n\n For intRow = intRow To Sheets(intSheet).UsedRange.Rows.Count\n For intCol = 1 To Sheets(intSheet).UsedRange.Columns.Count\n If Sheets(intSheet).Cells(intRow, intCol) = \"NULL\" Then Sheets(intSheet).Cells(intRow, intCol).Interior.Color = lngColor\n Next intCol\n Next intRow\nEnd Sub\n" }, { "answer_id": 34124537, "author": "GONeale", "author_id": 41211, "author_profile": "https://Stackoverflow.com/users/41211", "pm_score": -1, "selected": false, "text": "=MOD(ROW(),2)=0 =MOD(COLUMN(),2)=0" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2798/" ]
27,027
<p>So you know a lot of Mac apps use "bundles": It looks like a single file to your application, but it's actually a folder with many files inside.</p> <p>For a version control system to handle this, it needs to:</p> <ul> <li>check out all the files in a directory, so the app can modify them as necessary</li> <li>at checkin, <ul> <li>commit files which have been modified</li> <li>add new files which the application has created</li> <li>mark as deleted files which are no longer there (since the app deleted them)</li> <li>manage this as one atomic change</li> </ul></li> </ul> <p>Any ideas on the best way to handle this with existing version control systems? Are any of the versioning systems more adept in this area? </p>
[ { "answer_id": 19727594, "author": "akauppi", "author_id": 14455, "author_profile": "https://Stackoverflow.com/users/14455", "pm_score": 1, "selected": false, "text": "hg addremove $ hg help addremove\nhg addremove [OPTION]... [FILE]...\n\nadd all new files, delete all missing files\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
27,030
<p>I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?</p>
[ { "answer_id": 27212, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 7, "selected": true, "text": "function objectsAreSame(x, y) {\n var objectsAreSame = true;\n for(var propertyName in x) {\n if(x[propertyName] !== y[propertyName]) {\n objectsAreSame = false;\n break;\n }\n }\n return objectsAreSame;\n}\n" }, { "answer_id": 649465, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "objectsAreSame x[propertyName] y[propertyName] typeof x[propertyName] == 'object'" }, { "answer_id": 3746944, "author": "Yuval", "author_id": 404861, "author_profile": "https://Stackoverflow.com/users/404861", "pm_score": 4, "selected": false, "text": "map // compare contents of two objects and return a list of differences\n// returns an array where each element is also an array in the form:\n// [accessor, diffType, leftValue, rightValue ]\n//\n// diffType is one of the following:\n// value: when primitive values at that index are different\n// undefined: when values in that index exist in one object but don't in \n// another; one of the values is always undefined\n// null: when a value in that index is null or undefined; values are\n// expressed as boolean values, indicated wheter they were nulls\n// type: when values in that index are of different types; values are \n// expressed as types\n// length: when arrays in that index are of different length; values are\n// the lengths of the arrays\n//\n\nfunction DiffObjects(o1, o2) {\n // choose a map() impl.\n // you may use $.map from jQuery if you wish\n var map = Array.prototype.map?\n function(a) { return Array.prototype.map.apply(a, Array.prototype.slice.call(arguments, 1)); } :\n function(a, f) { \n var ret = new Array(a.length), value;\n for ( var i = 0, length = a.length; i < length; i++ ) \n ret[i] = f(a[i], i);\n return ret.concat();\n };\n\n // shorthand for push impl.\n var push = Array.prototype.push;\n\n // check for null/undefined values\n if ((o1 == null) || (o2 == null)) {\n if (o1 != o2)\n return [[\"\", \"null\", o1!=null, o2!=null]];\n\n return undefined; // both null\n }\n // compare types\n if ((o1.constructor != o2.constructor) ||\n (typeof o1 != typeof o2)) {\n return [[\"\", \"type\", Object.prototype.toString.call(o1), Object.prototype.toString.call(o2) ]]; // different type\n\n }\n\n // compare arrays\n if (Object.prototype.toString.call(o1) == \"[object Array]\") {\n if (o1.length != o2.length) { \n return [[\"\", \"length\", o1.length, o2.length]]; // different length\n }\n var diff =[];\n for (var i=0; i<o1.length; i++) {\n // per element nested diff\n var innerDiff = DiffObjects(o1[i], o2[i]);\n if (innerDiff) { // o1[i] != o2[i]\n // merge diff array into parent's while including parent object name ([i])\n push.apply(diff, map(innerDiff, function(o, j) { o[0]=\"[\" + i + \"]\" + o[0]; return o; }));\n }\n }\n // if any differences were found, return them\n if (diff.length)\n return diff;\n // return nothing if arrays equal\n return undefined;\n }\n\n // compare object trees\n if (Object.prototype.toString.call(o1) == \"[object Object]\") {\n var diff =[];\n // check all props in o1\n for (var prop in o1) {\n // the double check in o1 is because in V8 objects remember keys set to undefined \n if ((typeof o2[prop] == \"undefined\") && (typeof o1[prop] != \"undefined\")) {\n // prop exists in o1 but not in o2\n diff.push([\"[\" + prop + \"]\", \"undefined\", o1[prop], undefined]); // prop exists in o1 but not in o2\n\n }\n else {\n // per element nested diff\n var innerDiff = DiffObjects(o1[prop], o2[prop]);\n if (innerDiff) { // o1[prop] != o2[prop]\n // merge diff array into parent's while including parent object name ([prop])\n push.apply(diff, map(innerDiff, function(o, j) { o[0]=\"[\" + prop + \"]\" + o[0]; return o; }));\n }\n\n }\n }\n for (var prop in o2) {\n // the double check in o2 is because in V8 objects remember keys set to undefined \n if ((typeof o1[prop] == \"undefined\") && (typeof o2[prop] != \"undefined\")) {\n // prop exists in o2 but not in o1\n diff.push([\"[\" + prop + \"]\", \"undefined\", undefined, o2[prop]]); // prop exists in o2 but not in o1\n\n }\n }\n // if any differences were found, return them\n if (diff.length)\n return diff;\n // return nothing if objects equal\n return undefined;\n }\n // if same type and not null or objects or arrays\n // perform primitive value comparison\n if (o1 != o2)\n return [[\"\", \"value\", o1, o2]];\n\n // return nothing if values are equal\n return undefined;\n}\n" }, { "answer_id": 6074070, "author": "jwood", "author_id": 346392, "author_profile": "https://Stackoverflow.com/users/346392", "pm_score": 4, "selected": false, "text": "function arraysAreEqual(ary1,ary2){\n return (ary1.join('') == ary2.join(''));\n}\n" }, { "answer_id": 25237317, "author": "Keshav Kalra", "author_id": 1746436, "author_profile": "https://Stackoverflow.com/users/1746436", "pm_score": 1, "selected": false, "text": "function used_to_compare_two_arrays(a, b)\n{\n // This block will make the array of indexed that array b contains a elements\n var c = a.filter(function(value, index, obj) {\n return b.indexOf(value) > -1;\n });\n\n // This is used for making comparison that both have same length if no condition go wrong \n if (c.length !== a.length) {\n return 0;\n } else{\n return 1;\n }\n}\n" }, { "answer_id": 42904039, "author": "Maxime Pacary", "author_id": 488666, "author_profile": "https://Stackoverflow.com/users/488666", "pm_score": 2, "selected": false, "text": "var assert = require('assert');\nvar hash = require('object-hash');\n\nvar obj1 = {a: 1, b: 2, c: 333},\n obj2 = {b: 2, a: 1, c: 444},\n obj3 = {b: \"AAA\", c: 555},\n obj4 = {c: 555, b: \"AAA\"};\n\nvar array1 = [obj1, obj2, obj3, obj4];\nvar array2 = [obj3, obj2, obj4, obj1]; // [obj3, obj3, obj2, obj1] should work as well\n\n// calling assert.deepEquals(array1, array2) at this point FAILS (throws an AssertionError)\n// even if array1 and array2 contain the same objects in different order,\n// because array1[0].c !== array2[0].c\n\n// sort objects in arrays by their hashes, so that if the arrays are identical,\n// their objects can be compared in the same order, one by one\nvar array1 = sortArrayOnHash(array1);\nvar array2 = sortArrayOnHash(array2);\n\n// then, this should output \"PASS\"\ntry {\n assert.deepEqual(array1, array2);\n console.log(\"PASS\");\n} catch (e) {\n console.log(\"FAIL\");\n console.log(e);\n}\n\n// You could define as well something like Array.prototype.sortOnHash()...\nfunction sortArrayOnHash(array) {\n return array.sort(function(a, b) {\n return hash(a) > hash(b);\n });\n}\n" }, { "answer_id": 52842903, "author": "Sanjay Verma", "author_id": 10515006, "author_profile": "https://Stackoverflow.com/users/10515006", "pm_score": 4, "selected": false, "text": "JSON.stringify() let array1 = [1,2,{value:'alpha'}] , array2 = [{value:'alpha'},'music',3,4];\n\nJSON.stringify(array1) // \"[1,2,{\"value\":\"alpha\"}]\"\n\nJSON.stringify(array2) // \"[{\"value\":\"alpha\"},\"music\",3,4]\"\n\nJSON.stringify(array1) === JSON.stringify(array2); // false\n" }, { "answer_id": 54031184, "author": "Henry Sellars", "author_id": 9643152, "author_profile": "https://Stackoverflow.com/users/9643152", "pm_score": 0, "selected": false, "text": "_.some const array1AndArray2NotEqual = \n _.some(array1, (a1, idx) => a1.key1 !== array2[idx].key1 \n || a1.key2 !== array2[idx].key2 \n || a1.key3 !== array2[idx].key3);\n" }, { "answer_id": 55256318, "author": "ttulka", "author_id": 2190498, "author_profile": "https://Stackoverflow.com/users/2190498", "pm_score": 6, "selected": false, "text": "JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1}) const objectsEqual = (o1, o2) =>\n Object.keys(o1).length === Object.keys(o2).length \n && Object.keys(o1).every(p => o1[p] === o2[p]);\n\nconst obj1 = { name: 'John', age: 33};\nconst obj2 = { age: 33, name: 'John' };\nconst obj3 = { name: 'John', age: 45 };\n \nconsole.log(objectsEqual(obj1, obj2)); // true\nconsole.log(objectsEqual(obj1, obj3)); // false const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };\nconst obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };\nconst obj3 = { name: 'John', age: 33 };\n\nconst objectsEqual = (o1, o2) => \n typeof o1 === 'object' && Object.keys(o1).length > 0 \n ? Object.keys(o1).length === Object.keys(o2).length \n && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))\n : o1 === o2;\n \nconsole.log(objectsEqual(obj1, obj2)); // true\nconsole.log(objectsEqual(obj1, obj3)); // false const arr1 = [obj1, obj1];\nconst arr2 = [obj1, obj2];\nconst arr3 = [obj1, obj3];\n\nconst arraysEqual = (a1, a2) => \n a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));\n\nconsole.log(arraysEqual(arr1, arr2)); // true\nconsole.log(arraysEqual(arr1, arr3)); // false\n" }, { "answer_id": 66147209, "author": "Wolfram", "author_id": 12634461, "author_profile": "https://Stackoverflow.com/users/12634461", "pm_score": 3, "selected": false, "text": "const objectsEqual = (o1, o2) => {\n if (o2 === null && o1 !== null) return false;\n return o1 !== null && typeof o1 === 'object' && Object.keys(o1).length > 0 ?\n Object.keys(o1).length === Object.keys(o2).length && \n Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))\n : (o1 !== null && Array.isArray(o1) && Array.isArray(o2) && !o1.length && \n !o2.length) ? true : o1 === o2;\n}\n" }, { "answer_id": 66199056, "author": "Vladimir Malikov", "author_id": 14929085, "author_profile": "https://Stackoverflow.com/users/14929085", "pm_score": 0, "selected": false, "text": "const array1 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];\nconst array2 = [{a: 1}, {b: 2}, { c: 0, d: { e: 1, f: 2, } }, [1,2,3,54]];\n\nconst arraysCompare = (a1, a2) => {\n if (a1.length !== a2.length) return false;\n const objectIteration = (object) => {\n const result = [];\n const objectReduce = (obj) => {\n for (let i in obj) {\n if (typeof obj[i] !== 'object') {\n result.push(`${i}${obj[i]}`);\n } else {\n objectReduce(obj[i]);\n }\n }\n };\n objectReduce(object);\n return result;\n };\n const reduceArray1 = a1.map(item => {\n if (typeof item !== 'object') return item;\n return objectIteration(item).join('');\n });\n const reduceArray2 = a2.map(item => {\n if (typeof item !== 'object') return item;\n return objectIteration(item).join('');\n });\n const compare = reduceArray1.map(item => reduceArray2.includes(item));\n return compare.reduce((acc, item) => acc + Number(item)) === a1.length;\n};\n\nconsole.log(arraysCompare(array1, array2));\n" }, { "answer_id": 67489928, "author": "Shawn W", "author_id": 3621197, "author_profile": "https://Stackoverflow.com/users/3621197", "pm_score": 2, "selected": false, "text": "const obj1 = { name: 'John', age: 33};\nconst obj2 = { age: 33, name: 'John' };\nconst obj3 = { name: 'John', age: 45 };\n\nconst equalObjs = ( obj1, obj2 ) => {\nlet keyExist = false;\nfor ( const [key, value] of Object.entries(obj1) ) {\n // Search each key in reference object and attach a callback function to \n // compare the two object keys\n if( Object.keys(obj2).some( ( e ) => e == key ) ) {\n keyExist = true;\n }\n}\n\nreturn keyExist;\n\n}\n\n\nconsole.info( equalObjs( obj1, obj2 ) );\n // Sort Arrays\n var arr1 = arr1.sort(( a, b ) => {\n var fa = Object.keys(a);\n var fb = Object.keys(b);\n\n if (fa < fb) {\n return -1;\n }\n if (fa > fb) {\n return 1;\n }\n return 0;\n});\n\nvar arr2 = arr2.sort(( a, b ) => {\n var fa = Object.keys(a);\n var fb = Object.keys(b);\n\n if (fa < fb) {\n return -1;\n }\n if (fa > fb) {\n return 1;\n }\n return 0;\n});\n\nconst equalArrays = ( arr1, arr2 ) => {\n // If the arrays are different length we an eliminate immediately\n if( arr1.length !== arr2.length ) {\n return false;\n } else if ( arr1.every(( obj, index ) => equalObjs( obj, arr2[index] ) ) ) {\n return true;\n } else { \n return false;\n }\n }\n\n console.info( equalArrays( arr1, arr2 ) );\n" }, { "answer_id": 69896160, "author": "i6f70", "author_id": 11617744, "author_profile": "https://Stackoverflow.com/users/11617744", "pm_score": 2, "selected": false, "text": " /*\n null AND null // true\n undefined AND undefined // true\n null AND undefined // false\n [] AND [] // true\n [1, 2, 'test'] AND ['test', 2, 1] // true\n [1, 2, 'test'] AND ['test', 2, 3] // false\n [undefined, 2, 'test'] AND ['test', 2, 1] // false\n [undefined, 2, 'test'] AND ['test', 2, undefined] // true\n [[1, 2], 'test'] AND ['test', [2, 1]] // true\n [1, 'test'] AND ['test', [2, 1]] // false\n [[2, 1], 'test'] AND ['test', [2, 1]] // true\n [[2, 1], 'test'] AND ['test', [2, 3]] // false\n [[[3, 4], 2], 'test'] AND ['test', [2, [3, 4]]] // true\n [[[3, 4], 2], 'test'] AND ['test', [2, [5, 4]]] // false\n [{x: 1, y: 2}, 'test'] AND ['test', {x: 1, y: 2}] // true\n 1 AND 1 // true\n {test: 1} AND ['test', 2, 1] // false\n {test: 1} AND {test: 1} // true\n {test: 1} AND {test: 2} // false\n {test: [1, 2]} AND {test: [1, 2]} // true\n {test: [1, 2]} AND {test: [1]} // false\n {test: [1, 2], x: 1} AND {test: [1, 2], x: 2} // false\n {test: [1, { z: 5 }], x: 1} AND {x: 1, test: [1, { z: 5}]} // true\n {test: [1, { z: 5 }], x: 1} AND {x: 1, test: [1, { z: 6}]} // false\n */\n function is_equal(x, y) {\n const\n arr1 = x,\n arr2 = y,\n is_objects_equal = function (obj_x, obj_y) {\n if (!(\n typeof obj_x === 'object' &&\n Object.keys(obj_x).length > 0\n ))\n return obj_x === obj_y;\n\n return Object.keys(obj_x).length === Object.keys(obj_y).length &&\n Object.keys(obj_x).every(p => is_objects_equal(obj_x[p], obj_y[p]));\n }\n ;\n\n if (!( Array.isArray(arr1) && Array.isArray(arr2) ))\n return (\n arr1 && typeof arr1 === 'object' &&\n arr2 && typeof arr2 === 'object'\n )\n ? is_objects_equal(arr1, arr2)\n : arr1 === arr2;\n\n if (arr1.length !== arr2.length)\n return false;\n\n for (const idx_1 of arr1.keys())\n for (const idx_2 of arr2.keys())\n if (\n (\n Array.isArray(arr1[idx_1]) &&\n this.is_equal(arr1[idx_1], arr2[idx_2])\n ) ||\n is_objects_equal(arr1[idx_1], arr2[idx_2])\n )\n {\n arr2.splice(idx_2, 1);\n break;\n }\n\n return !arr2.length;\n }" }, { "answer_id": 70286558, "author": "Mr.P", "author_id": 3257387, "author_profile": "https://Stackoverflow.com/users/3257387", "pm_score": 1, "selected": false, "text": "const objectsEqual = (o1, o2) => {\n let match = false\n if(typeof o1 === 'object' && Object.keys(o1).length > 0) {\n match = (Object.keys(o1).length === Object.keys(o2).length && Object.keys(o1).every(p => objectsEqual(o1[p], o2[p])))\n }else {\n match = (o1 === o2)\n }\n return match\n}\n\nconst arraysEqual = (a1, a2) => {\n let finalMatch = []\n let itemFound = []\n \n if(a1.length === a2.length) {\n finalMatch = []\n a1.forEach( i1 => {\n itemFound = []\n a2.forEach( i2 => { \n itemFound.push(objectsEqual(i1, i2)) \n })\n finalMatch.push(itemFound.some( i => i === true)) \n }) \n } \n return finalMatch.every(i => i === true)\n}\n\nconst ar1 = [\n { id: 1, name: \"Johnny\", data: { body: \"Some text\"}},\n { id: 2, name: \"Jimmy\"}\n]\nconst ar2 = [\n {name: \"Jimmy\", id: 2},\n {name: \"Johnny\", data: { body: \"Some text\"}, id: 1}\n]\n\n\nconsole.log(\"Match:\",arraysEqual(ar1, ar2))\n const _ = require('lodash')\n\nconst isArrayEqual = (x, y) => {\n return _.isEmpty(_.xorWith(x, y, _.isEqual));\n};\n" }, { "answer_id": 72691567, "author": "Oussama Filani", "author_id": 9012478, "author_profile": "https://Stackoverflow.com/users/9012478", "pm_score": 0, "selected": false, "text": "const collection1 = [\n { id: \"1\", name: \"item 1\", subtitle: \"This is a subtitle\", parentId: \"1\" },\n { id: \"2\", name: \"item 2\", parentId: \"1\" },\n { id: \"3\", name: \"item 3\", parentId: \"1\" },\n]\nconst collection2 = [\n { id: \"3\", name: \"item 3\", parentId: \"1\" },\n { id: \"2\", name: \"item 2\", parentId: \"1\" },\n { id: \"1\", name: \"item 1\", subtitle: \"This is a subtitle\", parentId: \"1\" },\n]\n\n\nconst contains = (arr, obj) => {\n let i = arr.length;\n while (i--) {\n if (JSON.stringify(arr[i]) === JSON.stringify(obj)) {\n return true;\n }\n }\n return false;\n}\n\nconst isEqual = (obj1, obj2) => {\n let n = 0\n if (obj1.length !== obj2.length) {\n return false;\n }\n for (let i = 0; i < obj1.length; i++) {\n if (contains(obj2, obj1[i])) {\n n++\n }\n }\n return n === obj1.length\n}\n\nconsole.log(isEqual(collection1,collection2))" }, { "answer_id": 72846327, "author": "C-lio Garcia", "author_id": 2638849, "author_profile": "https://Stackoverflow.com/users/2638849", "pm_score": -1, "selected": false, "text": "type AB = {\n nome: string;\n}\n\nconst a: AB[] = [{ nome: 'Célio' }];\nconst b: AB[] = [{ nome: 'Célio' }];\n\nconsole.log(a === b); // false\nconsole.log(JSON.stringify(a) === JSON.stringify(b)); // true\n\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2176/" ]
27,034
<p>My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled:</p> <pre><code>var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings"); shareProxiesPref.disabled = proxyTypePref.value != 1; </code></pre> <p>Isn't it better to do an if on <code>proxyTypePref.value</code>, and then declare the var inside the result, only if you need it?</p> <p>(Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.)</p> <hr> <p><strong>UPDATE:</strong></p> <p>The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here:</p> <p><a href="http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js" rel="nofollow noreferrer">http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js</a></p> <p>Basically, when you look at the <strong>Connect</strong> preferences window in Firefox, clicking the proxy <strong>modes</strong> (radio buttons), causes various form elements to enable|disable.</p>
[ { "answer_id": 27039, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "sharedProxiesPref.disabled" }, { "answer_id": 27319, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 1, "selected": false, "text": "shareProxiesPref.disabled proxyTypePref.value document.getElementById" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
27,044
<p>I'm accessing an Ubuntu machine using PuTTY, and using gcc.</p> <p>The default <code>LANG</code> environment variable on this machine is set to <code>en_NZ.UTF-8</code>, which causes GCC to think PuTTY is capable of displaying UTF-8 text, which it doesn't seem to be. Maybe it's my font, I don't know - it does this:</p> <pre><code>foo.c:1: error: expected â=â, â,â, â;â, âasmâ or â__attribute__â at end of input </code></pre> <p>If I set it with <code>export LANG=en_NZ</code>, then this causes GCC to behave correctly, I get:</p> <pre><code>foo.c:1: error: expected '=', ',', ';', 'asm' or '__attribute__' at end of input </code></pre> <p>but this then causes everything else to go wrong. For example</p> <pre><code>man foo man: can't set the locale; make sure $LC_* and $LANG are correct </code></pre> <p>I've trawled Google and I can't for the life of me find out what I have to put in there for it to just use ASCII. <code>en_NZ.ASCII</code> doesn't work, nor do any of the other things I can find.</p> <p>Thanks</p>
[ { "answer_id": 27051, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": true, "text": "LANG=en_NZ en_NZ /var/lib/locales/supported.d/local en_NZ ISO-8859-1 /usr/sbin/locale-gen locale-gen en_NZ" }, { "answer_id": 1419312, "author": "drewr", "author_id": 3227, "author_profile": "https://Stackoverflow.com/users/3227", "pm_score": 0, "selected": false, "text": "aptitude install locales\n dpkg-reconfigure locales\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
27,065
<p>Do any of you know of a tool that will search for .class files and then display their compiled versions?</p> <p>I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).</p>
[ { "answer_id": 27123, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 6, "selected": false, "text": "ClassFile {\n u4 magic;\n u2 minor_version;\n u2 major_version;\n CA FE BA BE 00 00 00 33\n import java.io.*;\n\npublic class Demo {\n public static void main(String[] args) throws IOException {\n ClassLoader loader = Demo.class.getClassLoader();\n try (InputStream in = loader.getResourceAsStream(\"Demo.class\");\n DataInputStream data = new DataInputStream(in)) {\n if (0xCAFEBABE != data.readInt()) {\n throw new IOException(\"invalid header\");\n }\n int minor = data.readUnsignedShort();\n int major = data.readUnsignedShort();\n System.out.println(major + \".\" + minor);\n }\n }\n}\n Target Major.minor Hex\n1.1 45.3 0x2D\n1.2 46.0 0x2E\n1.3 47.0 0x2F\n1.4 48.0 0x30\n5 (1.5) 49.0 0x31\n6 (1.6) 50.0 0x32\n7 (1.7) 51.0 0x33\n8 (1.8) 52.0 0x34\n9 53.0 0x35\n" }, { "answer_id": 27505, "author": "staffan", "author_id": 988, "author_profile": "https://Stackoverflow.com/users/988", "pm_score": 8, "selected": true, "text": "-verbose > javap -verbose MyClass\nCompiled from \"MyClass.java\"\npublic class MyClass\n SourceFile: \"MyClass.java\"\n minor version: 0\n major version: 46\n...\n WINDOWS> javap -verbose MyClass | find \"version\"\nLINUX > javap -verbose MyClass | grep version\n" }, { "answer_id": 27904, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 3, "selected": false, "text": "find /target-folder -name \\*.class | xargs file | grep \"version 50\\.0\"\n" }, { "answer_id": 25201428, "author": "igo", "author_id": 1795220, "author_profile": "https://Stackoverflow.com/users/1795220", "pm_score": 3, "selected": false, "text": "od -t d -j 7 -N 1 ApplicationContextProvider.class | head -1 | awk '{print \"Java\", $2 - 44}'\n" }, { "answer_id": 37256401, "author": "Radoslav Kastiel", "author_id": 6341080, "author_profile": "https://Stackoverflow.com/users/6341080", "pm_score": 2, "selected": false, "text": "System.out.println(\"JAVA DEV ver.: \" + com.sun.deploy.config.BuiltInProperties.CURRENT_VERSION);\nSystem.out.println(\"JAVA RUN v. X.Y: \" + System.getProperty(\"java.specification.version\") );\nSystem.out.println(\"JAVA RUN v. W.X.Y.Z: \" + com.sun.deploy.config.Config.getJavaVersion() ); //_javaVersionProperty\nSystem.out.println(\"JAVA RUN full ver.: \" + System.getProperty(\"java.runtime.version\") + \" (may return unknown)\" );\nSystem.out.println(\"JAVA RUN type: \" + com.sun.deploy.config.Config.getJavaRuntimeNameProperty() );\n JAVA DEV ver.: 1.8.0_77\nJAVA RUN v. X.Y: 1.8\nJAVA RUN v. W.X.Y.Z: 1.8.0_91\nJAVA RUN full ver.: 1.8.0_91-b14 (may return unknown)\nJAVA RUN type: Java(TM) SE Runtime Environment\n" }, { "answer_id": 58642950, "author": "Marinos An", "author_id": 1555615, "author_profile": "https://Stackoverflow.com/users/1555615", "pm_score": 2, "selected": false, "text": "import java.io.IOException;\nimport java.io.InputStream;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.apache.commons.codec.DecoderException;\nimport org.apache.commons.codec.binary.Hex;\nimport org.apache.commons.io.IOUtils;\npublic class Main {\n public static void main(String[] args) throws DecoderException, IOException {\n Class clazz = Main.class;\n Map<String,String> versionMapping = new HashMap();\n versionMapping.put(\"002D\",\"1.1\");\n versionMapping.put(\"002E\",\"1.2\");\n versionMapping.put(\"002F\",\"1.3\");\n versionMapping.put(\"0030\",\"1.4\");\n versionMapping.put(\"0031\",\"5.0\");\n versionMapping.put(\"0032\",\"6.0\");\n versionMapping.put(\"0033\",\"7\");\n versionMapping.put(\"0034\",\"8\");\n versionMapping.put(\"0035\",\"9\");\n versionMapping.put(\"0036\",\"10\");\n versionMapping.put(\"0037\",\"11\");\n versionMapping.put(\"0038\",\"12\");\n versionMapping.put(\"0039\",\"13\");\n versionMapping.put(\"003A\",\"14\");\n\n InputStream stream = clazz.getClassLoader()\n .getResourceAsStream(clazz.getName().replace(\".\", \"/\") + \".class\");\n byte[] classBytes = IOUtils.toByteArray(stream);\n String versionInHexString = \n Hex.encodeHexString(new byte[]{classBytes[6],classBytes[7]});\n System.out.println(\"bytecode version: \"+versionMapping.get(versionInHexString));\n }\n}\n" }, { "answer_id": 63204108, "author": "DuncG", "author_id": 4712734, "author_profile": "https://Stackoverflow.com/users/4712734", "pm_score": 0, "selected": false, "text": "public static void main(String[] args) throws IOException {\n var files = Arrays.stream(args).map(Path::of).collect(Collectors.toList());\n ShowClassVersions v = new ShowClassVersions();\n for (var f : files) {\n v.scan(f);\n }\n v.print();\n}\n Version: 49.0 ~ JDK-5\n C:\\jars\\junit-platform-console-standalone-1.7.1.jar\nVersion: 50.0 ~ JDK-6\n C:\\jars\\junit-platform-console-standalone-1.7.1.jar\nVersion: 52.0 ~ JDK-8\n C:\\java\\apache-tomcat-10.0.12\\lib\\catalina.jar\n C:\\jars\\junit-platform-console-standalone-1.7.1.jar\nVersion: 53.0 ~ JDK-9\n C:\\java\\apache-tomcat-10.0.12\\lib\\catalina.jar\n C:\\jars\\junit-platform-console-standalone-1.7.1.jar\n public class ShowClassVersions {\n private TreeMap<String, ArrayList<String>> vers = new TreeMap<>();\n private static final byte[] CLASS_MAGIC = new byte[] { (byte) 0xca, (byte) 0xfe, (byte) 0xba, (byte) 0xbe };\n private final byte[] bytes = new byte[8];\n\n private String versionOfClass(InputStream in) throws IOException {\n int c = in.readNBytes(bytes, 0, bytes.length);\n if (c == bytes.length && Arrays.mismatch(bytes, CLASS_MAGIC) == CLASS_MAGIC.length) {\n int minorVersion = (bytes[4] << 8) + (bytes[4] << 0);\n int majorVersion = (bytes[6] << 8) + (bytes[7] << 0);\n return \"\"+ majorVersion + \".\" + minorVersion;\n }\n return \"Unknown\";\n }\n\n private Matcher classes = Pattern.compile(\"\\\\.(class|ear|war|jar)$\").matcher(\"\");\n\n // This code scans any path (dir or file):\n public void scan(Path f) throws IOException {\n try (var stream = Files.find(f, Integer.MAX_VALUE,\n (p, a) -> a.isRegularFile() && classes.reset(p.toString()).find())) {\n stream.forEach(this::scanFile);\n }\n }\n\n private void scanFile(Path f) {\n String fn = f.getFileName().toString();\n try {\n if (fn.endsWith(\".ear\") || fn.endsWith(\".war\") || fn.endsWith(\".jar\"))\n scanArchive(f);\n else if (fn.endsWith(\".class\"))\n store(f.toAbsolutePath().toString(), versionOfClass(f));\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n\n private void scanArchive(Path p) throws IOException {\n try (InputStream in = Files.newInputStream(p)) {\n scanArchive(p.toAbsolutePath().toString(), Files.newInputStream(p));\n }\n }\n\n private void scanArchive(String desc, InputStream in) throws IOException {\n HashSet<String> versions = new HashSet<>();\n ZipInputStream zip = new ZipInputStream(in);\n for (ZipEntry entry = null; (entry = zip.getNextEntry()) != null; ) {\n String name = entry.getName();\n // There could be different compiler versions per class in one jar\n if (name.endsWith(\".class\")) {\n versions.add(versionOfClass(zip));\n } else if (name.endsWith(\".jar\") || name.endsWith(\".war\")) {\n scanArchive(desc + \" => \" + name, zip);\n }\n }\n if (versions.size() > 1)\n System.out.println(\"Warn: \"+desc+\" contains multiple versions: \"+versions);\n\n for (String version : versions)\n store(desc, version);\n }\n\n private String versionOfClass(Path p) throws IOException {\n try (InputStream in = Files.newInputStream(p)) {\n return versionOfClass(in);\n }\n }\n\n private void store(String path, String jdkVer) {\n vers.computeIfAbsent(jdkVer, k -> new ArrayList<>()).add(path);\n }\n\n // Could add a mapping table for JDK names, this guesses based on (JDK17 = 61.0)\n public void print() {\n for (var ver : vers.keySet()) {\n System.out.println(\"Version: \" + ver + \" ~ \" +jdkOf(ver));\n for (var p : vers.get(ver)) {\n System.out.println(\" \" + p);\n }\n }\n }\n\n private static String jdkOf(String ver) {\n try {\n return \"JDK-\"+((int)Float.parseFloat(ver)-44);\n }\n catch(NumberFormatException nfe)\n {\n return \"JDK-??\";\n }\n }\n}\n" }, { "answer_id": 70299029, "author": "BaiJiFeiLong", "author_id": 5254103, "author_profile": "https://Stackoverflow.com/users/5254103", "pm_score": 2, "selected": false, "text": "hexdump -s 7 -n 1 -e '\"%d\"' Main.class busybox.exe hexdump -s 7 -n 1 -e '\"%d\"' Main.class 55 -s 7 -n 1 -e '\"%d\"' JDK 1.1 = 45 (0x2D hex)\nJDK 1.2 = 46 (0x2E hex)\nJDK 1.3 = 47 (0x2F hex)\nJDK 1.4 = 48 (0x30 hex)\nJava SE 5.0 = 49 (0x31 hex)\nJava SE 6.0 = 50 (0x32 hex)\nJava SE 7 = 51 (0x33 hex)\nJava SE 8 = 52 (0x34 hex)\nJava SE 9 = 53 (0x35 hex)\nJava SE 10 = 54 (0x36 hex)\nJava SE 11 = 55 (0x37 hex)\nJava SE 12 = 56 (0x38 hex)\nJava SE 13 = 57 (0x39 hex)\nJava SE 14 = 58 (0x3A hex)\nJava SE 15 = 59 (0x3B hex)\nJava SE 16 = 60 (0x3C hex)\nJava SE 17 = 61 (0x3D hex)\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
27,071
<p>I have an old C library with a function that takes a void**:</p> <pre><code>oldFunction(void** pStuff); </code></pre> <p>I'm trying to call this function from managed C++ (m_pStuff is a member of the parent ref class of type void*):</p> <pre><code>oldFunction( static_cast&lt;sqlite3**&gt;( &amp;m_pStuff ) ); </code></pre> <p>This gives me the following error from Visual Studio:</p> <blockquote> <p>error C2440: 'static_cast' : cannot convert from 'cli::interior_ptr' to 'void **'</p> </blockquote> <p>I'm guessing the compiler is converting the void* member pointer to a cli::interior_ptr behind my back.</p> <p>Any advice on how to do this?</p>
[ { "answer_id": 27326, "author": "Ben Childs", "author_id": 2925, "author_profile": "https://Stackoverflow.com/users/2925", "pm_score": 2, "selected": true, "text": "#pragma unmanaged\n\nvoid* m_pStuff\n\n#pragma managed\n // TestSol.cpp : main project file.\n\n#include \"stdafx.h\"\n\nusing namespace System;\n\n#pragma unmanaged\n\nvoid oldFunction(void** pStuff)\n{\n return;\n}\n\n#pragma managed\n\nref class Test\n{\npublic:\n void* m_test;\n\n};\n\nint main(array<System::String ^> ^args)\n{\n Console::WriteLine(L\"Hello World\");\n\n Test^ test = gcnew Test();\n void* pStuff = test->m_test;\n oldFunction(&pStuff);\n test->m_test = pStuff;\n\n return 0;\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39040/" ]
27,077
<p>When I do:</p> <pre><code>$ find / </code></pre> <p>It searches the entire system.<br> How do I prevent that?</p> <p>(This question comes from an "<a href="https://stackoverflow.com/questions/18836/why-doesnt-find-find-anything#26182">answer</a>" to another question.)</p>
[ { "answer_id": 27084, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "$ ls *.ksh\n" }, { "answer_id": 27089, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 3, "selected": false, "text": "-maxdepth n\n True if the depth of the current file into the tree is less than\n or equal to n.\n\n-mindepth n\n True if the depth of the current file into the tree is greater\n than or equal to n.\n" }, { "answer_id": 27161, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "echo /specific/dir/*.jpg\n ls *.jpg\n ls foo.jpg bar.jpg\n" }, { "answer_id": 28262, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 3, "selected": true, "text": "find . \\( -type d ! -name . -prune \\) -o \\( <the bit you want to look for> \\)\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
27,078
<p>I am debugging my ASP.NET application on my Windows XP box with a virtual directory set up in IIS (5.1).</p> <p>I am also running <strong>VirtualPC</strong> with XP and IE6 for testing purposes. When I connect to my real machine from the virtual machine, I enter the URL: <a href="http://machinename/projectname" rel="nofollow noreferrer">http://machinename/projectname</a>.</p> <p>I get a security popup to connect to my machine (which I expect), but the User name field is disabled. I cannot change it from machinename\Guest to machinename\username in order to connect.</p> <p>How do I get this to enable so I can enter the correct credentials.</p>
[ { "answer_id": 27084, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "$ ls *.ksh\n" }, { "answer_id": 27089, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 3, "selected": false, "text": "-maxdepth n\n True if the depth of the current file into the tree is less than\n or equal to n.\n\n-mindepth n\n True if the depth of the current file into the tree is greater\n than or equal to n.\n" }, { "answer_id": 27161, "author": "aib", "author_id": 1088, "author_profile": "https://Stackoverflow.com/users/1088", "pm_score": 0, "selected": false, "text": "echo /specific/dir/*.jpg\n ls *.jpg\n ls foo.jpg bar.jpg\n" }, { "answer_id": 28262, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 3, "selected": true, "text": "find . \\( -type d ! -name . -prune \\) -o \\( <the bit you want to look for> \\)\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/417/" ]
27,095
<p>I did this Just for kicks (so, not exactly a question, i can see the downmodding happening already) but, in lieu of Google's newfound <a href="http://www.google.com/search?hl=en&amp;q=1999999999999999-1999999999999995&amp;btnG=Search" rel="nofollow noreferrer">inability</a> to do <a href="http://www.google.com/search?hl=en&amp;q=400000000000002-400000000000001&amp;btnG=Search" rel="nofollow noreferrer">math</a> <a href="http://www.google.com/search?hl=en&amp;q=10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001-10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000&amp;btnG=Search" rel="nofollow noreferrer">correctly</a> (check it! according to google 500,000,000,000,002 - 500,000,000,000,001 = 0), i figured i'd try the following in C to run a little theory.</p> <pre><code>int main() { char* a = "399999999999999"; char* b = "399999999999998"; float da = atof(a); float db = atof(b); printf("%s - %s = %f\n", a, b, da-db); a = "500000000000002"; b = "500000000000001"; da = atof(a); db = atof(b); printf("%s - %s = %f\n", a, b, da-db); } </code></pre> <p>When you run this program, you get the following</p> <pre><code> 399999999999999 - 399999999999998 = 0.000000 500000000000002 - 500000000000001 = 0.000000 </code></pre> <p>It would seem like Google is using simple 32 bit floating precision (the error here), if you switch float for double in the above code, you fix the issue! Could this be it?</p> <p>/mp</p>
[ { "answer_id": 28443, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 1, "selected": false, "text": "Double.MaxValue Double.MaxValue Double.PositiveInfinity" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/27095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547/" ]
27,148
<p>I want to merge multiple rss feeds into a single feed, removing any duplicates. Specifically, I'm interested in merging the feeds for the <a href="https://stackoverflow.com/tags">tags</a> I'm interested in.</p> <p>[A quick <a href="http://www.google.com/search?q=rss+merge+reader" rel="nofollow noreferrer">search</a> turned up some promising links, which I don't have time to visit at the moment]</p> <hr /> <p>Broadly speaking, the ideal would be a reader that would list all the available tags on the site and toggle them on and off, allowing me to explore what's available, keep track of questions I've visited, new answers on interesting feeds, etc, etc . . . though I don't suppose such a things exists right now.</p> <p>As I randomly explore the site and see questions I think are interesting, I inevitably find &quot;oh yes, that one looked interesting a couple days ago when I read it the first time, and hasn't been updated since&quot;. It would be much nicer if my machine would keep track of such deails for me :)</p> <hr /> <p><strong>Update:</strong> You can now use &quot;and&quot;, &quot;or&quot;, and &quot;not&quot; to combine multiple tags into a single feed: <a href="https://blog.stackoverflow.com/2008/10/tags-and-tags-or-tags/">Tags AND Tags OR Tags</a></p> <hr /> <p><strong>Update:</strong> You can now use <a href="https://stackexchange.com/filters">Filters</a> to watch tags across one or multiple sites: <a href="https://blog.stackoverflow.com/2011/04/improved-tag-sets/">Improved Tag Stes</a></p>
[ { "answer_id": 36441, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 2, "selected": false, "text": "'#' '+' '+' http://pipes.yahoo.com/pipes/pipe.run?_id=uP22vN923RG_c71O1ZzWFw&_render=rss&tags=.net+c%23+powershell\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
27,219
<p>Given a select with multiple option's in jQuery. </p> <pre><code>$select = $("&lt;select&gt;&lt;/select&gt;"); $select.append("&lt;option&gt;Jason&lt;/option&gt;") //Key = 1 .append("&lt;option&gt;John&lt;/option&gt;") //Key = 32 .append("&lt;option&gt;Paul&lt;/option&gt;") //Key = 423 </code></pre> <p>How should the key be stored and retrieved?</p> <p>The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).</p> <p>Thanks</p> <p>and in the spirit of TMTOWTDI.</p> <pre><code>$option = $("&lt;option&gt;&lt;/option&gt;"); $select = $("&lt;select&gt;&lt;/select&gt;"); $select.addOption = function(value,text){ $(this).append($("&lt;option/&gt;").val(value).text(text)); }; $select.append($option.val(1).text("Jason").clone()) .append("&lt;option value=32&gt;John&lt;/option&gt;") .append($("&lt;option/&gt;").val(423).text("Paul")) .addOption("321","Lenny"); </code></pre>
[ { "answer_id": 27231, "author": "Lucas Wilson-Richter", "author_id": 1157, "author_profile": "https://Stackoverflow.com/users/1157", "pm_score": 3, "selected": false, "text": "<option> <option value=1>Jason</option>\n" }, { "answer_id": 27259, "author": "Juan", "author_id": 550, "author_profile": "https://Stackoverflow.com/users/550", "pm_score": 5, "selected": true, "text": "$select = $('<select id=\"mySelect\"></select>');\n$select.append('<option value=\"1\">Jason</option>') //Key = 1\n .append('<option value=\"32\">John</option>') //Key = 32\n .append('<option value=\"423\">Paul</option>') //Key = 423\n $( '#mySelect' ).val(); //Gets the value for the current selected option\n\n$( '#mySelect > option' ).each( function( index, option ) {\n option.val(); //The value for each individual option\n} );\n" }, { "answer_id": 27281, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 2, "selected": false, "text": "$select = $(\"<select></select>\");\n$select.append(\"<option data-key=\\\"1\\\">Jason</option>\") //Key = 1\n .append(\"<option data-key=\\\"32\\\">John</option>\") //Key = 32\n .append(\"<option data-key=\\\"423\\\">Paul</option>\") //Key = 423\n var key = $('select option:selected').attr('data-key');\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1293/" ]
27,220
<p>I'm looking for a method, or a code snippet for converting std::string to LPCWSTR</p>
[ { "answer_id": 27291, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 4, "selected": false, "text": "#include <atlbase.h>\n#include <atlconv.h>\n\n. . .\n\nstring myStr(\"My string\");\nCA2W unicodeStr(myStr);\n" }, { "answer_id": 4139684, "author": "Benny Hilfiger", "author_id": 502542, "author_profile": "https://Stackoverflow.com/users/502542", "pm_score": 7, "selected": false, "text": "std::wstring stemp = std::wstring(s.begin(), s.end());\nLPCWSTR sw = stemp.c_str();\n" }, { "answer_id": 64532484, "author": "Ashi", "author_id": 592651, "author_profile": "https://Stackoverflow.com/users/592651", "pm_score": 2, "selected": false, "text": "#include <codecvt>\n\nstd::string s = \"Hi\";\nstd::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;\nstd::wstring wide = converter.from_bytes(s);\nLPCWSTR result = wide.c_str();\n codecvt_utf8_utf16" }, { "answer_id": 66507740, "author": "Top-Master", "author_id": 8740349, "author_profile": "https://Stackoverflow.com/users/8740349", "pm_score": 1, "selected": false, "text": ".c_str() .data() const_cast const_cast const const_cast std::wstring s2ws(const std::string &s, bool isUtf8 = true)\n{\n int len;\n int slength = (int)s.length() + 1;\n len = MultiByteToWideChar(isUtf8 ? CP_UTF8 : CP_ACP, 0, s.c_str(), slength, 0, 0);\n std::wstring buf;\n buf.resize(len);\n MultiByteToWideChar(isUtf8 ? CP_UTF8 : CP_ACP, 0, s.c_str(), slength,\n const_cast<wchar_t *>(buf.c_str()), len);\n return buf;\n}\n\nstd::wstring wrapper = s2ws(u8\"My UTF8 string!\");\nLPCWSTR result = wrapper.c_str();\n CP_UTF8 CP_ACP false" }, { "answer_id": 67597861, "author": "Sabbir Pulak", "author_id": 7134879, "author_profile": "https://Stackoverflow.com/users/7134879", "pm_score": -1, "selected": false, "text": "string s = \"So Easy Bro\"\nLPCWSTR wide_string;\n\nwide_string = CA2T(s.c_str());\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701/" ]
27,222
<p>I am looking for good methods of manipulating HTML in PHP. For example, the problem I currently have is dealing with malformed HTML.</p> <p>I am getting input that looks something like this:</p> <pre><code>&lt;div&gt;This is some &lt;b&gt;text </code></pre> <p>As you noticed, the HTML is missing closing tags. I could use regex or an XML Parser to solve this problem. However, it is likely that I will have to do other DOM manipulation in the future. I wonder if there are any good PHP libraries that handle DOM manipulation similar to how Javascript deals with DOM manipulation.</p>
[ { "answer_id": 4303405, "author": "Decko", "author_id": 320702, "author_profile": "https://Stackoverflow.com/users/320702", "pm_score": 2, "selected": false, "text": "$d = new DOMDocument;\n$d->loadHTML('<div>This is some <b>text');\n$d->saveHTML();\n <!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\" \"http://www.w3.org/TR/REC-html40/loose.dtd\">\n<html>\n <body>\n <div>This is some <b>text</b></div>\n </body>\n</html>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
27,240
<p>In Java 5 and above you have the foreach loop, which works magically on anything that implements <code>Iterable</code>:</p> <pre><code>for (Object o : list) { doStuff(o); } </code></pre> <p>However, <code>Enumerable</code> still does not implement <code>Iterable</code>, meaning that to iterate over an <code>Enumeration</code> you must do the following:</p> <pre><code>for(; e.hasMoreElements() ;) { doStuff(e.nextElement()); } </code></pre> <p>Does anyone know if there is a reason why <code>Enumeration</code> still does not implement <code>Iterable</code>?</p> <p><strong>Edit:</strong> As a clarification, I'm not talking about the language concept of an <a href="http://en.wikipedia.org/wiki/Enumerated_type" rel="noreferrer">enum</a>, I'm talking a Java-specific class in the Java API called '<a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Enumeration.html" rel="noreferrer">Enumeration</a>'. </p>
[ { "answer_id": 38518, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 6, "selected": false, "text": "Enumeration Iterable Iterable Iterator Enumeration Iterator Enumeration Iterable Iterable iterator() Iterator Enumeration Enumeration DirectoryStream Enumeration Iterator Iterable Collection Iterable Iterator Vector<X> list = …\nIterator<X> i = list.iterator();\nfor (X x : i) {\n x.doStuff();\n}\n Vector<X> list = …\nEnumeration<X> i = list.enumeration();\nfor (X x : i) {\n x.doStuff();\n}\n Enumerable Iterable Enumerable Iterable" }, { "answer_id": 46674, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 6, "selected": false, "text": "for (TableColumn col : Collections.list(columnModel.getColumns()) {\n" }, { "answer_id": 31172283, "author": "user5071455", "author_id": 5071455, "author_profile": "https://Stackoverflow.com/users/5071455", "pm_score": 2, "selected": false, "text": "while(e.hasMoreElements()) {\n doStuff(e.nextElement());\n}\n" }, { "answer_id": 72718011, "author": "Clement Cherlin", "author_id": 4455546, "author_profile": "https://Stackoverflow.com/users/4455546", "pm_score": 0, "selected": false, "text": "Iterators.forEnumeration asIterator HttpSession.getAttributeNames() Enumeration<String> Iterator<String> Iterable<String> iterable = () -> Iterators.forEnumeration(session.getAttributeNames());\n Iterable<String> iterable = () -> session.getAttributeNames().asIterator();\n for StreamSupport.stream(iterable.spliterator(), false) iterable.forEach() Iterable<Something> iterable = notIterable::createIterator;" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
27,242
<p>I've had a lot of good experiences learning about web development on <a href="http://www.w3schools.com/" rel="nofollow noreferrer">w3schools.com</a>. It's hit or miss, I know, but the PHP and CSS sections specifically have proven very useful for reference.</p> <p>Anyway, I was wondering if there was a similar site for <a href="http://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery</a>. I'm interested in learning, but I need it to be online/searchable, so I can refer back to it easily when I need the information in the future.</p> <p>Also, as a brief aside, is jQuery worth learning? Or should I look at different JavaScript libraries? I know Jeff uses jQuery on Stack Overflow and it seems to be working well.</p> <p>Thanks!</p> <p><strong>Edit</strong>: jQuery's website has a <a href="http://docs.jquery.com/Tutorials" rel="nofollow noreferrer">pretty big list of tutorials</a>, and a seemingly comprehensive <a href="http://docs.jquery.com/Main_Page" rel="nofollow noreferrer">documentation page</a>. I haven't had time to go through it all yet, has anyone else had experience with it?</p> <p><strong>Edit 2</strong>: It seems Google is now hosting the jQuery libraries. That should give jQuery a pretty big advantage in terms of publicity. </p> <p>Also, if everyone uses a single unified aQuery library hosted at the same place, it should get cached for most Internet users early on and therefore not impact the download footprint of your site should you decide to use it.</p> <h2>2 Months Later...</h2> <p><strong>Edit 3</strong>: I started using jQuery on a project at work recently and it is great to work with! Just wanted to let everyone know that I have concluded it is <strong><em>ABSOLUTELY</em></strong> worth it to learn and use jQuery.</p> <p>Also, I learned almost entirely from the Official jQuery <a href="http://docs.jquery.com/Main_Page" rel="nofollow noreferrer">documentation</a> and <a href="http://docs.jquery.com/Tutorials" rel="nofollow noreferrer">tutorials</a>. It's very straightforward.</p> <h2>10 Months Later...</h2> <p>jQuery is a part of just about every web app I've made since I initially wrote this post. It makes progressive enhancement a breeze, and helps make the code maintainable.</p> <p>Also, all the jQuery plug-ins are an invaluable resource!</p> <h2>3 Years Later...</h2> <p>Still using jQuery just about every day. I now author jQuery plug-ins and consult full time. I'm primarily a Djangonaut but I've done several javascript only contracts with jQuery. It's a life saver.</p> <p>From one jQuery user to another... You should look at <a href="http://api.jquery.com/category/plugins/templates/" rel="nofollow noreferrer">templating with jQuery</a> (or underscore -- see below).</p> <p>Other things I've found valuable in addition to jQuery (with estimated portion of projects I use it on):</p> <ul> <li><a href="http://jquery.malsup.com/form/" rel="nofollow noreferrer">jQuery Form Plugin</a> (95%)</li> <li><a href="http://mudge.github.com/jquery_example/" rel="nofollow noreferrer">jQuery Form Example Plugin</a> (75%)</li> <li><a href="http://jqueryui.com/" rel="nofollow noreferrer">jQuery UI</a> (70%)</li> <li><a href="http://documentcloud.github.com/underscore/" rel="nofollow noreferrer">Underscore.js</a> (80%)</li> <li><a href="http://jashkenas.github.com/coffee-script/" rel="nofollow noreferrer">CoffeeScript</a> (30%)</li> <li><a href="http://documentcloud.github.com/backbone/" rel="nofollow noreferrer">Backbone.js</a> (10%)</li> </ul>
[ { "answer_id": 926131, "author": "egyamado", "author_id": 66493, "author_profile": "https://Stackoverflow.com/users/66493", "pm_score": 2, "selected": false, "text": "<script language=\"javascript\" type=\"text/javascript\">\n $(function() {\n $('a').click(function() {\n var originalSize = $('p').css('font-size'); // Get the font size.\n var number = parseFloat(originalSize, 10); // That method will chop off any integer \n // from the specifid varibale \"originalSize\".\n var unitOfMassure = originalSize.slice(-2); // Store the unit of massure, Pixle or Inch.\n\n $('p').css('font-size', number / 1.2 + unitOfMassure);\n if (this.id == 'larger') {\n $('p').css('font-size', number * 1.2 + unitOfMassure);\n } // Figure out which element is triggered.\n });\n });\n</script>\n <style type=\"text/css\" >\n body{ \n margin-left:300px;text-align:center; \n width:700px; \n background-color:#666666;}\n .box {\n width:500px; \n text-align:justify; \n padding:5px; \n font-family:verdana; \n font-size:11px; \n color:#0033FF; \n background-color:#FFFFCC;}\n</style>\n <div class=\"box\">\n <a href=\"#\" id=\"larger\">Larger</a> |\n <a href=\"#\" id=\"Smaller\">Smaller</a>\n <p>\n In today’s video tutorial, I’ll show you how to resize text every \n time an associated anchor tag is clicked. We’ll be examining \n the “slice”, “parseFloat”, and “CSS” Javascript/jQuery methods.\n </p>\n</div>\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
27,247
<p>I need to know about Epoll On linux System.</p> <p>Could you recommend manual or guides about epoll library?</p> <p>need more detailed guides. it's better to have some examples.</p> <p>help me. and Thank you for reading.</p>
[ { "answer_id": 6150841, "author": "Viswesn", "author_id": 527813, "author_profile": "https://Stackoverflow.com/users/527813", "pm_score": 4, "selected": false, "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <unistd.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <sys/epoll.h>\n\n#define PORT 1500 \n\n#define MAX_CON (1200)\n\nstatic struct epoll_event *events;\n\nint main(int argc, char *argv[])\n{\n fd_set master;\n fd_set read_fds;\n struct sockaddr_in serveraddr;\n struct sockaddr_in clientaddr;\n int fdmax;\n int listener;\n int newfd;\n char buf[1024];\n int nbytes;\n int addrlen;\n int yes;\n int epfd = -1;\n int res = -1;\n struct epoll_event ev;\n int i=0;\n int index = 0;\n int client_fd = -1;\n\n int SnumOfConnection = 0;\n time_t Sstart, Send;\n\n if((listener = socket(AF_INET, SOCK_STREAM, 0)) == -1)\n {\n perror(\"Server-socket() error lol!\");\n exit(1);\n }\n\n if(setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)\n {\n perror(\"Server-setsockopt() error lol!\");\n exit(1);\n }\n serveraddr.sin_family = AF_INET;\n serveraddr.sin_addr.s_addr = INADDR_ANY;\n serveraddr.sin_port = htons(PORT);\n memset(&(serveraddr.sin_zero), '\\0', 8);\n if(bind(listener, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == -1)\n {\n perror(\"Server-bind() error lol!\");\n exit(1);\n }\n if(listen(listener, 10) == -1)\n {\n perror(\"Server-listen() error lol!\");\n exit(1);\n }\n fdmax = listener; /* so far, it's this one*/\n\n events = calloc(MAX_CON, sizeof(struct epoll_event));\n if ((epfd = epoll_create(MAX_CON)) == -1) {\n perror(\"epoll_create\");\n exit(1);\n }\n ev.events = EPOLLIN;\n ev.data.fd = fdmax;\n if (epoll_ctl(epfd, EPOLL_CTL_ADD, fdmax, &ev) < 0) {\n perror(\"epoll_ctl\");\n exit(1);\n }\n //time(&start);\n for(;;)\n {\n res = epoll_wait(epfd, events, MAX_CON, -1);\n client_fd = events[index].data.fd;\n\n for (index = 0; index < MAX_CON; index++) {\n if(client_fd == listener)\n {\n addrlen = sizeof(clientaddr);\n if((newfd = accept(listener, (struct sockaddr *)&clientaddr, &addrlen)) == -1)\n {\n perror(\"Server-accept() error lol!\");\n }\n else\n {\n // printf(\"Server-accept() is OK...\\n\");\n ev.events = EPOLLIN;\n ev.data.fd = newfd;\n if (epoll_ctl(epfd, EPOLL_CTL_ADD, newfd, &ev) < 0) {\n perror(\"epoll_ctl\");\n exit(1);\n }\n }\n break;\n }\n else\n {\n if (events[index].events & EPOLLHUP)\n {\n if (epoll_ctl(epfd, EPOLL_CTL_DEL, client_fd, &ev) < 0) {\n perror(\"epoll_ctl\");\n }\n close(client_fd);\n break;\n }\n if (events[index].events & EPOLLIN) {\n if((nbytes = recv(client_fd, buf, sizeof(buf), 0)) <= 0)\n {\n if(nbytes == 0) {\n // printf(\"socket %d hung up\\n\", client_fd);\n }\n else {\n printf(\"recv() error lol! %d\", client_fd);\n perror(\"\");\n }\n\n if (epoll_ctl(epfd, EPOLL_CTL_DEL, client_fd, &ev) < 0) {\n perror(\"epoll_ctl\");\n }\n close(client_fd);\n }\n else\n {\n if(send(client_fd, buf, nbytes, 0) == -1)\n perror(\"send() error lol!\");\n }\n break;\n }\n }\n }\n }\n return 0;\n}\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2370764/" ]
27,258
<p>I'm about to start a fairly Ajax heavy feature in my company's application. What I need to do is make an Ajax callback every few minutes a user has been on the page. </p> <ul> <li>I don't need to do any DOM updates before, after, or during the callbacks. </li> <li>I don't need any information from the page, just from a site cookie which should always be sent with requests anyway, and an ID value.</li> </ul> <p>What I'm curious to find out, is if there is any clean and simple way to make a JavaScript Ajax callback to an ASP.NET page without posting back the rest of the information on the page. I'd like to not have to do this if it is possible.</p> <p>I really just want to be able to call a single method on the page, nothing else.</p> <p>Also, I'm restricted to ASP.NET 2.0 so I can't use any of the new 3.5 framework ASP AJAX features, although I can use the ASP AJAX extensions for the 2.0 framework.</p> <p><strong>UPDATE</strong><br> I've decided to accept <a href="https://stackoverflow.com/questions/27258/aspnet-javascript-callbacks-without-full-postbacks#27270">DanP</a>'s answer as it seems to be exactly what I'm looking for. Our site already uses jQuery for some things so I'll probably use jQuery for making requests since in my experience it seems to perform much better than ASP's AJAX framework does. </p> <p>What do you think would be the best method of transferring data to the IHttpHandler? Should I add variables to the query string or POST the data I need to send?</p> <p>The only thing I think I have to send is a single ID, but I can't decide what the best method is to send the ID and have the IHttpHandler handle it. I'd like to come up with a solution that would prevent a person with basic computer skills from accidentally or intentionally accessing the page directly or repeating requests. Is this possible?</p>
[ { "answer_id": 27270, "author": "Daniel Pollard", "author_id": 2758, "author_profile": "https://Stackoverflow.com/users/2758", "pm_score": 4, "selected": true, "text": "public class RSSHandler : IHttpHandler\n {\n public void ProcessRequest (HttpContext context)\n { \n context.Response.ContentType = \"text/xml\";\n\n string sXml = BuildXMLString(); //not showing this function, \n //but it creates the XML string\n context.Response.Write( sXml );\n }\n\n public bool IsReusable\n {\n get { return true; }\n }\n\n }\n" }, { "answer_id": 28105, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 1, "selected": false, "text": "namespace MyDemo\n{\n public class Default\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n AjaxPro.Utility.RegisterTypeForAjax(typeof(Default));\n }\n\n [AjaxPro.AjaxMethod]\n public DateTime GetServerTime()\n {\n return DateTime.Now;\n }\n }\n}\n function getServerTime()\n{\n MyDemo._Default.GetServerTime(getServerTime_callback); // asynchronous call\n}\n\n// This method will be called after the method has been executed\n// and the result has been sent to the client.\n\nfunction getServerTime_callback(res)\n{\n alert(res.value);\n}\n" }, { "answer_id": 1958357, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 1, "selected": false, "text": "$.ajax({\n type: \"POST\",\n url: \"Default.aspx/GetFeedburnerItems\",\n // Pass the \"Count\" parameter, via JSON object.\n data: \"{'Count':'7'}\",\n contentType: \"application/json; charset=utf-8\",\n dataType: \"json\",\n success: function(msg) {\n BuildTable(msg.d);\n }\n });\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
27,266
<p>I heard that if you use port 443 (the port usually used for https) for ssh, the encrypted packets look the same to your isp.</p> <p>Could this be a way to avoid traffic shaping/throttling?</p>
[ { "answer_id": 27463, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 2, "selected": false, "text": "SecureSocket" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
27,267
<p>I've been interacting with Amazon S3 through <a href="https://addons.mozilla.org/en-US/firefox/addon/3247" rel="noreferrer">S3Fox</a> and I can't seem to delete my buckets. I select a bucket, hit delete, confirm the delete in a popup, and... nothing happens. Is there another tool that I should use?</p>
[ { "answer_id": 1179190, "author": "MattLor", "author_id": 144148, "author_profile": "https://Stackoverflow.com/users/144148", "pm_score": 5, "selected": false, "text": "./s3cmd.rb deleteall <your bucket name>\n require 'aws/s3'\n\nAWS::S3::Base.establish_connection!(\n:access_key_id => 'your access key',\n:secret_access_key => 'your secret key'\n)\n\nbucket = AWS::S3::Bucket.find('the bucket name')\n\nwhile(!bucket.empty?)\nbegin\nputs \"Deleting objects in bucket\"\n\nbucket.objects.each do |object|\nobject.delete\nputs \"There are #{bucket.objects.size} objects left in the bucket\"\nend\n\nputs \"Done deleting objects\"\n\nrescue SocketError\nputs \"Had socket error\"\nend\n\nend\n #!/usr/bin/perl\nuse Net::Amazon::S3;\nmy $aws_access_key_id = 'your access key';\nmy $aws_secret_access_key = 'your secret access key';\nmy $increment = 50; # 50 at a time\nmy $bucket_name = 'bucket_name';\n\nmy $s3 = Net::Amazon::S3->new({aws_access_key_id => $aws_access_key_id, aws_secret_access_key => $aws_secret_access_key, retry => 1, });\nmy $bucket = $s3->bucket($bucket_name);\n\nprint \"Incrementally deleting the contents of $bucket_name\\n\";\n\nmy $deleted = 1;\nmy $total_deleted = 0;\nwhile ($deleted > 0) {\nprint \"Loading up to $increment keys...\\n\";\n$response = $bucket->list({'max-keys' => $increment, }) or die $s3->err . \": \" . $s3->errstr . \"\\n\";\n$deleted = scalar(@{ $response->{keys} }) ;\n$total_deleted += $deleted;\nprint \"Deleting $deleted keys($total_deleted total)...\\n\";\nforeach my $key ( @{ $response->{keys} } ) {\nmy $key_name = $key->{key};\n$bucket->delete_key($key->{key}) or die $s3->err . \": \" . $s3->errstr . \"\\n\";\n}\n}\nprint \"Deleting bucket...\\n\";\n$bucket->delete_bucket or die $s3->err . \": \" . $s3->errstr;\nprint \"Done.\\n\";\n" }, { "answer_id": 1829655, "author": "robbyt", "author_id": 222500, "author_profile": "https://Stackoverflow.com/users/222500", "pm_score": 4, "selected": false, "text": "~/$ s3cmd rb --recursive s3://bucketwithfiles\n" }, { "answer_id": 3848338, "author": "sent-hil", "author_id": 236655, "author_profile": "https://Stackoverflow.com/users/236655", "pm_score": 0, "selected": false, "text": "case bucket.size\n when 0\n puts \"Nothing left to delete\"\n when 1..1000\n bucket.objects.each do |item|\n item.delete\n puts \"Deleting - #{bucket.size} left\" \n end\nend\n" }, { "answer_id": 3951883, "author": "Jonathan Kamens", "author_id": 478321, "author_profile": "https://Stackoverflow.com/users/478321", "pm_score": 1, "selected": false, "text": "#!/usr/bin/perl\n\n# Copyright (c) 2010 Jonathan Kamens.\n# Released under the GNU General Public License, Version 3.\n# See <http://www.gnu.org/licenses/>.\n\n# $Id: delete-s3-bucket.pl,v 1.3 2010/10/17 03:21:33 jik Exp $\n\n# Deleting an Amazon S3 bucket is hard.\n#\n# * You can't delete the bucket unless it is empty.\n#\n# * There is no API for telling Amazon to empty the bucket, so you have to\n# delete all of the objects one by one yourself.\n#\n# * If you've recently added a lot of large objects to the bucket, then they\n# may not all be visible yet on all S3 servers. This means that even after the\n# server you're talking to thinks all the objects are all deleted and lets you\n# delete the bucket, additional objects can continue to propagate around the S3\n# server network. If you then recreate the bucket with the same name, those\n# additional objects will magically appear in it!\n# \n# It is not clear to me whether the bucket delete will eventually propagate to\n# all of the S3 servers and cause all the objects in the bucket to go away, but\n# I suspect it won't. I also suspect that you may end up continuing to be\n# charged for these phantom objects even though the bucket they're in is no\n# longer even visible in your S3 account.\n#\n# * If there's a CR, LF, or CRLF in an object name, then it's sent just that\n# way in the XML that gets sent from the S3 server to the client when the\n# client asks for a list of objects in the bucket. Unfortunately, the XML\n# parser on the client will probably convert it to the local line ending\n# character, and if it's different from the character that's actually in the\n# object name, you then won't be able to delete it. Ugh! This is a bug in the\n# S3 protocol; it should be enclosing the object names in CDATA tags or\n# something to protect them from being munged by the XML parser.\n#\n# Note that this bug even affects the AWS Web Console provided by Amazon!\n#\n# * If you've got a whole lot of objects and you serialize the delete process,\n# it'll take a long, long time to delete them all.\n\nuse threads;\nuse strict;\nuse warnings;\n\n# Keys can have newlines in them, which screws up the communication\n# between the parent and child processes, so use URL encoding to deal\n# with that. \nuse CGI qw(escape unescape); # Easiest place to get this functionality.\nuse File::Basename;\nuse Getopt::Long;\nuse Net::Amazon::S3;\n\nmy $whoami = basename $0;\nmy $usage = \"Usage: $whoami [--help] --access-key-id=id --secret-access-key=key\n --bucket=name [--processes=#] [--wait=#] [--nodelete]\n\n Specify --processes to indicate how many deletes to perform in\n parallel. You're limited by RAM (to hold the parallel threads) and\n bandwidth for the S3 delete requests.\n\n Specify --wait to indicate seconds to require the bucket to be verified\n empty. This is necessary if you create a huge number of objects and then\n try to delete the bucket before they've all propagated to all the S3\n servers (I've seen a huge backlog of newly created objects take *hours* to\n propagate everywhere). See the comment at the top of the script for more\n information about this issue.\n\n Specify --nodelete to empty the bucket without actually deleting it.\\n\";\n\nmy($aws_access_key_id, $aws_secret_access_key, $bucket_name, $wait);\nmy $procs = 1;\nmy $delete = 1;\n\ndie if (! GetOptions(\n \"help\" => sub { print $usage; exit; },\n \"access-key-id=s\" => \\$aws_access_key_id,\n \"secret-access-key=s\" => \\$aws_secret_access_key,\n \"bucket=s\" => \\$bucket_name,\n \"processess=i\" => \\$procs,\n \"wait=i\" => \\$wait,\n \"delete!\" => \\$delete,\n ));\ndie if (! ($aws_access_key_id && $aws_secret_access_key && $bucket_name));\n\nmy $increment = 0;\n\nprint \"Incrementally deleting the contents of $bucket_name\\n\";\n\n$| = 1;\n\nmy(@procs, $current);\nfor (1..$procs) {\n my($read_from_parent, $write_to_child);\n my($read_from_child, $write_to_parent);\n pipe($read_from_parent, $write_to_child) or die;\n pipe($read_from_child, $write_to_parent) or die;\n threads->create(sub {\n close($read_from_child);\n close($write_to_child);\n my $old_select = select $write_to_parent;\n $| = 1;\n select $old_select;\n &child($read_from_parent, $write_to_parent);\n }) or die;\n close($read_from_parent);\n close($write_to_parent);\n my $old_select = select $write_to_child;\n $| = 1;\n select $old_select;\n push(@procs, [$read_from_child, $write_to_child]);\n}\n\nmy $s3 = Net::Amazon::S3->new({aws_access_key_id => $aws_access_key_id,\n aws_secret_access_key => $aws_secret_access_key,\n retry => 1,\n });\nmy $bucket = $s3->bucket($bucket_name);\n\nmy $deleted = 1;\nmy $total_deleted = 0;\nmy $last_start = time;\nmy($start, $waited);\nwhile ($deleted > 0) {\n $start = time;\n print \"\\nLoading \", ($increment ? \"up to $increment\" :\n \"as many as possible\"),\" keys...\\n\";\n my $response = $bucket->list({$increment ? ('max-keys' => $increment) : ()})\n or die $s3->err . \": \" . $s3->errstr . \"\\n\";\n $deleted = scalar(@{ $response->{keys} }) ;\n if (! $deleted) {\n if ($wait and ! $waited) {\n my $delta = $wait - ($start - $last_start);\n if ($delta > 0) {\n print \"Waiting $delta second(s) to confirm bucket is empty\\n\";\n sleep($delta);\n $waited = 1;\n $deleted = 1;\n next;\n }\n else {\n last;\n }\n }\n else {\n last;\n }\n }\n else {\n $waited = undef;\n }\n $total_deleted += $deleted;\n print \"\\nDeleting $deleted keys($total_deleted total)...\\n\";\n $current = 0;\n foreach my $key ( @{ $response->{keys} } ) {\n my $key_name = $key->{key};\n while (! &send(escape($key_name) . \"\\n\")) {\n print \"Thread $current died\\n\";\n die \"No threads left\\n\" if (@procs == 1);\n if ($current == @procs-1) {\n pop @procs;\n $current = 0;\n }\n else {\n $procs[$current] = pop @procs;\n }\n }\n $current = ($current + 1) % @procs;\n threads->yield();\n }\n print \"Sending sync message\\n\";\n for ($current = 0; $current < @procs; $current++) {\n if (! &send(\"\\n\")) {\n print \"Thread $current died sending sync\\n\";\n if ($current = @procs-1) {\n pop @procs;\n last;\n }\n $procs[$current] = pop @procs;\n $current--;\n }\n threads->yield();\n }\n print \"Reading sync response\\n\";\n for ($current = 0; $current < @procs; $current++) {\n if (! &receive()) {\n print \"Thread $current died reading sync\\n\";\n if ($current = @procs-1) {\n pop @procs;\n last;\n }\n $procs[$current] = pop @procs;\n $current--;\n }\n threads->yield();\n } \n}\ncontinue {\n $last_start = $start;\n}\n\nif ($delete) {\n print \"Deleting bucket...\\n\";\n $bucket->delete_bucket or die $s3->err . \": \" . $s3->errstr;\n print \"Done.\\n\";\n}\n\nsub send {\n my($str) = @_;\n my $fh = $procs[$current]->[1];\n print($fh $str);\n}\n\nsub receive {\n my $fh = $procs[$current]->[0];\n scalar <$fh>;\n}\n\nsub child {\n my($read, $write) = @_;\n threads->detach();\n my $s3 = Net::Amazon::S3->new({aws_access_key_id => $aws_access_key_id,\n aws_secret_access_key => $aws_secret_access_key,\n retry => 1,\n });\n my $bucket = $s3->bucket($bucket_name);\n while (my $key = <$read>) {\n if ($key eq \"\\n\") {\n print($write \"\\n\") or die;\n next;\n }\n chomp $key;\n $key = unescape($key);\n if ($key =~ /[\\r\\n]/) {\n my(@parts) = split(/\\r\\n|\\r|\\n/, $key, -1);\n my(@guesses) = shift @parts;\n foreach my $part (@parts) {\n @guesses = (map(($_ . \"\\r\\n\" . $part,\n $_ . \"\\r\" . $part,\n $_ . \"\\n\" . $part), @guesses));\n }\n foreach my $guess (@guesses) {\n if ($bucket->get_key($guess)) {\n $key = $guess;\n last;\n }\n }\n }\n $bucket->delete_key($key) or\n die $s3->err . \": \" . $s3->errstr . \"\\n\";\n print \".\";\n threads->yield();\n }\n return;\n}\n" }, { "answer_id": 4550709, "author": "mfonda", "author_id": 492401, "author_profile": "https://Stackoverflow.com/users/492401", "pm_score": 2, "selected": false, "text": "s3cmd rb --force s3://bucket-name\n" }, { "answer_id": 7427700, "author": "Željko Filipin", "author_id": 17469, "author_profile": "https://Stackoverflow.com/users/17469", "pm_score": 2, "selected": false, "text": "gem install aws-s3\n sudo gem install aws-s3\n delete_bucket.rb require \"rubygems\" # optional\nrequire \"aws/s3\"\nAWS::S3::Base.establish_connection!(\n :access_key_id => 'access_key_id',\n :secret_access_key => 'secret_access_key')\nAWS::S3::Bucket.delete(\"bucket_name\", :force => true)\n ruby delete_bucket.rb\n Bucket#delete require \"rubygems\" # optional\nrequire \"aws/s3\"\nAWS::S3::Base.establish_connection!(\n :access_key_id => 'access_key_id',\n :secret_access_key => 'secret_access_key')\nwhile AWS::S3::Bucket.find(\"bucket_name\")\n begin\n AWS::S3::Bucket.delete(\"bucket_name\", :force => true)\n rescue\n end\nend\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
27,288
<p>I know that this should be easy but how do I export/save a DataGridView to excel?</p>
[ { "answer_id": 27306, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": -1, "selected": false, "text": "\n Public Overloads Shared Function BuildExcel(ByVal gView As System.Web.UI.WebControls.GridView) As String\n\n PrepareGridViewForExport(gView)\n\n\n Dim excelDoc As New StringBuilder\n\n Dim startExcelXML As String = \" \" + _\n \" \" + _\n \" \" + _\n \" \" + _\n \" \" + _\n \" \" + _\n \" \" + _\n \" \" + _\n \" \"\n Dim endExcelXML As String = \"\"\n\n Dim rowCount As Int64 = 0\n Dim sheetCount As Int16 = 1\n\n\n excelDoc.Append(startExcelXML)\n excelDoc.Append(\"\")\n excelDoc.Append(\"\")\n\n ' write out column headers\n excelDoc.Append(\"\")\n\n For x As Int32 = 0 To gView.Columns.Count - 1\n\n 'Only write out columns that have column headers.\n If Not gView.Columns(x).HeaderText = String.Empty Then\n excelDoc.Append(\"\")\n excelDoc.Append(gView.Columns(x).HeaderText.ToString)\n excelDoc.Append(\"\")\n End If\n Next\n\n excelDoc.Append(\"\")\n\n For r As Int32 = 0 To gView.Rows.Count - 1\n\n rowCount += rowCount\n\n If rowCount = 64000 Then\n rowCount = 0\n sheetCount += sheetCount\n excelDoc.Append(\"\")\n excelDoc.Append(\" \")\n excelDoc.Append(\"\")\n excelDoc.Append(\"\")\n End If\n\n excelDoc.Append(\"\")\n\n For c As Int32 = 0 To gView.Rows(r).Cells.Count - 1\n\n 'Don't write out a column without a column header.\n\n If Not gView.Columns(c).HeaderText = String.Empty Then\n Dim XMLstring As String = gView.Rows(r).Cells(c).Text\n\n XMLstring = XMLstring.Trim()\n XMLstring = XMLstring.Replace(\"&\", \"&\")\n XMLstring = XMLstring.Replace(\">\", \">\")\n XMLstring = XMLstring.Replace(\"\" + \"\")\n excelDoc.Append(XMLstring)\n excelDoc.Append(\"\")\n End If\n\n Next\n\n excelDoc.Append(\"\")\n Next\n\n excelDoc.Append(\"\")\n excelDoc.Append(\" \")\n excelDoc.Append(endExcelXML)\n\n\n\n Return excelDoc.ToString\n\n\n End Function\n\n Shared Sub PrepareGridViewForExport(ByVal gview As System.Web.UI.Control)\n ' Cleans up grid for exporting. Takes links and visual elements and turns them into text.\n Dim lb As New System.Web.UI.WebControls.LinkButton\n Dim l As New System.Web.UI.WebControls.Literal\n Dim name As String = String.Empty\n\n\n For i As Int32 = 0 To gview.Controls.Count - 1\n\n If TypeOf gview.Controls(i) Is System.Web.UI.WebControls.LinkButton Then\n l.Text = CType(gview.Controls(i), System.Web.UI.WebControls.LinkButton).Text\n gview.Controls.Remove(gview.Controls(i))\n gview.Controls.AddAt(i, l)\n ElseIf TypeOf gview.Controls(i) Is System.Web.UI.WebControls.DropDownList Then\n l.Text = CType(gview.Controls(i), System.Web.UI.WebControls.DropDownList).SelectedItem.Text\n gview.Controls.Remove(gview.Controls(i))\n gview.Controls.AddAt(i, l)\n ElseIf TypeOf gview.Controls(i) Is System.Web.UI.WebControls.CheckBox Then\n l.Text = CType(gview.Controls(i), System.Web.UI.WebControls.CheckBox).Checked.ToString\n gview.Controls.Remove(gview.Controls(i))\n gview.Controls.AddAt(i, l)\n End If\n\n\n If gview.Controls(i).HasControls() Then\n PrepareGridViewForExport(gview.Controls(i))\n End If\n\n Next\n End Sub\n\n" }, { "answer_id": 27313, "author": "Dhaust", "author_id": 242, "author_profile": "https://Stackoverflow.com/users/242", "pm_score": 0, "selected": false, "text": " Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs)\n 'Export to excel\n Response.Clear()\n Response.Buffer = True\n Response.ContentType = \"application/vnd.ms-excel\"\n Response.Charset = \"\"\n Me.EnableViewState = False\n Dim oStringWriter As System.IO.StringWriter = New System.IO.StringWriter\n Dim oHtmlTextWriter As System.Web.UI.HtmlTextWriter = New System.Web.UI.HtmlTextWriter(oStringWriter)\n Me.ClearControls(gvSearchTerms)\n gvSearchTerms.RenderControl(oHtmlTextWriter)\n Response.Write(oStringWriter.ToString)\n Response.End()\nEnd Sub\n\n\n\nPrivate Sub ClearControls(ByVal control As Control)\n Dim i As Integer = (control.Controls.Count - 1)\n Do While (i >= 0)\n ClearControls(control.Controls(i))\n i = (i - 1)\n Loop\n If Not (TypeOf control Is TableCell) Then\n If (Not (control.GetType.GetProperty(\"SelectedItem\")) Is Nothing) Then\n Dim literal As LiteralControl = New LiteralControl\n control.Parent.Controls.Add(literal)\n Try\n literal.Text = CType(control.GetType.GetProperty(\"SelectedItem\").GetValue(control, Nothing), String)\n Catch ex As System.Exception\n\n End Try\n control.Parent.Controls.Remove(control)\n ElseIf (Not (control.GetType.GetProperty(\"Text\")) Is Nothing) Then\n Dim literal As LiteralControl = New LiteralControl\n control.Parent.Controls.Add(literal)\n literal.Text = CType(control.GetType.GetProperty(\"Text\").GetValue(control, Nothing), String)\n control.Parent.Controls.Remove(control)\n End If\n End If\n Return\nEnd Sub\n\n\n\nPublic Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)\n Return\nEnd Sub\n" }, { "answer_id": 27341, "author": "Jas", "author_id": 777, "author_profile": "https://Stackoverflow.com/users/777", "pm_score": 0, "selected": false, "text": " Dim report_source As CrystalDecisions.Web.CrystalReportSource\n report_source.ReportDocument.SetDataSource(dt) 'DT IS A DATATABLE\n report_source.Report.FileName = \"test.rpt\"\n report_source.ReportDocument.Refresh()\n report_source.ReportDocument.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.Excel, \"c:\\test.xls\")\n" }, { "answer_id": 44138, "author": "Industrial Themes", "author_id": 4222, "author_profile": "https://Stackoverflow.com/users/4222", "pm_score": 1, "selected": false, "text": "Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n 'get the select command of the gridview\n sqlGridview.SelectCommand = Session(\"strSql\")\n gvCompaniesExport.DataBind()\n lblTemp.Text = Session(\"strSql\")\n\n 'do the export\n doExport()\n\n 'close the window\n Dim closeScript As String = \"<script language='javascript'> window.close() </scri\"\n closeScript = closeScript & \"pt>\"\n 'split the ending script tag across a concatenate to keep it from causing problems\n 'this will write it to the asp.net page and fire it off, closing the window\n Page.RegisterStartupScript(\"closeScript\", closeScript)\nEnd Sub\nPublic Sub doExport()\n Response.AddHeader(\"content-disposition\", \"attachment;filename=IndianaCompanies.xls\")\n Response.ContentType = \"application/vnd.ms-excel\"\n Response.Charset = \"\"\n Me.EnableViewState = False\n Dim objStrWriter As New System.IO.StringWriter\n Dim objHtmlTextWriter As New System.Web.UI.HtmlTextWriter(objStrWriter)\n 'Get the gridview HTML from the control\n gvCompaniesExport.RenderControl(objHtmlTextWriter)\n 'writes the dg info\n Response.Write(objStrWriter.ToString())\n Response.End()\nEnd Sub\n" }, { "answer_id": 1370416, "author": "Merritt", "author_id": 60385, "author_profile": "https://Stackoverflow.com/users/60385", "pm_score": 1, "selected": false, "text": "public static class GridViewExtensions\n {\n public static void ExportToExcel(this GridView gridView, string fileName, IEnumerable<string> excludeColumnNames)\n {\n //Prepare Response\n HttpContext.Current.Response.Clear();\n HttpContext.Current.Response.AddHeader(\"content-disposition\",\n string.Format(\"attachment; filename={0}\", fileName));\n HttpContext.Current.Response.ContentType = \"application/ms-excel\";\n\n\n\n using (StringWriter sw = new StringWriter())\n {\n using (HtmlTextWriter htw = new HtmlTextWriter(sw))\n {\n // Create a table to contain the grid\n Table table = new Table();\n\n // include the gridline settings\n table.GridLines = gridView.GridLines;\n\n // add the header row to the table\n if (gridView.HeaderRow != null)\n {\n PrepareControlForExport(gridView.HeaderRow);\n table.Rows.Add(gridView.HeaderRow);\n }\n\n // add each of the data rows to the table\n foreach (GridViewRow row in gridView.Rows)\n {\n PrepareControlForExport(row);\n table.Rows.Add(row);\n }\n\n // add the footer row to the table\n if (gridView.FooterRow != null)\n {\n PrepareControlForExport(gridView.FooterRow);\n table.Rows.Add(gridView.FooterRow);\n }\n\n // Remove unwanted columns (header text listed in removeColumnList arraylist)\n foreach (DataControlField column in gridView.Columns)\n {\n if (excludeColumnNames != null && excludeColumnNames.Contains(column.HeaderText))\n {\n column.Visible = false;\n }\n }\n\n // render the table into the htmlwriter\n table.RenderControl(htw);\n\n // render the htmlwriter into the response\n HttpContext.Current.Response.Write(sw.ToString());\n HttpContext.Current.Response.End();\n }\n }\n }\n\n /// <summary>\n /// Replace any of the contained controls with literals\n /// </summary>\n /// <param name=\"control\"></param>\n private static void PrepareControlForExport(Control control)\n {\n for (int i = 0; i < control.Controls.Count; i++)\n {\n Control current = control.Controls[i];\n\n if (current is LinkButton)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text));\n }\n else if (current is ImageButton)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText));\n }\n else if (current is HyperLink)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text));\n }\n else if (current is DropDownList)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text));\n }\n else if (current is CheckBox)\n {\n control.Controls.Remove(current);\n control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? \"True\" : \"False\"));\n }\n\n if (current.HasControls())\n {\n PrepareControlForExport(current);\n }\n }\n }\n }\n" }, { "answer_id": 23004284, "author": "GoroundoVipa", "author_id": 3471643, "author_profile": "https://Stackoverflow.com/users/3471643", "pm_score": 0, "selected": false, "text": "Public Sub exportOfficePCandWorkstation(ByRef mainForm As Form1, ByVal Location As String, ByVal WorksheetName As String)\n Dim xlApp As New Excel.Application\n Dim xlWorkBook As Excel.Workbook\n Dim xlWorkSheet As Excel.Worksheet\n Dim misValue As Object = System.Reflection.Missing.Value\n Dim Header(23) As String\n Dim HeaderCell(23) As String\n Header = {\"No.\", \"PC Name\", \"User\", \"E-mail\", \"Department/Location\", \"CPU Model\", \"CPU Processor\", \"CPU Speed\", \"CPU HDD#1\", \"CPU HDD#2\", \"CPU Memory\", \"CPU OS\", \"CPU Asset Tag\", \"CPU MAC Address\", \"Monitor 1 Model\", \"Monitor Serial Number\", \"Monitor2 Model\", \"Monitor2 Serial Number\", \"Office\", \"Wi-LAN\", \"KVM Switch\", \"Attachment\", \"Remarks\", \"Date and Time\"}\n HeaderCell = {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"X\"}\n xlWorkBook = xlApp.Workbooks.Add\n xlWorkSheet = xlWorkBook.Sheets(\"Sheet1\")\n xlWorkSheet.Name = WorksheetName\n xlApp.Visible = True\n xlWorkSheet.Application.ActiveWindow.SplitRow = 1\n xlWorkSheet.Application.ActiveWindow.SplitColumn = 3\n xlWorkSheet.Application.ActiveWindow.FreezePanes = True\n With xlWorkSheet\n For count As Integer = 0 To 23\n .Range(HeaderCell(count) & 1).Value = Header(count)\n Next\n With .Range(\"A1:X1\")\n .Interior.Color = 1\n With .Font\n .Size = 16\n .ColorIndex = 2\n .Name = \"Times New Roman\"\n End With\n End With\n For i = 0 To mainForm.DataGridView1.RowCount - 1\n For j = 0 To mainForm.DataGridView1.ColumnCount - 1\n If mainForm.DataGridView1(j, i).Value.ToString = \"System.Byte[]\" Then\n xlWorkSheet.Cells(i + 2, j + 2) = \"Attached\"\n Else\n xlWorkSheet.Cells(i + 2, j + 2) = mainForm.DataGridView1(j, i).Value.ToString()\n End If\n Next\n .Range(\"A\" & i + 2).Value = (i + 1).ToString\n Next\n With .Range(\"A:Z\")\n .EntireColumn.AutoFit()\n End With\n With .Range(\"B2:X\" & mainForm.DataGridView1.RowCount + 1)\n .HorizontalAlignment = Excel.XlVAlign.xlVAlignJustify\n End With\n With .Range(\"A1:A\" & mainForm.DataGridView1.RowCount + 1)\n .HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter\n End With\n '-----------------------------------Insert Border Lines--------------------------------------\n With .Range(\"A1:X\" & mainForm.DataGridView1.RowCount + 1)\n With .Borders(Excel.XlBordersIndex.xlEdgeLeft)\n .LineStyle = Excel.XlLineStyle.xlDouble\n .ColorIndex = 0\n .TintAndShade = 0\n .Weight = Excel.XlBorderWeight.xlThin\n End With\n With .Borders(Excel.XlBordersIndex.xlEdgeTop)\n .LineStyle = Excel.XlLineStyle.xlContinuous\n .ColorIndex = 0\n .TintAndShade = 0\n .Weight = Excel.XlBorderWeight.xlThin\n End With\n With .Borders(Excel.XlBordersIndex.xlEdgeBottom)\n .LineStyle = Excel.XlLineStyle.xlContinuous\n .ColorIndex = 0\n .TintAndShade = 0\n .Weight = Excel.XlBorderWeight.xlThin\n End With\n With .Borders(Excel.XlBordersIndex.xlEdgeRight)\n .LineStyle = Excel.XlLineStyle.xlContinuous\n .ColorIndex = 0\n .TintAndShade = 0\n .Weight = Excel.XlBorderWeight.xlThin\n End With\n With .Borders(Excel.XlBordersIndex.xlInsideVertical)\n .LineStyle = Excel.XlLineStyle.xlContinuous\n .ColorIndex = 0\n .TintAndShade = 0\n .Weight = Excel.XlBorderWeight.xlThin\n End With\n With .Borders(Excel.XlBordersIndex.xlInsideHorizontal)\n .LineStyle = Excel.XlLineStyle.xlContinuous\n .ColorIndex = 0\n .TintAndShade = 0\n .Weight = Excel.XlBorderWeight.xlThin\n End With\n End With\n End With\n xlWorkSheet.SaveAs(Location)\n xlWorkBook.Close()\n xlApp.Quit()\n MsgBox(\"Export Record successful\", MsgBoxStyle.Information, \"Export to Excel\")\nEnd Sub\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/359/" ]
27,294
<p>I'm working on an internal project for my company, and part of the project is to be able to parse various "Tasks" from an XML file into a collection of tasks to be ran later.</p> <p>Because each type of Task has a multitude of different associated fields, I decided it would be best to represent each type of Task with a seperate class.</p> <p>To do this, I constructed an abstract base class:</p> <pre><code>public abstract class Task { public enum TaskType { // Types of Tasks } public abstract TaskType Type { get; } public abstract LoadFromXml(XmlElement task); public abstract XmlElement CreateXml(XmlDocument currentDoc); } </code></pre> <p>Each task inherited from this base class, and included the code necessary to create itself from the passed in XmlElement, as well as serialize itself back out to an XmlElement.</p> <p>A basic example:</p> <pre><code>public class MergeTask : Task { public override TaskType Type { get { return TaskType.Merge; } } // Lots of Properties / Methods for this Task public MergeTask (XmlElement elem) { this.LoadFromXml(elem); } public override LoadFromXml(XmlElement task) { // Populates this Task from the Xml. } public override XmlElement CreateXml(XmlDocument currentDoc) { // Serializes this class back to xml. } } </code></pre> <p>The parser would then use code similar to this to create a task collection:</p> <pre><code>XmlNode taskNode = parent.SelectNode("tasks"); TaskFactory tf = new TaskFactory(); foreach (XmlNode task in taskNode.ChildNodes) { // Since XmlComments etc will show up if (task is XmlElement) { tasks.Add(tf.CreateTask(task as XmlElement)); } } </code></pre> <p>All of this works wonderfully, and allows me to pass tasks around using the base class, while retaining the structure of having individual classes for each task.</p> <p>However, I am not happy with my code for TaskFactory.CreateTask. This method accepts an XmlElement, and then returns an instance of the appropriate Task class:</p> <pre><code>public Task CreateTask(XmlElement elem) { if (elem != null) { switch(elem.Name) { case "merge": return new MergeTask(elem); default: throw new ArgumentException("Invalid Task"); } } } </code></pre> <p>Because I have to parse the XMLElement, I'm using a huge (10-15 cases in the real code) switch to pick which child class to instantiate. I'm hoping there is some sort of polymorphic trick I can do here to clean up this method.</p> <p>Any advice?</p>
[ { "answer_id": 27310, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 5, "selected": true, "text": "public Task CreateTask(XmlElement elem)\n{\n if (elem != null)\n { \n try\n {\n Assembly a = typeof(Task).Assembly\n string type = string.Format(\"{0}.{1}Task\",typeof(Task).Namespace,elem.Name);\n\n //this is only here, so that if that type doesn't exist, this method\n //throws an exception\n Type t = a.GetType(type, true, true);\n\n return a.CreateInstance(type, true) as Task;\n }\n catch(System.Exception)\n {\n throw new ArgumentException(\"Invalid Task\");\n }\n }\n}\n" }, { "answer_id": 27320, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "if (CurrentTask is MergeTask)\n{\n // Do Something Specific to MergeTask\n}\n" }, { "answer_id": 28659, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "public class TaskFactory\n {\n private Dictionary<String, Type> _taskTypes = new Dictionary<String, Type>();\n\n public TaskFactory()\n {\n // Preload the Task Types into a dictionary so we can look them up later\n foreach (Type type in typeof(TaskFactory).Assembly.GetTypes())\n {\n if (type.IsSubclassOf(typeof(CCTask)))\n {\n _taskTypes[type.Name.ToLower()] = type;\n }\n }\n }\n\n public CCTask CreateTask(XmlElement task)\n {\n if (task != null)\n {\n string taskName = task.Name;\n taskName = taskName.ToLower() + \"task\";\n\n // If the Type information is in our Dictionary, instantiate a new instance of that task\n Type taskType;\n if (_taskTypes.TryGetValue(taskName, out taskType))\n {\n return (CCTask)Activator.CreateInstance(taskType, task);\n }\n else\n {\n throw new ArgumentException(\"Unrecognized Task:\" + task.Name);\n } \n }\n else\n {\n return null;\n }\n }\n }\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
27,303
<p>Anyone know if it's possible to databind the ScaleX and ScaleY of a render transform in Silverlight 2 Beta 2? Binding transforms is possible in WPF - But I'm getting an error when setting up my binding in Silverlight through XAML. Perhaps it's possible to do it through code?</p> <pre><code>&lt;Image Height="60" HorizontalAlignment="Right" Margin="0,122,11,0" VerticalAlignment="Top" Width="60" Source="Images/Fish128x128.png" Stretch="Fill" RenderTransformOrigin="0.5,0.5" x:Name="fishImage"&gt; &lt;Image.RenderTransform&gt; &lt;TransformGroup&gt; &lt;ScaleTransform ScaleX="1" ScaleY="1"/&gt; &lt;SkewTransform/&gt; &lt;RotateTransform/&gt; &lt;TranslateTransform/&gt; &lt;/TransformGroup&gt; &lt;/Image.RenderTransform&gt; &lt;/Image&gt; </code></pre> <p>I want to bind the ScaleX and ScaleY of the ScaleTransform element.</p> <p>I'm getting a runtime error when I try to bind against a double property on my data context: </p> <pre><code>Message="AG_E_PARSER_BAD_PROPERTY_VALUE [Line: 1570 Position: 108]" </code></pre> <p>My binding looks like this:</p> <pre><code>&lt;ScaleTransform ScaleX="{Binding Path=SelectedDive.Visibility}" ScaleY="{Binding Path=SelectedDive.Visibility}"/&gt; </code></pre> <p>I have triple verified that the binding path is correct - I'm binding a slidebar against the same value and that works just fine...</p> <p>Visibility is of type double and is a number between 0.0 and 30.0. I have a value converter that scales that number down to 0.5 and 1 - I want to scale the size of the fish depending on the clarity of the water. So I don't think it's a problem with the type I'm binding against...</p>
[ { "answer_id": 27309, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "<ScaleTransform ScaleX=\"{Binding Foo}\" ScaleY=\"{Binding Bar}\" />\n" }, { "answer_id": 27401, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<ScaleTransform ScaleX=\"{Binding ElementName=slider1,Path=Value}\" ... />\n" }, { "answer_id": 27413, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<ScaleTransform x:Name=\"myScaler\" ... />\n myScaler.DataContext = fishImage.DataContext;\n" }, { "answer_id": 27424, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<Image Tooltip=\"{Binding SelectedDive.Visibility}\" ... />\n" }, { "answer_id": 27487, "author": "Jonas Follesø", "author_id": 1199387, "author_profile": "https://Stackoverflow.com/users/1199387", "pm_score": 0, "selected": false, "text": " private ScaleConverter converter;\n\n public DiveLog()\n { \n InitializeComponent();\n\n converter = new ScaleConverter();\n visibilitySlider.ValueChanged += new \n RoutedPropertyChangedEventHandler<double>(visibilitySlider_ValueChanged);\n } \n\n private void visibilitySlider_ValueChanged(object sender, \n RoutedPropertyChangedEventArgs<double> e)\n {\n fishScale.ScaleX = (double)converter.Convert(e.NewValue, \n typeof(double), null, CultureInfo.CurrentCulture);\n fishScale.ScaleY = fishScale.ScaleX;\n }\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199387/" ]
27,359
<p>I want to setup a cron job to rsync a remote system to a backup partition, something like:</p> <pre><code>bash -c 'rsync -avz --delete --exclude=proc --exclude=sys root@remote1:/ /mnt/remote1/' </code></pre> <p>I would like to be able to "set it and forget it" but what if <code>/mnt/remote1</code> becomes unmounted? (After a reboot or something) I'd like to error out if <code>/mnt/remote1</code> isn't mounted, rather than filling up the local filesystem.</p> <p><strong>Edit:</strong><br /> Here is what I came up with for a script, cleanup improvements appreciated (especially for the empty then ... else, I couldn't leave them empty or bash errors)</p> <pre><code>#!/bin/bash DATA=data ERROR="0" if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1\$"; then ERROR=0 else if mount /dev/vg/$1 /mnt/$1; then ERROR=0 else ERROR=$? echo "Can't backup $1, /mnt/$1 could not be mounted: $ERROR" fi fi if [ "$ERROR" = "0" ]; then if cut -d' ' -f2 /proc/mounts | grep -q "^/mnt/$1/$DATA\$"; then ERROR=0 else if mount /dev/vg/$1$DATA /mnt/$1/data; then ERROR=0 else ERROR=$? echo "Can't backup $1, /mnt/$1/data could not be mounted." fi fi fi if [ "$ERROR" = "0" ]; then rsync -aqz --delete --numeric-ids --exclude=proc --exclude=sys \ root@$1.domain:/ /mnt/$1/ RETVAL=$? echo "Backup of $1 completed, return value of rsync: $RETVAL" fi </code></pre>
[ { "answer_id": 27370, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 2, "selected": false, "text": "if df |grep -q '/mnt/mountpoint$'\n then\n echo \"Found mount point, running task\"\n # Do some stuff\n else\n echo \"Aborted because the disk is not mounted\"\n # Do some error correcting stuff\n exit -1\nfi\n" }, { "answer_id": 27371, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 4, "selected": true, "text": "if cut -d' ' -f2 /proc/mounts | grep '^/mnt/remote1$' >/dev/null; then\n rsync -avz ...\nfi\n /proc/mounts /mnt/remote1 /dev/null rsync grep -q /dev/null" }, { "answer_id": 3576205, "author": "bob esponja", "author_id": 19927, "author_profile": "https://Stackoverflow.com/users/19927", "pm_score": 3, "selected": false, "text": "mountpoint #!/bin/bash\nif [[ `mountpoint -q /path` ]]; then\n echo \"filesystem mounted\"\nelse\n echo \"filesystem not mounted\"\nfi\n" }, { "answer_id": 28752314, "author": "miu", "author_id": 2524925, "author_profile": "https://Stackoverflow.com/users/2524925", "pm_score": 1, "selected": false, "text": "chmod +x backup.sh backup.sh [username (for rsync)] [backup source device] [backup source location] [backup target device] [backup target location] #!/bin/bash\n\n##\n## COMMAND USAGE: backup.sh [username] [backup source device] [backup source location] [backup target device] [backup target location]\n##\n## for example: sudo /home/manu/bin/backup.sh \"manu\" \"/media/disk1\" \"/media/disk1/.\" \"/media/disk2\" \"/media/disk2\"\n##\n\n##\n## VARIABLES\n##\n\n# execute as user\nUSER=\"$1\"\n\n# Set source location\nBACKUP_SOURCE_DEV=\"$2\"\nBACKUP_SOURCE=\"$3\"\n\n# Set target location\nBACKUP_TARGET_DEV=\"$4\"\nBACKUP_TARGET=\"$5\"\n\n# Log file\nLOG_FILE=\"/var/log/backup_script.log\"\n\n##\n## SCRIPT\n##\n\nfunction end() {\n echo -e \"###########################################################################\\\n#########################################################################\\n\\n\" >> \"$LOG_FILE\"\n exit $1\n}\n\n# Check that the log file exists\nif [ ! -e \"$LOG_FILE\" ]; then\n touch \"$LOG_FILE\"\n chown $USER \"$LOG_FILE\"\nfi\n\n# Check if backup source device is mounted\nif ! mountpoint \"$BACKUP_SOURCE_DEV\"; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Backup source device is not mounted!\" >> \"$LOG_FILE\"\n end 1\nfi\n\n# Check that source dir exists and is readable.\nif [ ! -r \"$BACKUP_SOURCE\" ]; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to read source dir.\" >> \"$LOG_FILE\"\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to sync.\" >> \"$LOG_FILE\"\n end 1\nfi\n\n# Check that target dir exists and is writable.\nif [ ! -w \"$BACKUP_TARGET\" ]; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to write to target dir.\" >> \"$LOG_FILE\"\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to sync.\" >> \"$LOG_FILE\"\n end 1\nfi\n\n# Check if the drive is mounted\nif ! mountpoint \"$BACKUP_TARGET_DEV\"; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - WARNING: Backup device needs mounting!\" >> \"$LOG_FILE\"\n\n # If not, mount the drive\n if mount \"$BACKUP_TARGET_DEV\" > /dev/null 2>&1 || /bin/false; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - Backup device mounted.\" >> \"$LOG_FILE\"\n else\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to mount backup device.\" >> \"$LOG_FILE\"\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - ERROR: Unable to sync.\" >> \"$LOG_FILE\"\n end 1\n fi\nfi\n\n# Start entry in the log\necho \"$(date \"+%Y-%m-%d %k:%M:%S\") - Sync started.\" >> \"$LOG_FILE\"\n\n# Start sync\nsu -c \"rsync -ayhEAX --progress --delete-after --inplace --compress-level=0 --log-file=\\\"$LOG_FILE\\\" \\\"$BACKUP_SOURCE\\\" \\\"$BACKUP_TARGET\\\"\" $USER\necho \"\" >> \"$LOG_FILE\"\n\n# Unmount the drive so it does not accidentally get damaged or wiped\nif umount \"$BACKUP_TARGET_DEV\" > /dev/null 2>&1 || /bin/false; then\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - Backup device unmounted.\" >> \"$LOG_FILE\"\nelse\n echo \"$(date \"+%Y-%m-%d %k:%M:%S\") - WARNING: Backup device could not be unmounted.\" >> \"$LOG_FILE\"\nfi\n\n# Exit successfully\nend 0\n" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/163/" ]
27,381
<p>I'm asking this question purely from a usability <code>standpoint</code>!</p> <p>Should a website <code>expand/stretch</code> to fill the viewing area when you resize a browser window?</p> <p>I know for sure there are the obvious cons:</p> <ul> <li>Wide columns of text are hard to read.</li> <li>Writing html/css using percents can be a pain.</li> <li>It makes you vulnerable to having your design stretched past it's limits if an image is too wide, or a block of text is added that is too long. <strong>(see it's a pain to code the html/css</strong>).</li> </ul> <p>The only Pro I can think of is that users who use the font-resizing that is built into their browser won't have to deal with columns that are only a few words long, with a body of <code>white-space</code> on either side.</p> <p>However, I think that may be a browser problem more than anything else (Firefox 3 allows you to zoom <strong>everything</strong> instead of just the text, which comes in handy all the time)</p> <p><strong>edit</strong>: I noticed stack overflow is fixed width, but coding horror resizes. It seems Jeff doesn't have a strong preference either way.</p>
[ { "answer_id": 132102, "author": "paperhorse", "author_id": 4498, "author_profile": "https://Stackoverflow.com/users/4498", "pm_score": 0, "selected": false, "text": "max-width window width fixed width" }, { "answer_id": 216295, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 2, "selected": false, "text": "min-width max-width" } ]
2008/08/26
[ "https://Stackoverflow.com/questions/27381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]