qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
258,590
|
<p>I have an SVN repository structure like below. We are using multiple levels under branches for various release maintenance branches, plus a directory for feature branches.</p>
<p>git-svn init seems to work with a single --branches argument, i.e. it seems to expect all of the branches to be in a single location.</p>
<pre><code>trunk
branches
1.1
1.2.1
1.2.2
1.2
1.2.1
1.2.2
1.2.3
features
feature1
feature2
</code></pre>
<p>Any ideas on how to handle this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 258604,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "git"
},
{
"answer_id": 258659,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "git-svn branches git-svn git losing history git-svn"
},
{
"answer_id": 267217,
"author": "Peter Burns",
"author_id": 101,
"author_profile": "https://Stackoverflow.com/users/101",
"pm_score": 0,
"selected": false,
"text": "git svn git svn fetch"
},
{
"answer_id": 630684,
"author": "Greg",
"author_id": 42882,
"author_profile": "https://Stackoverflow.com/users/42882",
"pm_score": 5,
"selected": true,
"text": "[svn-remote \"svn\"]\n url = svn://svnserver/repo\n fetch = trunk:refs/remotes/trunk\n branches = branches/*/*:refs/remotes/*\n tags = tags/*:refs/remotes/tags/*\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15203/"
] |
258,625
|
<p>I've come across a couple of popular PHP-related answers recently that suggested using the superglobal <code>$_REQUEST</code>, which I think of as code smell, because it reminds me of <code>register_globals</code>.</p>
<p>Can you provide a good explanation/evidence of why <code>$_REQUEST</code> is bad practice? I'll throw out a couple of examples I've dug up, and would love more information/perspective on both theoretical attack vectors and real-world exploits, as well as suggestions of reasonable steps the sysadmin can take to reduce risk (short of rewriting the app ... or, do we <em>need</em> to go to management and insist on a rewrite?).</p>
<p><strong>Example vulnerabilities:</strong> Default <code>GPC</code> array merge-order means that COOKIE values override GET and POST, so <code>$_REQUEST</code> can be used for XSS and HTTP attacks. PHP lets cookie vars overwrite the superglobal arrays. First 10 slides of <a href="http://www.slideshare.net/ZendCon/lesser-known-security-problems-in-php-applications-presentation" rel="nofollow noreferrer">this talk</a> give examples (whole talk is great). <a href="http://www.hardened-php.net/advisory_072006.130.html" rel="nofollow noreferrer">phpMyAdmin exploit</a> example of CSRF attack.</p>
<p><strong>Example countermeasures:</strong> Reconfigure <code>$_REQUEST</code> array merge-order from <code>GPC</code> to <code>CGP</code> so GET/POST overwrite COOKIE, not the other way around. Use <a href="http://www.hardened-php.net/suhosin/" rel="nofollow noreferrer">Suhosin</a> to block overwrite of superglobals.</p>
<p>(Also, wouldn't be asking if I thought my question was a dupe, but happily the overwhelming SO answer to <a href="https://stackoverflow.com/questions/107683/when-and-why-should-request-be-used-instead-of-get-post-cookie">"When and why should $_REQUEST be used instead of $_GET / $_POST / $_COOKIE?"</a> was "Never.")</p>
|
[
{
"answer_id": 259336,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 3,
"selected": false,
"text": "$_REQUEST $_GET $_POST"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11438/"
] |
258,655
|
<p>Anyone know how to detect if a television is currently connected to a PC in c#?</p>
<p>Cheers</p>
|
[
{
"answer_id": 258697,
"author": "Kristian",
"author_id": 23246,
"author_profile": "https://Stackoverflow.com/users/23246",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Drawing;\nusing System.Collections;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nusing System.Data;\nusing System.Runtime.InteropServices;\nnamespace WindowsApplication\n{\n /// <summary>\n /// Summary description for Form1.\n /// </summary>\n public class Form1 : System.Windows.Forms.Form\n {\n /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.Container components = null;\n\n public Form1()\n {\n //\n // Required for Windows Form Designer support\n //\n InitializeComponent();\n\n //\n // TODO: Add any constructor code after InitializeComponent call\n //\n }\n\n [StructLayout(LayoutKind.Sequential)] \n public struct DEV_BROADCAST_VOLUME \n { \n public int dbcv_size; \n public int dbcv_devicetype; \n public int dbcv_reserved; \n public int dbcv_unitmask; \n } \n\n protected override void WndProc(ref Message m) \n { \n //you may find these definitions in dbt.h and winuser.h \n const int WM_DEVICECHANGE = 0x0219; \n const int DBT_DEVICEARRIVAL = 0x8000; // system detected a new device \n const int DBT_DEVICEREMOVECOMPLETE = 0x8001; // system detected a new device \n const int DBT_DEVTYP_VOLUME = 0x00000002; // logical volume \n switch(m.Msg)\n {\n case WM_DEVICECHANGE:\n switch(m.WParam.ToInt32())\n {\n case DBT_DEVICEARRIVAL:\n { \n int devType = Marshal.ReadInt32(m.LParam,4); \n if(devType == DBT_DEVTYP_VOLUME) \n { \n DEV_BROADCAST_VOLUME vol; \n vol = (DEV_BROADCAST_VOLUME) \n Marshal.PtrToStructure(m.LParam,typeof(DEV_BROADCAST_VOLUME)); \n MessageBox.Show(vol.dbcv_unitmask.ToString(\"x\")); \n } \n } \n break;\n case DBT_DEVICEREMOVECOMPLETE:\n MessageBox.Show(\"Removal\");\n break;\n }\n\n break;\n }\n //we detect the media arrival event \n base.WndProc (ref m); \n\n\n } \n /// <summary>\n /// Clean up any resources being used.\n /// </summary>\n protected override void Dispose( bool disposing )\n {\n if( disposing )\n {\n if (components != null) \n {\n components.Dispose();\n }\n }\n base.Dispose( disposing );\n }\n\n\n #region Windows Form Designer generated code\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 {\n // \n // Form1\n // \n this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);\n this.ClientSize = new System.Drawing.Size(292, 273);\n this.Name = \"Form1\";\n this.Text = \"Form1\";\n this.Load += new System.EventHandler(this.Form1_Load);\n\n }\n #endregion\n\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main() \n {\n Application.Run(new Form1());\n }\n\n private void Form1_Load(object sender, System.EventArgs e)\n {\n\n }\n }\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33647/"
] |
258,661
|
<p>I have a GridView defined like this:</p>
<pre><code><asp:GridView ID="myGridView" ruant="server">
<asp:BoundField DataField="myField" />
<asp:CommandField ShowDeleteButton="true" ShowEditButton="true" />
</asp:GridView>
</code></pre>
<p>After I put a row into edit mode with the Edit button, how do I capture the Enter key and trigger the resulting Update on the row? Right now if I hit enter, the page reloads, what was entered into the TextBox is lost, and the row stays in edit mode. I know how to <a href="https://stackoverflow.com/questions/152099/i-want-to-prevent-aspnet-gridview-from-reacting-to-the-enter-button">disable the enter key entirely</a> on the form (the current workaround), but I'd like to have it fire the Update command.</p>
|
[
{
"answer_id": 258669,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "string js = \"if (event.keyCode == 13) this.form.submit();\"\nmyGridView.Attributes.Add(\"onkeydown\", js);\n GridView_RowUpdating __EVENTTARGET form.submit() string js = \"if ((event.which && event.which == 13) || \" \n + \"(event.keyCode && event.keyCode == 13)) \"\n + \"{document.myForm.Update.click();return false;} \"\n + \"else return true;\";\nmyGridView.Attributes.Add(\"onkeydown\", js);\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
258,662
|
<p>My WinForms app uses a number of <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="noreferrer">BackgroundWorker</a> objects to retrieve information from a database. I'm using BackgroundWorker because it allows the UI to remain unblocked during long-running database queries and it simplifies the threading model for me.</p>
<p>I'm getting occasional DatabaseExceptions in some of these background threads, and I have witnessed at least one of these exceptions in a worker thread while debugging. I'm fairly confident these exceptions are timeouts which I suppose its reasonable to expect from time to time.</p>
<p>My question is about what happens when an unhandled exception occurs in one of these background worker threads.</p>
<p>I don't think I can catch an exception in another thread, but can I expect my WorkerCompleted method to be executed? Is there any property or method of the BackgroundWorker I can interrogate for exceptions?</p>
|
[
{
"answer_id": 258664,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 7,
"selected": true,
"text": "BackgroundWorker RunWorkerCompleted System.ComponentModel.RunWorkerCompletedEventArgs"
},
{
"answer_id": 2636352,
"author": "CallMeLaNN",
"author_id": 186334,
"author_profile": "https://Stackoverflow.com/users/186334",
"pm_score": 5,
"selected": false,
"text": "BackgroundWorker RunWorkerCompleted e.Error Throw New Exception(\"Test\") DoWork DoWork e.Error Form BackgroundWorker e.Error RunWorkerCompleted BackgroundWorker RunWorkerCompleted e.Error e.Cancelled e.Result e.Result e.Cancelled = True e.Result e.Error null Nothing e.Result e.Error null Nothing e.Result e.Error DoWork RunWorkerCompleted DoWork RunWorkerCompleted If e.Error IsNot Nothing Then\n ' Handle the error here\nElse\n If e.Cancelled Then\n ' Tell user the process canceled here\n Else\n ' Tell user the process completed\n ' and you can use e.Result only here.\n End If\nEnd If\n Dim ThreadInfos as Dictionary(Of BackgroundWorker, YourObjectOrStruct)\n ThreadInfos(sender).Field"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4200/"
] |
258,667
|
<p>I'm wondering whether something like this is possible (and relatively easy to do), and if so, how I could do it?</p>
<p>I would like to do band filtering on a wave file I'm reproducing. Something similar to the "Equalizer" you see in most Winamp-like applications.<br>
My idea is, however, not to equalize the sound, but to use very high negative dB values, to almost kill the band I'm filtering.</p>
<p>The first question is: Does DirectSound give me something that allows me to do this?<br>
If not: How would you go around implementing this?<br>
I know (although I don't quite understand it completely) that you can convert from the sampled waveform to the distribution of frequencies using a Fast Fourier Transform. Now, I obviously can't go back from that distribution to the original waveform after changing the amplitude values of certain frequencies :-) </p>
<p>How could I do something like this?</p>
<p>Also, how precise can I make these filters? (If I wanted to filter out everything from 2250Hz to 2275Hz, what would be the error a filter would have? What would the maximum precision that I can get depend on?)</p>
<p>Thanks!</p>
|
[
{
"answer_id": 258696,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 2,
"selected": false,
"text": "for (int i = 0; i < samples.Length - delay; i++)\n{\n samples[i + delay] += samples[i] * decay;\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
258,668
|
<p>In GWT, what is the best way to convert a JavaScriptObject overlay type into a JSON string?</p>
<p>I currently have</p>
<pre><code>public final String toJSON() {
return new JSONObject(this).toString();
}
</code></pre>
<p>Which seems to work fine. I would like to know if there are any better approaches.</p>
|
[
{
"answer_id": 332195,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 3,
"selected": true,
"text": "public native String toJSON() /*-{\n return this.toString();\n}-*/;\n"
},
{
"answer_id": 7109319,
"author": "Nick Franceschina",
"author_id": 130221,
"author_profile": "https://Stackoverflow.com/users/130221",
"pm_score": 2,
"selected": false,
"text": "public native String stringify() /*-{\n return JSON.stringify();\n}-*/;\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32320/"
] |
258,680
|
<p>Is there a possible htaccess directive that can transparently forward request from index.php to index_internal.php if the request is coming from an internal ip range?</p>
|
[
{
"answer_id": 258704,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "RewriteCond %{REMOTE_ADDR} ^192\\.168\\.\nRewriteRule index.php index_internal.php\n RewriteRule index.php index_internal.php [L,R,QSA]"
},
{
"answer_id": 258717,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 3,
"selected": true,
"text": "RewriteEngine on\n\nRewriteCond %{REMOTE_ADDR} ^192\\.168\\.1\\. [OR]\nRewriteCond %{REMOTE_ADDR} ^10\\.15\\.\nRewriteRule ^index\\.php$ index_internal.php [R,NC,QSA,L]\n index.php?foo=bar index_internal.php?foo=bar"
},
{
"answer_id": 258741,
"author": "ken",
"author_id": 20300,
"author_profile": "https://Stackoverflow.com/users/20300",
"pm_score": 1,
"selected": false,
"text": "RewriteEngine on\nRewriteCond %{REMOTE_ADDR} ^10\\. [OR]\nRewriteCond %{REMOTE_ADDR} ^172\\.[1-3]{1}\\d{1}\\. [OR]\nRewriteCond %{REMOTE_ADDR} ^192\\.168\\.\nRewriteRule ^index\\.php index_internal.php [NC,QSA,L]\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20300/"
] |
258,691
|
<p>I am using an XmlDocument to parse and manipulate an XHTML string, converting some nodes to non-HTML nodes.</p>
<p>What is the best way to get a list of all nodes with a given class name? Can it be done with XPath?</p>
|
[
{
"answer_id": 258698,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "Split() var qry = from XmlElement el in d.SelectNodes(\"//*[@class!='']\")\n let classes = el.GetAttribute(\"class\").Split(new[] {' '},\n StringSplitOptions.RemoveEmptyEntries)\n where classes.Contains(\"foo\")\n select el;\n"
},
{
"answer_id": 258700,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "//*[@class='foo']\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
258,694
|
<p>For a one-shot operation, i need to parse the contents of an XML string and change the numbers of the "ID" field. However, i can not risk changing anything else of the string, eg. whitespace, line feeds, etc. MUST remain as they are! </p>
<p>Since i have made the experience that XmlReader tends to mess whitespace up and may even reformat your XML i don't want to use it (but feel free to convince me otherwise). This also screams for RegEx but ... i'm not good at RegEx, particularly not with the .NET implementation.</p>
<p>Here's a short part of the string, the number of the ID field needs to be updated in some cases. There can be many such VAR entries in the string. So i need to convert each ID to Int32, compare & modify it, then put it back into the string.</p>
<pre><code><VAR NAME="sf_name" ID="1001210">
</code></pre>
<p>I am looking for the simplest (in terms of coding time) and safest way to do this.</p>
|
[
{
"answer_id": 258723,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "ID=\"(\\d+)\"\n Regex r = new Regex(\"ID=\\\"(\\\\d+)\\\"\");\nstring outputXml = r.Replace(inputXml, new MatchEvaluator(ReplaceFunction));\n ReplaceFunction public string ReplaceFunction(Match m)\n{\n // do stuff with m.Groups(1);\n return result.ToString();\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
] |
258,701
|
<p>Is there an easy way to test whether your named pipe is working correctly? I want to make sure that the data I'm sending from my app is actually being sent. Is there a quick and easy way to get a list of all the named pipes?</p>
|
[
{
"answer_id": 4209848,
"author": "Omar Elsherif",
"author_id": 511410,
"author_profile": "https://Stackoverflow.com/users/511410",
"pm_score": 4,
"selected": false,
"text": "String[] listOfPipes = System.IO.Directory.GetFiles(@\"\\\\.\\pipe\\\");\n"
},
{
"answer_id": 4252118,
"author": "Vincent Lidou",
"author_id": 365356,
"author_profile": "https://Stackoverflow.com/users/365356",
"pm_score": 6,
"selected": false,
"text": "String[] listOfPipes = System.IO.Directory.GetFiles(@\"\\\\.\\pipe\\\");\n"
},
{
"answer_id": 4589019,
"author": "Vincent Lidou",
"author_id": 561869,
"author_profile": "https://Stackoverflow.com/users/561869",
"pm_score": 3,
"selected": false,
"text": "System.IO.Directory.GetFiles(@\"\\\\.\\pipe\\\")"
},
{
"answer_id": 12066420,
"author": "Andrew Shepherd",
"author_id": 25216,
"author_profile": "https://Stackoverflow.com/users/25216",
"pm_score": 7,
"selected": false,
"text": "[System.IO.Directory]::GetFiles(\"\\\\.\\\\pipe\\\\\")\n get-childitem \\\\.\\pipe\\\n (get-childitem \\\\.\\pipe\\).FullName\n \\\\.\\pipe\\"
},
{
"answer_id": 59066859,
"author": "Constantin Konstantinidis",
"author_id": 6161244,
"author_profile": "https://Stackoverflow.com/users/6161244",
"pm_score": 4,
"selected": false,
"text": "CMD >ver\n\nMicrosoft Windows [Version 10.0.18362.476]\n\n>dir \\\\.\\pipe\\\\\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258701",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8123/"
] |
258,725
|
<p>When working with my .Net 2.0 code base ReSharper continually recommends applying the latest c# 3.0 language features, most notably; convert simple properties into auto-implement properties or declaring local variables as var. Amongst others.</p>
<p>When a new language feature arrives do you go back and religiously apply it across your existing code base or do you leave the code as originally written accepting that if new code is written using new language features there will be inconsistencies across your code?</p>
|
[
{
"answer_id": 258739,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": " static void Main() {\n using (TextReader reader = File.OpenText(\"foo.bar\")) { // [HERE]\n Write(reader);\n }\n }\n static void Write(TextReader reader) {\n Console.Write(reader.ReadToEnd());\n }\n static void Write(StreamReader reader) {\n throw new NotImplementedException();\n }\n var reader [HERE]"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26409/"
] |
258,726
|
<p>I am using a bat file on a Windows 2000 SP4 server to copy database files while the database is shut down. Once the bat file hits the xcopy command, it does the copy, but never returns to the bat file to continue with the other commands (start up the database, etc). I should mention that the xcopy takes several hours. Is there some sort of time out or time max with bat files? Is this normal? If so, is there any way around this?</p>
|
[
{
"answer_id": 258761,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "-Y to suppress prompts about overwriting files\n\n-C continue even if errors occur\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
258,727
|
<p>I'd like to display a stack trace in an error dialog in Delphi 2007 (Win32).</p>
<p>Ideally, I'd like something like this:</p>
<pre><code>try
//do something
except on e : exception do
begin
//rollback a transaction or whatever i need to do here
MessageDlg('An error has occurred!' + #13#10 +
e.Message + #13#10 +
'Here is the stack trace:' + #13#10 +
e.StackTrace,mtError,[mbOK],0);
end; //except
end; /try-except
</code></pre>
<p>And for the output to be like the Call Stack in the IDE:</p>
<pre><code>MYPROGRAM.SomeFunction
MYPROGRAM.SomeProcedure
MYPROGRAM.MYPROGRAM
:7c817067 kernel32.RegisterWaitForInputIdle + 0x49
</code></pre>
|
[
{
"answer_id": 2288441,
"author": "Martin Binder",
"author_id": 125092,
"author_profile": "https://Stackoverflow.com/users/125092",
"pm_score": 3,
"selected": false,
"text": "try\n raise Exception.Create('Something bad happened...');\nexcept\n on e: Exception do begin\n CallStack := TStringList.Create;\n try\n ExceptionHook.LogException; // Logs call stack\n ExceptionHook.CallStack.Dump(CallStack);\n ShowMessage(CallStack.Text);\n finally\n CallStack.Free;\n end;\n end;\n end;\n Exception 'Exception' in module BOAppTemplate.exe at 003F3C36\nSomething bad happened...\n\nModule: BOAppUnit, Source: BOAppUnit.pas, Line 66\nProcedure: MyProcedure\n\nCall stack:\n:007F4C36 [BOAppTemplate.exe] MyProcedure (BOAppUnit.pas, line 66)\n:7C812AFB [kernel32.dll]\n:007F4C36 [BOAppTemplate.exe] MyProcedure (BOAppUnit.pas, line 66)\n:00404DF4 [BOAppTemplate.exe] System::__linkproc__ AfterConstruction\nRecursive call (2 times):\n:007F4C36 [BOAppTemplate.exe] MyProcedure (BOAppUnit.pas, line 66)\n:007F4CE6 [BOAppTemplate.exe] MyProcedure (BOAppUnit.pas, line 79)\n:007F4D22 [BOAppTemplate.exe] Boappunit::TBOAppForm::Button1Click (BOAppUnit.pas, line 82)\n:004604C2 [BOAppTemplate.exe] Controls::TControl::Click\n:004487FB [BOAppTemplate.exe] Stdctrls::TButton::Click\n:004488F9 [BOAppTemplate.exe] Stdctrls::TButton::CNCommand\n:0045FFBA [BOAppTemplate.exe] Controls::TControl::WndProc\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
258,728
|
<p>When I try to create a new task in the task scheduler via the Java ProcessBuilder class I get an access denied error an Windows Vista. On XP it works just fine.</p>
<p>When I use the "Run as adminstrator" option it runs on Vista as well..</p>
<p>However this is a additional step requeried an the users might not know about this. When the user just double clicks on the app icon it will fail with access denied. My question is how can I force a java app to reuest admin privileges right after startup?</p>
|
[
{
"answer_id": 2318883,
"author": "freecouch",
"author_id": 279535,
"author_profile": "https://Stackoverflow.com/users/279535",
"pm_score": 5,
"selected": false,
"text": "<target name=\"wrapMyApp\" depends=\"myapp.jar\">\n <launch4j configFile=\"myappConfig.xml\" />\n</target>\n <launch4jConfig>\n <dontWrapJar>false</dontWrapJar>\n <headerType>gui</headerType>\n <jar>bin\\myapp.jar</jar>\n <outfile>bin\\myapp.exe</outfile>\n <priority>normal</priority>\n <downloadUrl>http://java.com/download</downloadUrl>\n <customProcName>true</customProcName>\n <stayAlive>false</stayAlive>\n <manifest>myapp.manifest</manifest>\n <jre>\n <path></path>\n <minVersion>1.5.0</minVersion>\n <maxVersion></maxVersion>\n <jdkPreference>preferJre</jdkPreference>\n </jre>\n</launch4jConfig>\n <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"highestAvailable\"\n uiAccess=\"False\" />\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly> \n"
},
{
"answer_id": 26848405,
"author": "Airy",
"author_id": 2026065,
"author_profile": "https://Stackoverflow.com/users/2026065",
"pm_score": 1,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"highestAvailable\" uiAccess=\"False\" />\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly> \n Basic"
},
{
"answer_id": 49644489,
"author": "PHPirate",
"author_id": 4126843,
"author_profile": "https://Stackoverflow.com/users/4126843",
"pm_score": 0,
"selected": false,
"text": "myapp.manifest <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"highestAvailable\"\n uiAccess=\"False\" />\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly> \n build.gradle plugins {\n id 'java'\n id 'edu.sc.seis.launch4j' version '2.4.3'\n}\n\nlaunch4j {\n mainClassName = 'com.mypackage.MainClass'\n icon = \"$projectDir/icons/icon.ico\"\n manifest = \"$projectDir/myapp.manifest\"\n}\n build.gradle.kts plugins {\n application\n kotlin(\"jvm\") version \"1.2.31\"\n java\n id(\"edu.sc.seis.launch4j\") version \"2.4.3\"\n}\n\nlaunch4j {\n mainClassName = \"com.mypackage.MainKt\"\n icon = \"$projectDir/icons/icon.ico\"\n manifest = \"$projectDir/myapp.manifest\"\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20999/"
] |
258,729
|
<p>I have a simple linux script:</p>
<pre><code>#!/bin/sh
for i in `ls $1`
do
echo $i
done
</code></pre>
<p>In my temp folder are 4 file: a.a, a.aa, a.ab and a.ac</p>
<p>When i call ./script temp/*.?? i get:</p>
<pre><code>temp/a.aa
</code></pre>
<p>When i call ./script "temp/*.??" i get:</p>
<pre><code>temp/a.aa
temp/a.ab
temp/a.ac
</code></pre>
<p>Why do the double quote change the result?</p>
|
[
{
"answer_id": 258778,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "./script temp/a.aa temp/a.ab temp/a.ac\n $1 temp/a.aa temp/*.??"
},
{
"answer_id": 258783,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "temp/*.?? temp/a.aa temp/a.ab temp/a.ac\n temp/a.aa temp/*.?? ls"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860/"
] |
258,735
|
<p>I am using this command:</p>
<p>cut -d: -f2
<p>To sort and reedit text, Is there a more efficient way to do this without using sed or awk?</p>
<p>I would also like to know how I would append a period to the end of each field</p>
<p>At the moment the output is like $x['s'] and I would like it to be $x['s'] .</p>
<p>Just using standard unix tools</p>
<p>edit: I just wanted to know if it was possible without sed or awk, otherwise how would you do it with awk?</p>
|
[
{
"answer_id": 258787,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": true,
"text": "cut perl sed awk"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
258,738
|
<p>I have a Java maven project which includes XSLT transformations. I load the stylesheet as follows:</p>
<pre><code>TransformerFactory tFactory = TransformerFactory.newInstance();
DocumentBuilderFactory dFactory = DocumentBuilderFactory
.newInstance();
dFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
ClassLoader cl = this.getClass().getClassLoader();
java.io.InputStream in = cl.getResourceAsStream("xsl/stylesheet.xsl");
InputSource xslInputSource = new InputSource(in);
Document xslDoc = dBuilder.parse(xslInputSource);
DOMSource xslDomSource = new DOMSource(xslDoc);
Transformer transformer = tFactory.newTransformer(xslDomSource);
</code></pre>
<p>The stylesheet.xsl has a number of statements. These appear to be causing problems, when I try to run my unit tests I get the following errors:</p>
<pre><code>C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: footer.xsl
C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: topbar.xsl
</code></pre>
<p>The include statements in the XSLT are relative links</p>
<pre><code>xsl:include href="footer.xsl"
xsl:include href="topbar.xsl"
</code></pre>
<p>I have tried experimenting and changing these to the following - but I still get the error.</p>
<pre><code>xsl:include href="xsl/footer.xsl"
xsl:include href="xsl/topbar.xsl"
</code></pre>
<p>Any ideas? Any help much appreciated.</p>
|
[
{
"answer_id": 258951,
"author": "will",
"author_id": 8633,
"author_profile": "https://Stackoverflow.com/users/8633",
"pm_score": 5,
"selected": true,
"text": "class MyURIResolver implements URIResolver {\n@Override\npublic Source resolve(String href, String base) throws TransformerException {\n try {\n ClassLoader cl = this.getClass().getClassLoader();\n java.io.InputStream in = cl.getResourceAsStream(\"xsl/\" + href);\n InputSource xslInputSource = new InputSource(in);\n Document xslDoc = dBuilder.parse(xslInputSource);\n DOMSource xslDomSource = new DOMSource(xslDoc);\n xslDomSource.setSystemId(\"xsl/\" + href);\n return xslDomSource;\n } catch (...\n tFactory.setURIResolver(new MyURIResolver());\n"
},
{
"answer_id": 11138263,
"author": "Rajdeep Kwatra",
"author_id": 1472087,
"author_profile": "https://Stackoverflow.com/users/1472087",
"pm_score": 3,
"selected": false,
"text": "class XsltURIResolver implements URIResolver {\n\n @Override\n public Source resolve(String href, String base) throws TransformerException {\n try{\n InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(\"xslts/\" + href);\n return new StreamSource(inputStream);\n }\n catch(Exception ex){\n ex.printStackTrace();\n return null;\n }\n }\n}\n TransformerFactory transFact = TransformerFactory.newInstance();\ntransFact.setURIResolver(new XsltURIResolver());\n transFact.setURIResolver((href, base) -> {\n final InputStream s = this.getClass().getClassLoader().getResourceAsStream(\"xslts/\" + href);\n return new StreamSource(s);\n});\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8633/"
] |
258,742
|
<p>This is hopefully a simple question: I have an OpenGL texture and would like to be able to change its opacity, how do I do that? The texture already has an alpha channel and blending works fine, but I want to be able to decrease the opacity of the whole texture, to fade it into the background. I have fiddled with <code>glBlendFunc</code>, but with no luck – it seems that I would need something like <code>GL_SRC_ALPHA_MINUS_CONSTANT</code>, which is not available. I am working on iPhone, with OpenGL ES.</p>
|
[
{
"answer_id": 258848,
"author": "Dan",
"author_id": 11606,
"author_profile": "https://Stackoverflow.com/users/11606",
"pm_score": 4,
"selected": false,
"text": "// R, G, B, A\nglColor4f(1.0, 1.0, 1.0, 0.5);\n"
},
{
"answer_id": 258941,
"author": "mstrobl",
"author_id": 25965,
"author_profile": "https://Stackoverflow.com/users/25965",
"pm_score": 1,
"selected": false,
"text": "glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_DST_ALPHA),\n"
},
{
"answer_id": 262516,
"author": "NeARAZ",
"author_id": 6799,
"author_profile": "https://Stackoverflow.com/users/6799",
"pm_score": 3,
"selected": false,
"text": "GL_MODULATE glTexEnv GL_TEXTURE_ENV_COLOR"
},
{
"answer_id": 61943225,
"author": "Samuel",
"author_id": 8754125,
"author_profile": "https://Stackoverflow.com/users/8754125",
"pm_score": 2,
"selected": false,
"text": "void main()\n{\n color = vec4(1.0f, 1.0f, 1.0f, OPACITY) * texture(u_Texture, TexCoord);\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17279/"
] |
258,746
|
<p>I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below:</p>
<pre><code>http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3
</code></pre>
<p>How could I slice out:</p>
<pre><code>http://www.domainname.com/page?CONTENT_ITEM_ID=1234
</code></pre>
<p>Sometimes there is more than two parameters after the CONTENT_ITEM_ID and the ID is different each time, I am thinking it can be done by finding the first & and then slicing off the chars before that &, not quite sure how to do this tho.</p>
<p>Cheers</p>
|
[
{
"answer_id": 258797,
"author": "RailsSon",
"author_id": 30786,
"author_profile": "https://Stackoverflow.com/users/30786",
"pm_score": 1,
"selected": false,
"text": "url = \"http://www.domainname.com/page?CONTENT_ITEM_ID=1234¶m2¶m3\"\nurl = url[: url.find(\"&\")]\nprint url\n'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'\n"
},
{
"answer_id": 258798,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 0,
"selected": false,
"text": "import re\nurl = 'http://www.domainname.com/page?CONTENT_ITEM_ID=1234¶m2¶m3'\nm = re.search('(.*?)&', url)\nprint m.group(1)\n"
},
{
"answer_id": 258800,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 2,
"selected": false,
"text": ">>> \"http://something.com/page?CONTENT_ITEM_ID=1234¶m3\".split(\"&\")[0]\n'http://something.com/page?CONTENT_ITEM_ID=1234'\n"
},
{
"answer_id": 258810,
"author": "Kena",
"author_id": 8027,
"author_profile": "https://Stackoverflow.com/users/8027",
"pm_score": 2,
"selected": false,
"text": " url.split(\"&\") \n ['http://www.domainname.com/page?CONTENT_ITEM_ID=1234', 'param2', 'param3']\n"
},
{
"answer_id": 258993,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 0,
"selected": false,
"text": "url = 'http://www.domainname.com/page?CONTENT_ITEM_ID=1234¶m2¶m3'\nparts = url.split('?')\nid = dict(i.split('=') for i in parts[1].split('&'))['CONTENT_ITEM_ID']\nnew_url = parts[0] + '?CONTENT_ITEM_ID=' + id\n"
},
{
"answer_id": 259054,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 1,
"selected": false,
"text": "import urllib\nurl =\"http://www.domainname.com/page?CONTENT_ITEM_ID=1234¶m2¶m3\"\nquery = urllib.splitquery(url)\nresult = \"?\".join((query[0], query[1].split(\"&\")[0]))\nprint result\n'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'\n"
},
{
"answer_id": 259159,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": true,
"text": "import urlparse\n\ndef process_url(url, keep_params=('CONTENT_ITEM_ID=',)):\n parsed= urlparse.urlsplit(url)\n filtered_query= '&'.join(\n qry_item\n for qry_item in parsed.query.split('&')\n if qry_item.startswith(keep_params))\n return urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:])\n >>> process_url(a)\n'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'\n >>> url='http://www.domainname.com/page?other_value=xx¶m3&CONTENT_ITEM_ID=1234¶m1'\n>>> process_url(url, ('CONTENT_ITEM_ID', 'other_value'))\n'http://www.domainname.com/page?other_value=xx&CONTENT_ITEM_ID=1234'\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
258,757
|
<p>How do I escape a string in SQL Server's stored procedure so that it is safe to use in <code>LIKE</code> expression.</p>
<p>Suppose I have an <code>NVARCHAR</code> variable like so:</p>
<pre><code>declare @myString NVARCHAR(100);
</code></pre>
<p>And I want to use it in a <code>LIKE</code> expression:</p>
<pre><code>... WHERE ... LIKE '%' + @myString + '%';
</code></pre>
<p>How do I escape the string (more specifically, characters that are meaningful to <code>LIKE</code> pattern matching, e.g. <code>%</code> or <code>?</code>) in T-SQL, so that it is safe to use in this manner?</p>
<p>For example, given:</p>
<pre><code>@myString = 'aa%bb'
</code></pre>
<p>I want:</p>
<pre><code>WHERE ... LIKE '%' + @somehowEscapedMyString + '%'
</code></pre>
<p>to match <code>'aa%bb'</code>, <code>'caa%bbc'</code> but not <code>'aaxbb'</code> or <code>'caaxbb'</code>.</p>
|
[
{
"answer_id": 258808,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "select * from table where myfield like '%10%%'.\n select * from table where myfield like '%10!%%' ESCAPE '!'\n"
},
{
"answer_id": 258947,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 8,
"selected": true,
"text": "select * from table where myfield like '%15\\% off%' ESCAPE '\\'\n set @myString = replace( \n replace( \n replace( \n replace( @myString\n , '\\', '\\\\' )\n , '%', '\\%' )\n , '_', '\\_' )\n , '[', '\\[' )\n replace replace select * from table where myfield like '%' + @myString + '%' ESCAPE '\\'\n"
},
{
"answer_id": 1178393,
"author": "Dries Van Hansewijck",
"author_id": 95981,
"author_profile": "https://Stackoverflow.com/users/95981",
"pm_score": 4,
"selected": false,
"text": "WHERE ... LIKE '%aa[%]bb%'\n create table test (field nvarchar(100))\ngo\ninsert test values ('abcdef%hijklm')\ninsert test values ('abcdefghijklm')\ngo\nselect * from test where field like 'abcdef[%]hijklm'\ngo\n"
},
{
"answer_id": 9242060,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 4,
"selected": false,
"text": "SELECT * \nFROM YourTable\nWHERE CHARINDEX(@myString , YourColumn) > 0\n YourColumn LIKE CHARINDEX ESCAPE"
},
{
"answer_id": 56923634,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 0,
"selected": false,
"text": "SELECT *\nFROM tab\nWHERE col LIKE 'a\\_c' {escape '\\'};\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
258,762
|
<p>Is there a way in .NET 2.0 (C#) to serialize object like you do using XmlSerializer in a simple / customizable human readable format thats for instance looks like <a href="http://community.moertel.com/pxsl/" rel="noreferrer">PXLS</a> or JSON?
Also I know that XML is human readable, I'm looking for something with less annoying redundancy, something that you can output to the console as a result for the user.</p>
|
[
{
"answer_id": 258876,
"author": "ullmark",
"author_id": 23044,
"author_profile": "https://Stackoverflow.com/users/23044",
"pm_score": 4,
"selected": true,
"text": "public static string ToJson(IEnumerable collection)\n {\n DataContractJsonSerializer ser = new DataContractJsonSerializer(collection.GetType());\n string json;\n using (MemoryStream m = new MemoryStream())\n {\n XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(m);\n ser.WriteObject(m, collection);\n writer.Flush();\n\n json = Encoding.Default.GetString(m.ToArray());\n }\n return json;\n }\n"
},
{
"answer_id": 2554460,
"author": "Zax",
"author_id": 306087,
"author_profile": "https://Stackoverflow.com/users/306087",
"pm_score": 2,
"selected": false,
"text": "using System.Runtime.Serialization;\nusing System.Runtime.Serialization.Json;\n\npublic class JSONHelper\n{\n public static string Serialize<T>(T obj)\n {\n DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());\n MemoryStream ms = new MemoryStream();\n serializer.WriteObject(ms, obj);\n string retVal = Encoding.Default.GetString(ms.ToArray());\n ms.Dispose();\n return retVal;\n }\n\n public static T Deserialize<T>(string json)\n {\n T obj = Activator.CreateInstance<T>();\n MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));\n DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());\n obj = (T)serializer.ReadObject(ms);\n ms.Close();\n ms.Dispose();\n return obj;\n }\n}\n"
},
{
"answer_id": 38538472,
"author": "Makeman",
"author_id": 6627992,
"author_profile": "https://Stackoverflow.com/users/6627992",
"pm_score": 1,
"selected": false,
"text": " public readonly DataContractJsonSerializerSettings Settings = \n new DataContractJsonSerializerSettings\n { UseSimpleDictionaryFormat = true };\n\n public void Keep<TValue>(TValue item, string path)\n {\n try\n {\n using (var stream = File.Open(path, FileMode.Create))\n {\n var currentCulture = Thread.CurrentThread.CurrentCulture;\n Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\n\n try\n {\n using (var writer = JsonReaderWriterFactory.CreateJsonWriter(\n stream, Encoding.UTF8, true, true, \" \"))\n {\n var serializer = new DataContractJsonSerializer(type, Settings);\n serializer.WriteObject(writer, item);\n writer.Flush();\n }\n }\n catch (Exception exception)\n {\n Debug.WriteLine(exception.ToString());\n }\n finally\n {\n Thread.CurrentThread.CurrentCulture = currentCulture;\n }\n }\n }\n catch (Exception exception)\n {\n Debug.WriteLine(exception.ToString());\n }\n }\n var currentCulture = Thread.CurrentThread.CurrentCulture;\n Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\n ....\n Thread.CurrentThread.CurrentCulture = currentCulture;\n public TValue Revive<TValue>(string path, params object[] constructorArgs)\n {\n try\n {\n using (var stream = File.OpenRead(path))\n {\n var currentCulture = Thread.CurrentThread.CurrentCulture;\n Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\n\n try\n {\n var serializer = new DataContractJsonSerializer(type, Settings);\n var item = (TValue) serializer.ReadObject(stream);\n if (Equals(item, null)) throw new Exception();\n return item;\n }\n catch (Exception exception)\n {\n Debug.WriteLine(exception.ToString());\n return (TValue) Activator.CreateInstance(type, constructorArgs);\n }\n finally\n {\n Thread.CurrentThread.CurrentCulture = currentCulture;\n }\n }\n }\n catch\n {\n return (TValue) Activator.CreateInstance(typeof (TValue), constructorArgs);\n }\n }\n"
},
{
"answer_id": 42370310,
"author": "frenchone",
"author_id": 461581,
"author_profile": "https://Stackoverflow.com/users/461581",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n<xsl:output method=\"text\" indent=\"yes\"/>\n <xsl:template match=\"*\">\n <xsl:value-of select=\"name()\" /><xsl:text>\n</xsl:text>\n <xsl:apply-templates select=\"@*\"/>\n<xsl:apply-templates select=\"*\"/>\n </xsl:template>\n <xsl:template match=\"@*|text()|comment()|processing-instruction\">\n <xsl:value-of select=\"name()\" />:<xsl:value-of select=\".\" /><xsl:text>\n</xsl:text>\n </xsl:template>\n</xsl:stylesheet>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25782/"
] |
258,767
|
<p>I am using <strong>0.97-pre-SVN-unknown</strong> release of Django.</p>
<p>I have a model for which I have not given any primary_key. Django, consequently, automatically provides an AutoField that is called "id". Everything's fine with that. But now, I have to change the "verbose_name" of that AutoField to something other than "id". I cannot override the "id" field the usual way, because that would require dropping/resetting the entire model and its data (which is strictly not an option). I cannot find another way around it. Does what I want even possible to achieve? If you may suggest any alternatives that would get me away with what I want without having to drop the model/table, I'd be happy.</p>
|
[
{
"answer_id": 259027,
"author": "Justin Voss",
"author_id": 5616,
"author_profile": "https://Stackoverflow.com/users/5616",
"pm_score": 2,
"selected": false,
"text": "manage.py db_column 'id' dumpdata loaddata"
},
{
"answer_id": 259077,
"author": "Alex Koshelev",
"author_id": 19772,
"author_profile": "https://Stackoverflow.com/users/19772",
"pm_score": 3,
"selected": true,
"text": "class Entry(models.Model):\n id = models.AutoField(verbose_name=\"custom name\")\n # and other fields...\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23191/"
] |
258,775
|
<p>With SQLAlchemy, is there a way to know beforehand whether a relation would be lazy-loaded?<br>
For example, given a lazy parent->children relation and an instance X of "parent", I'd like to know if "X.children" is already loaded, without triggering the query.</p>
|
[
{
"answer_id": 261191,
"author": "Haes",
"author_id": 4993,
"author_profile": "https://Stackoverflow.com/users/4993",
"pm_score": 4,
"selected": true,
"text": "__dict__"
},
{
"answer_id": 14335831,
"author": "foz",
"author_id": 1671320,
"author_profile": "https://Stackoverflow.com/users/1671320",
"pm_score": 2,
"selected": false,
"text": ">>> hasattr(X, 'children')\nFalse\n"
},
{
"answer_id": 25011704,
"author": "kolypto",
"author_id": 134904,
"author_profile": "https://Stackoverflow.com/users/134904",
"pm_score": 5,
"selected": false,
"text": "sqlalchemy.orm.attributes.instance_state(obj).unloaded inspect() from sqlalchemy import inspect\nfrom sqlalchemy.orm import lazyload\n\nuser = session.query(User).options(lazyload(User.articles)).first()\nins = inspect(user)\n\nins.unloaded # <- set or properties that are not yet loaded\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497/"
] |
258,793
|
<p>I need to be able to compare some month names I have in an array.</p>
<p>It would be nice if there were some direct way like:</p>
<pre><code>Month.toInt("January") > Month.toInt("May")
</code></pre>
<p>My Google searching seems to suggest the only way is to write your own method, but this seems like a common enough problem that I would think it would have been already implemented in .Net, anyone done this before?</p>
|
[
{
"answer_id": 258828,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 9,
"selected": true,
"text": "DateTime.ParseExact(monthName, \"MMMM\", CultureInfo.CurrentCulture ).Month Dictionary<string, int>"
},
{
"answer_id": 258833,
"author": "Aaron Palmer",
"author_id": 24908,
"author_profile": "https://Stackoverflow.com/users/24908",
"pm_score": 5,
"selected": false,
"text": "Convert.ToDate(month + \" 01, 1900\").Month\n"
},
{
"answer_id": 258836,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 3,
"selected": false,
"text": "int month = DateTime.Parse(\"1.\" + monthName + \" 2008\").Month;\n"
},
{
"answer_id": 258851,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 3,
"selected": false,
"text": "public enum Month\n{\n January,\n February,\n // (...)\n December,\n} \n\npublic Month ToInt(Month Input)\n{\n return (int)Enum.Parse(typeof(Month), Input, true));\n}\n"
},
{
"answer_id": 258895,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 4,
"selected": false,
"text": "DateTime.ParseExact() ParseExact(\"Januar\", ...) ParseExact(\"January\", ...) CultureInfo.CurrentCulture CultureInfo.InvariantCulture"
},
{
"answer_id": 4132642,
"author": "Thabiso",
"author_id": 501747,
"author_profile": "https://Stackoverflow.com/users/501747",
"pm_score": 2,
"selected": false,
"text": "Public Function returnMonthNumber(ByVal monthName As String) As Integer\n Select Case monthName.ToLower\n Case Is = \"january\"\n Return 1\n Case Is = \"february\"\n Return 2\n Case Is = \"march\"\n Return 3\n Case Is = \"april\"\n Return 4\n Case Is = \"may\"\n Return 5\n Case Is = \"june\"\n Return 6\n Case Is = \"july\"\n Return 7\n Case Is = \"august\"\n Return 8\n Case Is = \"september\"\n Return 9\n Case Is = \"october\"\n Return 10\n Case Is = \"november\"\n Return 11\n Case Is = \"december\"\n Return 12\n Case Else\n Return 0\n End Select\nEnd Function\n"
},
{
"answer_id": 12312505,
"author": "Ebenezer Ampiah",
"author_id": 1653844,
"author_profile": "https://Stackoverflow.com/users/1653844",
"pm_score": 0,
"selected": false,
"text": "int year = 2012 \\\\or any other year\nString monthName = \"January\" \\\\or any other month\nSimpleDateFormat format = new SimpleDateFormat(\"dd-MMM-yyyy\");\nint monthNumber = format.parse(\"01-\" + monthName + \"-\" + year).getMonth();\n"
},
{
"answer_id": 12547484,
"author": "Mark Seemann",
"author_id": 126014,
"author_profile": "https://Stackoverflow.com/users/126014",
"pm_score": 3,
"selected": false,
"text": "public static class Month\n{\n public static int ToInt(this string month)\n {\n return Array.IndexOf(\n CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,\n month.ToLower(CultureInfo.CurrentCulture))\n + 1;\n }\n}\n da-DK [Theory]\n[InlineData(\"Januar\", 1)]\n[InlineData(\"Februar\", 2)]\n[InlineData(\"Marts\", 3)]\n[InlineData(\"April\", 4)]\n[InlineData(\"Maj\", 5)]\n[InlineData(\"Juni\", 6)]\n[InlineData(\"Juli\", 7)]\n[InlineData(\"August\", 8)]\n[InlineData(\"September\", 9)]\n[InlineData(\"Oktober\", 10)]\n[InlineData(\"November\", 11)]\n[InlineData(\"December\", 12)]\npublic void Test(string monthName, int expected)\n{\n var actual = monthName.ToInt();\n Assert.Equal(expected, actual);\n}\n"
},
{
"answer_id": 16174698,
"author": "Maria Carolina Araujo",
"author_id": 2312262,
"author_profile": "https://Stackoverflow.com/users/2312262",
"pm_score": 1,
"selected": false,
"text": "public string ObtenerNumeroMes(string NombreMes){\n\n string NumeroMes; \n\n switch(NombreMes) {\n\n case (\"ENERO\") :\n NumeroMes = \"01\";\n return NumeroMes;\n\n case (\"FEBRERO\") :\n NumeroMes = \"02\";\n return NumeroMes;\n\n case (\"MARZO\") :\n NumeroMes = \"03\";\n return NumeroMes;\n\n case (\"ABRIL\") :\n NumeroMes = \"04\";\n return NumeroMes;\n\n case (\"MAYO\") :\n NumeroMes = \"05\";\n return NumeroMes;\n\n case (\"JUNIO\") :\n NumeroMes = \"06\";\n return NumeroMes;\n\n case (\"JULIO\") :\n NumeroMes = \"07\";\n return NumeroMes;\n\n case (\"AGOSTO\") :\n NumeroMes = \"08\";\n return NumeroMes;\n\n case (\"SEPTIEMBRE\") :\n NumeroMes = \"09\";\n return NumeroMes;\n\n case (\"OCTUBRE\") :\n NumeroMes = \"10\";\n return NumeroMes;\n\n case (\"NOVIEMBRE\") :\n NumeroMes = \"11\";\n return NumeroMes;\n\n case (\"DICIEMBRE\") :\n NumeroMes = \"12\";\n return NumeroMes;\n\n default:\n Console.WriteLine(\"Error\");\n return \"ERROR\";\n\n }\n\n }\n"
},
{
"answer_id": 30089582,
"author": "Carlos A. Ortiz",
"author_id": 4872590,
"author_profile": "https://Stackoverflow.com/users/4872590",
"pm_score": 3,
"selected": false,
"text": "Dictionary<string, string> months = new Dictionary<string, string>()\n{\n { \"january\", \"01\"},\n { \"february\", \"02\"},\n { \"march\", \"03\"},\n { \"april\", \"04\"},\n { \"may\", \"05\"},\n { \"june\", \"06\"},\n { \"july\", \"07\"},\n { \"august\", \"08\"},\n { \"september\", \"09\"},\n { \"october\", \"10\"},\n { \"november\", \"11\"},\n { \"december\", \"12\"},\n};\nforeach (var month in months)\n{\n if (StringThatContainsMonth.ToLower().Contains(month.Key))\n {\n string thisMonth = month.Value;\n }\n}\n"
},
{
"answer_id": 30770498,
"author": "David Clarke",
"author_id": 132599,
"author_profile": "https://Stackoverflow.com/users/132599",
"pm_score": 2,
"selected": false,
"text": "Month.toInt(\"January\") > Month.toInt(\"May\")\n Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,\n t => t.Equals(\"January\", StringComparison.CurrentCultureIgnoreCase)) >\nArray.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,\n t => t.Equals(\"May\", StringComparison.CurrentCultureIgnoreCase))\n Dump() void Main()\n{\n (\"January\".GetMonthIndex() > \"May\".GetMonthIndex()).Dump();\n (\"January\".GetMonthIndex() == \"january\".GetMonthIndex()).Dump();\n (\"January\".GetMonthIndex() < \"May\".GetMonthIndex()).Dump();\n}\n\npublic static class Extension {\n public static int GetMonthIndex(this string month) {\n return Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,\n t => t.Equals(month, StringComparison.CurrentCultureIgnoreCase));\n }\n}\n False\nTrue\nTrue\n"
},
{
"answer_id": 58725406,
"author": "Nitika Chopra",
"author_id": 7534013,
"author_profile": "https://Stackoverflow.com/users/7534013",
"pm_score": 0,
"selected": false,
"text": "using System.Globalization;\n\n....\n\nstring FullMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.UtcNow.Month);\n DateTime dt= DateTime.UtcNow;\nint month= dt.Month;\n"
},
{
"answer_id": 67821590,
"author": "user15276771",
"author_id": 15276771,
"author_profile": "https://Stackoverflow.com/users/15276771",
"pm_score": 0,
"selected": false,
"text": "int selectedValue = 0;\n switch (curentMonth)\n {\n case \"January\":\n selectedValue = 1;\n break;\n case \"February\":\n selectedValue = 2;\n break;\n }\n if (selectedValue != 0)\n {\n /* var list= db.model_name.Where(x => x.column== selectedValue);\n return list; */\n }\n return Ok(selectedValue);\n"
},
{
"answer_id": 74273272,
"author": "RARE Kpop Manifesto",
"author_id": 14672114,
"author_profile": "https://Stackoverflow.com/users/14672114",
"pm_score": 0,
"selected": false,
"text": "awk C/C++/C# awk \"1-based\" \"0-based\" \"=\" \"=\" function __(_) { # input - Eng. month names, any casing, min. 3 letters\n # output - MM : [01-12], zero-padded\n return \\\n ((_=toupper(_)) ~ \"^[OND]\" ? \"\" : _<_) \\\n (index(\"=ANEBARPRAYUNULUGEPCTOVEC\", substr(_ \"\",_+=_^=_<_,_))/_)\n}\n the 2nd + 3rd letters of month names constitute a unique set awk \"0th-power\" string \"Boston\" ^ 0 \n numeric 1"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21367/"
] |
258,807
|
<p>I've got 2 remote databases as part of a query </p>
<pre><code>select p.ID,p.ProjectCode_VC,p.Name_VC,v.*
FROM [serverB].Projects.dbo.Projects_T p
LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on
p.ProjectCode_VC = v.PROJ_CODE
</code></pre>
<p>The problem is that serverA uses collation <code>Latin1_General_BIN</code> and serverB uses <code>Latin1_General_CP1_CP_AS</code> and the query refuses to run. </p>
<p>Both servers are SQL 2000 servers. Both databases are set in stone so I cannot change their collations, unfortunately. </p>
<p>Is there anyway you guys know how to get this to work?</p>
<p><strong>Update:</strong> I found an alternative solution. In the Linked Server Properties, you can specify the linked server's collation there.</p>
|
[
{
"answer_id": 258855,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 4,
"selected": true,
"text": "select \n p.ID,\n p.ProjectCode_VC,\n p.Name_VC,\n v.* \nFROM\n [serverB].Projects.dbo.Projects_T p \n LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on p.ProjectCode_VC \n collate Latin1_General_Bin = v.PROJ_CODE\n"
},
{
"answer_id": 8045282,
"author": "djoko soewarno",
"author_id": 1034834,
"author_profile": "https://Stackoverflow.com/users/1034834",
"pm_score": 2,
"selected": false,
"text": "select * from profile, userinfo\nwhere profile.custid collate database_default = userinfo.custid collate database_default\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2995/"
] |
258,812
|
<p>I've created a Silverlight project that produces [something].xap file to package a few silverlight UserControls. I would like to manipulate that .xap file through the use of javascript in the browser to show and hide user controls based upon java script events.</p>
<p>Is it possible to do this?</p>
<p>If so any sample could or links to documentation would be appreciated.</p>
<p>Thanks in advance</p>
<p>Kevin</p>
|
[
{
"answer_id": 259144,
"author": "Kevin",
"author_id": 2723,
"author_profile": "https://Stackoverflow.com/users/2723",
"pm_score": 1,
"selected": false,
"text": " private Page _page = null;\n private void Application_Startup(object sender, StartupEventArgs e)\n {\n _page = new Page();\n this.RootVisual = _page;\n\n HtmlPage.RegisterScriptableObject(\"App\", this);\n }\n [ScriptableMember]\n public void ShowTeamSearch(Guid ctxId, Guid teamId)\n {\n _page.ShowTeamSearcher(ctxId, teamId);\n }\n Login oLogin;\n TeamSearcher oSearcher;\n\n public Page()\n {\n InitializeComponent();\n oLogin = new Login();\n oSearcher = new TeamSearcher();\n\n oLogin.Visibility = Visibility;\n this.LayoutRoot.Children.Add(oLogin);\n }\n public void ShowTeamSearcher(Guid ctxId, Guid teamId)\n {\n oSearcher.UserTeamId = teamId;\n oSearcher.UserContextId = ctxId;\n\n LayoutRoot.Children.Remove(oLogin);\n LayoutRoot.Children.Add(oSearcher);\n }\n var slControl = document.getElementById('oXaml');\n slControl.Content.App.ShowTeamSearch(sessionId, teamId); \n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723/"
] |
258,824
|
<p>I have a window which overrides a <code>RadioButton</code>'s <code>ControlTemplate</code> to show a custom control inside of it. Inside the custom control, I have a button's visibility tied to <code>IsMouseOver</code>, which works correctly in showing the button only when the mouse is hovering over the control. However, when I click on the <code>RadioButton</code>, the <code>Button</code> disappears. After some debugging and reading, it seems that the <code>RadioButton</code> is capturing the mouse on click, and this makes <code>IsMouseOver</code> for the <code>UserControl</code> false.</p>
<p>I tried binding the <code>Button</code>'s visibility to <code>FindAncestor {x:Type RadioButton}</code> and it works, but it seems a bit fragile to me to have the <code>UserControl</code> depend on who is containing it. The code for the window and the user control is below. Any suggestions?</p>
<pre><code><Window x:Name="window" x:Class="WPFTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WPFTest="clr-namespace:WPFTest"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style TargetType="{x:Type RadioButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RadioButton}">
<WPFTest:TestUC />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Border BorderBrush="Black" BorderThickness="2">
<StackPanel>
<RadioButton x:Name="OptionButton" Height="100" />
<TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}" />
</StackPanel>
</Border>
</Window>
<UserControl x:Name="_this" x:Class="WPFTest.TestUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</UserControl.Resources>
<StackPanel>
<TextBlock Text="SomeText" />
<TextBlock Text="{Binding ElementName=_this, Path=IsMouseOver}" />
<Button x:Name="_cancelTextBlock" Content="Cancel" Visibility="{Binding ElementName=_this, Path=IsMouseOver, Converter={StaticResource BooleanToVisibilityConverter}}" />
</StackPanel>
</UserControl>
</code></pre>
|
[
{
"answer_id": 258935,
"author": "DavidN",
"author_id": 33662,
"author_profile": "https://Stackoverflow.com/users/33662",
"pm_score": 2,
"selected": true,
"text": "<ControlTemplate TargetType=\"{x:Type RadioButton}\">\n <WPFTest:TestUC x:Name=\"UC\" />\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsMouseOver\" Value=\"True\">\n <Setter Property=\"ShowCancel\" Value=\"True\" TargetName=\"UC\"/>\n </Trigger>\n </ControlTemplate.Triggers>\n</ControlTemplate>\n"
},
{
"answer_id": 259178,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 0,
"selected": false,
"text": "<Window\n x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:WpfApplication1\"\n Title=\"Window1\"\n Width=\"300\"\n Height=\"300\"\n>\n <Window.Resources>\n <Style TargetType=\"{x:Type Control}\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type Control}\">\n <local:UserControl1/>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n </Window.Resources>\n\n <Border BorderBrush=\"Black\" BorderThickness=\"2\">\n <StackPanel>\n <Control x:Name=\"OptionButton\" Height=\"100\"/>\n <TextBlock Text=\"{Binding ElementName=OptionButton, Path=IsMouseOver}\"/>\n </StackPanel>\n </Border>\n</Window>\n <Window\n x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:WpfApplication1\"\n Title=\"Window1\"\n Width=\"300\"\n Height=\"300\"\n>\n <Border BorderBrush=\"Black\" BorderThickness=\"2\">\n <StackPanel>\n <local:UserControl1 x:Name=\"OptionButton\" Height=\"100\"/>\n <TextBlock Text=\"{Binding ElementName=OptionButton, Path=IsMouseOver}\"/>\n </StackPanel>\n </Border>\n</Window>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33662/"
] |
258,857
|
<p>In C#, how do I set the Identity of a Thread?</p>
<p>For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?</p>
<p>Or is this not possible?</p>
|
[
{
"answer_id": 258884,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 2,
"selected": false,
"text": "using (new Impersonation())\n{\n // your elevated code\n}\n [PermissionSet(SecurityAction.Demand, Name = \"FullTrust\")]\npublic class Impersonation : IDisposable\n{\n private readonly SafeTokenHandle _handle;\n private readonly WindowsImpersonationContext _context;\n\n //const int Logon32LogonNewCredentials = 9; \n private const int Logon32LogonInteractive = 2;\n\n public Impersonation()\n {\n var settings = Settings.Instance.Whatever;\n var domain = settings.Domain;\n var username = settings.User;\n var password = settings.Password;\n var ok = LogonUser(username, domain, password, Logon32LogonInteractive, 0, out _handle);\n if (!ok)\n {\n var errorCode = Marshal.GetLastWin32Error();\n throw new ApplicationException(string.Format(\"Could not impersonate the elevated user. LogonUser returned error code {0}.\", errorCode));\n }\n _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());\n }\n\n public void Dispose()\n {\n _context.Dispose();\n _handle.Dispose();\n }\n\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Unicode)]\n private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);\n\n public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid\n {\n private SafeTokenHandle()\n : base(true)\n { }\n\n [DllImport(\"kernel32.dll\")]\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]\n [SuppressUnmanagedCodeSecurity]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CloseHandle(IntPtr handle);\n\n protected override bool ReleaseHandle()\n {\n return CloseHandle(handle);\n }\n }\n}\n"
},
{
"answer_id": 259167,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 6,
"selected": true,
"text": " using System.Security.Principal;\n\n // ...\n GenericIdentity identity = new GenericIdentity(\"M.Brown\");\n identity.IsAuthenticated = true;\n\n // ...\n System.Threading.Thread.CurrentPrincipal =\n new GenericPrincipal(\n identity,\n new string[] { \"Role1\", \"Role2\" }\n );\n\n //...\n if (!System.Threading.Thread.CurrentPrincipal.IsInRole(\"Role1\"))\n {\n Console.WriteLine(\"Permission denied\");\n return;\n }\n"
},
{
"answer_id": 32156975,
"author": "Hakan Fıstık",
"author_id": 4390133,
"author_profile": "https://Stackoverflow.com/users/4390133",
"pm_score": 2,
"selected": false,
"text": ".NET 4.5 IsAuthenticated GenericIdentity identity = new GenericIdentity(\"someuser\", \"Forms\");\nThread.CurrentPrincipal = new GenericPrincipal(identity, new string[] { \"somerole\" });\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] |
258,858
|
<p>I'm dynamically generating an asp form, and I would like to add the <strong>label</strong> and <strong>input</strong> elements inside a list.</p>
<p>For example, I would like to end up with something like:</p>
<pre><code><ul>
<li><label for="input"/><input id=input"/></li>
</ul>
</code></pre>
<p>To do this, I create a Label object and a TextBox object, then assign the AssociatedControlId property of the Label to link these. But I cannot add any of these in a ListItem, nor can I add these in the Controls collection of BulletedList...</p>
<p>Any ideas would be greatly apreciated.</p>
|
[
{
"answer_id": 259043,
"author": "Michael DeLorenzo",
"author_id": 1383003,
"author_profile": "https://Stackoverflow.com/users/1383003",
"pm_score": 0,
"selected": false,
"text": "<asp:Repeater ID=\"rpt\" runat=\"server\">\n <HeaderTemplate>\n <ul>\n </HeaderTemplate>\n <ItemTemplate>\n <li>\n <label for='<%# string.Format(\"ctrl-{0}\", Container.ItemIndex) %>'>label for ctrl #<%# Container.ItemIndex %></label>\n <input id='<%# string.Format(\"ctrl-{0}\", Container.ItemIndex) %>' type=\"text\" /> \n </li>\n </ItemTemplate>\n <FooterTemplate>\n </ul>\n </FooterTemplate>\n</asp:Repeater>\n"
},
{
"answer_id": 261020,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 3,
"selected": true,
"text": "<asp:PlaceHolder ID=\"PlaceHolder1\" runat=\"server\" />\n HtmlGenericControl list = new HtmlGenericControl(\"ul\");\nfor (int i = 0; i < 10; i++)\n{\n HtmlGenericControl listItem = new HtmlGenericControl(\"li\");\n Label textLabel = new Label();\n textLabel.Text = String.Format(\"Label {0}\", i);\n listItem.Controls.Add(textLabel);\n // etc...\n list.Controls.Add(listItem);\n}\nPlaceHolder1.Controls.Add(list);\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/920/"
] |
258,864
|
<p>When an <code>Expression<T></code> is compiled, is the resultant code implicitly cached by the framework? I'm thinking along the lines of the static <code>Regex</code> methods where the framework implicitly compiles and caches the last few regexes.</p>
<p>If compiled <code>Expression<T></code> objects are <b>not</b> cached, can you recommend some best practices for keeping the compile-time down or any gotchas that could cause problems if I manually cache an expression?</p>
<pre><code>public MyResultType DoSomething(int arg1, int arg2)
{
var result = invokeHandler(
(IDoSomethingHandler h) => h.DoSomething(arg1, arg2)
);
return result;
}
private TResult invokeHandler<T, TResult>(Expression<Func<T, TResult>> action)
where T : class
{
// Here, I might want to check to see if action is already cached.
var compiledAction = action.Compile();
var methodCallExpr = action as MethodCallExpression;
// Here, I might want to store methodCallExpr in a cache somewhere.
var handler = ServiceLocator.Current.GetInstance<T>();
var result = compiledAction(handler);
return result;
}
</code></pre>
<p>In this example, I'm slightly concerned that if I cache the compiled expression, that it will use the values of <code>arg1</code> and <code>arg2</code> as they were at the time the expression was compiled, rather than retrieving those values from the appropriate place in the stack (i.e. rather than getting the current values).</p>
|
[
{
"answer_id": 258907,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "Delegate Func<...> Action<...> public MyResultType DoSomething(int arg1, int arg2)\n{\n var result = invokeHandler(\n (IDoSomethingHandler h, int a1, int a2) => h.DoSomething(a1, a2),\n arg1, arg2);\n return result;\n}\n\nprivate TResult invokeHandler<T, TResult>(Expression<Func<T,int,int,TResult>> action,\n int arg1, int arg2)\n where T : class\n{\n // Here, I might want to check to see if action is already cached.\n\n var compiledAction = action.Compile();\n var methodCallExpr = action as MethodCallExpression;\n\n // Here, I might want to store methodCallExpr in a cache somewhere.\n\n var handler = ServiceLocator.Current.GetInstance<T>();\n var result = compiledAction(handler, arg1, arg2);\n\n return result;\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30321/"
] |
258,871
|
<p>I want to find in a vector of Object pointers for a matching object. Here's a sample code to illustrate my problem:</p>
<pre><code>class A {
public:
A(string a):_a(a) {}
bool operator==(const A& p) {
return p._a == _a;
}
private:
string _a;
};
vector<A*> va;
va.push_back(new A("one"));
va.push_back(new A("two"));
va.push_back(new A("three"));
find(va.begin(), va.end(), new A("two"));
</code></pre>
<p>I want to find the second item pushed into the vector. But since vector is defined as a pointers collection, C++ does not use my overloaded operator, but uses implicit pointer comparison. What is the preferred C++-way of solutiono in this situation?</p>
|
[
{
"answer_id": 258913,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 5,
"selected": true,
"text": "template <typename T>\nstruct pointer_values_equal\n{\n const T* to_find;\n\n bool operator()(const T* other) const\n {\n return *to_find == *other;\n }\n};\n\n\n// usage:\nvoid test(const vector<A*>& va)\n{\n A* to_find = new A(\"two\");\n pointer_values_equal<A> eq = { to_find };\n find_if(va.begin(), va.end(), eq);\n // don't forget to delete A!\n}\n"
},
{
"answer_id": 261714,
"author": "MattyT",
"author_id": 7405,
"author_profile": "https://Stackoverflow.com/users/7405",
"pm_score": 1,
"selected": false,
"text": "using namespace boost::lambda;\nfind_if(va.begin(), va.end(), *_1 == A(\"two\"));\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28161/"
] |
258,875
|
<p>I was looking into using some .NET code from within a Delphi program, I will need to make my program extensible using .net assemblies and predefined functions (I already support regular DLLs).</p>
<p>After a lot of searching online, I found <a href="http://www.managed-vcl.com/" rel="noreferrer">Managed-VCL</a>, but I'm not ready to pay $250 for what I need, I also found some newsgroups with code that's incomplete and doesn't work.</p>
<p>I'm using Delphi 2007 for win32. What can I use to dynamically execute a function from an assembly with predefined parameters?</p>
<p>Something like:</p>
<pre><code>procedure ExecAssembly(AssemblyFileName:String; Parameters: Variant);
</code></pre>
<p>I just want to add that I need to be able to load an arbitrary assemblies (maybe all the assemblies in a specific folder), so creating a C# wrapper may not work.</p>
|
[
{
"answer_id": 301263,
"author": "Stefan Schultze",
"author_id": 6358,
"author_profile": "https://Stackoverflow.com/users/6358",
"pm_score": 4,
"selected": true,
"text": " TJclClrHost = class(TJclClrBase, ICorRuntimeHost)\n private\n FDefaultInterface: ICorRuntimeHost;\n FAppDomains: TObjectList;\n procedure EnumAppDomains;\n function GetAppDomain(const Idx: Integer): TJclClrAppDomain;\n function GetAppDomainCount: Integer;\n function GetDefaultAppDomain: IJclClrAppDomain;\n function GetCurrentAppDomain: IJclClrAppDomain;\n protected\n function AddAppDomain(const AppDomain: TJclClrAppDomain): Integer;\n function RemoveAppDomain(const AppDomain: TJclClrAppDomain): Integer; \n public\n constructor Create(const ClrVer: WideString = '';\n const Flavor: TJclClrHostFlavor = hfWorkStation;\n const ConcurrentGC: Boolean = True;\n const LoaderFlags: TJclClrHostLoaderFlags = [hlOptSingleDomain]);\n destructor Destroy; override;\n procedure Start;\n procedure Stop;\n procedure Refresh;\n function CreateDomainSetup: TJclClrAppDomainSetup;\n function CreateAppDomain(const Name: WideString;\n const Setup: TJclClrAppDomainSetup = nil;\n const Evidence: IJclClrEvidence = nil): TJclClrAppDomain;\n function FindAppDomain(const Intf: IJclClrAppDomain; var Ret: TJclClrAppDomain): Boolean; overload;\n function FindAppDomain(const Name: WideString; var Ret: TJclClrAppDomain): Boolean; overload;\n class function CorSystemDirectory: WideString;\n class function CorVersion: WideString;\n class function CorRequiredVersion: WideString;\n class procedure GetClrVersions(VersionNames: TWideStrings); overload;\n class procedure GetClrVersions(VersionNames: TStrings); overload;\n property DefaultInterface: ICorRuntimeHost read FDefaultInterface implements ICorRuntimeHost;\n property AppDomains[const Idx: Integer]: TJclClrAppDomain read GetAppDomain; default;\n property AppDomainCount: Integer read GetAppDomainCount;\n property DefaultAppDomain: IJclClrAppDomain read GetDefaultAppDomain;\n property CurrentAppDomain: IJclClrAppDomain read GetCurrentAppDomain;\n end;\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25544/"
] |
258,877
|
<p>I am trying to render a user control into a string. The application is set up to enable user to use tokens and user controls are rendered where the tokens are found.</p>
<pre><code>StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);
Control uc = LoadControl("~/includes/HomepageNews.ascx");
uc.RenderControl(writer);
return sb.ToString();
</code></pre>
<p><strong>That code renders the control but none of the events called in the Page_Load of the control are firing. There's a Repeater in the control needs to fire.</strong></p>
|
[
{
"answer_id": 259791,
"author": "Hauge",
"author_id": 17368,
"author_profile": "https://Stackoverflow.com/users/17368",
"pm_score": 5,
"selected": true,
"text": "public class ViewManager\n{\n public static string RenderView(string path, object data)\n {\n Page pageHolder = new Page();\n UserControl viewControl = (UserControl) pageHolder.LoadControl(path);\n\n if (data != null)\n {\n Type viewControlType = viewControl.GetType();\n FieldInfo field = viewControlType.GetField(\"Data\");\n if (field != null)\n {\n field.SetValue(viewControl, data);\n }\n else\n {\n throw new Exception(\"ViewFile: \" + path + \"has no data property\");\n }\n }\n\n pageHolder.Controls.Add(viewControl);\n StringWriter result = new StringWriter();\n HttpContext.Current.Server.Execute(pageHolder, result, false);\n return result.ToString();\n }\n}\n object data"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12252/"
] |
258,883
|
<p>I've got an unusual situation: I'm using a Linux system in an embedded situation (Intel box, currently using a 2.6.20 kernel.) which has to communicate with an embedded system that has a partially broken TCP implementation. As near as I can tell right now they expect each message from us to come in a separate Ethernet frame! They seem to have problems when messages are split across Ethernet frames. </p>
<p>We are on the local network with the device, and there are no routers between us (just a switch).</p>
<p>We are, of course, trying to force them to fix their system, but that may not end up being feasible.</p>
<p>I've already set TCP_NODELAY on my sockets (I connect to them), but that only helps if I don't try to send more than one message at a time. If I have several outgoing messages in a row, those messages tend to end up in one or two Ethernet frames, which causes trouble on the other system.</p>
<p>I can generally avoid the problem by using a timer to avoid sending messages too close together, but that obviously limits our throughput. Further, if I turn the time down too low, I risk network congestion holding up packet transmits and ending up allowing more than one of my messages into the same packet.</p>
<p>Is there any way that I can tell whether the driver has data queued or not? Is there some way I can force the driver to send independent write calls in independent transport layer packets? I've had a look through the socket(7) and tcp(7) man pages and I didn't find anything. It may just be that I don't know what I'm looking for. </p>
<p>Obviously, UDP would be one way out, but again, I don't think we can make the other end change anything much at this point.</p>
<p>Any help greatly appreciated.</p>
|
[
{
"answer_id": 259527,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": -1,
"selected": false,
"text": "echo 1 > /proc/sys/net/ipv4/tcp_low_latency\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5801/"
] |
258,908
|
<p>I'm trying to find a way to determine how many parameters a constructor has.</p>
<p>Now I've built one constructor with no parameters and 1 constructor with 4 parameters.</p>
<p>Is there, in C#, a way to find out how many parameters a used or given constructor has?</p>
<p>Thing is, I'm using a third constructor to read log files. These logs files are read as string[] elements and there should be just as many as there are arguments. If not, I have a corrupt log file.</p>
<p>But I'm using a lot of subclasses and each constructor has more parameters for their specific log-type.</p>
<p>So I wanted to know: is there a method to check the amount of parameters on a constructor?</p>
<p>And yes, this is a school assignment. I don't know what terms to look for really, so the VS2008 object browser is currently not of much use.</p>
|
[
{
"answer_id": 258921,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": true,
"text": " System.Type.GetType(\"MYClassName\").GetConstructors()\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
258,917
|
<p>I have a problem applying the <code>DebuggerDisplay</code> attribute on a generic class:</p>
<pre><code>[DebuggerDisplay("--foo--")]
class Foo
{
}
[DebuggerDisplay("Bar: {t}")]
class Bar<T>
{
public T t;
}
</code></pre>
<p>When inspecting an object of type <code>Bar<Foo></code> I would expect it to show as <code>Bar: --foo--</code>, but I get <code>Bar: {Foo}</code></p>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 32602031,
"author": "Ofir",
"author_id": 595859,
"author_profile": "https://Stackoverflow.com/users/595859",
"pm_score": 3,
"selected": false,
"text": "[DebuggerDisplay(\"Bar<{typeof(T).Name,nq}>\")]//nq - no quotes"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31890/"
] |
258,954
|
<p>Java is nearing version 7. It occurs to me that there must be plenty of textbooks and training manuals kicking around that teach methods based on older versions of Java, where the methods taught, would have far better solutions now.</p>
<p>What are some boilerplate code situations, especially ones that you see people implement through force of habit, that you find yourself refactoring to utilize the latest versions of Java?</p>
|
[
{
"answer_id": 258956,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 5,
"selected": false,
"text": "List l = someList;\nIterator i = l.getIterator();\nwhile (i.hasNext()) {\n MyObject o = (MyObject)i.next();\n}\n List<MyObject> l = someList;\nfor (MyObject o : l) {\n //do something\n}\n"
},
{
"answer_id": 258984,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 3,
"selected": false,
"text": "String s = n + \"\";\n String s = String.valueOf(n);\n"
},
{
"answer_id": 259013,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 4,
"selected": false,
"text": "myframe.getContentPane().add(mycomponent);\n myframe.add(mycomponent);\n"
},
{
"answer_id": 259053,
"author": "Eek",
"author_id": 18752,
"author_profile": "https://Stackoverflow.com/users/18752",
"pm_score": 7,
"selected": true,
"text": "public static final int CLUBS = 0;\npublic static final int DIAMONDS = 1;\npublic static final int HEARTS = 2;\npublic static final int SPADES = 3;\n public enum Suit { \n CLUBS, \n DIAMONDS, \n HEARTS, \n SPADES \n}\n"
},
{
"answer_id": 259084,
"author": "Julien Chastang",
"author_id": 32174,
"author_profile": "https://Stackoverflow.com/users/32174",
"pm_score": 5,
"selected": false,
"text": "String.split() StringTokenizer StringTokenizer"
},
{
"answer_id": 259186,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 5,
"selected": false,
"text": "StringBuffer StringBuilder"
},
{
"answer_id": 259215,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 4,
"selected": false,
"text": "Integer myInteger = 6;\nint myInt = myInteger.intValue();\n Integer myInteger = 6;\nint myInt = myInteger;\n"
},
{
"answer_id": 259441,
"author": "Ogre Psalm33",
"author_id": 13140,
"author_profile": "https://Stackoverflow.com/users/13140",
"pm_score": 4,
"selected": false,
"text": "Vector stringVector = new Vector();\nstringVector.add(\"hi\");\nstringVector.add(528); // oops!\nstringVector.add(new Whatzit()); // Oh my, could spell trouble later on!\n ArrayList<String> stringList = new ArrayList<String>();\nstringList.add(\"hello again\");\nstringList.add(new Whatzit()); // Won't compile!\n"
},
{
"answer_id": 260490,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "List list = getTheList();\nIterator iter = list.iterator()\nwhile (iter.hasNext()) {\n String s = (String) iter.next();\n // .. do something\n}\n List list = getTheList();\nfor (Iterator iter = list.iterator(); iter.hasNext();) {\n String s = (String) iter.next();\n // .. do something\n}\n List<String> list = getTheList();\nfor (String s : list) {\n // .. do something\n}\n"
},
{
"answer_id": 260497,
"author": "Jack Leow",
"author_id": 31506,
"author_profile": "https://Stackoverflow.com/users/31506",
"pm_score": 1,
"selected": false,
"text": "String s1 = \"...\", s2 = \"...\";\n\nif (s1.intern() == s2.intern()) {\n ....\n}\n String s1 = \"...\", s2 = \"...\";\n\nif (s1.equals(s2)) {\n ....\n}\n"
},
{
"answer_id": 261297,
"author": "dogbane",
"author_id": 7412,
"author_profile": "https://Stackoverflow.com/users/7412",
"pm_score": 4,
"selected": false,
"text": "public int add(int... numbers){\n int sum = 0 ;\n for (int i : numbers){\n sum+=i;\n }\n return sum ;\n}\n public int add(int n1, int n2, int n3, int n4) ;\n public int add(List<Integer> numbers) ;\n"
},
{
"answer_id": 617418,
"author": "TofuBeer",
"author_id": 65868,
"author_profile": "https://Stackoverflow.com/users/65868",
"pm_score": 1,
"selected": false,
"text": " public class Enum\n {\n public static final Enum FOO = new Enum();\n public static final Enum BAR = new Enum();\n }\n"
},
{
"answer_id": 622385,
"author": "Kjetil Ødegaard",
"author_id": 74185,
"author_profile": "https://Stackoverflow.com/users/74185",
"pm_score": 3,
"selected": false,
"text": "class Test extends TestCase {\n public void testYadaYada() { ... }\n}\n class Test {\n @Test public void yadaYada() { ... }\n}\n"
},
{
"answer_id": 623007,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "import static Math.* ;\n"
},
{
"answer_id": 623053,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 3,
"selected": false,
"text": "for for // AGGHHH!!!\nint[] array = new int[] {0, 1, 2, 3, 4};\nfor (int i = 0; i < array.length; i++)\n{\n // Do something...\n}\n for // Nice and clean. \nint[] array = new int[] {0, 1, 2, 3, 4};\nfor (int n : array)\n{\n // Do something...\n}\n for"
},
{
"answer_id": 626185,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 4,
"selected": false,
"text": "String str = \"test \" + intValue + \" test \" + doubleValue;\n String str = String.format(\"test %d test %lg\", intValue, doubleValue);\n"
},
{
"answer_id": 635078,
"author": "Jonik",
"author_id": 56285,
"author_profile": "https://Stackoverflow.com/users/56285",
"pm_score": 3,
"selected": false,
"text": "List<String> items = new ArrayList<String>();\nitems.add(\"one\");\nitems.add(\"two\");\nitems.add(\"three\");\nhandleItems(items);\n handleItems(Arrays.asList(\"one\", \"two\", \"three\"));\n"
},
{
"answer_id": 930073,
"author": "cd1",
"author_id": 38333,
"author_profile": "https://Stackoverflow.com/users/38333",
"pm_score": 5,
"selected": false,
"text": "try {\n BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));\n String str = reader.readLine();\n reader.close();\n}\ncatch (IOException e) {\n System.err.println(\"error when closing input stream.\");\n}\n Scanner reader = new Scanner(System.in);\nString str = reader.nextLine();\nreader.close();\n Console reader = System.console();\nString str = reader.readLine();\n"
},
{
"answer_id": 930087,
"author": "Nash",
"author_id": 113914,
"author_profile": "https://Stackoverflow.com/users/113914",
"pm_score": 2,
"selected": false,
"text": "DefaultRowSorter"
},
{
"answer_id": 992375,
"author": "cd1",
"author_id": 38333,
"author_profile": "https://Stackoverflow.com/users/38333",
"pm_score": 3,
"selected": false,
"text": "int[] src = new int[] {1, 2, 3, 4, 5};\nint[] dest = new int[src.length];\nSystem.arraycopy(src, 0, dest, 0, src.length);\n int[] src = new int[] {1, 2, 3, 4, 5};\nint[] dest = Arrays.copyOf(src, src.length);\n"
},
{
"answer_id": 1441504,
"author": "Pops",
"author_id": 122607,
"author_profile": "https://Stackoverflow.com/users/122607",
"pm_score": 2,
"selected": false,
"text": "public enum Singleton {\n INSTANCE;\n\n public void someMethod() {\n ...\n }\n}\n public class Singleton {\n public static final Singleton INSTANCE = new Singleton();\n\n private Singleton() {\n ...\n }\n\n public void someMethod() {\n ...\n }\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
258,960
|
<p>Is there a way for me to serialize an object in .NET without the XML Namespaces automatically serializing also? It seems that by default .NET believes the XSI and XSD namespaces should be included, but I don't want them there.</p>
|
[
{
"answer_id": 258974,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 8,
"selected": true,
"text": "obj Dim xs As New XmlSerializer(GetType(cEmploymentDetail))\nDim ns As New XmlSerializerNamespaces()\nns.Add(\"\", \"\")\n\nDim settings As New XmlWriterSettings()\nsettings.OmitXmlDeclaration = True\n\nUsing ms As New MemoryStream(), _\n sw As XmlWriter = XmlWriter.Create(ms, settings), _\n sr As New StreamReader(ms)\n xs.Serialize(sw, obj, ns)\n ms.Position = 0\n Console.WriteLine(sr.ReadToEnd())\nEnd Using\n //Create our own namespaces for the output\nXmlSerializerNamespaces ns = new XmlSerializerNamespaces();\n\n//Add an empty namespace and empty value\nns.Add(\"\", \"\");\n\n//Create the serializer\nXmlSerializer slz = new XmlSerializer(someType);\n\n//Serialize the object with our own namespaces (notice the overload)\nslz.Serialize(myXmlTextWriter, someObject, ns);\n"
},
{
"answer_id": 2249034,
"author": "Ali B",
"author_id": 271447,
"author_profile": "https://Stackoverflow.com/users/271447",
"pm_score": 4,
"selected": false,
"text": "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://schemas.YourCompany.com/YourSchema/\" // Add lib namespace with empty prefix \nns.Add(\"\", \"http://schemas.YourCompany.com/YourSchema/\"); \n"
},
{
"answer_id": 24705961,
"author": "vinjenzo",
"author_id": 735725,
"author_profile": "https://Stackoverflow.com/users/735725",
"pm_score": 3,
"selected": false,
"text": "<manyElementWith xmlns=\"urn:names:specification:schema:xsd:one\" />\n Dim xmlns = New XmlSerializerNamespaces()\nxmlns.Add(\"one\", \"urn:names:specification:schema:xsd:one\")\nxmlns.Add(\"two\", \"urn:names:specification:schema:xsd:two\")\nxmlns.Add(\"three\", \"urn:names:specification:schema:xsd:three\")\n serializer.Serialize(writer, object, xmlns);\n <root xmlns:one=\"urn:names:specification:schema:xsd:one\" ... />\n <one:Element />\n <two:ElementFromAnotherNameSpace /> ...\n"
},
{
"answer_id": 28606746,
"author": "Maziar Taheri",
"author_id": 753645,
"author_profile": "https://Stackoverflow.com/users/753645",
"pm_score": 3,
"selected": false,
"text": "public static class Xml\n{\n #region Fields\n\n private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};\n private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName(\"\", \"\")});\n\n #endregion\n\n #region Methods\n\n public static string Serialize(object obj)\n {\n if (obj == null)\n {\n return null;\n }\n\n return DoSerialize(obj);\n }\n\n private static string DoSerialize(object obj)\n {\n using (var ms = new MemoryStream())\n using (var writer = XmlWriter.Create(ms, WriterSettings))\n {\n var serializer = new XmlSerializer(obj.GetType());\n serializer.Serialize(writer, obj, Namespaces);\n return Encoding.UTF8.GetString(ms.ToArray());\n }\n }\n\n public static T Deserialize<T>(string data)\n where T : class\n {\n if (string.IsNullOrEmpty(data))\n {\n return null;\n }\n\n return DoDeserialize<T>(data);\n }\n\n private static T DoDeserialize<T>(string data) where T : class\n {\n using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))\n {\n var serializer = new XmlSerializer(typeof (T));\n return (T) serializer.Deserialize(ms);\n }\n }\n\n #endregion\n}\n"
},
{
"answer_id": 39737083,
"author": "D34th",
"author_id": 6398327,
"author_profile": "https://Stackoverflow.com/users/6398327",
"pm_score": 4,
"selected": false,
"text": " public static string XmlSerialize<T>(T entity) where T : class\n {\n // removes version\n XmlWriterSettings settings = new XmlWriterSettings();\n settings.OmitXmlDeclaration = true;\n\n XmlSerializer xsSubmit = new XmlSerializer(typeof(T));\n using (StringWriter sw = new StringWriter())\n using (XmlWriter writer = XmlWriter.Create(sw, settings))\n {\n // removes namespace\n var xmlns = new XmlSerializerNamespaces();\n xmlns.Add(string.Empty, string.Empty);\n\n xsSubmit.Serialize(writer, entity, xmlns);\n return sw.ToString(); // Your XML\n }\n }\n"
},
{
"answer_id": 58979104,
"author": "Taurus999able",
"author_id": 11739338,
"author_profile": "https://Stackoverflow.com/users/11739338",
"pm_score": 0,
"selected": false,
"text": " XmlWriterSettings settings = new XmlWriterSettings\n {\n OmitXmlDeclaration = true\n };\n\n XmlSerializerNamespaces ns = new XmlSerializerNamespaces();\n ns.Add(\"\", \"\");\n\n StringBuilder sb = new StringBuilder();\n\n XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));\n\n using (XmlWriter xw = XmlWriter.Create(sb, settings))\n {\n xs.Serialize(xw, model, ns);\n xw.Flush();\n return sb.ToString();\n }\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
258,968
|
<p>Just wondering what the difference between MFC control messages prefixed with the following is:</p>
<pre><code>LVN (e.g. LVN_ITEMCHANGED)
HDN (e.g. HDN_TRACK)
NM (e.g. NM_HOVER)
</code></pre>
<p>Also, I am using a ListControl and trapping when the user clicks on an item using the NM_CLICK message. I also want to trap when a user selects a new item view a key e.g. up/down arrow keys. Can anyone tell me which message I should be trapping for this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 259057,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 3,
"selected": true,
"text": "NMLISTVIEW & nm = *(NMLISTVIEW *) pnmh;\nif ( (nm.uNewState ^ nm.uOldState) & LVIS_SELECTED) \n{ \n // nm.iItem was selected or deselected\n if (!m_internalUIChange)\n {\n // see below\n }\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
258,988
|
<p>I'm <a href="http://channel9.msdn.com/shows/Going+Deep/Inside-C-40-dynamic-type-optional-parameters-more-COM-friendly/" rel="noreferrer">listening to a talk</a> about <strong>C#4</strong>'s <code>dynamic</code> keyword and I'm wondering... Will this feature be orthogonal to other .NET features, for example will it support extension methods?</p>
<pre><code>public static class StrExtension {
public static string twice(this string str) { return str + str; }
}
...
dynamic x = "Yo";
x.twice(); // will this work?
</code></pre>
<hr>
<p><strong>Note:</strong> This question was asked before C#4 was shipped which is why it's phrased in the future tense.</p>
|
[
{
"answer_id": 1822926,
"author": "Ian Warburton",
"author_id": 221683,
"author_profile": "https://Stackoverflow.com/users/221683",
"pm_score": 2,
"selected": false,
"text": "public static class StrExtension\n{\n public static string twice(this string str) { return str + str; }\n}\n\n...\ndynamic x = \"Yo\";\nStrExtension.twice(x);\n"
},
{
"answer_id": 14651601,
"author": "JoelFan",
"author_id": 16012,
"author_profile": "https://Stackoverflow.com/users/16012",
"pm_score": 1,
"selected": false,
"text": "public static void MyExt(this object o) {\n dynamic d = o;\n d.myProp = \"foo\";\n}\n ClassWithMyProp x;\nx.MyExt();\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
259,000
|
<p>I have a system which is using phone numbers as unique identifiers. For this reason, I want to format all phone numbers as they come in using a normalized format. Because I have no control over my source data, I need to parse out these numbers myself and format them before adding them to my DB.</p>
<p>I'm about to write a parser that can read phone numbers in and output a normalized phone format, but before I do I was wondering if anyone knew of any pre-existing libraries I could use to format phone numbers.</p>
<p>If there are no pre-existing libraries out there, what things should I be keeping in mind when creating this feature that may not be obvious?</p>
<p>Although my system is only dealing with US numbers right now, I plan to try to include support for international numbers just in case since there is a chance it will be needed.</p>
<p><strong>Edit</strong> I forgot to mention I'm using C#.NET 2.0.</p>
|
[
{
"answer_id": 259016,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "[^\\d]"
},
{
"answer_id": 9137831,
"author": "friism",
"author_id": 2942,
"author_profile": "https://Stackoverflow.com/users/2942",
"pm_score": 5,
"selected": false,
"text": "libphonenumber var util = PhoneNumberUtil.GetInstance();\nvar number = util.Parse(\"555-555-5555\", \"US\");\n util.Format(number, PhoneNumberFormat.E164);\n libphonenumber"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
259,014
|
<p>I'm reading up on event-driven design. I am having trouble getting my head around some of it in practice. I'm considering using this for a windows service that monitors, parses, and handles information coming from a 3rd party TCP stream. Is the following a decent approach, or am I missing something? </p>
<p>My plan is to have a the main service be simply a container for events:</p>
<pre><code>public class MyService
{
public void RegisterAgent(ServiceAgent agent)
{
Log("Initializing agent " + agent);
agent.Initialize(this);
Log("Done intializing agent " + agent);
}
public void Log(string messageText)
{
OnSimpleLogEventLogged(this, new SimpleLogEventArgs(messageText));
}
protected void Raise<T>(EventHandler<T> eventHandler, object sender, T args) where T : EventArgs
{
var handler = eventHandler;
if (handler == null) return;
handler(sender, args);
}
public event EventHandler<SimpleLogEventArgs> SimpleLogEventLogged;
protected void OnSimpleLogEventLogged(object sender, SimpleLogEventArgs args)
{
Raise(SimpleLogEventLogged, sender, args);
}
public event EventHandler<TextRecievedEventArgs > TextRecieved;
public void OnTextRecieved(object sender, TextRecievedEventArgs args)
{
Raise(TextRecieved, sender, args);
}
public event EventHandler<TextParsedEventArgs> TextParsed;
public void OnTextParsed(object sender, TextParsedEventArgs args)
{
Raise(TextParsed, sender, args);
}
...
}
</code></pre>
<p>Then, using MEF or similar, I'll register "ServiceAgent" instances, which simply handle and/or raise events, optionally doing so on a background thread. For example:</p>
<pre><code>public class TextParsingAgent : ServiceAgent
{
public override void Initialize(MyService service)
{
service.TextRecieved += TextRecieved;
base.Initialize(service);
}
void TextRecieved(object sender, TextRecievedEventArgs e)
{
ThreadPool.QueueUserWorkItem(TextRecievedAsync, e);
}
private void TextRecieved(object state)
{
var e = (TextRecievedEventArgs)state;
//TODO:Parse text into something meaningful and store in textParseEventArgs
service.OnTextParsed(textParseEventArgs);
}
}
</code></pre>
|
[
{
"answer_id": 259016,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "[^\\d]"
},
{
"answer_id": 9137831,
"author": "friism",
"author_id": 2942,
"author_profile": "https://Stackoverflow.com/users/2942",
"pm_score": 5,
"selected": false,
"text": "libphonenumber var util = PhoneNumberUtil.GetInstance();\nvar number = util.Parse(\"555-555-5555\", \"US\");\n util.Format(number, PhoneNumberFormat.E164);\n libphonenumber"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
259,015
|
<p>Can every possible value of a <code>float</code> variable can be represented exactly in a <code>double</code> variable?</p>
<p>In other words, for all possible values <code>X</code> will the following be successful:</p>
<pre><code>float f1 = X;
double d = f1;
float f2 = (float)d;
if(f1 == f2)
System.out.println("Success!");
else
System.out.println("Failure!");
</code></pre>
<p>My suspicion is that there is no exception, or if there is it is only for an edge case (like +/- infinity or NaN).</p>
<p><strong>Edit</strong>: Original wording of question was confusing (stated two ways, one which would be answered "no" the other would be answered "yes" for the same answer). I've reworded it so that it matches the question title.</p>
|
[
{
"answer_id": 259113,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 0,
"selected": false,
"text": "NaN"
},
{
"answer_id": 259130,
"author": "Ryan",
"author_id": 29762,
"author_profile": "https://Stackoverflow.com/users/29762",
"pm_score": 0,
"selected": false,
"text": "typedef unsigned int uint;\nfor (uint i = 0; i < 0xFFFFFFFF; ++i)\n{\n float f1 = *(float *)&i;\n double d = f1;\n float f2 = (float)d;\n if(f1 != f2)\n printf(\"**** FAILURE **** %u | %f -- 0x%08x 0x%08x\\n\", i, f1, f1, f2);\n if ((i % 1000000) == 0)\n printf(\"Iteration: %d\\n\", i);\n}\n"
},
{
"answer_id": 259356,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 1,
"selected": false,
"text": "float a = 0.1F\nprintln \"a=${a}\"\ndouble d = a\nprintln \"d=${d}\"\n"
},
{
"answer_id": 259514,
"author": "mfx",
"author_id": 8015,
"author_profile": "https://Stackoverflow.com/users/8015",
"pm_score": 6,
"selected": true,
"text": "public class TestDoubleFloat {\n public static void main(String[] args) {\n for (long i = Integer.MIN_VALUE; i <= Integer.MAX_VALUE; i++) {\n float f1 = Float.intBitsToFloat((int) i);\n double d = (double) f1;\n float f2 = (float) d;\n if (f1 != f2) {\n if (Float.isNaN(f1) && Float.isNaN(f2)) {\n continue; // ok, NaN\n }\n fail(\"oops: \" + f1 + \" != \" + f2);\n }\n }\n }\n}\n"
},
{
"answer_id": 260459,
"author": "Chris Dodd",
"author_id": 29759,
"author_profile": "https://Stackoverflow.com/users/29759",
"pm_score": 0,
"selected": false,
"text": "if (!(f1 != f2))"
},
{
"answer_id": 12152511,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 0,
"selected": false,
"text": "float double double float float double"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
] |
259,018
|
<p>This is what I have written:</p>
<pre><code>if ((lstProperty[i].PropertyIdentifier as string).CompareTo("Name") == 0)
</code></pre>
<p>Resharper put me an error (I am new with ReSharper... I am trying it) and it suggests me :</p>
<pre><code> if (((string) lstProperty[i].PropertyIdentifier).CompareTo("Name") == 0)
</code></pre>
<p>Why is the second is NullException safe? For me both will crash if null value appear?</p>
|
[
{
"answer_id": 259062,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 4,
"selected": true,
"text": "string propertyIdentifier = lstProperty[u].PropertyIdentifier as string;\nif(propertyIdentifier != null && propertyIdentifier.CompareTo(\"Name\") == 0)\n{\n ... your if statement ...\n}\n"
},
{
"answer_id": 259114,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "InvalidCastException NullReferenceException null string try/catch string null var propertyI = lstProperty[i];\nvar propertyIdentifier = propertyI.PropertyIdentifier;\n\n// pick one of these:\nvar propertyIdentifierAsString = propertyIdentifier as string;\nvar propertyIdentifierAsString = (string)propertyIdentifier;\n\nif (propertyIdentifierAsString.CompareTo(\"Name\") == 0)\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13913/"
] |
259,026
|
<p>Why was C# designed this way?</p>
<p>As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.</p>
<p>If classes wish to implement that behavour in a shared method, why shouldn't they?</p>
<p>Here is an example of what I have in mind:</p>
<pre><code>// These items will be displayed in a list on the screen.
public interface IListItem {
string ScreenName();
...
}
public class Animal: IListItem {
// All animals will be called "Animal".
public static string ScreenName() {
return "Animal";
}
....
}
public class Person: IListItem {
private string name;
// All persons will be called by their individual names.
public string ScreenName() {
return name;
}
....
}
</code></pre>
|
[
{
"answer_id": 259042,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 4,
"selected": false,
"text": "IMyInterface val = GetObjectImplementingIMyInterface();\nval.SomeThingDefinedinInterface();\n"
},
{
"answer_id": 259079,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 9,
"selected": true,
"text": "public interface IFoo {\n void Bar();\n}\n\npublic class Foo: IFoo {\n public static void Bar() {}\n}\n public class Animal: IListItem {\n /* Can be tough to come up with a different, yet meaningful name!\n * A different casing convention, like Java has, would help here.\n */\n public const string AnimalScreenName = \"Animal\";\n public string ScreenName(){ return AnimalScreenName; }\n}\n"
},
{
"answer_id": 259413,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 3,
"selected": false,
"text": "public interface MyInterface { void MyMethod(); }\npublic class MyClass: MyInterface\n{\n public static void MyMethod() { //Do Something; }\n}\n\n // inside of some other class ... \n // How would you call the method on the interface ???\n MyClass.MyMethod(); // this calls the method normally \n // not through the interface...\n\n // This next fails you can't cast a classname to a different type... \n // Only instances can be Cast to a different type...\n MyInterface myItf = MyClass as MyInterface; \n"
},
{
"answer_id": 589484,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "interface IDataRow {\n string GetDataSTructre(); // How to read data from the DB\n void Read(IDBDataRow); // How to populate this datarow from DB data\n}\n\npublic class DataTable<T> : List<T> where T : IDataRow {\n\n public string GetDataStructure()\n // Desired: Static or Type method:\n // return (T.GetDataStructure());\n // Required: Instantiate a new class:\n return (new T().GetDataStructure());\n }\n\n}\n"
},
{
"answer_id": 7945206,
"author": "Ivan Arjentinski",
"author_id": 1020711,
"author_profile": "https://Stackoverflow.com/users/1020711",
"pm_score": 7,
"selected": false,
"text": "Repository GetRepository<T>()\n{\n //need to call T.IsQueryable, but can't!!!\n //need to call T.RowCount\n //need to call T.DoSomeStaticMath(int param)\n}\n\n...\nvar r = GetRepository<Customer>()\n public class Customer \n{\n //create new customer\n public Customer(Transaction t) { ... }\n\n //open existing customer\n public Customer(Transaction t, int id) { ... }\n\n void SomeOtherMethod() \n { \n //do work...\n }\n}\n public class Customer: IDoSomeStaticMath\n{\n //create new customer\n public Customer(Transaction t) { ... }\n\n //open existing customer\n public Customer(Transaction t, int id) { ... }\n\n //dummy instance\n public Customer() { IsDummy = true; }\n\n int DoSomeStaticMath(int a) { }\n\n void SomeOtherMethod() \n { \n if(!IsDummy) \n {\n //do work...\n }\n }\n}\n"
},
{
"answer_id": 17925193,
"author": "Stephen Westlake",
"author_id": 934859,
"author_profile": "https://Stackoverflow.com/users/934859",
"pm_score": 1,
"selected": false,
"text": " static public bool IsHandled(XElement xml)\n"
},
{
"answer_id": 18215459,
"author": "Jeremy Sorensen",
"author_id": 2325220,
"author_profile": "https://Stackoverflow.com/users/2325220",
"pm_score": 2,
"selected": false,
"text": "T SumElements<T>(T initVal, T[] values)\n{\n foreach (var v in values)\n {\n initVal += v;\n }\n}\n constraint CHasPlusEquals\n{\n static CHasPlusEquals operator + (CHasPlusEquals a, CHasPlusEquals b);\n}\n\nT SumElements<T>(T initVal, T[] values) where T : CHasPlusEquals\n{\n foreach (var v in values)\n {\n initVal += v;\n }\n}\n"
},
{
"answer_id": 29149949,
"author": "William Jockusch",
"author_id": 246568,
"author_profile": "https://Stackoverflow.com/users/246568",
"pm_score": 0,
"selected": false,
"text": "public interface IZeroWrapper<TNumber> {\n TNumber Zero {get;}\n}\n\npublic class DoubleWrapper: IZeroWrapper<double> {\n public double Zero { get { return 0; } }\n}\n"
},
{
"answer_id": 31632377,
"author": "Thomas Phaneuf",
"author_id": 3152063,
"author_profile": "https://Stackoverflow.com/users/3152063",
"pm_score": 1,
"selected": false,
"text": "public interface ICrudModel<T, Tk>\n{\n Boolean Create(T obj);\n T Retrieve(Tk key);\n Boolean Update(T obj);\n Boolean Delete(T obj);\n}\n"
},
{
"answer_id": 70913376,
"author": "unknown6656",
"author_id": 3902603,
"author_profile": "https://Stackoverflow.com/users/3902603",
"pm_score": 3,
"selected": false,
"text": "static abstract interface INumber<T>\n{\n static abstract T Zero { get; }\n}\n\nstruct Fraction : INumber<Fraction>\n{\n public static Fraction Zero { get; } = new Fraction();\n\n public long Numerator;\n public ulong Denominator;\n\n ....\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11514/"
] |
259,031
|
<p>Consider that I have a transaction:</p>
<pre><code>BEGIN TRANSACTION
DECLARE MONEY @amount
SELECT Amount AS @amount
FROM Deposits
WHERE UserId = 123
UPDATE Deposits
SET Amount = @amount + 100.0
WHERE UserId = 123
COMMIT
</code></pre>
<p>And it gets executed on 2 threads, in the order:</p>
<ol>
<li>thread 1 - select</li>
<li>thread 2 - select</li>
<li>thread 1 - update</li>
<li>thread 2 - update</li>
</ol>
<p>Assume that before execution Amount is 0.</p>
<p>What will happen in this case in the different settings of SQL Server (read uncommited, read commited, repeatable read, serializable), what will be amount at the end, will there be a deadlock?</p>
|
[
{
"answer_id": 259399,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 1,
"selected": false,
"text": "BEGIN TRANSACTION\nDECLARE MONEY @amount\nSELECT Amount AS @amount\n FROM Deposits\n WHERE UserId = 123\nUPDATE Deposits\n SET Amount = @amount + 100.0\n WHERE UserId = 123 AND Amount = @amount\nIF @@ROWCOUNT <> 1 BEGIN ROLLBACK; RAISERROR(...) END\nELSE COMMIT END\n"
},
{
"answer_id": 259423,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 2,
"selected": false,
"text": "UPDATE Deposits\nSET Amount = Amount + 100.0\nWHERE UserId = 123\n"
},
{
"answer_id": 259505,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": true,
"text": "CREATE TABLE Deposits(Amount Money, UserID int)\nINSERT INTO Deposits (Amount, UserID)\nSELECT 0.0, 123\n--Reset\nUPDATE Deposits\nSET Amount = 0.00\nWHERE UserID = 123\n SET TRANSACTION ISOLATION LEVEL Serializable\n----------------------------------------\n-- Part 1\n----------------------------------------\nBEGIN TRANSACTION\nDECLARE @amount MONEY\nSET @amount =\n(\nSELECT Amount\nFROM Deposits\nWHERE UserId = 123\n)\nSELECT @amount as Amount\n----------------------------------------\n-- Part 2\n----------------------------------------\nDECLARE @amount MONEY\nSET @amount = *value from step 1*\nUPDATE Deposits\nSET Amount = @amount + 100.0\nWHERE UserId = 123\nCOMMIT\nSELECT *\nFROM Deposits\nWHERE UserID = 123\n 1 T1.@Amount = 0.00\n2 T1.@Amount = 0.00\n3 Deposits.Amount = 100.00\n4 Deposits.Amount = 100.00\n 1 T1.@Amount = 0.00\n2 T1.@Amount = 0.00\n3 Deposits.Amount = 100.00\n4 Deposits.Amount = 100.00\n 1 T1.@Amount = 0.00 (locks out changes by others on Deposit.UserID = 123)\n2 T1.@Amount = 0.00 (locks out changes by others on Deposit.UserID = 123)\n3 Hangs until step 4. (due to lock in step 2)\n4 Deadlock!\nFinal result: Deposits.Amount = 100.00\n 1 T1.@Amount = 0.00 (locks out changes by others on Deposit)\n2 T1.@Amount = 0.00 (locks out changes by others on Deposit)\n3 Hangs until step 4. (due to lock in step 2)\n4 Deadlock!\nFinal result: Deposits.Amount = 100.00\n"
},
{
"answer_id": 259520,
"author": "Arvo",
"author_id": 35777,
"author_profile": "https://Stackoverflow.com/users/35777",
"pm_score": 1,
"selected": false,
"text": "BEGIN TRANSACTION\nDECLARE MONEY @amount\nSELECT Amount AS @amount\n FROM Deposits WITH(UPDLOCK)\n WHERE UserId = 123\nUPDATE Deposits\n SET Amount = @amount + 100.0\n WHERE UserId = 123\nCOMMIT\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6176/"
] |
259,039
|
<p>I've written a paged search stored procedure using SQL Server 2005. It takes a number of parameters and the search criteria is moderately complex.</p>
<p>Due to the front-end architecture I need to be able to return the number of results that would come back <strong>without</strong> actually returning the results. The front end would then call the stored procedure a second time to get the actual results.</p>
<p>On the one hand I can write two stored procedures - one to handle the count and one to handle the actual data, but then I need to maintain the search logic in at least two different places. Alternatively, I can write the stored procedure so that it takes a bit parameter and based on that I either return data or just a count. Maybe fill a temporary table with the data and if it's count only just do a count from that, otherwise do a select from it. The problem here is that the count process could be optimized so that's a lot of extra overhead it seems (have to get unneeded columns, etc.). Also, using this kind of logic in a stored procedure could result in bad query plans as it goes back and forth between the two uses.</p>
<p>The amount of data in the system isn't too high (only a couple million rows for even the larger tables). There may be many concurrent users though.</p>
<p>What are people's thoughts on these approaches? Has anyone solved this problem before in a way that I haven't thought of?</p>
<p>They <strong>CANNOT</strong> take the results and count at the same time from a single call.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 1709064,
"author": "cloggins",
"author_id": 179026,
"author_profile": "https://Stackoverflow.com/users/179026",
"pm_score": 1,
"selected": false,
"text": "procedure get_sample_results (\n startrow in number default 1,\n numberofrows in number default 10,\n whereclause in varchar2,\n matchingrows out number,\n rc out sys_refcursor\n)\nis\n stmnt varchar2(5000);\n endrow number;\nbegin\n\n stmnt := stmnt || 'select * from table t where 1=1';\n if whereclause is not null then\n stmnt := stmnt || ' and ' || whereclause;\n end if;\n\n execute immediate 'select count(*) from (' || stmnt || ')' into matchingrows;\n\n stmnt := 'select * from (' || stmnt || ') where rownum between :1 and :2'; \n\n -- must subtract one to compenstate for the inclusive between clause\n endrow := startrow + numberofrows - 1;\n open rc for stmnt using startrow, endrow;\n\nend get_sample_results;\n"
},
{
"answer_id": 4184712,
"author": "Pure.Krome",
"author_id": 30674,
"author_profile": "https://Stackoverflow.com/users/30674",
"pm_score": 0,
"selected": false,
"text": "CREATE PROCEDURE WhatEver\n(\n @SomeParam1 NVARCHAR(200),\n ....\n @SomeParam_X INT,\n @NumberOfResults INTEGER OUTPUT\n)\nBEGIN\n SET NOCOUNT ON\n\n -- Do your search stuff.\n -- ....\n SELECT Whatever\n FROM WhatWhat\n ...\n\n -- Ok, the results/recordset has been sent prepared.\n -- Now the rowcount\n SET @NumberOfResults = @@ROWCOUNT\nEND\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5696608/"
] |
259,063
|
<h3>Problem</h3>
<p>I've got a collection of <code>IThing</code>s and I'd like to create a <code>HierarchicalDataTemplate</code> for a <code>TreeView</code>. The straightforward <code>DataType={x:Type local:IThing}</code> of course doesn't work, probably because the WPF creators didn't want to handle the possible ambiguities.</p>
<p>Since this should handle <code>IThing</code>s from different sources at the same time, referencing the implementing class is out of question. </p>
<h3>Current solution</h3>
<p>For now I'm using a ViewModel which proxies IThing through a concrete implementation:</p>
<pre><code>public interface IThing {
string SomeString { get; }
ObservableCollection<IThing> SomeThings { get; }
// many more stuff
}
public class IThingViewModel
{
public IThing Thing { get; }
public IThingViewModel(IThing it) { this.Thing = it; }
}
<!-- is never applied -->
<HierarchicalDataTemplate DataType="{x:Type local:IThing}">
<!-- is applied, but looks strange -->
<HierarchicalDataTemplate
DataType="{x:Type local:IThingViewModel}"
ItemsSource="{Binding Thing.SomeThings}">
<TextBox Text="{Binding Thing.SomeString}"/>
</HierarchicalDataTemplate>
</code></pre>
<h3>Question</h3>
<p>Is there a better (i.e. no proxy) way?</p>
|
[
{
"answer_id": 2565665,
"author": "jing boxian",
"author_id": 307538,
"author_profile": "https://Stackoverflow.com/users/307538",
"pm_score": 2,
"selected": false,
"text": "<TreeView ItemDataTemplate={StaticResource templateKey}/>"
},
{
"answer_id": 9804166,
"author": "Daniel Rose",
"author_id": 318317,
"author_profile": "https://Stackoverflow.com/users/318317",
"pm_score": 3,
"selected": false,
"text": "public ObservableCollection<IThing> Thingies { get; private set; }\n <TreeView ItemsSource=\"{Binding Thingies}\">\n <TreeView.ItemTemplate>\n <HierarchicalDataTemplate ItemsSource=\"{Binding SomeThings}\">\n <TextBox Text=\"{Binding SomeString}\" /> \n </HierarchicalDataTemplate>\n </TreeView.ItemTemplate>\n</TreeView>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
259,085
|
<p>I thought this was asked before, but 15 minutes of searching on Google and the site search didn't turn anything up...so:</p>
<p>Where can I obtain free (as in beer and/or as in speech) dictionary files? I'm mainly interested in English, but if you know of any dictionary files, please point them out.</p>
<p>Note: This question doesn't have a right/wrong answer, so I made it community-wiki. However, I feel that it might be valuable to not only myself, but anyone who wishes to implement or use a spell checker with various dictionary files.</p>
|
[
{
"answer_id": 259199,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 2,
"selected": false,
"text": "/usr/share/dict/words"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
259,091
|
<h1>The Problem</h1>
<p>I use a tool at work that lets me do queries and get back HTML tables of info. I do not have any kind of back-end access to it.</p>
<p>A lot of this info would be much more useful if I could put it into a spreadsheet for sorting, averaging, etc. <strong>How can I screen-scrape this data to a CSV file?</strong></p>
<h2>My First Idea</h2>
<p>Since I know jQuery, I thought I might use it to strip out the table formatting onscreen, insert commas and line breaks, and just copy the whole mess into notepad and save as a CSV. <strong>Any better ideas?</strong></p>
<h1>The Solution</h1>
<p>Yes, folks, it really was as easy as copying and pasting. Don't I feel silly.</p>
<p>Specifically, when I pasted into the spreadsheet, I had to select "Paste Special" and choose the format "text." Otherwise it tried to paste everything into a single cell, even if I highlighted the whole spreadsheet.</p>
|
[
{
"answer_id": 279743,
"author": "Thorvaldur",
"author_id": 35781,
"author_profile": "https://Stackoverflow.com/users/35781",
"pm_score": 4,
"selected": false,
"text": "from BeautifulSoup import BeautifulSoup\nimport urllib,string,csv,sys,os\nfrom string import replace\n\ndate_s = '&date1=01/01/08'\ndate_f = '&date=11/10/08'\nfx_url = 'http://www.oanda.com/convert/fxhistory?date_fmt=us'\nfx_url_end = '&lang=en&margin_fixed=0&format=CSV&redirected=1'\ncur1,cur2 = 'USD','AUD'\nfx_url = fx_url + date_f + date_s + '&exch=' + cur1 +'&exch2=' + cur1\nfx_url = fx_url +'&expr=' + cur2 + '&expr2=' + cur2 + fx_url_end\ndata = urllib.urlopen(fx_url).read()\nsoup = BeautifulSoup(data)\ndata = str(soup.findAll('pre', limit=1))\ndata = replace(data,'[<pre>','')\ndata = replace(data,'</pre>]','')\nfile_location = '/Users/location_edit_this'\nfile_name = file_location + 'usd_aus.csv'\nfile = open(file_name,\"w\")\nfile.write(data)\nfile.close()\n from mechanize import Browser\nfrom BeautifulSoup import BeautifulSoup\n\nmech = Browser()\n\nurl = \"http://www.palewire.com/scrape/albums/2007.html\"\npage = mech.open(url)\n\nhtml = page.read()\nsoup = BeautifulSoup(html)\n\ntable = soup.find(\"table\", border=1)\n\nfor row in table.findAll('tr')[1:]:\n col = row.findAll('td')\n\n rank = col[0].string\n artist = col[1].string\n album = col[2].string\n cover_link = col[3].img['src']\n\n record = (rank, artist, album, cover_link)\n print \"|\".join(record)\n"
},
{
"answer_id": 16697784,
"author": "Juan A. Navarro",
"author_id": 359178,
"author_profile": "https://Stackoverflow.com/users/359178",
"pm_score": 4,
"selected": false,
"text": "$ sudo easy_install beautifulsoup4\n #!/usr/bin/python\nfrom bs4 import BeautifulSoup\nimport sys\nimport re\nimport csv\n\ndef cell_text(cell):\n return \" \".join(cell.stripped_strings)\n\nsoup = BeautifulSoup(sys.stdin.read())\noutput = csv.writer(sys.stdout)\n\nfor table in soup.find_all('table'):\n for row in table.find_all('tr'):\n col = map(cell_text, row.find_all(re.compile('t[dh]')))\n output.writerow(col)\n output.writerow([])\n"
},
{
"answer_id": 28083469,
"author": "n8henrie",
"author_id": 1588795,
"author_profile": "https://Stackoverflow.com/users/1588795",
"pm_score": 3,
"selected": false,
"text": "importHTML =importHTML(\"http://example.com/page/with/table\", \"table\", index copy paste values read_html to_csv"
},
{
"answer_id": 29276277,
"author": "Aviad",
"author_id": 2539074,
"author_profile": "https://Stackoverflow.com/users/2539074",
"pm_score": 2,
"selected": false,
"text": "from BeautifulSoup import BeautifulSoup\n\ndef table2csv(html_txt):\n csvs = []\n soup = BeautifulSoup(html_txt)\n tables = soup.findAll('table')\n\n for table in tables:\n csv = ''\n rows = table.findAll('tr')\n row_spans = []\n do_ident = False\n\n for tr in rows:\n cols = tr.findAll(['th','td'])\n\n for cell in cols:\n colspan = int(cell.get('colspan',1))\n rowspan = int(cell.get('rowspan',1))\n\n if do_ident:\n do_ident = False\n csv += ','*(len(row_spans))\n\n if rowspan > 1: row_spans.append(rowspan)\n\n csv += '\"{text}\"'.format(text=cell.text) + ','*(colspan)\n\n if row_spans:\n for i in xrange(len(row_spans)-1,-1,-1):\n row_spans[i] -= 1\n if row_spans[i] < 1: row_spans.pop()\n\n do_ident = True if row_spans else False\n\n csv += '\\n'\n\n csvs.append(csv)\n #print csv\n\n return '\\n\\n'.join(csvs)\n"
},
{
"answer_id": 43380841,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/python\n\nfrom bs4 import BeautifulSoup\nimport sys\nimport re\nimport csv\nimport grequests\nimport time\n\ndef cell_text(cell):\n return \" \".join(cell.stripped_strings)\n\ndef parse_table(body_html):\n soup = BeautifulSoup(body_html)\n for table in soup.find_all('table'):\n for row in table.find_all('tr'):\n col = map(cell_text, row.find_all(re.compile('t[dh]')))\n print(col)\n\ndef process_a_page(response, *args, **kwargs): \n parse_table(response.content)\n\ndef download_a_chunk(k):\n chunk_size = 10 #number of html pages\n x = \"http://www.blahblah....com/inclusiones.php?p=\"\n x2 = \"&name=...\"\n URLS = [x+str(i)+x2 for i in range(k*chunk_size, k*(chunk_size+1)) ]\n reqs = [grequests.get(url, hooks={'response': process_a_page}) for url in URLS]\n resp = grequests.map(reqs, size=10)\n\n# download slowly so the server does not block you\nfor k in range(0,500):\n print(\"downloading chunk \",str(k))\n download_a_chunk(k)\n time.sleep(11)\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4376/"
] |
259,095
|
<p>I am trying to print something at the bottom of a report. I am using a section <code>Pagefooter</code>.<br>
I thought that if you used <code>Pagefooter</code> that it would print at the bottom on the report.</p>
|
[
{
"answer_id": 279743,
"author": "Thorvaldur",
"author_id": 35781,
"author_profile": "https://Stackoverflow.com/users/35781",
"pm_score": 4,
"selected": false,
"text": "from BeautifulSoup import BeautifulSoup\nimport urllib,string,csv,sys,os\nfrom string import replace\n\ndate_s = '&date1=01/01/08'\ndate_f = '&date=11/10/08'\nfx_url = 'http://www.oanda.com/convert/fxhistory?date_fmt=us'\nfx_url_end = '&lang=en&margin_fixed=0&format=CSV&redirected=1'\ncur1,cur2 = 'USD','AUD'\nfx_url = fx_url + date_f + date_s + '&exch=' + cur1 +'&exch2=' + cur1\nfx_url = fx_url +'&expr=' + cur2 + '&expr2=' + cur2 + fx_url_end\ndata = urllib.urlopen(fx_url).read()\nsoup = BeautifulSoup(data)\ndata = str(soup.findAll('pre', limit=1))\ndata = replace(data,'[<pre>','')\ndata = replace(data,'</pre>]','')\nfile_location = '/Users/location_edit_this'\nfile_name = file_location + 'usd_aus.csv'\nfile = open(file_name,\"w\")\nfile.write(data)\nfile.close()\n from mechanize import Browser\nfrom BeautifulSoup import BeautifulSoup\n\nmech = Browser()\n\nurl = \"http://www.palewire.com/scrape/albums/2007.html\"\npage = mech.open(url)\n\nhtml = page.read()\nsoup = BeautifulSoup(html)\n\ntable = soup.find(\"table\", border=1)\n\nfor row in table.findAll('tr')[1:]:\n col = row.findAll('td')\n\n rank = col[0].string\n artist = col[1].string\n album = col[2].string\n cover_link = col[3].img['src']\n\n record = (rank, artist, album, cover_link)\n print \"|\".join(record)\n"
},
{
"answer_id": 16697784,
"author": "Juan A. Navarro",
"author_id": 359178,
"author_profile": "https://Stackoverflow.com/users/359178",
"pm_score": 4,
"selected": false,
"text": "$ sudo easy_install beautifulsoup4\n #!/usr/bin/python\nfrom bs4 import BeautifulSoup\nimport sys\nimport re\nimport csv\n\ndef cell_text(cell):\n return \" \".join(cell.stripped_strings)\n\nsoup = BeautifulSoup(sys.stdin.read())\noutput = csv.writer(sys.stdout)\n\nfor table in soup.find_all('table'):\n for row in table.find_all('tr'):\n col = map(cell_text, row.find_all(re.compile('t[dh]')))\n output.writerow(col)\n output.writerow([])\n"
},
{
"answer_id": 28083469,
"author": "n8henrie",
"author_id": 1588795,
"author_profile": "https://Stackoverflow.com/users/1588795",
"pm_score": 3,
"selected": false,
"text": "importHTML =importHTML(\"http://example.com/page/with/table\", \"table\", index copy paste values read_html to_csv"
},
{
"answer_id": 29276277,
"author": "Aviad",
"author_id": 2539074,
"author_profile": "https://Stackoverflow.com/users/2539074",
"pm_score": 2,
"selected": false,
"text": "from BeautifulSoup import BeautifulSoup\n\ndef table2csv(html_txt):\n csvs = []\n soup = BeautifulSoup(html_txt)\n tables = soup.findAll('table')\n\n for table in tables:\n csv = ''\n rows = table.findAll('tr')\n row_spans = []\n do_ident = False\n\n for tr in rows:\n cols = tr.findAll(['th','td'])\n\n for cell in cols:\n colspan = int(cell.get('colspan',1))\n rowspan = int(cell.get('rowspan',1))\n\n if do_ident:\n do_ident = False\n csv += ','*(len(row_spans))\n\n if rowspan > 1: row_spans.append(rowspan)\n\n csv += '\"{text}\"'.format(text=cell.text) + ','*(colspan)\n\n if row_spans:\n for i in xrange(len(row_spans)-1,-1,-1):\n row_spans[i] -= 1\n if row_spans[i] < 1: row_spans.pop()\n\n do_ident = True if row_spans else False\n\n csv += '\\n'\n\n csvs.append(csv)\n #print csv\n\n return '\\n\\n'.join(csvs)\n"
},
{
"answer_id": 43380841,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "#!/usr/bin/python\n\nfrom bs4 import BeautifulSoup\nimport sys\nimport re\nimport csv\nimport grequests\nimport time\n\ndef cell_text(cell):\n return \" \".join(cell.stripped_strings)\n\ndef parse_table(body_html):\n soup = BeautifulSoup(body_html)\n for table in soup.find_all('table'):\n for row in table.find_all('tr'):\n col = map(cell_text, row.find_all(re.compile('t[dh]')))\n print(col)\n\ndef process_a_page(response, *args, **kwargs): \n parse_table(response.content)\n\ndef download_a_chunk(k):\n chunk_size = 10 #number of html pages\n x = \"http://www.blahblah....com/inclusiones.php?p=\"\n x2 = \"&name=...\"\n URLS = [x+str(i)+x2 for i in range(k*chunk_size, k*(chunk_size+1)) ]\n reqs = [grequests.get(url, hooks={'response': process_a_page}) for url in URLS]\n resp = grequests.map(reqs, size=10)\n\n# download slowly so the server does not block you\nfor k in range(0,500):\n print(\"downloading chunk \",str(k))\n download_a_chunk(k)\n time.sleep(11)\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
259,111
|
<p>I'm running in a strange issue.
My controller calls a drb object</p>
<pre><code>@request_handler = DRbObject.new(nil, url)
availability_result = @request_handler.fetch_availability(request, @reservation_search, params[:selected_room_rates])
</code></pre>
<p>and this Drb object is making some searches.</p>
<p>but sometimes, in a linux environments, I get a "0xdba87b30 is recycled object" with this stacktrace</p>
<pre><code>---
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:375:in `_id2ref'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:375:in `to_obj'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1402:in `to_obj'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1704:in `to_obj'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:613:in `recv_request'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:911:in `recv_request'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1530:in `init_with_client'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1542:in `setup_message'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1494:in `perform'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1589:in `main_loop'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1585:in `loop'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1585:in `main_loop'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1581:in `start'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1581:in `main_loop'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1430:in `run'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1427:in `start'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1427:in `run'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1347:in `initialize'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1627:in `new'
- (druby://10.254.143.159:9001) /usr/lib/ruby/1.8/drb/drb.rb:1627:in `start_service'
- (druby://10.254.143.159:9001) ./core/request_handler.rb:244
- (druby://10.254.143.159:9001) /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
- (druby://10.254.143.159:9001) /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:27:in `require'
- (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
- (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:355:in `new_constants_in'
- (druby://10.254.143.159:9001) /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:510:in `require'
- (druby://10.254.143.159:9001) core/request_handler.rb:31
- (druby://10.254.143.159:9001) core/request_handler.rb:29:in `each'
- (druby://10.254.143.159:9001) core/request_handler.rb:29
- app/drops/room_drop.rb:18:in `room_rates'
- lib/liquid/liquid_templates.rb:47:in `parse_template'
- lib/liquid/liquid_templates.rb:21:in `render_liquid_template_without_layout'
- app/helpers/skins_helper.rb:6:in `render_respond_by_format'
- app/helpers/skins_helper.rb:4:in `render_respond_by_format'
- app/helpers/skins_helper.rb:25:in `render_availability_action'
- app/controllers/web_reservations_controller.rb:109:in `availability_simplified'
- /usr/bin/mongrel_rails:19:in `load'
- /usr/bin/mongrel_rails:19
</code></pre>
<p>The strange thing is that I can't reproduce the error in my (windows) development machine, but I get it only in my linux testing server (2 mongrels instead of one in my machine).</p>
<p>What's wrong? I think it is a garbage collector problem (object collected before reusing it), but I don't understand where I'm doing something wrong. I simply create the object in my controller and call a method on it.</p>
<p>Any idea?</p>
<p>Thanks!
Roberto</p>
|
[
{
"answer_id": 367394,
"author": "Ripta Pasay",
"author_id": 46227,
"author_profile": "https://Stackoverflow.com/users/46227",
"pm_score": 4,
"selected": true,
"text": "GC.disable"
},
{
"answer_id": 54403314,
"author": "philant",
"author_id": 18804,
"author_profile": "https://Stackoverflow.com/users/18804",
"pm_score": 2,
"selected": false,
"text": " DRb.install_id_conv TimerIdConv.new 60 # one minute\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22083/"
] |
259,123
|
<p>My app has a DataGridView object and a List of type MousePos. MousePos is a custom class that holds mouse X,Y coordinates (of type "Point") and a running count of this position. I have a thread (System.Timers.Timer) that raises an event once every second, checks the mouse position, adds and/or updates the count of the mouse position on this List.</p>
<p>I would like to have a similar running thread (again, I think System.Timers.Timer is a good choice) which would again raise an event once a second to automatically Refresh() the DataGridView so that the user can see the data on the screen update. (like TaskManager does.)</p>
<p>Unfortunately, calling the DataGridView.Refresh() method results in VS2005 stopping execution and noting that I've run into a cross-threading situation.</p>
<p>If I'm understanding correctly, I have 3 threads now:</p>
<ul>
<li>Primary UI thread</li>
<li>MousePos List thread (Timer)</li>
<li>DataGridView Refresh thread (Timer)</li>
</ul>
<p>To see if I could Refresh() the DataGridView on the primary thread, I added a button to the form which called DataGridView.Refresh(), but this (strangely) didn't do anything. I found a topic which seemed to indicate that if I set DataGridView.DataSource = null and back to my List, that it would refresh the datagrid. And indeed this worked, but only thru the button (which gets handled on the primary thread.)</p>
<hr>
<p>So this question has turned into a two-parter:</p>
<ol>
<li>Is setting DataGridView.DataSource to null and back to my List an acceptable way to refresh the datagrid? (It seems inefficient to me...)</li>
<li>How do I safely do this in a multi-threaded environment?</li>
</ol>
<hr>
<p>Here's the code I've written so far (C#/.Net 2.0)</p>
<pre><code>public partial class Form1 : Form
{
private static List<MousePos> mousePositionList = new List<MousePos>();
private static System.Timers.Timer mouseCheck = new System.Timers.Timer(1000);
private static System.Timers.Timer refreshWindow = new System.Timers.Timer(1000);
public Form1()
{
InitializeComponent();
mousePositionList.Add(new MousePos()); // ANSWER! Must have at least 1 entry before binding to DataSource
dataGridView1.DataSource = mousePositionList;
mouseCheck.Elapsed += new System.Timers.ElapsedEventHandler(mouseCheck_Elapsed);
mouseCheck.Start();
refreshWindow.Elapsed += new System.Timers.ElapsedEventHandler(refreshWindow_Elapsed);
refreshWindow.Start();
}
public void mouseCheck_Elapsed(object source, EventArgs e)
{
Point mPnt = Control.MousePosition;
MousePos mPos = mousePositionList.Find(ByPoint(mPnt));
if (mPos == null) { mousePositionList.Add(new MousePos(mPnt)); }
else { mPos.Count++; }
}
public void refreshWindow_Elapsed(object source, EventArgs e)
{
//dataGridView1.DataSource = null; // Old way
//dataGridView1.DataSource = mousePositionList; // Old way
dataGridView1.Invalidate(); // <= ANSWER!!
}
private static Predicate<MousePos> ByPoint(Point pnt)
{
return delegate(MousePos mPos) { return (mPos.Pnt == pnt); };
}
}
public class MousePos
{
private Point position = new Point();
private int count = 1;
public Point Pnt { get { return position; } }
public int X { get { return position.X; } set { position.X = value; } }
public int Y { get { return position.Y; } set { position.Y = value; } }
public int Count { get { return count; } set { count = value; } }
public MousePos() { }
public MousePos(Point mouse) { position = mouse; }
}
</code></pre>
|
[
{
"answer_id": 259477,
"author": "Pretzel",
"author_id": 21244,
"author_profile": "https://Stackoverflow.com/users/21244",
"pm_score": 4,
"selected": true,
"text": " dataGridView1.Invalidate();\n dataGridView1.Invalidate(true);\n dataGridView1.Update(); // <== forces immediate redraw\n private static System.Windows.Forms.Timer refreshWindow2;\nrefreshWindow2 = new Timer();\nrefreshWindow2.Interval = 1000;\nrefreshWindow2.Tick += new EventHandler(refreshWindow2_Tick);\nrefreshWindow2.Start();\n private void refreshWindow2_Tick(object sender, EventArgs e)\n{\n dataGridView1.Invalidate();\n}\n"
},
{
"answer_id": 768143,
"author": "Fredrik Bonde",
"author_id": 45187,
"author_profile": "https://Stackoverflow.com/users/45187",
"pm_score": 2,
"selected": false,
"text": "public void refreshWindow_Elapsed(object source, EventArgs e)\n{\n\n // we use anonymous delgate here as it saves us declaring a named delegate in our class\n // however, as c# type inference sometimes need a bit of 'help' we need to cast it \n // to an instance of MethodInvoker\n dataGridView1.Invoke((MethodInvoker)delegate() { dataGridView1.Invalidate(); });\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21244/"
] |
259,126
|
<p>Is there any way to change the entire width of the horizontal scroll bar on a scrolling div (including the nudge arrows and the handle).</p>
<p>EDIT: I only need an IE7 solution - it's for a scrolling DIV on a touch screen terminal</p>
<p>Thanks</p>
<p>Matt</p>
|
[
{
"answer_id": 259270,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 3,
"selected": true,
"text": "<div style=\"zoom:5;font-size:20%;overflow-x:auto;\">\n Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!\n</div>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5185/"
] |
259,139
|
<p>Use case:</p>
<ol>
<li>A does something on his box and gots stuck. He asks B (remote) for support.</li>
<li>B logs into the session of A, sees all windows, A was seeing and is able to manipulate the GUI.</li>
</ol>
<p>If A uses Windows it is very convenient to log into a running session e.g. via VNC. But if A uses Linux, AFAIK, this is not possible. Using VNC requires a "vncserver"-session, which is a separate session. You could get screen captures from remote by querying the X-server, but you cannot press buttons on the screen.</p>
<p>Is there some workaround for this?</p>
|
[
{
"answer_id": 259270,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 3,
"selected": true,
"text": "<div style=\"zoom:5;font-size:20%;overflow-x:auto;\">\n Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!\n</div>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11344/"
] |
259,140
|
<p>How do I search the whole classpath for an annotated class?</p>
<p>I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.</p>
<p>I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with <code>@WebService</code> or <code>@EJB</code> and the system finds these classes while loading so they are accessible remotely.</p>
|
[
{
"answer_id": 1415338,
"author": "Arthur Ronald",
"author_id": 127359,
"author_profile": "https://Stackoverflow.com/users/127359",
"pm_score": 9,
"selected": true,
"text": "ClassPathScanningCandidateComponentProvider scanner =\nnew ClassPathScanningCandidateComponentProvider(<DO_YOU_WANT_TO_USE_DEFALT_FILTER>);\n\nscanner.addIncludeFilter(new AnnotationTypeFilter(<TYPE_YOUR_ANNOTATION_HERE>.class));\n\nfor (BeanDefinition bd : scanner.findCandidateComponents(<TYPE_YOUR_BASE_PACKAGE_HERE>))\n System.out.println(bd.getBeanClassName());\n"
},
{
"answer_id": 8209445,
"author": "rmuller",
"author_id": 868941,
"author_profile": "https://Stackoverflow.com/users/868941",
"pm_score": 5,
"selected": false,
"text": "annotation-detector"
},
{
"answer_id": 8642568,
"author": "Sławek",
"author_id": 1116153,
"author_profile": "https://Stackoverflow.com/users/1116153",
"pm_score": 4,
"selected": false,
"text": "ClassIndex.getAnnotated(com.test.YourCustomAnnotation.class)\n"
},
{
"answer_id": 33091899,
"author": "magiccrafter",
"author_id": 896981,
"author_profile": "https://Stackoverflow.com/users/896981",
"pm_score": 2,
"selected": false,
"text": "Class<?> clazz = AnnotationUtils.findAnnotationDeclaringClass(Target.class, null);\n"
},
{
"answer_id": 47428495,
"author": "voucher_wolves",
"author_id": 6249539,
"author_profile": "https://Stackoverflow.com/users/6249539",
"pm_score": 3,
"selected": false,
"text": "public class ElementScanner {\n\npublic void scanElements(){\n try {\n //Get the package name from configuration file\n String packageName = readConfig();\n\n //Load the classLoader which loads this class.\n ClassLoader classLoader = getClass().getClassLoader();\n\n //Change the package structure to directory structure\n String packagePath = packageName.replace('.', '/');\n URL urls = classLoader.getResource(packagePath);\n\n //Get all the class files in the specified URL Path.\n File folder = new File(urls.getPath());\n File[] classes = folder.listFiles();\n\n int size = classes.length;\n List<Class<?>> classList = new ArrayList<Class<?>>();\n\n for(int i=0;i<size;i++){\n int index = classes[i].getName().indexOf(\".\");\n String className = classes[i].getName().substring(0, index);\n String classNamePath = packageName+\".\"+className;\n Class<?> repoClass;\n repoClass = Class.forName(classNamePath);\n Annotation[] annotations = repoClass.getAnnotations();\n for(int j =0;j<annotations.length;j++){\n System.out.println(\"Annotation in class \"+repoClass.getName()+ \" is \"+annotations[j].annotationType().getName());\n }\n classList.add(repoClass);\n }\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n}\n\n/**\n * Unmarshall the configuration file\n * @return\n */\npublic String readConfig(){\n try{\n URL url = getClass().getClassLoader().getResource(\"WEB-INF/config.xml\");\n JAXBContext jContext = JAXBContext.newInstance(RepositoryConfig.class);\n Unmarshaller um = jContext.createUnmarshaller();\n RepositoryConfig rc = (RepositoryConfig) um.unmarshal(new File(url.getFile()));\n return rc.getRepository().getPackageName();\n }catch(Exception e){\n e.printStackTrace();\n }\n return null;\n\n}\n}\n"
},
{
"answer_id": 51842140,
"author": "dzikoysk",
"author_id": 3426515,
"author_profile": "https://Stackoverflow.com/users/3426515",
"pm_score": 1,
"selected": false,
"text": "AnnotationsScannerProcess ClassFiles AnnotationsScanner AnnotationsScanner scanner = AnnotationsScanner.createScanner()\n .includeSources(ExampleApplication.class)\n .build();\n\nAnnotationsScannerProcess process = scanner.createWorker()\n .addDefaultProjectFilters(\"net.dzikoysk\")\n .fetch();\n\nSet<Class<?>> classes = process.createSelector()\n .selectTypesAnnotatedWith(AnnotationTest.class);\n"
},
{
"answer_id": 53972609,
"author": "madhu_karnati",
"author_id": 2333311,
"author_profile": "https://Stackoverflow.com/users/2333311",
"pm_score": 1,
"selected": false,
"text": "ClassPathScanningCandidateComponentProvider"
},
{
"answer_id": 56339620,
"author": "swayamraina",
"author_id": 6183182,
"author_profile": "https://Stackoverflow.com/users/6183182",
"pm_score": 3,
"selected": false,
"text": "AnnotatedTypeScanner ClassPathScanningCandidateComponentProvider\n /**\n * Creates a new {@link AnnotatedTypeScanner} for the given annotation types.\n * \n * @param considerInterfaces whether to consider interfaces as well.\n * @param annotationTypes the annotations to scan for.\n */\n public AnnotatedTypeScanner(boolean considerInterfaces, Class<? extends Annotation>... annotationTypes) {\n\n this.annotationTypess = Arrays.asList(annotationTypes);\n this.considerInterfaces = considerInterfaces;\n }\n"
},
{
"answer_id": 59239204,
"author": "Zon",
"author_id": 1112963,
"author_profile": "https://Stackoverflow.com/users/1112963",
"pm_score": 4,
"selected": false,
"text": "new Reflections(\"my.package\").getTypesAnnotatedWith(MyAnnotation.class)\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
] |
259,147
|
<p>I'm using <a href="http://urlrewriter.net/" rel="nofollow noreferrer">http://urlrewriter.net/</a> to rewrite urls at my website. For example, I'm rewriting:</p>
<blockquote>
<p><a href="http://www.example.com/schedule.aspx?state=ca" rel="nofollow noreferrer">http://www.example.com/schedule.aspx?state=ca</a></p>
</blockquote>
<p>to</p>
<blockquote>
<p><a href="http://www.example.com/california.aspx" rel="nofollow noreferrer">http://www.example.com/california.aspx</a></p>
</blockquote>
<p>What I'm trying to do (for SEO purposes) to to dynamically add the meta tag:</p>
<pre><code><meta name="robots" content="noindex,follow" />
</code></pre>
<p><em>only</em> to the page that hasn't been rewritten. This is because I want both URLs to work, but only the rewritten one to be indexed by search engines. </p>
<p>How do I determine which version of the page has been requested?</p>
<p><strong>EDIT</strong></p>
<p>Answers below suggest a 301 redirect instead of using a meta tag. Maybe I'll do this, but I still want to know the answer to the underlying question... how do I know if the page has been rewritten?</p>
|
[
{
"answer_id": 259175,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 2,
"selected": false,
"text": "<add header=\"X-WasRewritten\" value=\"true\" />\n"
},
{
"answer_id": 259177,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 1,
"selected": false,
"text": "if (Path.GetFileName(Request.Url.FilePath) == \"schedule.aspx\")\n //Not rewritten\nelse\n //rewritten\n"
},
{
"answer_id": 274797,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 0,
"selected": false,
"text": "HttpContext.Current.Items[\"Redirected_From\"] = currentUrlHere;\n if (!string.IsNullOrEmpty(HttpContext.Current.Items[\"Redirected_From\"]))\n // the page's been redirected, do something!\nelse\n // no it's visited normally.\n"
},
{
"answer_id": 294818,
"author": "Chris Fulstow",
"author_id": 38126,
"author_profile": "https://Stackoverflow.com/users/38126",
"pm_score": 2,
"selected": false,
"text": "bool isPageRewritten = \n !string.IsNullOrEmpty(HttpContext.Current.Items[\"UrlRewriter.NET.RawUrl\"]);\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28260/"
] |
259,150
|
<p>I have an incoming soap message wich form is TStream (Delphi7), server that send this soap is in development mode and adds a html header to the message for debugging purposes. Now i need to cut out the html header part from it before i can pass it to soap converter. It starts from the beginning with 'pre' tag and ends with '/pre' tag. Im thinking it should be fairly easy to but i havent done it before in Delphi7, so can someone help me? </p>
|
[
{
"answer_id": 259700,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 2,
"selected": true,
"text": "function DepreStream(Stm : tStream):tStream;\nvar\n sTemp : String;\n oStrStm : tStringStream;\n i : integer;\nbegin\n oStrStm := tStringStream.create('');\n try\n Stm.Seek(0,soFromBeginning);\n oStrStm.copyfrom(Stm,Stm.Size);\n sTemp := oStrStm.DataString;\n if (Pos('<pre>',sTemp) > 0) and (Pos('</pre>',sTemp) > 0) then\n begin\n delete(sTemp,Pos('<pre>',sTemp),(Pos('</pre>',sTemp)-Pos('<pre>',sTemp))+6);\n oStrStm.free;\n oStrStm := tStringStream.Create(sTemp);\n end;\n Result := tMemoryStream.create;\n oStrStm.Seek(0,soFromBeginning);\n Result.CopyFrom(oStrStm,oStrStm.Size);\n Result.Seek(0,soFromBeginning);\n finally\n oStrStm.free;\n end;\nend;\n"
},
{
"answer_id": 261192,
"author": "Frank Shearar",
"author_id": 10259,
"author_profile": "https://Stackoverflow.com/users/10259",
"pm_score": 0,
"selected": false,
"text": "//pre[1][1]"
},
{
"answer_id": 267277,
"author": "Francesca",
"author_id": 9842,
"author_profile": "https://Stackoverflow.com/users/9842",
"pm_score": 2,
"selected": false,
"text": "// returns position of a string token (its 1st char) into a Stream. 0 if not found\nfunction StreamPos(Token: string; AStream: TStream): Int64;\nvar\n TokenLength: Integer;\n StringToMatch: string;\nbegin\n Result := 0;\n TokenLength := Length(Token);\n if TokenLength > 0 then\n begin\n SetLength(StringToMatch, TokenLength);\n while AStream.Read(StringToMatch[1], 1) > 0 do\n begin\n if (StringToMatch[1] = Token[1]) and\n ((TokenLength = 1) or\n ((AStream.Read(StringToMatch[2], Length(Token)-1) = Length(Token)-1) and\n (Token = StringToMatch))) then\n begin\n Result := AStream.Seek(0, soCurrent) - (Length(Token) - 1); // i.e. AStream.Position - (Length(Token) - 1);\n Break;\n end;\n end;\n end;\nend;\n\n// Returns portion of a stream after the end of a tag delimited header. Works for 1st header.\n// Everything preceding the header is removed too. Returns same stream if no valid header detected.\n// Result is True if valid header found and stream has been filtered.\nfunction FilterBeginStream(const AStartTag, AEndTag: string; const AStreamIn, AStreamOut: TStream): Boolean;\nbegin\n AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;\n Result := (StreamPos(AStartTag, TStream(AStreamIn)) > 0) and (StreamPos(AEndTag, AStreamIn) > 0);\n if Result then\n AStreamOut.CopyFrom(AStreamIn, AStreamIn.Size - AStreamIn.Position)\n else\n AStreamOut.CopyFrom(AStreamIn, 0);\nend;\n\n// Returns a stream after removal of a tag delimited portion. Works for 1st encountered tag.\n// Returns same stream if no valid tag detected.\n// Result is True if valid tag found and stream has been filtered.\nfunction FilterMiddleStream(const AStartTag, AEndTag: string; const AStreamIn, AStreamOut: TStream): Boolean;\nvar\n StartPos, EndPos: Int64;\nbegin\n Result := False;\n AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;\n StartPos := StreamPos(AStartTag, TStream(AStreamIn));\n if StartPos > 0 then\n begin\n EndPos := StreamPos(AEndTag, AStreamIn);\n Result := EndPos > 0;\n end;\n if Result then\n begin\n if StartPos > 1 then\n begin\n AStreamIn.Seek(0, soBeginning); // i.e. AStreamIn.Position := 0;\n AStreamOut.CopyFrom(AStreamIn, StartPos - 1);\n AStreamIn.Seek(EndPos - StartPos + Length(AEndTag), soCurrent);\n end;\n AStreamOut.CopyFrom(AStreamIn, AStreamIn.Size - AStreamIn.Position);\n end\n else\n AStreamOut.CopyFrom(AStreamIn, 0);\nend;\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26207/"
] |
259,166
|
<p>I'm looking for a good open source Windows FTP client library with a public domain or BSD-type license. Something that I have access to the source code and I can use it from C++ for Windows applications in a commercial app.</p>
<p>We have used Wininet for years and it's buggy and horrible. The last straw is the IE8 beta 2 contains a new bug in InternetGetLastResponseInfo(). I can no longer justify using Wininet when our users can install the latest version of IE and break our app.</p>
<p>I have looked at libcurl but it is way too heavy for our needs. The only thing I need is FTP support. I could spend a day stripping out all the code in libcurl I don't need, but I'd rather just start with a nice simple FTP client library, if possible.</p>
<p>I looked at ftplib (<a href="http://nbpfaus.net/~pfau/ftplib/" rel="noreferrer">http://nbpfaus.net/~pfau/ftplib/</a>) but it's GPL and I need this for a closed-source commercial app.</p>
<p>I've written FTP client code before, it's not that hard (unfortunately it was 15 years ago and I don't have the source code anymore). There must be a nice simple free client library that does nothing but FTP and has a license that can be used in closed-source commercial apps. </p>
<p>(If you are curious, the bug is that if you attempt to FtpFindFirstFile() with an FTP site where you can't make a passive-mode connection, InternetGetLastResponseInfo() doesn't return the full response. This is just one of many bugs I've found over the years. Another is that Wininet's FTP support ignores all timeout values. That particular bug has existed for years.)</p>
|
[
{
"answer_id": 259220,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "wget"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24267/"
] |
259,173
|
<p>I have a web login page with the standard username password and login button controls. I would like to write a wrapper page that will render and auto fill the username and login form text boxes with a constant and force the onclick event for login button. Any suggestions how to accomplish this?</p>
|
[
{
"answer_id": 1068842,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "input demo/demo input"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
259,183
|
<p>We have an app in AppStore <a href="http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=292436957" rel="nofollow noreferrer">Bust~A~Spook</a> we had an issue with. When you tap the screen we use CALayer to find the position of all the views during their animation and if you hit one we start a die sequence. However, there is a noticeable delay, it appears as if the touches are buffered and we we receive the event to late. Is there a way to poll or any better way to respond to touches to avoid this lag time?</p>
<p>This is in a UIView not a UIScrollView </p>
|
[
{
"answer_id": 852599,
"author": "Rob Napier",
"author_id": 97337,
"author_profile": "https://Stackoverflow.com/users/97337",
"pm_score": 1,
"selected": false,
"text": "layer touchesBegan:withEvent: UITouchPhaseBegan hitTest: layer"
},
{
"answer_id": 918646,
"author": "Andrew Pouliot",
"author_id": 113455,
"author_profile": "https://Stackoverflow.com/users/113455",
"pm_score": 0,
"selected": false,
"text": "CALayer presentationLayer hitTest:"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
259,212
|
<p>I am trying to find an algorithm to count from 0 to 2<sup>n</sup>-1 but their bit pattern reversed. I care about only n LSB of a word. As you may have guessed I failed.</p>
<p>For n=3: </p>
<pre><code>000 -> 0
100 -> 4
010 -> 2
110 -> 6
001 -> 1
101 -> 5
011 -> 3
111 -> 7
</code></pre>
<p>You get the idea.</p>
<p>Answers in pseudo-code is great. Code fragments in any language are welcome, answers without bit operations are preferred.</p>
<p>Please don't just post a fragment without even a short explanation or a pointer to a source.</p>
<p>Edit: I forgot to add, I already have a naive implementation which just bit-reverses a count variable. In a sense, this method is not really counting.</p>
|
[
{
"answer_id": 259246,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 2,
"selected": false,
"text": "int incrementBizarre(int initial, int nBits)\n // in the 3 bit example, this should create 100\n mask=2^(nBits-1)\n // This should only return true if the first (least significant) bit is not set\n // if initial is 011 and mask is 100\n // 3 4, bit is not set\n if(initial < mask)\n // If it was not, just set it and bail.\n return initial+ mask // 011 (3) + 100 (4) = 111 (7)\n else\n // it was set, are we at the most significant bit yet?\n // mask 100 (4) / 2 = 010 (2), 001/2 = 0 indicating overflow\n if(mask / 2) > 0\n // No, we were't, so unset it (initial-mask) and increment the next bit\n return incrementBizarre(initial - mask, mask/2)\n else\n // Whoops we were at the most significant bit. Error condition\n throw new OverflowedMyBitsException()\n mask 100 (4), initial 110 (6); initial < mask=false; initial-mask = 010 (2), now try on the next bit\nmask 010 (2), initial 010 (2); initial < mask=false; initial-mask = 000 (0), now inc the next bit\nmask 001 (1), initial 000 (0); initial < mask=true; initial + mask = 001--correct answer\n"
},
{
"answer_id": 259254,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 0,
"selected": false,
"text": "void reverse(int nMaxVal, int nBits)\n{\n int thisVal, bit, out;\n\n // Calculate for each value from 0 to nMaxVal.\n for (thisVal=0; thisVal<=nMaxVal; ++thisVal)\n {\n out = 0;\n\n // Shift each bit from thisVal into out, in reverse order.\n for (bit=0; bit<nBits; ++bit)\n out = (out<<1) + ((thisVal>>bit) & 1)\n\n }\n printf(\"%d -> %d\\n\", thisVal, out);\n}\n"
},
{
"answer_id": 259258,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": true,
"text": " unsigned int i;\n i = (i & 0x55555555) << 1 | (i & 0xaaaaaaaa) >> 1;\n i = (i & 0x33333333) << 2 | (i & 0xcccccccc) >> 2;\n i = (i & 0x0f0f0f0f) << 4 | (i & 0xf0f0f0f0) >> 4;\n i = (i & 0x00ff00ff) << 8 | (i & 0xff00ff00) >> 8;\n i = (i & 0x0000ffff) << 16 | (i & 0xffff0000) >> 16;\n i >>= (32 - n);\n"
},
{
"answer_id": 259319,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "~value"
},
{
"answer_id": 259653,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 0,
"selected": false,
"text": "sub reverse_increment {\n my($n, $bits) = @_;\n\n my $carry = 2**$bits;\n while($carry > 1) {\n $carry /= 2;\n if($carry > $n) {\n return $carry + $n;\n } else {\n $n -= $carry;\n }\n }\n return 0;\n}\n"
},
{
"answer_id": 259666,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 0,
"selected": false,
"text": "(defun inv-step (x n) ; the following is a function declaration\n \"returns a bit-inverse step of x, bounded by 2^n\" ; documentation\n (do ((i (expt 2 (- n 1)) ; loop, init of i\n (/ i 2)) ; stepping of i\n (s x)) ; init of s as x\n ((not (integerp i)) ; breaking condition\n s) ; returned value if all bits are 1 (is 0 then)\n (if (< s i) ; the loop's body: if s < i\n (return-from inv-step (+ s i)) ; -> add i to s and return the result\n (decf s i)))) ; else: reduce s by i\n (defun inv-step (x n)\n (let ((i (expt 2 (- n 1))))\n (cond ((= n 1)\n (if (zerop x) 1 0)) ; this is really (logxor x 1) \n ((< x i)\n (+ x i))\n (t\n (inv-step (- x i) (- n 1))))))\n"
},
{
"answer_id": 259727,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 0,
"selected": false,
"text": "#define FLIP(x, i) do { (x) ^= (1 << (i)); } while(0)\n\nint main() {\n int n = 3;\n int max = (1 << n);\n int x = 0;\n\n for(int i = 1; i <= max; ++i) {\n std::cout << x << std::endl;\n /* if n == 3, this next part is functionally equivalent to this:\n *\n * if((i % 1) == 0) FLIP(x, n - 1);\n * if((i % 2) == 0) FLIP(x, n - 2);\n * if((i % 4) == 0) FLIP(x, n - 3);\n */\n for(int j = 0; j < n; ++j) {\n if((i % (1 << j)) == 0) FLIP(x, n - (j + 1));\n } \n }\n}\n"
},
{
"answer_id": 14416167,
"author": "vaishuraj",
"author_id": 1993166,
"author_profile": "https://Stackoverflow.com/users/1993166",
"pm_score": 0,
"selected": false,
"text": "0 to 2^n-1 0-2^n-1 Sum = 2^n * (2^n+1)/2\n O(1)"
},
{
"answer_id": 45531406,
"author": "eXtranium",
"author_id": 8424358,
"author_profile": "https://Stackoverflow.com/users/8424358",
"pm_score": 0,
"selected": false,
"text": "function RevSum ($a,$b) {\n\n // loop until our adder, $b, is zero\n while ($b) {\n\n // get carry (aka overflow) bit for every bit-location by AND-operation\n // 0 + 0 --> 00 no overflow, carry is \"0\"\n // 0 + 1 --> 01 no overflow, carry is \"0\"\n // 1 + 0 --> 01 no overflow, carry is \"0\"\n // 1 + 1 --> 10 overflow! carry is \"1\"\n\n $c = $a & $b;\n\n\n // do 1-bit addition for every bit location at once by XOR-operation\n // 0 + 0 --> 00 result = 0\n // 0 + 1 --> 01 result = 1\n // 1 + 0 --> 01 result = 1\n // 1 + 1 --> 10 result = 0 (ignored that \"1\", already taken care above)\n\n $a ^= $b;\n\n\n // now: shift carry bits to the next bit-locations to be added to $a in\n // next iteration.\n // PHP_INT_MAX here is used to ensure that the most-significant bit of the\n // $b will be cleared after shifting. see link in the side note below.\n\n $b = ($c >> 1) & PHP_INT_MAX;\n\n }\n\n return $a;\n}\n $value = 0;\n$add = 0x80; // 10000000 <-- \"one\" as bit reversed\n\nfor ($count = 20; $count--;) { // loop 20 times\n printf(\"%08b\\n\", $value); // show value as 8-bit binary\n $value = RevSum($value, $add); // do addition\n}\n 00000000\n 10000000\n 01000000\n 11000000\n 00100000\n 10100000\n 01100000\n 11100000\n 00010000\n 10010000\n 01010000\n 11010000\n 00110000\n 10110000\n 01110000\n 11110000\n 00001000\n 10001000\n 01001000\n 11001000\n"
},
{
"answer_id": 45531781,
"author": "nwellnhof",
"author_id": 1956010,
"author_profile": "https://Stackoverflow.com/users/1956010",
"pm_score": 2,
"selected": false,
"text": "nnnn0111 nnnn1000 __builtin_ctz void iter_reversed(unsigned bits) {\n unsigned n = 1 << bits;\n\n for (unsigned i = 0, j = 0; i < n; i++) {\n printf(\"%x\\n\", j);\n\n // Compute a mask of LSBs.\n unsigned mask = i ^ (i + 1);\n // Length of the mask.\n unsigned len = __builtin_ctz(~mask);\n // Align the mask to MSB of n.\n mask <<= bits - len;\n // XOR with mask.\n j ^= mask;\n }\n}\n void iter_reversed(unsigned bits) {\n unsigned n = 1 << bits;\n\n for (unsigned i = 0, j = 0; i < n; i++) {\n printf(\"%x\\n\", j);\n\n // Find least significant zero bit.\n unsigned bit = ~i & (i + 1);\n // Using division to bit-reverse a single bit.\n unsigned rev = (n / 2) / bit;\n // XOR with mask.\n j ^= (n - 1) & ~(rev - 1);\n }\n}\n"
},
{
"answer_id": 59217692,
"author": "Marek Basovník",
"author_id": 5767740,
"author_profile": "https://Stackoverflow.com/users/5767740",
"pm_score": 0,
"selected": false,
"text": "#include <intrin.h>\nunsigned __int64 reversed_increment(unsigned __int64 number) \n{\n unsigned long index, result;\n _BitScanReverse64(&index, ~number); // returns index of the highest '1' on bit-reverse number (trick to find the highest '0')\n result = _bzhi_u64(number, index); // set to '0' all bits at number higher than index position\n result |= (unsigned __int64) 1 << index; // changes to '1' bit on index position\n return result;\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7988/"
] |
259,219
|
<p>On Linq to SQL's DataContext I am able to call SubmitChanges() to submit all changes.</p>
<p>What I want is to somehow reject all changes in the datacontext and rollback all changes (preferable without going to the database).</p>
<p>Is this possible?</p>
|
[
{
"answer_id": 259300,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 2,
"selected": false,
"text": "dataContext.Refresh(RefreshMode.OverwriteCurrentValues, someObject);\n"
},
{
"answer_id": 1239649,
"author": "Alexander Zwitbaum",
"author_id": 104930,
"author_profile": "https://Stackoverflow.com/users/104930",
"pm_score": 5,
"selected": true,
"text": "db.GetChangeSet().Updates.Clear() db.GetChangeSet().Inserts.Clear() db.GetChangeSet().Deletes.Clear()"
},
{
"answer_id": 2140036,
"author": "Theodore Zographos",
"author_id": 320229,
"author_profile": "https://Stackoverflow.com/users/320229",
"pm_score": 2,
"selected": false,
"text": "foreach (Customer c in MyDBContext.GetChangeSet().Updates)\n {\n MyDBContext.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, c);\n }\n"
},
{
"answer_id": 13057517,
"author": "Scott",
"author_id": 68043,
"author_profile": "https://Stackoverflow.com/users/68043",
"pm_score": 1,
"selected": false,
"text": "Public Sub DiscardInsertsAndDeletes(ByVal data As DataContext)\n ' Get the changes\n Dim changes = data.GetChangeSet()\n\n ' Delete the insertions\n For Each insertion In changes.Inserts\n data.GetTable(insertion.GetType).DeleteOnSubmit(insertion)\n Next\n\n ' Insert the deletions\n For Each deletion In changes.Deletes\n data.GetTable(deletion.GetType).InsertOnSubmit(deletion)\n Next\nEnd Sub\n\nPublic Sub DiscardUpdates(ByVal data As DataContext)\n ' Get the changes\n Dim changes = data.GetChangeSet()\n\n ' Refresh the tables with updates\n Dim updatedTables As New List(Of ITable)\n For Each update In changes.Updates\n Dim tbl = data.GetTable(update.GetType)\n ' Make sure not to refresh the same table twice\n If updatedTables.Contains(tbl) Then\n Continue For\n Else\n updatedTables.Add(tbl)\n data.Refresh(RefreshMode.OverwriteCurrentValues, tbl)\n End If\n Next\nEnd Sub\n"
},
{
"answer_id": 19019628,
"author": "Teddy",
"author_id": 1242114,
"author_profile": "https://Stackoverflow.com/users/1242114",
"pm_score": 4,
"selected": false,
"text": "public static class DataContextExtensions\n{\n /// <summary>\n /// Discard all pending changes of current DataContext.\n /// All un-submitted changes, including insert/delete/modify will lost.\n /// </summary>\n /// <param name=\"context\"></param>\n public static void DiscardPendingChanges(this DataContext context)\n {\n context.RefreshPendingChanges(RefreshMode.OverwriteCurrentValues);\n ChangeSet changeSet = context.GetChangeSet();\n if (changeSet != null)\n {\n //Undo inserts\n foreach (object objToInsert in changeSet.Inserts)\n {\n context.GetTable(objToInsert.GetType()).DeleteOnSubmit(objToInsert);\n }\n //Undo deletes\n foreach (object objToDelete in changeSet.Deletes)\n {\n context.GetTable(objToDelete.GetType()).InsertOnSubmit(objToDelete);\n }\n }\n }\n\n /// <summary>\n /// Refreshes all pending Delete/Update entity objects of current DataContext according to the specified mode.\n /// Nothing will do on Pending Insert entity objects.\n /// </summary>\n /// <param name=\"context\"></param>\n /// <param name=\"refreshMode\">A value that specifies how optimistic concurrency conflicts are handled.</param>\n public static void RefreshPendingChanges(this DataContext context, RefreshMode refreshMode)\n {\n ChangeSet changeSet = context.GetChangeSet();\n if (changeSet != null)\n {\n context.Refresh(refreshMode, changeSet.Deletes);\n context.Refresh(refreshMode, changeSet.Updates);\n }\n }\n}\n"
},
{
"answer_id": 20427609,
"author": "Kyght",
"author_id": 1636133,
"author_profile": "https://Stackoverflow.com/users/1636133",
"pm_score": 1,
"selected": false,
"text": "var changes = db.GetChangeSet();\nif ((changes.Updates.Count > 0) || (changes.Inserts.Count > 0) || (changes.Deletes.Count > 0))\n{\n if (MessageBox.Show(\"Would you like to save changes?\", \"Save Changes\", MessageBoxButton.YesNo) == MessageBoxResult.Yes)\n {\n db.SubmitChanges();\n } else\n {\n //Rollback Changes\n foreach (object objToInsert in changes.Inserts)\n {\n db.GetTable(objToInsert.GetType()).DeleteOnSubmit(objToInsert);\n }\n foreach (object objToDelete in changes.Deletes)\n {\n db.GetTable(objToDelete.GetType()).InsertOnSubmit(objToDelete);\n }\n foreach (object objToUpdate in changes.Updates)\n {\n db.Refresh(RefreshMode.OverwriteCurrentValues, objToUpdate);\n }\n CurrentForm.SetObject(null); //Application Code to Clear active form\n RefreshList(); //Application Code to Refresh active list\n }\n}\n"
},
{
"answer_id": 39515355,
"author": "M Moore",
"author_id": 5190423,
"author_profile": "https://Stackoverflow.com/users/5190423",
"pm_score": 0,
"selected": false,
"text": " public static bool UndoPendingChanges(this NtsSuiteDataContext dbContext)\n {\n if (dbContext.ChangesPending())\n {\n ChangeSet dbChangeSet = dbContext.GetChangeSet();\n\n dbContext.Refresh(RefreshMode.OverwriteCurrentValues, dbChangeSet.Deletes);\n dbContext.Refresh(RefreshMode.OverwriteCurrentValues, dbChangeSet.Updates);\n\n //Undo Inserts\n foreach (object objToInsert in dbChangeSet.Inserts)\n {\n dbContext.GetTable(objToInsert.GetType()).DeleteOnSubmit(objToInsert);\n }\n\n //Undo deletes\n foreach (object objToDelete in dbChangeSet.Deletes)\n {\n dbContext.GetTable(objToDelete.GetType()).InsertOnSubmit(objToDelete);\n }\n }\n\n return true;\n }\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8547/"
] |
259,234
|
<p>How do I run a function on a loop so all the results go straight into a list and is there a way to run a function which acts on all the values in a list?</p>
|
[
{
"answer_id": 259259,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": ">>> def square(x):\n... return x*x\n...\n>>> a = [1,2,3,4,5,6,7,8,9]\n\n>>> map(square,a)\n[1, 4, 9, 16, 25, 36, 49, 64, 81]\n"
},
{
"answer_id": 259260,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 1,
"selected": false,
"text": "new_list= [yourfunction(item) for item in a_sequence]\n def yourfunction(sequence):\n for item in sequence:\n …\n yourfunction(range(10))\nyourfunction(\"a string\")\n"
},
{
"answer_id": 259266,
"author": "gone",
"author_id": 26880,
"author_profile": "https://Stackoverflow.com/users/26880",
"pm_score": 4,
"selected": true,
"text": "test = list('asdf')\n[function(x) for x in test]\n test = list('asdf')\nmap(function, test)\n map"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33061/"
] |
259,240
|
<p>I'm just getting back into C++ after a couple of years of doing a lot of C#, and recently Objective C.</p>
<p>One thing I've done before is to roll my own iterator adapter for std::map that will deref to just the value part, rather than the key-value pair. This is quite a common and natural thing to do. C# provides this facility with its Keys and Values properties of its Dictionary class. Objective-C's NSDictionary, similarly, has allKeys and allValues.</p>
<p>Since I've been "away", Boost has acquired the Range and ForEach libraries, which I am now using extensively. I wondered if between the two there was some facility to do the same, but I haven't been able to find anything.</p>
<p>I'm thinking of knocking something up using Boost's iterator adapters, but before I go down that route I thought I'd ask here if anyone knows of such a facility in Boost, or somewhere else ready made?</p>
|
[
{
"answer_id": 259377,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 5,
"selected": true,
"text": "template<typename T1, typename T2> T2& take_second(const std::pair<T1, T2> &a_pair) \n{\n return a_pair.second;\n}\n\nvoid run_map_value()\n{\n map<int,string> a_map;\n a_map[0] = \"zero\";\n a_map[1] = \"one\";\n a_map[2] = \"two\";\n copy( boost::make_transform_iterator(a_map.begin(), take_second<int, string>),\n boost::make_transform_iterator(a_map.end(), take_second<int, string>),\n ostream_iterator<string>(cout, \"\\n\")\n );\n}\n"
},
{
"answer_id": 2316626,
"author": "klaus triendl",
"author_id": 279251,
"author_profile": "https://Stackoverflow.com/users/279251",
"pm_score": 3,
"selected": false,
"text": "namespace detail\n{\n\ntemplate<bool IsConst, bool IsVolatile, typename T>\nstruct add_cv_if_c\n{\n typedef T type;\n};\ntemplate<typename T>\nstruct add_cv_if_c<true, false, T>\n{\n typedef const T type;\n};\ntemplate<typename T>\nstruct add_cv_if_c<false, true, T>\n{\n typedef volatile T type;\n};\ntemplate<typename T>\nstruct add_cv_if_c<true, true, T>\n{\n typedef const volatile T type;\n};\n\ntemplate<typename TestConst, typename TestVolatile, typename T>\nstruct add_cv_if: public add_cv_if_c<TestConst::value, TestVolatile::value, T>\n{};\n\n} // namespace detail\n\n\n/** An unary function that accesses the member of class T specified in the MemberPtr template parameter.\n\n The cv-qualification of T is preserved for MemberType\n */\ntemplate<typename T, typename MemberType, MemberType T::*MemberPtr>\nstruct access_member_f\n{\n // preserve cv-qualification of T for T::second_type\n typedef typename detail::add_cv_if<\n std::tr1::is_const<T>, \n std::tr1::is_volatile<T>, \n MemberType\n >::type& result_type;\n\n result_type operator ()(T& t) const\n {\n return t.*MemberPtr;\n }\n};\n\n/** @short An iterator adaptor accessing the member called 'second' of the class the \n iterator is pointing to.\n */\ntemplate<typename Iterator>\nclass accessing_second_iterator: public \n boost::transform_iterator<\n access_member_f<\n // note: we use the Iterator's reference because this type \n // is the cv-qualified iterated type (as opposed to value_type).\n // We want to preserve the cv-qualification because the iterator \n // might be a const_iterator e.g. iterating a const \n // std::pair<> but std::pair<>::second_type isn't automatically \n // const just because the pair is const - access_member_f is \n // preserving the cv-qualification, otherwise compiler errors will \n // be the result\n typename std::tr1::remove_reference<\n typename std::iterator_traits<Iterator>::reference\n >::type, \n typename std::iterator_traits<Iterator>::value_type::second_type, \n &std::iterator_traits<Iterator>::value_type::second\n >, \n Iterator\n >\n{\n typedef boost::transform_iterator<\n access_member_f<\n typename std::tr1::remove_reference<\n typename std::iterator_traits<Iterator>::reference\n >::type, \n typename std::iterator_traits<Iterator>::value_type::second_type, \n &std::iterator_traits<Iterator>::value_type::second\n >, \n Iterator\n > baseclass;\n\npublic:\n accessing_second_iterator(): \n baseclass()\n {}\n\n // note: allow implicit conversion from Iterator\n accessing_second_iterator(Iterator it): \n baseclass(it)\n {}\n};\n void run_map_value()\n{\n typedef map<int, string> a_map_t;\n a_map_t a_map;\n a_map[0] = \"zero\";\n a_map[1] = \"one\";\n a_map[2] = \"two\";\n\n typedef accessing_second_iterator<a_map_t::const_iterator> ia_t;\n // note: specify the iterator adaptor type explicitly as template type, enabling \n // implicit conversion from begin()/end()\n copy<ia_t>(a_map.begin(), a_map.end(),\n ostream_iterator<string>(cout, \"\\n\")\n );\n}\n"
},
{
"answer_id": 15143836,
"author": "Kibbick",
"author_id": 837030,
"author_profile": "https://Stackoverflow.com/users/837030",
"pm_score": 3,
"selected": false,
"text": "int main(int argc, const char* argv[])\n{\n using namespace boost::assign;\n using namespace boost::adaptors;\n\n std::map<int,int> input;\n for (int i = 0; i < 10; ++i)\n input.insert(std::make_pair(i, i * 10));\n\n boost::copy(\n input | map_values,\n std::ostream_iterator<int>(std::cout, \",\"));\n\n return 0;\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32136/"
] |
259,248
|
<p>I would like to include a different file depending on the version of GCC. More precisely I want to write:</p>
<pre><code>#if GCC_VERSION >= 4.2
# include <unordered_map>
# define EXT std
#elif GCC_VERSION >= 4
# include <tr1/unordered_map>
# define EXT std
#else
# include <ext/hash_map>
# define unordered_map __gnu_cxx::hash_map
# define EXT __gnu_cxx
#endif
</code></pre>
<p>I don't care about gcc before 3.2.</p>
<p>I am pretty sure there is a variable defined at preprocessing time for that, I just can't find it again.</p>
|
[
{
"answer_id": 259277,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 6,
"selected": false,
"text": "__GNUC__ // major\n__GNUC_MINOR__ // minor\n__GNUC_PATCHLEVEL__ // patch\n"
},
{
"answer_id": 259279,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 6,
"selected": true,
"text": "__GNUC_PREREQ features.h #ifdef __GNUC__\n# include <features.h>\n# if __GNUC_PREREQ(4,0)\n// If gcc_version >= 4.0\n# elif __GNUC_PREREQ(3,2)\n// If gcc_version >= 3.2\n# else\n// Else\n# endif\n#else\n// If not gcc\n#endif\n"
},
{
"answer_id": 259383,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 5,
"selected": false,
"text": "g++ -E -dM t.cpp"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7136/"
] |
259,253
|
<p>What are the API calls to copy a file that is currently locked. I'm hoping to be able to use .Net, but Win32 calls would be fine as well. </p>
<p>Please feel free to chime in about the same functionality on Unix, or any other OS.</p>
|
[
{
"answer_id": 259262,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 3,
"selected": false,
"text": "MoveFileEx MOVEFILE_DELAY_UNTIL_REBOOT"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/415/"
] |
259,269
|
<p>I have a loop that reads each line in a file using <code>getline()</code>:</p>
<pre><code>istream is;
string line;
while (!getline(is, line).eof())
{
// ...
}
</code></pre>
<p>I noticed that calling <code>getline()</code> like this also seems to work:</p>
<pre><code>while (getline(is, line))
</code></pre>
<p>What's going on here? <code>getline()</code> returns a stream reference. Is it being converted to a pointer somehow? Is this actually a good practice or should I stick to the first form?</p>
|
[
{
"answer_id": 259286,
"author": "Charles Anderson",
"author_id": 11677,
"author_profile": "https://Stackoverflow.com/users/11677",
"pm_score": 6,
"selected": true,
"text": "istream getline() void*() eof()"
},
{
"answer_id": 259430,
"author": "Luc Hermitte",
"author_id": 15934,
"author_profile": "https://Stackoverflow.com/users/15934",
"pm_score": 3,
"selected": false,
"text": "std::basic_ios::operator void*() sentry::operator bool() std::getline() std::basic_istream std::basic_ios fail() xxx.good() !xxx.fail()"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086/"
] |
259,290
|
<p><a href="http://biochrom.fivesite.co.uk/catalogue4.asp" rel="nofollow noreferrer">http://biochrom.fivesite.co.uk/catalogue4.asp</a></p>
<p>On the page above there is an image floated to the left. To the right of it is a list, titled "features". The list items have a background image, however, it isn't appearing. List 2 shows how the background image looks.</p>
<p>Does anyone know how I can make the bullets visible?</p>
|
[
{
"answer_id": 259305,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 3,
"selected": true,
"text": "margin-left:200px;\n clear:both\n"
},
{
"answer_id": 1907977,
"author": "Helping Others",
"author_id": 232165,
"author_profile": "https://Stackoverflow.com/users/232165",
"pm_score": 3,
"selected": false,
"text": "overflow:hidden;\n"
},
{
"answer_id": 5928033,
"author": "onearmfrog",
"author_id": 743956,
"author_profile": "https://Stackoverflow.com/users/743956",
"pm_score": 2,
"selected": false,
"text": "display: inline-block;\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10023/"
] |
259,293
|
<p>WPF's view model oriented way of doing things makes it very tempting to just use business objects in the UI. Have you seen any issues with this? Why or why wouldn't you do this?</p>
|
[
{
"answer_id": 259405,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "ToString DataTemplate IValueConverter"
},
{
"answer_id": 259555,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 1,
"selected": false,
"text": "DependencyObject Data\n Binding System.Windows DependencyObjects INotifyPropertyChanged System.Windows System.ComponentModel why you should why should you not"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9401/"
] |
259,297
|
<p>I have an array of values that is passed to my function from a different part of the program that I need to store for later processing. Since I don't know how many times my function will be called before it is time to process the data, I need a dynamic storage structure, so I chose a <code>std::vector</code>. I don't want to have to do the standard loop to <code>push_back</code> all the values individually, it would be nice if I could just copy it all using something similar to <code>memcpy</code>.</p>
|
[
{
"answer_id": 259312,
"author": "bsruth",
"author_id": 23504,
"author_profile": "https://Stackoverflow.com/users/23504",
"pm_score": 4,
"selected": false,
"text": "int foo(int* data, int size)\n{\n static std::vector<int> my_data; //normally a class variable\n std::copy(data, data + size, std::back_inserter(my_data));\n return 0;\n}\n vector<int> x(size);\nmemcpy(&x[0], source, size*sizeof(int));\n"
},
{
"answer_id": 259316,
"author": "Thomas Jones-Low",
"author_id": 23030,
"author_profile": "https://Stackoverflow.com/users/23030",
"pm_score": 0,
"selected": false,
"text": "std::vector<int> myArray;\nmyArray.resize (item_count, 0);\nmemcpy (&myArray.front(), source, item_count * sizeof(int));\n"
},
{
"answer_id": 259379,
"author": "Drew Hall",
"author_id": 23934,
"author_profile": "https://Stackoverflow.com/users/23934",
"pm_score": 8,
"selected": true,
"text": "std::vector<ValueType> vec(a, a + n);\n a n std::copy() resize() memcpy() begin() ptr + n end()"
},
{
"answer_id": 259381,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 6,
"selected": false,
"text": "std::vector<int> data; // evil global :)\n\nvoid CopyData(int *newData, size_t count)\n{\n data.assign(newData, newData + count);\n}\n"
},
{
"answer_id": 259580,
"author": "Shane Powell",
"author_id": 23235,
"author_profile": "https://Stackoverflow.com/users/23235",
"pm_score": 2,
"selected": false,
"text": "vector<int> x;\n\nvoid AddValues(int* values, size_t size)\n{\n x.insert(x.end(), values, values+size);\n}\n vector<int> x;\n\nvoid AddValues(int* values, size_t size)\n{\n size_t old_size(x.size());\n x.resize(old_size + size, 0);\n memcpy(&x[old_size], values, size * sizeof(int));\n}\n"
},
{
"answer_id": 261607,
"author": "MattyT",
"author_id": 7405,
"author_profile": "https://Stackoverflow.com/users/7405",
"pm_score": 8,
"selected": false,
"text": "vector<int> dataVec;\n\nint dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\nunsigned dataArraySize = sizeof(dataArray) / sizeof(int);\n\n// Method 1: Copy the array to the vector using back_inserter.\n{\n copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));\n}\n\n// Method 2: Same as 1 but pre-extend the vector by the size of the array using reserve\n{\n dataVec.reserve(dataVec.size() + dataArraySize);\n copy(&dataArray[0], &dataArray[dataArraySize], back_inserter(dataVec));\n}\n\n// Method 3: Memcpy\n{\n dataVec.resize(dataVec.size() + dataArraySize);\n memcpy(&dataVec[dataVec.size() - dataArraySize], &dataArray[0], dataArraySize * sizeof(int));\n}\n\n// Method 4: vector::insert\n{\n dataVec.insert(dataVec.end(), &dataArray[0], &dataArray[dataArraySize]);\n}\n\n// Method 5: vector + vector\n{\n vector<int> dataVec2(&dataArray[0], &dataArray[dataArraySize]);\n dataVec.insert(dataVec.end(), dataVec2.begin(), dataVec2.end());\n}\n vector<char> v(50); // Ensure there's enough space\nstrcpy(&v[0], \"prefer vectors to c arrays\");\n"
},
{
"answer_id": 42535004,
"author": "Antonio Ramasco",
"author_id": 7642034,
"author_profile": "https://Stackoverflow.com/users/7642034",
"pm_score": 2,
"selected": false,
"text": "int dataArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };//source\n\nunsigned dataArraySize = sizeof(dataArray) / sizeof(int);\n\nstd::vector<int> myvector (dataArraySize );//target\n\nstd::copy ( myints, myints+dataArraySize , myvector.begin() );\n\n//myvector now has 1,2,3,...10 :-)\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259297",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23504/"
] |
259,309
|
<p>Is there a way using JSF to group two or more columns under a single parent column in JSF? I have a dataTableEx with hx:columnEx columns inside of it. What I want is something like this:</p>
<pre><code> [MAIN HEADER FOR COL1+2 ][Header for Col 3+4]
[ COL1 Header][COL2 Header][COL3 ][COL 4 ]
Data Data Data Data
Data Data Data Data
Data Data Data Data
Data Data Data Data
</code></pre>
<p>Data Data Data Data</p>
<p>Thanks</p>
|
[
{
"answer_id": 265964,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 2,
"selected": true,
"text": "<style type=\"text/css\">\n.colstyle {\n width: 25%\n}\n</style>\n</head>\n<body>\n\n<f:view>\n <h:dataTable border=\"1\" value=\"#{columnsBean.rows}\" var=\"row\"\n columnClasses=\"colstyle\">\n <f:facet name=\"header\">\n <h:panelGrid columns=\"2\" border=\"1\" style=\"width: 100%\">\n <h:outputLabel style=\"width: 100%\" value=\"MAIN HEADER FOR COL1+2\" />\n <h:outputLabel style=\"width: 100%\" value=\"MAIN HEADER FOR COL3+4\" />\n </h:panelGrid>\n </f:facet>\n <h:column>\n <f:facet name=\"header\">\n <h:outputText value=\"COL1 Header\" />\n </f:facet>\n <h:outputLabel value=\"#{row.col1}\" />\n </h:column>\n <h:column>\n <f:facet name=\"header\">\n <h:outputText value=\"COL2 Header\" />\n </f:facet>\n <h:outputLabel value=\"#{row.col2}\" />\n </h:column>\n <h:column>\n <f:facet name=\"header\">\n <h:outputText value=\"COL3 Header\" />\n </f:facet>\n <h:outputLabel value=\"#{row.col3}\" />\n </h:column>\n <h:column>\n <f:facet name=\"header\">\n <h:outputText value=\"COL4 Header\" />\n </f:facet>\n <h:outputLabel value=\"#{row.col4}\" />\n </h:column>\n </h:dataTable>\n</f:view>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32812/"
] |
259,311
|
<p>I am working in Visual Studio 2008 on an ASP.NET application, which has been deployed to a test server. I would like to make a build without debug information to place in production, but the configuration manager only shows "Debug" in the configuration dropdown for my project.</p>
<p>My other Visual Studio projects show "Debug", "Release", "New...", and "Edit...".</p>
<p>Why do I not see a release option, or the new and edit commands?</p>
|
[
{
"answer_id": 260921,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 0,
"selected": false,
"text": "GlobalSection(SolutionConfigurationPlatforms) = preSolution\n Debug|Any CPU = Debug|Any CPU\n Release|Any CPU = Release|Any CPU\nEndGlobalSection\nGlobalSection(ProjectConfigurationPlatforms) = postSolution\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.Build.0 = Debug|Any CPU\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Release|Any CPU.ActiveCfg = Release|Any CPU\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Release|Any CPU.Build.0 = Release|Any CPU\nEndGlobalSection\n GlobalSection(SolutionConfigurationPlatforms) = preSolution\n Debug|Any CPU = Debug|Any CPU\nEndGlobalSection\nGlobalSection(ProjectConfigurationPlatforms) = postSolution\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.Build.0 = Debug|Any CPU\nEndGlobalSection\n"
},
{
"answer_id": 334736,
"author": "Keith Walton",
"author_id": 22448,
"author_profile": "https://Stackoverflow.com/users/22448",
"pm_score": 6,
"selected": true,
"text": "web.config web.config <!--\n Set compilation debug=\"true\" to insert debugging\n symbols into the compiled page. Because this\n affects performance, set this value to true only\n during development.\n-->\n\n<compilation debug=\"true\">\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259311",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21253/"
] |
259,320
|
<p>I'm still learning Grails and seem to have hit a stumbling block.</p>
<p><strong>Here are the 2 domain classes:</strong></p>
<pre><code>class Photo {
byte[] file
static belongsTo = Profile
}
class Profile {
String fullName
Set photos
static hasMany = [photos:Photo]
}
</code></pre>
<p><strong>The relevant controller snippet:</strong> </p>
<pre><code>class PhotoController {
def viewImage = {
def photo = Photo.get( params.id )
byte[] image = photo.file
response.outputStream << image
}
}
</code></pre>
<p><strong>Finally the GSP snippet:</strong></p>
<pre><code><img class="Photo" src="${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}" />
</code></pre>
<p>Now how do I access the photo so that it will be shown on the GSP? I'm pretty sure that
<code>profileInstance.photos.get(1).id</code> is not correct.</p>
|
[
{
"answer_id": 259361,
"author": "Hates_",
"author_id": 3410,
"author_profile": "https://Stackoverflow.com/users/3410",
"pm_score": 3,
"selected": true,
"text": "profileInstance.photos.toArray()[0].id\n profileInstance.photos.iterator().next()\n"
},
{
"answer_id": 260022,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 0,
"selected": false,
"text": "response.ContentType = \"image/jpeg\"\n"
},
{
"answer_id": 275877,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 2,
"selected": false,
"text": " def viewImage= {\n //retrieve photo code here\n response.setHeader(\"Content-disposition\", \"attachment; filename=${photo.name}\")\n response.contentType = photo.fileType //'image/jpeg' will do too\n response.outputStream << photo.file //'myphoto.jpg' will do too\n response.outputStream.flush()\n return;\n }\n"
},
{
"answer_id": 9901244,
"author": "stitakis",
"author_id": 704264,
"author_profile": "https://Stackoverflow.com/users/704264",
"pm_score": 1,
"selected": false,
"text": "<img class=\"Photo\" src=\"${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}\" />\n <img class=\"Photo\" src=\"${createLink(controller:'photo', action:'viewImage', id:\"profileInstance.photos.get(1).id\")}\" />\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27163/"
] |
259,330
|
<p>I've been adding css support for <strong>handheld</strong> to my website but haven't been able to find a good tool for testing. </p>
<p>I tried using the webdeveloper plugin for Firefox but it doesn't work for me. Maybe that is because all my css is in the html and not a seperate css file.</p>
<p>Are there any other testing tools available aside from going out and buying a handheld device?</p>
|
[
{
"answer_id": 996820,
"author": "ilya n.",
"author_id": 115200,
"author_profile": "https://Stackoverflow.com/users/115200",
"pm_score": 3,
"selected": false,
"text": " @media handheld, screen and (max-width: 500px) { /* your css */ }\n"
},
{
"answer_id": 6344160,
"author": "Fordnox",
"author_id": 341590,
"author_profile": "https://Stackoverflow.com/users/341590",
"pm_score": 1,
"selected": false,
"text": "<!-- <link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"screen.css\" /> -->\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen,handheld\" href=\"handheld.css\" />\n"
},
{
"answer_id": 6374477,
"author": "Smashing Ninja",
"author_id": 801783,
"author_profile": "https://Stackoverflow.com/users/801783",
"pm_score": 0,
"selected": false,
"text": "handheld.css mediatype=\"screen\""
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
259,343
|
<p>Is there any way to reboot the JVM? As in don't actually exit, but close and reload all classes, and run main from the top?</p>
|
[
{
"answer_id": 259464,
"author": "Andru Luvisi",
"author_id": 5922,
"author_profile": "https://Stackoverflow.com/users/5922",
"pm_score": 5,
"selected": true,
"text": "#!/bin/sh\nwhile true\ndo\n java MainClass\ndone\n #!/bin/sh\nSTATUS=0\nwhile [ $STATUS -eq 0 ]\ndo\n java MainClass\n STATUS=$?\ndone\n"
},
{
"answer_id": 23980517,
"author": "2xsaiko",
"author_id": 3074505,
"author_profile": "https://Stackoverflow.com/users/3074505",
"pm_score": 0,
"selected": false,
"text": "restartMinecraft(getCommandLineArgs());\n public static boolean isProcessExited(Process p) {\n try {\n p.exitValue();\n } catch (IllegalThreadStateException e) {\n return false;\n }\n return true;\n}\n public static void restartMinecraft(String args) throws IOException, InterruptedException {\n//Here you can do shutdown code etc\n Process p = Runtime.getRuntime().exec(args);\n RunnableWithObject<Process> inputStreamPrinter = new RunnableWithObject<Process>() {\n\n @Override\n public void run() {\n // TODO Auto-generated method stub\n while (!Tools.isProcessExited(data)) {\n try {\n while (data.getInputStream().available() > 0) {\n System.out.print((char) data.getInputStream().read());\n }\n } catch (IOException e) {\n }\n }\n }\n };\n RunnableWithObject<Process> errorStreamPrinter = new RunnableWithObject<Process>() {\n\n @Override\n public void run() {\n // TODO Auto-generated method stub\n while (!Tools.isProcessExited(data)) {\n try {\n while (data.getErrorStream().available() > 0) {\n System.err.print((char) data.getErrorStream().read());\n }\n } catch (IOException e) {\n }\n }\n }\n };\n\n inputStreamPrinter.data = p;\n errorStreamPrinter.data = p;\n\n new Thread(inputStreamPrinter).start();\n new Thread(errorStreamPrinter).start();\n p.waitFor();\n System.out.println(\"Minecraft exited. (\" + p.exitValue() + \")\");\n System.exit(p.exitValue());\n }\n public static String getCommandLineArgs() {\n String cmdline = \"\";\n List<String> l = ManagementFactory.getRuntimeMXBean().getInputArguments();\n cmdline += \"java \";\n for (int i = 0; i < l.size(); i++) {\n cmdline += l.get(i) + \" \";\n }\n cmdline += \"-cp \" + System.getProperty(\"java.class.path\") + \" \" + System.getProperty(\"sun.java.command\");\n\n return cmdline;\n}\n package generic.minecraft.infinityclient;\n\npublic abstract class RunnableWithObject<T> implements Runnable {\n public T data;\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259343",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/420/"
] |
259,354
|
<p>Is there a substitute in emacs for the vi "gf" command?
meaning try to open the file which is under the cursor right now
if a real file name is in fact there.</p>
<p>Thanks</p>
|
[
{
"answer_id": 259376,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 7,
"selected": true,
"text": "find-file-at-point ffap M-x ffap\n .emacs (ffap-bindings)\n find-file C-x C-f ffap ffap.el"
},
{
"answer_id": 261257,
"author": "Nir",
"author_id": 33707,
"author_profile": "https://Stackoverflow.com/users/33707",
"pm_score": 3,
"selected": false,
"text": "(defun shell-command-to-string (command)\n \"Execute shell command COMMAND and return its output as a string.\"\n (with-output-to-string\n (with-current-buffer standard-output\n (call-process shell-file-name nil t nil shell-command-switch command))))\n\n(defun goto-file ()\n \"open file under cursor\"\n (interactive)\n (find-file (shell-command-to-string (concat \"locate \" (current-word) \"|head -c -1\" )) ))\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33707/"
] |
259,355
|
<blockquote>
<p>It turns out this whole misunderstanding of the open() versus fopen() stems from a buggy I2C driver in the Linux 2.6.14 kernel on an ARM. Backporting a working bit bashed driver solved the root cause of the problem I was trying to address here.</p>
</blockquote>
<p>I'm trying to figure out an issue with a serial device driver in Linux (I2C). It appears that by adding timed OS pauses (sleeps) between writes and reads on the device things work ... (much) better. </p>
<blockquote>
<p>Aside: <em>The nature of I2C is that each byte read or written by the master is acknowledged by the device on the other end of the wire (slave) - the pauses improving things encourage me to think of the driver as working asynchronously - something that I can't reconcile with how the bus works. Anyhoo ...</em></p>
</blockquote>
<p>I'd either like to <strong>flush</strong> the write to be sure (rather than using fixed duration pause), <strong><em>or</em></strong> somehow test that the write/read transaction has <strong>completed</strong> in an multi-threaded friendly way. </p>
<p>The trouble with using <code>fflush(fd);</code> is that it requires 'fd' to be stream pointer (not a file descriptor) i.e.</p>
<pre><code>FILE * fd = fopen("filename","r+");
... // do read and writes
fflush(fd);
</code></pre>
<p>My problem is that I require the use of the <code>ioctl()</code>, which doesn't use a stream pointer. i.e.</p>
<pre><code>int fd = open("filename",O_RDWR);
ioctl(fd,...);
</code></pre>
<p>Suggestions?</p>
|
[
{
"answer_id": 259370,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 6,
"selected": true,
"text": "fileno() stdio <stdio.h> write() stdio open() read() write() int fd = open(\"/dev/i2c\", O_RDWR);\nioctl(fd, IOCTL_COMMAND, args);\nwrite(fd, buf, length);\n"
},
{
"answer_id": 261163,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 4,
"selected": false,
"text": "fflush() fopen() FILE * FILE * fileno() write() fflush() ioctl() open() fopen<()"
},
{
"answer_id": 261994,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " FDOPEN(P)\n\nNAME\n\n fdopen - associate a stream with a file descriptor\n\nSYNOPSIS\n\n #include <stdio.h>\n\n FILE *fdopen(int fildes, const char *mode);\n"
},
{
"answer_id": 3173139,
"author": "Danke Xie",
"author_id": 382871,
"author_profile": "https://Stackoverflow.com/users/382871",
"pm_score": 6,
"selected": false,
"text": "int fsync(int fd);\n int fdatasync(int fd);\n fsync fdatasync"
},
{
"answer_id": 38752910,
"author": "rustyx",
"author_id": 485343,
"author_profile": "https://Stackoverflow.com/users/485343",
"pm_score": 3,
"selected": false,
"text": "setvbuf(fd, NULL, _IONBF, 0);\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32836/"
] |
259,364
|
<p>I'm using Emacs with <a href="http://mfgames.com/linux/csharp-mode" rel="nofollow noreferrer">C# Mode</a> and when I turn on the speedbar, no files show up by default. I can choose "show all files" on the speedbar mode, but then every .cs file shows up with a '[?]' next to the name. How do I properly configure speedbar so it shows up with .cs files by default? How do I get the '[+]' next to each file so I can navigate inside the file?</p>
|
[
{
"answer_id": 425847,
"author": "user9252",
"author_id": 9252,
"author_profile": "https://Stackoverflow.com/users/9252",
"pm_score": 3,
"selected": true,
"text": " (speedbar-add-supported-extension \".cs\")\n (add-to-list 'speedbar-fetch-etags-parse-list\n '(\"\\\\.cs\" . speedbar-parse-c-or-c++tag))\n"
},
{
"answer_id": 2790500,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 2,
"selected": false,
"text": "(speedbar-add-supported-extension \".cs\") \n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
] |
259,369
|
<p>I want to be able to rewrite a URL from:</p>
<pre><code>// examples
http://example.com/location/New York, NY -->
http://example.com/location/index.html?location=New York, NY
http://example.com/location/90210 -->
http://example.com/location/index.html?location=90210
http://example.com/location/Texas -->
http://example.com/location/index.html?location=Texas
http://example.com/location/ANYTHING.... -->
http://example.com/location/index.html?location=ANYTHING...
</code></pre>
<p>using <code>.htaccess</code> and mod_rewrite.</p>
<p>Anyone know how to do this?</p>
<p>I have tried:</p>
<pre><code>RewriteEngine on
RewriteCond %{REQUEST_URI} !location/index.html
RewriteRule ^location/(.*)$ /location/index.html?location=$1
</code></pre>
<p>However, it is not passing the GET location variable to the /location/index.html page when you use the "pretty url" (e.g. <a href="http://example.com/location/90210" rel="nofollow noreferrer">http://example.com/location/90210</a>).</p>
<p>I know this b/c when I echo out to the screen (<strong>using javascript</strong>) the location GET variable when the long url is used, it's set but when the pretty (short) url is used, the location GET variable is undefined.</p>
|
[
{
"answer_id": 259406,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 2,
"selected": false,
"text": "RewriteEngine on\nRewriteCond %{REQUEST_URI} !location/index.html [NC]\nRewriteRule ^location/(.*)$ /location/index.html?location=$1 [L,QSA]\n http://www.example.com/foo/bar/ http://www.example.com/foo/bar/ <?php\necho 'The location you entered is ' . $_GET['location'] . '.';\n?>\n http://www.example.com/location/Houston,TX The location you entered is Austin,TX.\n"
},
{
"answer_id": 259597,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 0,
"selected": false,
"text": "alert(document.location.href);\n var regex = /location\\/(.*)$/;\nvar query = document.location.href.match(regex);\nalert(query[1]);\n\n// query[1] will contain \"90210\" in your example\n// http://example.com/location/90210\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33554/"
] |
259,382
|
<p>I'm a bit confused about how MVC works and I can't find anything but basic examples.</p>
<p>I want to make a kind of widget-based design; you can choose various widgets to go on your page. Each widget should be responsible for itself - it should have a controller and a view. But what about the main page? Suddenly I've got a page with lots of controllers on it!</p>
<p>The obvious thing to do is to embed the controllers in the view somehow... <code>This is my widget {SomeWidget}</code> but I've read that "breaks the MVC paradigm".</p>
<p>Some widgets will need to POST to different urls (like a search box goes to the result page) and some will need to POST back to the same URL (like adding a comment to an article brings you back to the article).</p>
<p>To top things off, the user should be able to edit the HTML around the widget - for example if they want a search box on the right, they can type <code><div style="float: right;">{SearchController}</div></code> (in my paradigm-breaking world)</p>
|
[
{
"answer_id": 267748,
"author": "Jamey McElveen",
"author_id": 30099,
"author_profile": "https://Stackoverflow.com/users/30099",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\n function OnFailure(error) {\n alert(\"We have encounterd an error \" + error);\n }\n</script>\n<% using (Ajax.BeginForm(\"Add\", new AjaxOptions{UpdateTargetId=\"sum\", OnFailure=\"OnFailure\"})){ %>\n <%= Html.TextBox(\"x\") %> + \n <%= Html.TextBox(\"y\") %> = \n <span id=\"sum\">?</span>\n <input type=\"submit\" value=\"AddEm\" />\n<% } %>\n [AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Add(string x, string y)\n{\n int sum = int.Parse(x) + int.Parse(y); \n return Content(sum.ToString());\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24181/"
] |
259,385
|
<p>What end-user clients (not libraries) expose <a href="http://en.wikipedia.org/wiki/Extensible_Messaging_and_Presence_Protocol" rel="noreferrer">XMPP</a> <a href="http://en.wikipedia.org/wiki/Publish/subscribe#See_also" rel="noreferrer">XEP-0060</a> to users right now?</p>
|
[
{
"answer_id": 267748,
"author": "Jamey McElveen",
"author_id": 30099,
"author_profile": "https://Stackoverflow.com/users/30099",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\">\n function OnFailure(error) {\n alert(\"We have encounterd an error \" + error);\n }\n</script>\n<% using (Ajax.BeginForm(\"Add\", new AjaxOptions{UpdateTargetId=\"sum\", OnFailure=\"OnFailure\"})){ %>\n <%= Html.TextBox(\"x\") %> + \n <%= Html.TextBox(\"y\") %> = \n <span id=\"sum\">?</span>\n <input type=\"submit\" value=\"AddEm\" />\n<% } %>\n [AcceptVerbs(HttpVerbs.Post)]\npublic ActionResult Add(string x, string y)\n{\n int sum = int.Parse(x) + int.Parse(y); \n return Content(sum.ToString());\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32577/"
] |
259,386
|
<p>How can I change the <strong>background color</strong> of a <strong>Tab Control</strong>. I changed the forms color, but the tabs stay the same.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 259644,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 1,
"selected": false,
"text": " Me.NameOfTabControlPage.SetFocus\n Me.NameOfSubformControl.SourceObject = \"NameOfSuitableForm\"\n"
},
{
"answer_id": 13237506,
"author": "Christian d'Heureuse",
"author_id": 337221,
"author_profile": "https://Stackoverflow.com/users/337221",
"pm_score": 1,
"selected": false,
"text": "Private Const GWL_EXSTYLE = -20\nPrivate Const WS_EX_TRANSPARENT = &H20&\n\nPrivate Declare Function GetWindowLong Lib \"user32\" Alias \"GetWindowLongA\" (ByVal hwnd As Long, ByVal nIndex As Long) As Long\nPrivate Declare Function SetWindowLong Lib \"user32\" Alias \"SetWindowLongA\" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long\nPrivate Declare Function FindWindowEx Lib \"user32\" Alias \"FindWindowExA\" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long\n\nPublic Sub PatchTabControl(ByVal f As Form)\n Dim hwnd As Long\n hwnd = FindWindowEx(f.hwnd, 0, \"OFormSub\", vbNullString)\n If hwnd = 0 Then Exit Sub\n hwnd = FindWindowEx(f.hwnd, hwnd, \"OFormSub\", vbNullString)\n If hwnd = 0 Then Exit Sub\n hwnd = FindWindowEx(hwnd, 0, \"OTabControl\", vbNullString)\n If hwnd = 0 Then Exit Sub\n SetWindowLong hwnd, GWL_EXSTYLE, GetWindowLong(hwnd, GWL_EXSTYLE) Or WS_EX_TRANSPARENT\n End Sub\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
259,389
|
<p>On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP address using <code>gethostbyname</code> or similar functions, but I don't know any way to specify which named interface I want the IP address of. I could use ifconfig and parse the output, but shelling out for this information seems... inelegant.</p>
<p>Is there a way to, say, enumerate all the interfaces and their IP addresses (and maybe MAC addresses) into a collection? Or at least something along the lines of <code>gethostbyinterface("eth0")</code>?</p>
|
[
{
"answer_id": 259422,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 2,
"selected": false,
"text": "ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'\n ifconfig | egrep '^[^ ]' | awk '{print $1}'\n for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do\n echo -n \"${x}\"\n echo -n \" \"\n ifconfig \"${x}\" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'\ndone\n"
},
{
"answer_id": 259424,
"author": "Walter",
"author_id": 23840,
"author_profile": "https://Stackoverflow.com/users/23840",
"pm_score": 4,
"selected": true,
"text": "// Originally from http://www.tlug.org.za/wiki/index.php/Obtaining_your_own_IP_address\n\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/ioctl.h>\n#include <net/if.h>\n#include <netinet/in.h>\n#include <arpa/inet.h>\n#include <string.h>\n#include <stdio.h>\n#include <unistd.h>\n\n/**\n * getIPv4()\n *\n * This function takes a network identifier such as \"eth0\" or \"eth0:0\" and\n * a pointer to a buffer of at least 16 bytes and then stores the IP of that\n * device gets stored in that buffer.\n *\n * it return 0 on success or -1 on failure.\n *\n * Author: Jaco Kroon <jaco@kroon.co.za>\n */\nint getIPv4(const char * dev, char * ipv4) {\n struct ifreq ifc;\n int res;\n int sockfd = socket(AF_INET, SOCK_DGRAM, 0);\n\n if(sockfd < 0)\n return -1;\n strcpy(ifc.ifr_name, dev);\n res = ioctl(sockfd, SIOCGIFADDR, &ifc);\n close(sockfd);\n if(res < 0)\n return -1; \n strcpy(ipv4, inet_ntoa(((struct sockaddr_in*)&ifc.ifr_addr)->sin_addr));\n return 0;\n}\n\n\nint main() {\n char ip[16];\n if(getIPv4(\"eth0\", ip) == 0)\n printf(\"IPv4: %s\\n\", ip);\n else\n printf(\"No IP\\n\");\n return 0;\n }\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26286/"
] |
259,390
|
<p>One of the many quirks of Reporting Services we've run across is the complete and utter lack of a CheckBox control or even something remotely similar.</p>
<p>We have a form that should appear automatically filled out based on information pulled from a database. We have several bit datatype fields. Printing out "True" or "False" just looks silly, as this is supposed to look like a form that has been auto-filled out, so we want to have a series of checkboxes and labels that are either checked or unchecked.</p>
<p>We are running SSRS 2005 but I'm not aware of SSRS 2008 having added a CheckBox control. Even if it did, we'd need to have an alternative for the time being. The best we've found so far is:</p>
<ol>
<li>use Wingdings</li>
<li>use images</li>
<li>use text boxes with borders and print a blank/space or a capital X</li>
</ol>
<p>All three approaches require <code>IIF</code> expression shenanigans.</p>
<p>The Wingdings approach seemed to work acceptably, and was the most aesthetically pleasing except that for whatever reason it didn't always print correctly. More importantly, PDF exports, also for whatever reason, converted all fonts (generally) to Arial and so we got funky letters instead of the Windings dingbats.</p>
<p>Images, being a pixel-based raster, don't do so well when printed along side vector stuff like text. Unless handled carefully, they tend to stretch, pixelate, and do other unprofessional looking things.</p>
<p>While these methods do work (some with limitations as mentioned above) none of them are particularly elegant.</p>
<p><strong>Are we missing something obvious?</strong> Not so obvious? Does someone at Microsoft have a good reason why such a control was not provided in SSRS 2000, let alone 2 versions and 8 years later? This can't be the first time this issue has come up...</p>
|
[
{
"answer_id": 12873012,
"author": "Valentino Vranken",
"author_id": 316194,
"author_profile": "https://Stackoverflow.com/users/316194",
"pm_score": 4,
"selected": false,
"text": "=Switch(\n IsNothing(Fields!YourBoolean.Value), 50,\n Fields!YourBoolean.Value = False, 0,\n Fields!YourBoolean.Value = True, 100)\n"
},
{
"answer_id": 31692730,
"author": "bot",
"author_id": 1109033,
"author_profile": "https://Stackoverflow.com/users/1109033",
"pm_score": 4,
"selected": false,
"text": "=IIF(Fields!Active.Value,chr(254),\"o\")\n"
},
{
"answer_id": 46081018,
"author": "Dragos Durlut",
"author_id": 249895,
"author_profile": "https://Stackoverflow.com/users/249895",
"pm_score": 2,
"selected": false,
"text": "Html - Interpret HTML tag as styles Value Expression =\"<font face=\"\"Wingdings 2\"\" color=\"\"green\"\">\" & Chr(81) &\"</font>\" & \"some other text\"\n =\"<font face=\"\"Wingdings 2\"\" color=\"\"red\"\">\" & Chr(163) &\"</font>\" & \"some other text\"\n Later edit: Wingdings 2 Wingdings =\"<font face=\"\"Wingdings\"\" color=\"\"green\"\">\" & Chr(253) &\"</font>\" & \"some other text\"\n =\"<font face=\"\"Wingdings\"\" color=\"\"red\"\">\" & Chr(168) &\"</font>\" & \"some other text\"\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290/"
] |
259,398
|
<p>Sometimes while developing in Visual Studio IDE, when you use "Find in Files" dialog to find something, the search fails and you will see the following message in the "Find Results" window. </p>
<blockquote>
<p>No files were found to look in. Find stopped progress</p>
</blockquote>
<p>Once this message shows up, all the subsequent searches will result in the same message. Nothing fixes the problem including restarting the computer except pressing <kbd>Ctrl</kbd> + <kbd>ScrLk</kbd>. </p>
<p>What causes Visual Studio to get into this state and is there a setting to permanently prevent it from happening?</p>
|
[
{
"answer_id": 2958188,
"author": "Sandor Drieënhuizen",
"author_id": 198990,
"author_profile": "https://Stackoverflow.com/users/198990",
"pm_score": 4,
"selected": false,
"text": "MyComputer\\HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\[VS VERSION NUMBER]\\Find\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16470/"
] |
259,409
|
<p>I have a requirement to develop a .NET-based application whose data requirements are likely to exceed the 4 gig limit of SQL 2005 Express Edition.</p>
<p>There may be other customers of the same application (in the future) with a requirement to use a specific DB platform (such as Oracle or SQL Server) due to in-house DBA expertise.</p>
<h3>Questions</h3>
<ol>
<li><p>What RDBMS would you guys recommend? From the looks of it the major choices are PostGreSQL, MySQL or FireBird. I've only got experience of MYSQL from these.</p>
</li>
<li><p>Which ORM tool (if any) would you recommend using - ideally one that can be swapped out between DB platforms with minimal effort? I like the look of the entity framework but unsure as to the degree to which platforms other than SQL Server are supported. If it helps, we'll be using the 3.5 version of the Framework. I'm open to the idea of using a tool such as NHibernate. On the other hand, if it's going to be easier, I'm happy to write my own stored procedures / DAL code - there won't be that many tables (perhaps 30-35).</p>
</li>
</ol>
|
[
{
"answer_id": 259517,
"author": "aaimnr",
"author_id": 26444,
"author_profile": "https://Stackoverflow.com/users/26444",
"pm_score": 2,
"selected": false,
"text": "[Generator( Class = \"native\")]\n//...\npublic virtual int CustomerId {get; set; }\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
259,415
|
<p>When I changed the rankdir of my graph from LR to TD, my record nodes also changed their layout direction so they no longer look like a 'record'. I tried applying a separate rankdir to the nodes, but this had no effect.</p>
<p>How does one keep the record nodes with the correct layout?</p>
<pre><code>digraph sample {
graph [rankdir=TD];
node [shape=record];
A [label="ShouldBeTop | ShouldBeBottom"];
B [label="Top | Bottom"];
A -> B;
}
</code></pre>
|
[
{
"answer_id": 259535,
"author": "ADEpt",
"author_id": 10105,
"author_profile": "https://Stackoverflow.com/users/10105",
"pm_score": 5,
"selected": true,
"text": "digraph sample { graph [rankdir=TD]; node [shape=record];\n\nA [label=\"{ShouldBeTop | ShouldBeBottom}\"]; \nB [label=\"{Top | Bottom}\"]; A -> B; \n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32973/"
] |
259,416
|
<p>Does Ruby have a stepwise debugger, similar to Perl's "perl -d"?</p>
|
[
{
"answer_id": 259437,
"author": "jcoby",
"author_id": 2884,
"author_profile": "https://Stackoverflow.com/users/2884",
"pm_score": 3,
"selected": false,
"text": "-x --trace set linetrace"
},
{
"answer_id": 1344838,
"author": "Kevin",
"author_id": 114614,
"author_profile": "https://Stackoverflow.com/users/114614",
"pm_score": 1,
"selected": false,
"text": "debug ruby -r debug /path/to/ruby_script.rb\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8913/"
] |
259,428
|
<p>I have a source XML file that is used to create C# files that are then compiled as part of a project.<br>
Currently I have a BeforeBuild target that runs my XML to C# converter.<br>
The problem is that by the time the BeforeBuild step is run the old files appear to have been stored by the build system so the new files are ignored.</p>
<p>How can I get around this? It seems that Transforms would be the way but they are limited in what they can do.</p>
|
[
{
"answer_id": 259459,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 0,
"selected": false,
"text": "del \"$(ProjectDir)MyCsFile.cs\"\ncopy /b /y \"$(ProjectDir)\\MyXmlFile.xml\" \"$(TargetDir)\"\n\"$(ProjectDir)tt.bat\" \"$(ProjectDir)MyTemplateFile.tt\"\n"
},
{
"answer_id": 879601,
"author": "Bas Bossink",
"author_id": 74198,
"author_profile": "https://Stackoverflow.com/users/74198",
"pm_score": 2,
"selected": true,
"text": "<CreateItem> <Output>"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3786/"
] |
259,435
|
<p>I'm trying to create a jqgrid, but the table is empty. The table renders, but the data doesn't show.</p>
<p>The data I'm getting back from the php call is:</p>
<pre><code>{
"page":"1",
"total":1,
"records":"10",
"rows":[
{"id":"2:1","cell":["1","image","Chief Scout","Highest Award test","0"]},
{"id":"2:2","cell":["2","image","Link Badge","When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)","0"]},
{"id":"2:3","cell":["3","image","Pioneer Scout","Upon completion of requirements, the youth is invested as a Pioneer Scout","0"]},
{"id":"2:4","cell":["4","image","Voyageur Scout Award","Voyageur Scout Award is the right after Pioneer Scout.","0"]},
{"id":"2:5","cell":["5","image","Voyageur Citizenship","Learning about and caring for your community.","0"]},
{"id":"2:6","cell":["6","image","Fish and Wildlife","Demonstrate your knowledge and involvement in fish and wildlife management.","0"]},
{"id":"2:7","cell":["7","image","Photography","To recognize photography knowledge and skills","0"]},
{"id":"2:8","cell":["8","image","Recycling","Demonstrate your knowledge and involvement in Recycling","0"]},
{"id":"2:10","cell":["10","image","Voyageur Leadership ","Show leadership ability","0"]},
{"id":"2:11","cell":["11","image","World Conservation","World Conservation Badge","0"]}
]}
</code></pre>
<p>The javascript configuration looks like so:</p>
<pre><code>$("#"+tableId).jqGrid ({
url:'getAwards.php?id='+classId,
dataType : 'json',
mtype:'POST',
colNames:['Id','Badge','Name','Description',''],
colModel : [
{name:'awardId', width:30, sortable:true, align:'center'},
{name:'badge', width:40, sortable:false, align:'center'},
{name:'name', width:180, sortable:true, align:'left'},
{name:'description', width:380, sortable:true, align:'left'},
{name:'selected', width:0, sortable:false, align:'center'}
],
sortname: "awardId",
sortorder: "asc",
pager: $('#'+tableId+'_pager'),
rowNum:15,
rowList:[15,30,50],
caption: 'Awards',
viewrecords:true,
imgpath: 'scripts/jqGrid/themes/green/images',
jsonReader : {
root: "rows",
page: "page",
total: "total",
records: "records",
repeatitems: true,
cell: "cell",
id: "id",
userdata: "userdata",
subgrid: {root:"rows", repeatitems: true, cell:"cell" }
},
width: 700,
height: 200
});
</code></pre>
<p>The HTML looks like:</p>
<pre><code><table class="awardsList" id="awardsList2" class="scroll" name="awardsList" />
<div id="awardsList2_pager" class="scroll"></div>
</code></pre>
<p>I'm not sure that I needed to define jsonReader, since I've tried to keep to the default. If the php code will help, I can post it too.</p>
|
[
{
"answer_id": 711585,
"author": "darren",
"author_id": 51688,
"author_profile": "https://Stackoverflow.com/users/51688",
"pm_score": 0,
"selected": false,
"text": "{\n\"page\":\"1\",\n\"total\":1,\n\"records\":\"10\",\n\"rows\":[\n{\"id\":1 ,\"cell\":[\"1\",\"image\",\"Chief Scout\",\"Highest Award test\",\"0\"]},\n{\"id\":2,\"cell\":[\"2\",\"image\",\"Link Badge\",\"When you are invested as a Scout, you maybe eligible to receive a Link Badge. (See page 45)\",\"0\"]},\n{\"id\":3,\"cell\":[\"3\",\"image\",\"Pioneer Scout\",\"Upon completion of requirements, the youth is invested as a Pioneer Scout\",\"0\"]},\n{\"id\":4,\"cell\":[\"4\",\"image\",\"Voyageur Scout Award\",\"Voyageur Scout Award is the right after Pioneer Scout.\",\"0\"]},\n{\"id\":5,\"cell\":[\"5\",\"image\",\"Voyageur Citizenship\",\"Learning about and caring for your community.\",\"0\"]},\n{\"id\":6,\"cell\":[\"6\",\"image\",\"Fish and Wildlife\",\"Demonstrate your knowledge and involvement in fish and wildlife management.\",\"0\"]},\n{\"id\":7,\"cell\":[\"7\",\"image\",\"Photography\",\"To recognize photography knowledge and skills\",\"0\"]},\n{\"id\":8,\"cell\":[\"8\",\"image\",\"Recycling\",\"Demonstrate your knowledge and involvement in Recycling\",\"0\"]},\n{\"id\":9,\"cell\":[\"10\",\"image\",\"Voyageur Leadership \",\"Show leadership ability\",\"0\"]},\n{\"id\":10,\"cell\":[\"11\",\"image\",\"World Conservation\",\"World Conservation Badge\",\"0\"]}\n]}\n"
},
{
"answer_id": 3714881,
"author": "Rosdi Kasim",
"author_id": 193634,
"author_profile": "https://Stackoverflow.com/users/193634",
"pm_score": 2,
"selected": false,
"text": "{\npage:\"1\",\ntotal:1,\nrecords:\"10\",\nrows:[\n {\"id\":\"2:1\",\"cell\":[\"1\",\"image\",\"Chief Scout\",\"Highest Award test\",\"0\"]},\n {\"id\":\"2:2\",\"cell\":[\"2\",\"image\",\"Link Badge\",\"When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)\",\"0\"]},\n {\"id\":\"2:3\",\"cell\":[\"3\",\"image\",\"Pioneer Scout\",\"Upon completion of requirements, the youth is invested as a Pioneer Scout\",\"0\"]}\n]}\n {\n\"page\":\"1\",\n\"total\":1,\n\"records\":\"10\",\n\"rows\":[\n {\"id\":\"2:1\",\"cell\":[\"1\",\"image\",\"Chief Scout\",\"Highest Award test\",\"0\"]},\n {\"id\":\"2:2\",\"cell\":[\"2\",\"image\",\"Link Badge\",\"When you are invested as a Scout, you may be eligible to receive a Link Badge. (See page 45)\",\"0\"]},\n {\"id\":\"2:3\",\"cell\":[\"3\",\"image\",\"Pioneer Scout\",\"Upon completion of requirements, the youth is invested as a Pioneer Scout\",\"0\"]}\n]}\n"
},
{
"answer_id": 5037871,
"author": "jejernig",
"author_id": 616499,
"author_profile": "https://Stackoverflow.com/users/616499",
"pm_score": 1,
"selected": false,
"text": "{\n\"rows\": [\n {\n \"id\": 1,\n \"cell\": [\n 1,\n \"lname\",\n \"fname\",\n \"mi\",\n phone,\n \"cell1\",\n \"cell2\",\n \"address\",\n \"email\"\n ]\n },\n {\n \"id\": 2,\n \"cell\": [\n 2,\n \"lname\",\n \"fname\",\n \"mi\",\n phone,\n \"cell1\",\n \"cell2\",\n \"address\",\n \"email\"\n ]\n }\n]\n public function fetchall ($sid, $sord)\n{\n $select = $this->getDbTable()->select(Zend_Db_Table::SELECT_WITH_FROM_PART);\n $select->setIntegrityCheck(false)\n ->join('Subdiv', 'Subdiv.SID = Contacts.SID', array(\"RepLastName\" => \"LastName\", \n \"Subdivision\" => \"Subdivision\",\n \"RepFirstName\" => \"FirstName\"))\n ->order($sid . \" \". $sord);\n\n $resultset = $this->getDbTable()->fetchAll($select);\n $i=0;\n foreach ($resultset as $row) {\n $entry = new Application_Model_Contacts();\n\n $entry->setId($row->id);\n $entry->setLastName($row->LastName);\n $entry->setFirstName1($row->FirstName1);\n $entry->setFirstName2($row->FirstName2);\n $entry->setHomePhone($row->HomePhone);\n $entry->setCell1($row->Cell1);\n $entry->setCell2($row->Cell2);\n $entry->setAddress($row->Address);\n $entry->setSubdivision($row->Subdivision);\n $entry->setRepName($row->RepFirstName . \" \" . $row->RepLastName);\n $entry->setEmail1($row->Email1); \n $entry->setEmail2($row->Email2);\n\n $response['rows'][$i]['id'] = $entry->getId(); //id\n $response['rows'][$i]['cell'] = array (\n $entry->getId(),\n $entry->getLastName(),\n $entry->getFirstName1(),\n $entry->getFirstName2(),\n $entry->getHomePhone(),\n $entry->getCell1(),\n $entry->getCell2(),\n $entry->getAddress(),\n $entry->getSubdivision(),\n $entry->getRepName(),\n $entry->getEmail1(),\n $entry->getEmail2()\n );\n $i++;\n\n }\n return $response;\n}\n"
},
{
"answer_id": 8325828,
"author": "Anil Baviskar",
"author_id": 1073303,
"author_profile": "https://Stackoverflow.com/users/1073303",
"pm_score": 1,
"selected": false,
"text": "var mydata1 = { \"page\": \"1\", \"total\": 1, \"records\": \"4\",\"rows\": [{ \"id\": 1, \"cell\": [\"1\", \"cell11\", \"values1\" ] },\n { \"id\": 2, \"cell\": [\"2\", \"cell21\", \"values1\"] },\n { \"id\": 3, \"cell\": [\"3\", \"cell21\", \"values1\"] },\n { \"id\": 4, \"cell\": [\"4\", \"cell21\", \"values1\"] }\n]};\n datatype: \"jsonstring\",\n\ncontentType: \"application/json; charset=utf-8\",\n\ndatastr: mydata1,\n\ncolNames: ['Id1', 'Name1', 'Values1'],\n\ncolModel: [\n { name: 'id1', index: 'id1', width: 55 },\n { name: 'name1', index: 'name1', width: 80, align: 'right', sorttype: 'string' },\n { name: 'values1', index: 'values1', width: 80, align: 'right', sorttype: 'string'}],\n"
},
{
"answer_id": 8719851,
"author": "Mariusz",
"author_id": 1128843,
"author_profile": "https://Stackoverflow.com/users/1128843",
"pm_score": 1,
"selected": false,
"text": "$responce->page = $page;\n $responce Strict Standards: Creating default object from empty value in /home/mariusz/public_html/rezerwacja/apps/frontend/modules/service/actions/actions.class.php on line 35\n $responce = new stdClass();\n"
},
{
"answer_id": 20460166,
"author": "Alfx2",
"author_id": 3078388,
"author_profile": "https://Stackoverflow.com/users/3078388",
"pm_score": 0,
"selected": false,
"text": "$responce = new stdClass(); \n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16345/"
] |
259,451
|
<p>I want to record sound (voice) using PortAudio (PyAudio) and output the corresponding sound wave on the screen. Hopeless as I am, I am unable to extract the frequency information from the audio stream so that I can draw it in Hz/time form.</p>
<hr>
<p>Here's an example code snippet that records and plays recorded audio for five seconds, in case it helps any:</p>
<pre><code>p = pyaudio.PyAudio()
chunk = 1024
seconds = 5
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=44100,
input=True,
output=True)
for i in range(0, 44100 / chunk * seconds):
data = stream.read(chunk)
stream.write(data, chunk)
</code></pre>
<p>I wish to extract the needed information from the above variable "data". (Or use some other high-level approach with PortAudio or another library with Python bindings.)</p>
<hr>
<p>I'd be very grateful for any help! Even vaguely related tidbits of audio-analyzing wisdom are appreciated. :)</p>
|
[
{
"answer_id": 259521,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": true,
"text": "scipy numpy"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
259,455
|
<p>In the following code, both the INPUT and TEXTAREA elements render wider than they should. How can I limit them to 100% of the usable area within the div?</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
.mywidth{ width:100%; }
</style>
</head>
<body>
<div style="border: 3px solid green; width: 100px;">
<input class="mywidth" ><br />
<textarea class="mywidth"></textarea><br />
<div style="background-color: yellow;" class="mywidth">test</div>
</div>
</body>
</html>
</code></pre>
<p>Note: If I remove the DOCTYPE, it renders as expected, with the INPUT, TEXTAREA and inner DIV all the same width and not going outside the containing DIV.</p>
<p>Update: Not withstanding the default borders on those elements, it still appears to render incorrectly in <strong>IE7</strong>.</p>
|
[
{
"answer_id": 259479,
"author": "Jaime Garcia",
"author_id": 32812,
"author_profile": "https://Stackoverflow.com/users/32812",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n"
},
{
"answer_id": 259481,
"author": "philnash",
"author_id": 28376,
"author_profile": "https://Stackoverflow.com/users/28376",
"pm_score": 4,
"selected": true,
"text": "<style>\n .mywidth{ \n width:100%;\n border:0;\n } \n</style>\n <style>\n .mywidth{ width:100%; border:0; padding-left:0; padding-right:0; }\n</style>\n"
},
{
"answer_id": 259495,
"author": "Toby Mills",
"author_id": 12377,
"author_profile": "https://Stackoverflow.com/users/12377",
"pm_score": 0,
"selected": false,
"text": "<div style=\"border: 3px solid green;padding-right:3px; width: 100px;\">\n"
},
{
"answer_id": 3309303,
"author": "bmaupin",
"author_id": 399105,
"author_profile": "https://Stackoverflow.com/users/399105",
"pm_score": 4,
"selected": false,
"text": "<style>\n .mywidth{ \n width:100%;\n -moz-box-sizing: border-box;\n -ms-box-sizing: border-box;\n -webkit-box-sizing: border-box;\n box-sizing: border-box;\n } \n</style>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
259,456
|
<p>I am working on implementing Zend Framework within an existing project that has a public marketing area, a private members area, an administration site, and a marketing campaign management site. Currently these are poorly organized with the controller scripts for the marketing area and the members area all being under the root of the site and then a separate folder for admin and another folder for the marketing campaign site.</p>
<p>In implementing the Zend Framework, I would like to create be able to split the controllers and views into modules (one for the members area, one for the public marketing area, one for the admin site, and one for the marketing campaign admin site) but I need to be able to point each module to the same model's since all three components work on the same database and on the same business objects.</p>
<p>However, I haven't been able to find any information on how to do this in the documentation. Can anyone help with either a link on how to do this or some simple instructions on how to accomplish it?</p>
|
[
{
"answer_id": 259489,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "INCLUDE_PATH docroot/\n index.php\napplication/\n library/ <-- common classes go here\n default/\n controllers/\n models/\n views/\n members/\n controllers/\n models/\n views/\n admin/\n controllers/\n models/\n views/\n. . .\n application/library/ INCLUDE_PATH init() models/ INCLUDE_PATH setControllerDirectory() setModuleDirectory() INCLUDE_PATH $app = APPLICATION_HOME; // you should define this in your bootstrap\n$d = DIRECTORY_SEPARATOR;\n$module = $this->_request->getModuleName(); // available after routing\nset_include_path(\n join(PATH_SEPARATOR,\n array(\n \"$app{$d}library\",\n \"$app{$d}$module{$d}models\",\n get_include_path()\n )\n )\n);\n library models init() INCLUDE_PATH"
},
{
"answer_id": 293481,
"author": "D-Rock",
"author_id": 36780,
"author_profile": "https://Stackoverflow.com/users/36780",
"pm_score": 2,
"selected": false,
"text": "Zend_Loader Module_Models_ModelName Zend_Loader"
},
{
"answer_id": 942394,
"author": "Jake McGraw",
"author_id": 302,
"author_profile": "https://Stackoverflow.com/users/302",
"pm_score": 1,
"selected": false,
"text": "<?php\n\nclass My_Controller_Action_Helper_GetModel extends Zend_Controller_Action_Helper_Abstract\n{\n /**\n * @var Zend_Loader_PluginLoader\n */\n protected $_loader;\n\n /**\n * Initialize plugin loader for models\n * \n * @return void\n */\n public function __construct()\n {\n // Get all models across all modules\n $front = Zend_Controller_Front::getInstance();\n $curModule = $front->getRequest()->getModuleName();\n\n // Get all module names, move default and current module to\n // back of the list so their models get precedence\n $modules = array_diff(\n array_keys($front->getDispatcher()->getControllerDirectory()),\n array('default', $curModule)\n );\n $modules[] = 'default';\n if ($curModule != 'default') {\n $modules[] = $curModule;\n }\n\n // Generate namespaces and paths for plugin loader\n $pluginPaths = array();\n foreach($modules as $module) {\n $pluginPaths[ucwords($module)] = $front->getModuleDirectory($module) . '/models';\n }\n\n // Load paths\n $this->_loader = new Zend_Loader_PluginLoader($pluginPaths);\n }\n\n /**\n * Load a model class and return an object instance\n * \n * @param string $model \n * @return object\n */\n public function getModel($model)\n {\n $class = $this->_loader->load($model);\n return new $class;\n }\n\n /**\n * Proxy to getModel()\n * \n * @param string $model \n * @return object\n */\n public function direct($model)\n {\n return $this->getModel($model);\n }\n}\n Zend_Controller_Action_HelperBroker::addPrefix('My_Controller_Action_Helper');\n <?php\n\nclass IndexController extends Zend_Controller_Action \n{\n public function indexAction() \n {\n $model = $this->_helper->getModel('SomeModel');\n }\n}\n"
},
{
"answer_id": 19151620,
"author": "Dharmesh Vasani",
"author_id": 5748531,
"author_profile": "https://Stackoverflow.com/users/5748531",
"pm_score": 0,
"selected": false,
"text": "<?php\nreturn array(\n'modules' => array(\n 'Application',\n 'DoctrineModule',\n 'DoctrineORMModule',\n 'Merchant',\n),\n'module_listener_options' => array(\n 'config_glob_paths' => array(\n 'config/autoload/{,*.}{global,local}.php',\n ),\n 'module_paths' => array(\n './module',\n '../vendor',\n// 'here we can load module'\n 'comomonmodule' \n\n ),\n),\n);\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
259,457
|
<p>If I've got an array of values that are basically zerofilled string representations of various numbers and another array of integers, will <code>array_intersect()</code> still match elements of different types?</p>
<p>For example, would this work:</p>
<pre><code>$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);
$intersect = array_intersect($arrayOne, $arrayTwo);
// $intersect would then be = "array(4, 5)"
</code></pre>
<p>And if not, what would be the most efficient way to accomplish this? Just loop through and compare, or loop through and convert everything to integers and run <code>array_intersect()</code> after?</p>
|
[
{
"answer_id": 259467,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 3,
"selected": true,
"text": "<?php\n$arrayOne = array('0003', '0004', '0005');\n$arrayTwo = array(4, 5, 6);\n\n$intersect = array_intersect($arrayOne, $arrayTwo);\n\nprint_r($intersect );\n\n?>\n foreach($arrayOne as $key => $value)\n{\n $arrayOne[$key] = intval($value);\n}\n"
},
{
"answer_id": 259469,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 2,
"selected": false,
"text": "Note: Two elements are considered equal if and only if\n(string) $elem1 === (string) $elem2.\nIn words: when the string representation is the same. \n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
259,480
|
<p>I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null:</p>
<pre><code>bool isNull = (i == null);
</code></pre>
<p>or</p>
<pre><code>bool isNull = !i.HasValue;
</code></pre>
<p>Also when assigning to a non-null type is this:</p>
<pre><code>long? i = 1;
long j = (long)i;
</code></pre>
<p>better than:</p>
<pre><code>long? i = 1;
long j = i.Value;
</code></pre>
|
[
{
"answer_id": 259500,
"author": "Seiti",
"author_id": 27959,
"author_profile": "https://Stackoverflow.com/users/27959",
"pm_score": 4,
"selected": false,
"text": "long? i = 1;\n...some code...\nlong j = i ?? 0;\n"
},
{
"answer_id": 259604,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 5,
"selected": true,
"text": "int? i = 1;\nbool isINull = i == null;\nint j = (int)i;\n int? i = 1;\nbool isINull = !i.HasValue;\nint j = i.Value;\n"
},
{
"answer_id": 259756,
"author": "AdamSane",
"author_id": 805,
"author_profile": "https://Stackoverflow.com/users/805",
"pm_score": 1,
"selected": false,
"text": "public Nullable(T value)\n{\n this.value = value;\n this.hasValue = true;\n}\n\nprivate bool hasValue;\n\ninternal T value;\n\npublic bool HasValue\n{\n get\n {\n return this.hasValue;\n }\n}\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553/"
] |
259,484
|
<p>I'd like to externalize all of the strings used in the project into one file and be able to use it inside aspx, C# code behind and on the client side in JavaScript.<br>
The reason I want to do it is because many strings are shared, i.e. the same in two places. </p>
<p>Is it possible? Is there a better way?</p>
|
[
{
"answer_id": 259568,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 1,
"selected": false,
"text": "alert($MY_TEXT$)\n alert(\"The string associated with $MY_TEXT$\")\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28098/"
] |
259,486
|
<p>SQL Server 2005.</p>
<p>I'm adding Foreign Key constraints to the database of an application that allegedly didn't need them. Naturally, the data has become unreliable and there are orphaned entries in the foreign key field.</p>
<p>Setup:<br/>
Two tables, TableUser and TableOrder.
TableUser has Primary Key 'UserID', and TableOrder has Foreign Key 'UserID'.</p>
<p>How do I find the rows where TableOrder.UserID has no matching entry in TableUser.UserID?</p>
<p>For example, TableOrder.UserID has a value of 250, but there is no matching TableUser.UserID key for 250.</p>
|
[
{
"answer_id": 259498,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": true,
"text": "select * from TableOrder where UserID not in (select UserID from TableUser);\n"
},
{
"answer_id": 259586,
"author": "BradC",
"author_id": 21398,
"author_profile": "https://Stackoverflow.com/users/21398",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM TableOrder o\nLEFT OUTER JOIN TableUser u ON o.UserID = u.UserID\nWHERE u.UserID is NULL\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26508/"
] |
259,524
|
<p>I have started using Linq to SQL in a (bit DDD like) system which looks (overly simplified) like this:</p>
<pre><code>public class SomeEntity // Imagine this is a fully mapped linq2sql class.
{
public Guid SomeEntityId { get; set; }
public AnotherEntity Relation { get; set; }
}
public class AnotherEntity // Imagine this is a fully mapped linq2sql class.
{
public Guid AnotherEntityId { get; set; }
}
public interface IRepository<TId, TEntity>
{
Entity Get(TId id);
}
public class SomeEntityRepository : IRepository<Guid, SomeEntity>
{
public SomeEntity Get(Guid id)
{
SomeEntity someEntity = null;
using (DataContext context = new DataContext())
{
someEntity = (
from e in context.SomeEntity
where e.SomeEntityId == id
select e).SingleOrDefault<SomeEntity>();
}
return someEntity;
}
}
</code></pre>
<p>Now, I got a problem. When I try to use SomeEntityRepository like this</p>
<pre><code>public static class Program
{
public static void Main(string[] args)
{
IRepository<Guid, SomeEntity> someEntityRepository = new SomeEntityRepository();
SomeEntity someEntity = someEntityRepository.Get(new Guid("98011F24-6A3D-4f42-8567-4BEF07117F59"));
Console.WriteLine(someEntity.SomeEntityId);
Console.WriteLine(someEntity.Relation.AnotherEntityId);
}
}
</code></pre>
<p>everything works nicely until the program gets to the last WriteLine, because it throws an <code>ObjectDisposedException</code>, because the DataContext does not exist any more.</p>
<p>I do see the actual problem, but how do I solve this? I guess there are several solutions, but none of those I have thought of to date would be good in my situation.</p>
<ul>
<li>Get away from the repository pattern and using a new DataContext for each atomic part of work.
<ul>
<li>I really would not want to do this. A reason is that I do not want to be the applications to be aware of the repository. Another one is that I do not think making linq2sql stuff COM visible would be good.</li>
<li>Also, I think that doing <code>context.SubmitChanges()</code> would probably commit much more than I intended to.</li>
</ul></li>
<li>Specifying DataLoadOptions to fetch related elements.
<ul>
<li>As I want my Business Logic Layer to just reply with some entities in some cases, I do not know which sub-properties they need to use.</li>
</ul></li>
<li>Disabling lazy loading/delayed loading for all properties.
<ul>
<li>Not an option, because there are quite a few tables and they are heavily linked. This could cause a lot of unnecessary traffic and database load.</li>
</ul></li>
<li>Some post on the internet said that using .Single() should help.
<ul>
<li>Apparently it does not ...</li>
</ul></li>
</ul>
<p>Is there any way to solve this misery?</p>
<p>BTW: We decided to use Linq t0 SQL because it is a relatively lightweight ORM solution and included with the .NET framework and Visual Studio. If the .NET Entity Framework would fit better in this pattern, it may be an option to switch to it. (We are not that far in the implementation, yet.)</p>
|
[
{
"answer_id": 259570,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 0,
"selected": false,
"text": "DataLoadOptions loadOptions = new DataLoadOptions();\nloadOptions.LoadWith<Entity>(e => e.Relation);\nSomeEntity someEntity = someEntityRepository\n .Get(new Guid(\"98011F24-6A3D-4f42-8567-4BEF07117F59\"),\n loadOptions);\n using (DataContext context = new DataContext())\n{\n context.LoadOptions = loadOptions;\n"
},
{
"answer_id": 1376494,
"author": "Tom Lianza",
"author_id": 26624,
"author_profile": "https://Stackoverflow.com/users/26624",
"pm_score": 0,
"selected": false,
"text": "public SomeEntityRepository WithSomethingElseTheCallerMightNeed()\n{\n dlo.LoadWith<SomeEntity>(se => se.RelatedEntities);\n return this; //so you can do method chaining\n}\n SomeEntity someEntity = someEntityRepository.WithSomethingElseTheCallerMightNeed().Get(new Guid(\"98011F24-6A3D-4f42-8567-4BEF07117F59\"));\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/259524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11963/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.