qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
152,323
|
<p>I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box.</p>
<p>The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server.</p>
<p>Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software?</p>
<p><code>Edit:</code><br>
Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary.</p>
<p>I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here.</p>
<p>Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so:<br>
<code>wscript sendmail.vbs</code></p>
|
[
{
"answer_id": 152392,
"author": "Re0sless",
"author_id": 2098,
"author_profile": "https://Stackoverflow.com/users/2098",
"pm_score": 1,
"selected": false,
"text": "wscript mail.vbs\n"
},
{
"answer_id": 152411,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 5,
"selected": true,
"text": "Dim objMail\n\nSet objMail = CreateObject(\"CDO.Message\")\n\nobjMail.From = \"Me <Me@Server.com>\"\nobjMail.To = \"You <You@AnotherServer.com>\"\nobjMail.Subject = \"That's a mail\"\nobjMail.Textbody = \"Hello World\"\nobjMail.AddAttachment \"C:\\someFile.ext\"\n\n---8<----- You don't need this part if you have an active Outlook [Express] account -----\n' Use an SMTP server\nobjMail.Configuration.Fields.Item _\n (\"http://schemas.microsoft.com/cdo/configuration/sendusing\") = 2\n\n' Name or IP of Remote SMTP Server\nobjMail.Configuration.Fields.Item _\n (\"http://schemas.microsoft.com/cdo/configuration/smtpserver\") = _\n \"smtp.server.com\"\n\n' Server port (typically 25)\nobjMail.Configuration.Fields.Item _\n (\"http://schemas.microsoft.com/cdo/configuration/smtpserverport\") = 25\n\nobjMail.Configuration.Fields.Update\n----- End of SMTP usage ----->8---\n\nobjMail.Send\n\nSet objMail=Nothing\nWscript.Quit\n"
},
{
"answer_id": 13573876,
"author": "Nathan Hartley",
"author_id": 80161,
"author_profile": "https://Stackoverflow.com/users/80161",
"pm_score": 3,
"selected": false,
"text": "Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Body] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-DeliveryNotficationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] [-Priority {Normal | Low | High}] [-UseSsl] [<CommonParameters>]\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5264/"
] |
152,328
|
<p>What is better?</p>
<p><strong>A:</strong></p>
<pre><code>server:1080/repo/projectA/trunk/...
branches/branch1
branches/branch2
branches/branch3
tags/tag1/...
tags/tag2/...
server:1080/repo/projectB/trunk/...
branches/branch1
branches/branch2
branches/branch3
tags/tag1/...
tags/tag2/...
</code></pre>
<p><strong>B:</strong></p>
<pre><code>server:1080/repo/trunk/projectA/...
branches/projectA/branch1
branches/projectA/branch2
branches/projectA/branch3
tags/projectA/tag1/...
tags/projectA/tag2/...
server:1080/repo/trunk/projectB/trunk/...
branches/projectB/branch1
branches/projectB/branch2
branches/projectB/branch3
tags/projectB/tag1/...
tags/projectB/tag2/...
</code></pre>
<p>What repository structure do you use and WHY?</p>
|
[
{
"answer_id": 152345,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "server:1080/projectA/trunk/...\n branches/branch1\n branches/branch2\n branches/branch3\n tags/tag1/...\n tags/tag2/...\nserver:1080/projectB/trunk/...\n branches/branch1\n branches/branch2\n branches/branch3\n tags/tag1/...\n tags/tag2/...\n"
},
{
"answer_id": 152456,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "/repos/projectA/component1/trunk - branches - tags\n/repos/projectA/component2/trunk - branches - tags\n/repos/projectB/component3/trunk - branches - tags\n/repos/projectB/component4/trunk - branches - tags\n /repos/projectA/trunk - branches - tags\n/repos/projectB/trunk - branches - tags\n/repos/component1/trunk - branches - tags\n/repos/component2/trunk - branches - tags\n/repos/component3/trunk - branches - tags\n/repos/component4/trunk - branches - tags\n"
},
{
"answer_id": 8688758,
"author": "altern",
"author_id": 50962,
"author_profile": "https://Stackoverflow.com/users/50962",
"pm_score": 0,
"selected": false,
"text": "/project\n /trunk\n /tags\n /builds\n /PA\n /A\n /B\n /releases\n /AR\n /BR\n /RC\n /ST\n /branches\n /experimental\n /maintenance\n /versions\n /platforms\n /releases\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8986/"
] |
152,338
|
<p>How to unit test WCF services? Any 3rd Party tools available?</p>
|
[
{
"answer_id": 5029051,
"author": "Jeno Laszlo",
"author_id": 621390,
"author_profile": "https://Stackoverflow.com/users/621390",
"pm_score": 5,
"selected": false,
"text": " ServiceHost serviceHost = null;\n\n try\n {\n var baseAddress = new Uri(\"http://localhost:8000/TestService\");\n serviceHost = new ServiceHost(typeof (ServiceClass), baseAddress);\n Binding binding = new WSHttpBinding();\n var address = new EndpointAddress(\"http://localhost:8000/TestService/MyService\");\n var endpoint = serviceHost\n .AddServiceEndpoint(typeof (IServiceContract), binding, address.Uri);\n\n var smb = new ServiceMetadataBehavior {HttpGetEnabled = true};\n serviceHost.Description.Behaviors.Add(smb);\n\n using (var client = new ProxyClient(endpoint.Name, endpoint.Address))\n {\n endpoint.Name = client.Endpoint.Name;\n\n serviceHost.Open();\n\n // ... magic happens \n }\n\n serviceHost.Close();\n }\n catch (Exception ex)\n {\n // ... tests\n }\n finally\n {\n if (serviceHost != null)\n {\n ((IDisposable) serviceHost).Dispose();\n }\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11039/"
] |
152,342
|
<p>I fill a collection one single time when my J2EE webapp starts.
Then, several thread may access it at same time but only to read it.</p>
<p>I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ?</p>
|
[
{
"answer_id": 152348,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 5,
"selected": true,
"text": "class Test {\n public Test(final int a, final int b) {\n this.a = a;\n this.b = b;\n }\n\n public int a;\n public int b;\n}\n\npublic class Main {\n\n public static void main(String[] args) throws Exception {\n List<Test> values = new ArrayList<Test>(2);\n values.add(new Test(1, 2));\n values.add(new Test(3, 4));\n\n List<Test> readOnly = Collections.unmodifiableList(values);\n for (Test t : readOnly) {\n t.a = 5;\n }\n\n for (Test t : values) {\n System.out.println(t.a);\n }\n }\n\n}\n 5\n5\n"
},
{
"answer_id": 152367,
"author": "Nicolas",
"author_id": 1730,
"author_profile": "https://Stackoverflow.com/users/1730",
"pm_score": 2,
"selected": false,
"text": "yourCollection = Collections.unmodifableCollection(yourCollection);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3122/"
] |
152,344
|
<p>I have a statusItem application written in PyObjC. The statusItem has a menuItem which is supposed to launch a new window when it is clicked:</p>
<pre><code># Create statusItem
statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength)
statusItem.setHighlightMode_(TRUE)
statusItem.setEnabled_(TRUE)
statusItem.retain()
# Create menuItem
menu = NSMenu.alloc().init()
menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Preferences', 'launchPreferences:', '')
menu.addItem_(menuitem)
statusItem.setMenu_(menu)
</code></pre>
<p>The launchPreferences: method is:</p>
<pre><code>def launchPreferences_(self, notification):
preferences = Preferences.alloc().initWithWindowNibName_('Preferences')
preferences.showWindow_(self)
</code></pre>
<p>Preferences is an NSWindowController class:</p>
<pre><code>class Preferences(NSWindowController):
</code></pre>
<p>When I run the application in XCode (Build & Go), this works fine. However, when I run the built .app file externally from XCode, the statusItem and menuItem appear as expected but when I click on the Preferences menuItem the window does not appear. I have verified that the launchPreferences code is running by checking console output. </p>
<p>Further, if I then double click the .app file again, the window appears but if I change the active window away by clicking, for example, on a Finder window, the preferences window disappears. This seems to me to be something to do with the active window. </p>
<p><strong>Update 1</strong>
I have tried <a href="https://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152399">these</a> <a href="https://stackoverflow.com/questions/152344/nswindow-launched-from-statusitem-menuitem-does-not-appear-as-active-window#152409">two</a> answers but neither work. If I add in to the launchPreferences method:</p>
<pre><code>preferences.makeKeyAndOrderFront_()
</code></pre>
<p>or</p>
<pre><code>preferences.setLevel_(NSNormalWindowLevel)
</code></pre>
<p>then I just get an error:</p>
<blockquote>
<p>'Preferences' object has no attribute</p>
</blockquote>
|
[
{
"answer_id": 152399,
"author": "Nathan Kinsinger",
"author_id": 20045,
"author_profile": "https://Stackoverflow.com/users/20045",
"pm_score": 3,
"selected": false,
"text": "[NSApp activateIgnoringOtherApps:YES];\n[[self window] makeKeyAndOrderFront:self];\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2183/"
] |
152,376
|
<p>How do I set the background colour of items in a list box dynamically? i.e. there is some property on my business object that I'm binding too, so based on some business rules I want the background colour to be different?</p>
<pre><code> <ListBox Background="Red">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="Red"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal"
Margin="5">
<TextBlock VerticalAlignment="Bottom"
FontFamily="Comic Sans MS"
FontSize="12"
Width="70"
Text="{Binding Name}" />
<TextBlock VerticalAlignment="Bottom"
FontFamily="Comic Sans MS"
FontSize="12"
Width="70"
Text="{Binding Age}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</code></pre>
<p>EDIT: It says <a href="http://msdn.microsoft.com/en-us/library/cc189093(VS.95).aspx" rel="nofollow noreferrer">here</a></p>
<blockquote>
<p>In Silverlight, you must add x:Key
attributes to your custom styles and
reference them as static resources.
Silverlight does not support implicit
styles applied using the TargetType
attribute value.</p>
</blockquote>
<p>Does this impact my approach?</p>
|
[
{
"answer_id": 1123045,
"author": "Stephen Price",
"author_id": 24395,
"author_profile": "https://Stackoverflow.com/users/24395",
"pm_score": 0,
"selected": false,
"text": "<Border Margin=\"-2,-2,-2,0\" Background=\"{TemplateBinding Background}\" BorderBrush=\"{TemplateBinding BorderBrush}\" BorderThickness=\"1,1,1,0\" CornerRadius=\"11,11,0,0\">\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
152,382
|
<p>We recently installed SVN 1.5.2 (with VisualSVN/Apache) on some of our servers / virtual machines, and now when I send a commandline command with username/password they don't get cached anymore.
Before, we were running SVN 1.5.0 installed with CollabNet, on svn://, and the credentials were cached after the first command.</p>
<p>So far, I'm finding difficulties in troubleshooting this. My situation is:</p>
<ul>
<li>SERVER_SVN (SVN 1.5.2 via svn://)</li>
<li>SERVER_HTTP (SVN 1.5.2 via http://)</li>
</ul>
<p>Command from commandline to SERVER_SVN: credentials cached fine</p>
<p>Same command to SERVER_HTTP: credentials are not cached</p>
<p>So, it seems like an http/apache server problem... BUT, from Tortoise the credentials are cached to both servers, so it also seems a client call problem. I'm running out of ideas... </p>
<p>A sample command sequence I use:</p>
<pre><code>
svn ls c:\mylocalfolderSVN --username foo --password bar
svn ls c:\mylocalfolderSVN // this works
svn ls c:\mylocalfolderHTTP --username foo --password bar
svn ls c:\mylocalfolderHTTP // this fails
</code></pre>
<p>The last command stops and asks for authentication.</p>
<p>Is credentials caching different between svn:// and http://, or did we miss something in the server configuration?</p>
<p>Thanks in advance for any suggestion.</p>
|
[
{
"answer_id": 1071691,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "svn ls REPOSITORY_URL svn ls WORKING_COPY_PATH"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21162/"
] |
152,384
|
<p>I'm playing around with LinqToSQL using an existing multi-lingual database, but I'm running into issues mapping a fairly important one-to-one relationship, so I suspect I am using the feature incorrectly for my database design.</p>
<p>Assume two tables, Category and CategoryDetail. Category contains the CategoryId (PK), ParentId and TemplateId. CategoryDetail contains the CategoryId (FK), LanguageId, Title and Description (in the appropriate language), with a combined PK of CategoryId and LanguageId.</p>
<p>If I drag-and-drop these tables into the LinqToSQL designer, the resultant object model has Category with a collection of CategoryDetail objects, which should never be the case. I'd like to be able to filter on LanguageId at the DataContext level, meaning that the whole Category is encapsulated within Category.CategoryDetail, not all language version encapsulated within Category.CategoryDetails.</p>
<p>This database worked fine on my old object library (an old-school custom BOL and DAL), but I fear that LinqToSQL would require this to change in order to give me the required result.</p>
<p>What is the best way to make this relationship (and language filtering) as seamless as possible?</p>
|
[
{
"answer_id": 152446,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 0,
"selected": false,
"text": "public partial class Category \n{\n public IEnumerable<CategoryDetail> GetDetailsByLanguage(string langID)\n {\n return this.CategoryDetails.Where(c => c.LangID == langID);\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/192/"
] |
152,405
|
<p>I have a program with two TForm classes and have added a TMainMenu to them each. I am then trying to merge them dynamically at run-time.</p>
<p>My problem is that when they merge the menu items in the merged in TMainMenu now display images stored in the imagelist in the form they were merged into rather than the images stored in their original form's imagelist.</p>
<p>Am I doing something wrong? is there a work around so that the menu item's continue to use the imagelist in the form they originated from?</p>
<p>I use the merged-in form in a number of projects, otherwise a single shared imagelist would make sense.</p>
<p>If I need to clarify anything, please say.</p>
<p>Thanks</p>
<p>Peter</p>
|
[
{
"answer_id": 153799,
"author": "onnodb",
"author_id": 1037,
"author_profile": "https://Stackoverflow.com/users/1037",
"pm_score": 2,
"selected": false,
"text": "ImageIndex TImageList"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152405",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
152,416
|
<p>Given the following idioms:</p>
<p>1)</p>
<p><pre><code>variable = value1
if condition
variable = value2</code></pre></p>
<p>2)</p>
<p><pre><code>variable = value2
if not condition
variable = value1</pre></code></p>
<p>3)</p>
<p><pre><code>if condition
variable = value2
else
variable = value1</pre></code></p>
<p>4)</p>
<p><pre><code>if not condition
variable = value1
else
variable = value2</pre></code></p>
<p>Which do you prefer, and why?</p>
<p>We assume the most common execution path to be that of <code>condition</code> being false.</p>
<p>I tend to learn towards using 1), although I'm not exactly sure why I like it more.</p>
<p><em>Note: The following examples may be simpler—and thus possibly more readable—but not all languages provide such syntax, and they are not suitable for extending the variable assignment to include more than one statement in the future.</em></p>
<pre><code>variable = condition ? value2 : value1
...
variable = value2 if condition else value1</code></pre>
|
[
{
"answer_id": 152424,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 0,
"selected": false,
"text": "switch"
},
{
"answer_id": 152431,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "if condition if !condition"
},
{
"answer_id": 152600,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "condition switch if"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152416",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1709/"
] |
152,419
|
<p>I've added a custom soap header <code><MyApp:FOO></code> element to the <code><soap:Header></code> element and the requirments states that i must sign this element , how would one do that?
<code><MyApp:FOO></code> contains a number of things (username, preferences, etc) that identifies a user on higher level.
I've succesfully used a policy file and now a policyClass with CertificateAssertions and SoapFilters to sign wsu:Timestamp, wsu:action, wsu:MessageId etc. But now the <code><MyApp:FOO></code> element needs to signed aswell.</p>
<p>What i've understood this far is that the element that needs to be signed must be indentified with a wsu:Id attribute and then transformed using xml-exc-c14n.</p>
<p>So, how do I specify that the soap header should be signed aswell?
This is the current class that i use for signing my message.</p>
<pre><code>internal class FOOClientOutFilter: SendSecurityFilter
{
X509SecurityToken clientToken;
public FOOClientOutFilter(SSEKCertificateAssertion parentAssertion)
: base(parentAssertion.ServiceActor, true)
{
// Get the client security token.
clientToken = X509TokenProvider.CreateToken(StoreLocation.CurrentUser, StoreName.My, "CN=TestClientCert");
// Get the server security token.
serverToken = X509TokenProvider.CreateToken(StoreLocation.LocalMachine, StoreName.My, "CN=TestServerCert");
}
public override void SecureMessage(SoapEnvelope envelope, Security security)
{
// Sign the SOAP message with the client's security token.
security.Tokens.Add(clientToken);
security.Elements.Add(new MessageSignature(clientToken));
}
}
</code></pre>
|
[
{
"answer_id": 152522,
"author": "Carl-Johan",
"author_id": 15406,
"author_profile": "https://Stackoverflow.com/users/15406",
"pm_score": 2,
"selected": false,
"text": " public override void SecureMessage(SoapEnvelope envelope, Security security)\n {\n //EncryptedData data = new EncryptedData(userToken);\n SignatureReference ssekSignature = new SignatureReference();\n MessageSignature signature = new MessageSignature(clientToken);\n // encrypt custom headers\n\n for (int index = 0; index < envelope.Header.ChildNodes.Count; index++)\n {\n XmlElement child =\n envelope.Header.ChildNodes[index] as XmlElement;\n\n // find all FOO headers\n if (child != null && child.Name == \"FOO\")\n {\n string id = Guid.NewGuid().ToString();\n child.SetAttribute(\"Id\", \"http://docs.oasis-\" +\n \"open.org/wss/2004/01/oasis-200401-\" +\n \"wss-wssecurity-utility-1.0.xsd\", id);\n signature.AddReference(new SignatureReference(\"#\" + id));\n }\n }\n\n // Sign the SOAP message with the client's security token.\n security.Tokens.Add(clientToken);\n\n security.Elements.Add(signature);\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15406/"
] |
152,435
|
<p>Does anyone have tools or experience with code coverage for PL/SQL. I believe this is possible using DBMS_PROFILER?</p>
|
[
{
"answer_id": 214018,
"author": "Dilshod Tadjibaev",
"author_id": 29122,
"author_profile": "https://Stackoverflow.com/users/29122",
"pm_score": 1,
"selected": false,
"text": "select exec.cnt/total.cnt * 100 \"Code% coverage\"\nfrom (select count(1) cnt\n from plsql_profiler_data d, plsql_profiler_units u\n where d.runid = &&runid\n and u.runid = d.runid\n and u.unit_number = d.unit_number\n and u.unit_name = upper('&&name')\n and u.unit_owner = upper('&&owner')\n ) total,\n (select count(1) cnt\n from plsql_profiler_data d, plsql_profiler_units u\n where d.runid = &&runid\n and u.runid = d.runid\n and u.unit_number = d.unit_number\n and u.unit_name = upper('&&name')\n and u.unit_owner = upper('&&owner')\n and d.total_occur > 0) exec;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] |
152,439
|
<p>I am actually new to this forum and I kept trying for a few days to find an easy way to copy an entire LDAP subtree to another tree. Since I couldn't find anything useful, i thought of dropping a question here as well. Does anybody know how to do this programatically ?</p>
<p>For normal operations like add, remove, search, I've been using Spring LDAP. </p>
<p>Thanks a lot !</p>
|
[
{
"answer_id": 152529,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 1,
"selected": false,
"text": "function copySubtree(oldDn, newDn)\n{\n copyNode(oldDn, newDn); // the new node will be created here\n if (nodeHasChildren(oldDn) { \n foreach (nodeGetChildren(oldDn) as childDn) {\n childRdn=getRdn(childDn); // we have to get the 'local' part, the so called RDN \n newChildDn=childRdn + ',' + newDn; // the new DN will be the old RDN concatenated with the new parent's DN\n copySubtree(childDn, newChildDn); // call this function recursively\n } \n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
152,441
|
<p>Anyone have any experience or tools for unit testing PL/SQL. The best looking tool I've seen for this seems to be Quests Code Tester, but i'm not sure how well that would integration with continuous integration tools or command line testing?</p>
|
[
{
"answer_id": 269397,
"author": "GregW",
"author_id": 17783,
"author_profile": "https://Stackoverflow.com/users/17783",
"pm_score": 1,
"selected": false,
"text": "py.test cx_oracle"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3839/"
] |
152,447
|
<p>When I backup or restore a database using MS SQL Server Management Studio, I get a visual indication of how far the process has progressed, and thus how much longer I still need to wait for it to finish. If I kick off the backup or restore with a script, is there a way to monitor the progress, or do I just sit back and wait for it to finish (hoping that nothing has gone wrong?)</p>
<p><strong>Edited:</strong> My need is specifically to be able to monitor the backup or restore progress completely separate from the session where the backup or restore was initiated.</p>
|
[
{
"answer_id": 152477,
"author": "Veldmuis",
"author_id": 18826,
"author_profile": "https://Stackoverflow.com/users/18826",
"pm_score": 8,
"selected": false,
"text": "SELECT r.session_id,r.command,CONVERT(NUMERIC(6,2),r.percent_complete)\nAS [Percent Complete],CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time],\nCONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min],\nCONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) AS [ETA Min],\nCONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours],\nCONVERT(VARCHAR(1000),(SELECT SUBSTRING(text,r.statement_start_offset/2,\nCASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END)\nFROM sys.dm_exec_sql_text(sql_handle))) AS [SQL]\nFROM sys.dm_exec_requests r WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')\n"
},
{
"answer_id": 156112,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 5,
"selected": true,
"text": "sp_who2k5 1,1\n"
},
{
"answer_id": 11270498,
"author": "Allen",
"author_id": 1492386,
"author_profile": "https://Stackoverflow.com/users/1492386",
"pm_score": 4,
"selected": false,
"text": "SELECT * FROM sys.dm_exec_requests WHERE session_id = 62\n SELECT command, percent_complete, start_time FROM sys.dm_exec_requests WHERE session_id = 62\n"
},
{
"answer_id": 34287344,
"author": "Shahbaz I Shaikh",
"author_id": 5681714,
"author_profile": "https://Stackoverflow.com/users/5681714",
"pm_score": 3,
"selected": false,
"text": "SELECT session_id as SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time \nFROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a \nWHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE')\n"
},
{
"answer_id": 36465055,
"author": "Liam Fleming",
"author_id": 5479334,
"author_profile": "https://Stackoverflow.com/users/5479334",
"pm_score": 0,
"selected": false,
"text": "SELECT percent_complete, *\nFROM sys.dm_exec_requests\nWHERE command In ( 'RESTORE DATABASE', 'BACKUP DATABASE' )\n"
},
{
"answer_id": 40132685,
"author": "Wilfred Kimani",
"author_id": 7042562,
"author_profile": "https://Stackoverflow.com/users/7042562",
"pm_score": 4,
"selected": false,
"text": "SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time\n FROM sys.dm_exec_requests\n WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE') \n"
},
{
"answer_id": 43353366,
"author": "BMDaemon",
"author_id": 7852396,
"author_profile": "https://Stackoverflow.com/users/7852396",
"pm_score": 2,
"selected": false,
"text": "USE[master]\nGO\nSELECT session_id AS SPID, command, a.text AS Query, start_time, percent_complete, dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time \n FROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a \n WHERE r.command in ('BACKUP DATABASE','RESTORE DATABASE')\nGO\n"
},
{
"answer_id": 49243927,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "select \nr.session_id, \nr.blocking_session_id, \ndb_name(database_id) as [DatabaseName],\nr.command, \n[SQL_QUERY_TEXT] = Substring(Query.TEXT, (r.statement_start_offset / 2) + 1, (\n (\n CASE r.statement_end_offset\n WHEN - 1\n THEN Datalength(Query.TEXT)\n ELSE r.statement_end_offset\n END - r.statement_start_offset\n ) / 2\n ) + 1),\n [SP_Name] =Coalesce(Quotename(Db_name(Query.dbid)) + N'.' + Quotename(Object_schema_name(Query.objectid, Query.dbid)) + N'.' + \n Quotename(Object_name(Query.objectid, Query.dbid)), ''),\nr.percent_complete,\nstart_time,\nCONVERT(VARCHAR(20), DATEADD(ms, [estimated_completion_time],\nGETDATE()), 20) AS [ETA_COMPLETION_TIME],\nCONVERT(NUMERIC(6, 2), r.[total_elapsed_time] / 1000.0 / 60.0) AS [Elapsed_MIN],\nCONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0) AS [Remaning_ETA_MIN],\nCONVERT(NUMERIC(6, 2), r.[estimated_completion_time] / 1000.0 / 60.0/ 60.0) AS [ETA_Hours],\nwait_type,\nwait_time/1000 as Wait_Time_Sec, \nwait_resource\nfrom sys.dm_exec_requests r \ncross apply sys.fn_get_sql(r.sql_handle) as Query where r.session_id>50 and command IN ('RESTORE DATABASE','BACKUP DATABASE', 'RESTORE LOG', 'BACKUP LOG')\n"
},
{
"answer_id": 54400831,
"author": "Zaalouni Mohamed",
"author_id": 5897616,
"author_profile": "https://Stackoverflow.com/users/5897616",
"pm_score": 3,
"selected": false,
"text": "SELECT * FROM sys.dm_exec_requests where command like '%BACKUP%'\n\nSELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command like '%BACKUP%'\n\nSELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time\n FROM sys.dm_exec_requests\n WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')\n"
},
{
"answer_id": 54400876,
"author": "Zaalouni Mohamed",
"author_id": 5897616,
"author_profile": "https://Stackoverflow.com/users/5897616",
"pm_score": 2,
"selected": false,
"text": "STATS=10 STATS=1 BACKUP DATABASE [xxxxxx] TO DISK = N'E:\\\\Bachup_DB.bak' WITH NOFORMAT, NOINIT, \nNAME = N'xxxx-Complète Base de données Sauvegarde', SKIP, NOREWIND, NOUNLOAD, COMPRESSION, STATS = 10\nGO.\n"
},
{
"answer_id": 56609589,
"author": "Ben",
"author_id": 1830764,
"author_profile": "https://Stackoverflow.com/users/1830764",
"pm_score": 2,
"selected": false,
"text": "SELECT session_id as SPID, command, start_time, percent_complete,\n dateadd(second,estimated_completion_time/1000, getdate()) as estimated_completion_time,\n a.text AS Query \nFROM sys.dm_exec_requests r CROSS APPLY sys.dm_exec_sql_text(r.sql_handle) a\nWHERE r.command in ('BACKUP DATABASE', 'BACKUP LOG', 'RESTORE DATABASE', 'RESTORE LOG')\n"
},
{
"answer_id": 57171267,
"author": "bsplosion",
"author_id": 2738164,
"author_profile": "https://Stackoverflow.com/users/2738164",
"pm_score": 1,
"selected": false,
"text": "msdb exec msdb.dbo.rds_task_status;\n task_info"
},
{
"answer_id": 63606677,
"author": "Promise Preston",
"author_id": 10907864,
"author_profile": "https://Stackoverflow.com/users/10907864",
"pm_score": 1,
"selected": false,
"text": "USE master;\nGO\n\nALTER DATABASE mydb SET SINGLE_USER WITH ROLLBACK IMMEDIATE;\nGO\n \nRESTORE DATABASE mydb\n FROM DISK = 'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\Backup\\my_db_21-08-2020.bak'\n WITH REPLACE,\n STATS = 10,\n RESTART,\n MOVE 'my_db' TO 'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\my_db.mdf',\n MOVE 'my_db_log' TO 'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.MSSQLSERVER\\MSSQL\\DATA\\mydb_log.ldf'\nGO\n \nALTER DATABASE mydb SET MULTI_USER;\nGO\n SELECT command, percent_complete, start_time FROM sys.dm_exec_requests where command = 'RESTORE DATABASE'\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18826/"
] |
152,457
|
<p>This was a question raised by one of the software engineers in my organisation. I'm interested in the broadest definition.</p>
|
[
{
"answer_id": 152863,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 10,
"selected": false,
"text": "netstat -an -p tcp TCP 192.168.1.3:63240 54.252.94.236:80 SYN_SENT\n TCP 192.168.1.3:63241 54.252.94.236:80 SYN_SENT\n TCP 192.168.1.3:63242 207.38.110.62:80 SYN_SENT\n TCP 192.168.1.3:63243 207.38.110.62:80 SYN_SENT\n TCP 192.168.1.3:64161 65.54.225.168:443 ESTABLISHED\n 207.38.110.62:80 54.252.94.236:80 54.252.94.236:80"
},
{
"answer_id": 153015,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 5,
"selected": false,
"text": "SOCK_DGRAM SOCK_STREAM"
},
{
"answer_id": 10057986,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "AF_INET int fd = socket(AF_INET, SOCK_STREAM, 0); // tcp socket\nint fd = socket(AF_INET, SOCK_DGRAM, 0); // udp socket\n// later we bind...\n sockaddr int fd = socket(AF_UNIX, SOCK_STREAM, 0);\n /var/run/database.sock"
},
{
"answer_id": 15418988,
"author": "Colin",
"author_id": 423068,
"author_profile": "https://Stackoverflow.com/users/423068",
"pm_score": 4,
"selected": false,
"text": "> netstat -nWp tcp (on OS X)\nActive Internet connections\nProto Recv-Q Send-Q Local Address Foreign Address (state) \ntcp4 0 0 192.168.0.6.49871 17.172.232.57.5223 ESTABLISHED\n...\n"
},
{
"answer_id": 32303691,
"author": "guest",
"author_id": 5283279,
"author_profile": "https://Stackoverflow.com/users/5283279",
"pm_score": 2,
"selected": false,
"text": " TCP 192.168.100.2:9001 155.94.246.179:39255 ESTABLISHED 1312\n TCP 192.168.100.2:9001 171.25.193.9:61832 ESTABLISHED 1312\n TCP 192.168.100.2:9001 178.62.199.226:37912 ESTABLISHED 1312\n TCP 192.168.100.2:9001 188.193.64.150:40900 ESTABLISHED 1312\n TCP 192.168.100.2:9001 198.23.194.149:43970 ESTABLISHED 1312\n TCP 192.168.100.2:9001 198.49.73.11:38842 ESTABLISHED 1312\n"
},
{
"answer_id": 41834131,
"author": "Zaz",
"author_id": 405550,
"author_profile": "https://Stackoverflow.com/users/405550",
"pm_score": 4,
"selected": false,
"text": "123.132.213.231 # IP address\n :1234 # port number\n123.132.213.231:1234 # socket address\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1199234/"
] |
152,462
|
<p>I need to run a Java application, which we are trying to port to Java 6, on an NT box.</p>
<p>I manage to run java 5 on it (although not officially supported), but when I try to run java 6 I get the following error:</p>
<pre><code>Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\Program Files\Java\jre1.6.0_05\bin\awt.dll: The specified procedure could not be found
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(Unknown Source)
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at sun.security.action.LoadLibraryAction.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.awt.NativeLibLoader.loadLibraries(Unknown Source)
at sun.awt.DebugHelper.<clinit>(Unknown Source)
at java.awt.EventQueue.<clinit>(Unknown Source)
at javax.swing.SwingUtilities.invokeLater(Unknown Source)
at ui.sequencer.test.WindowTest.main(WindowTest.java:136)
</code></pre>
<p>Anybody has any idea how to solve this?</p>
<p>This persists even when I move the java executables to another directory with no spaces in its name.</p>
<p>p.s.
I know, I should upgrade, but it's not up to me or my company - this is a very very bug huge gigantic company we work with, and they intend to keep NT for another 5 years.</p>
|
[
{
"answer_id": 152607,
"author": "Roel Spilker",
"author_id": 12634,
"author_profile": "https://Stackoverflow.com/users/12634",
"pm_score": 1,
"selected": false,
"text": "java -Djava.awt.headless=true"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11699/"
] |
152,469
|
<p>I want to make a login system using ASP.NET (MVC).</p>
<p>On the internet, I found some bad examples that involved SQL in Click events. Other information pointed to the ASP.NET built-in membership provider.</p>
<p>However, I want to roll my own. I don't want to use the built-in membership provider, as it only seems to work on MS SQL, and I don't like the idea of having a few foreign tables in my database.</p>
<p>I could probably think of something, but I need a few pointers in the right direction. It does not have to be high-security, but just regular common-sense security.</p>
<p>And I have a few direct questions:</p>
<ol>
<li><p>A lot of systems seem to have the Session ID stored in a user table. I guess this is to tie a session to a user to prevent hijacking. Do check this every time a user enters a page? And what do I do if the session expires?</p></li>
<li><p>Hashing, salting, what does it do? I know of MD5 hashing and I have used it before. But not salting.</p></li>
<li><p>Best practices for cookies?</p></li>
</ol>
|
[
{
"answer_id": 152523,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 4,
"selected": true,
"text": "if(SecurityHelper.LoginUser(txtUsername.Text, txtPassword.Text))\n{ \n FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, true);\n}\n"
},
{
"answer_id": 152630,
"author": "Paco",
"author_id": 13376,
"author_profile": "https://Stackoverflow.com/users/13376",
"pm_score": -1,
"selected": false,
"text": "public void SignIn(User user)\n {\n FormsAuthentication.SignOut();\n var ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now.AddMinutes(30), expires, alse, null);\n var encryptedTicket = FormsAuthentication.Encrypt(ticket);\n var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)\n {\n Expires = ticket.Expiration\n };\n\n httpContextProvider.GetCurrentHttpContext().Response.Cookies.Add(authCookie);\n }\n\n public void SignOut()\n {\n FormsAuthentication.SignOut();\n }\n"
},
{
"answer_id": 152679,
"author": "Jarrett Meyer",
"author_id": 5834,
"author_profile": "https://Stackoverflow.com/users/5834",
"pm_score": 2,
"selected": false,
"text": "mySalt = abc123 passwd hashResult = md5(mySalt + password)"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
152,483
|
<p>Is there a way to print all methods of an object in JavaScript?</p>
|
[
{
"answer_id": 152499,
"author": "WalkingRandomly",
"author_id": 1856916,
"author_profile": "https://Stackoverflow.com/users/1856916",
"pm_score": 1,
"selected": false,
"text": "for (var myprop in navigator){\n document.write(myprop+\": \"+navigator[myprop]+\"<br>\")\n}\n"
},
{
"answer_id": 152554,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 2,
"selected": false,
"text": "function writeLn(s)\n{\n //your code to write a line to stdout\n WScript.Echo(s)\n}\n\nfunction Base() {}\nBase.prototype.methodA = function() {}\nBase.prototype.attribA = \"hello\"\n\nvar derived = new Base()\nderived.methodB = function() {}\nderived.attribB = \"world\";\n\nfunction getMethods(obj)\n{\n var retVal = {}\n\n for (var candidate in obj)\n {\n if (typeof(obj[candidate]) == \"function\")\n retVal[candidate] = {func: obj[candidate], inherited: !obj.hasOwnProperty(candidate)}\n }\n return retVal\n}\n\nvar result = getMethods(derived)\nfor (var name in result)\n{\n writeLn(name + \" is \" + (result[name].inherited ? \"\" : \"not\") + \" inherited\")\n}\n"
},
{
"answer_id": 152573,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 8,
"selected": true,
"text": "function getMethods(obj) {\n var result = [];\n for (var id in obj) {\n try {\n if (typeof(obj[id]) == \"function\") {\n result.push(id + \": \" + obj[id].toString());\n }\n } catch (err) {\n result.push(id + \": inaccessible\");\n }\n }\n return result;\n}\n alert(getMethods(document).join(\"\\n\"));\n"
},
{
"answer_id": 38848631,
"author": "Gianluca Esposito",
"author_id": 843493,
"author_profile": "https://Stackoverflow.com/users/843493",
"pm_score": 3,
"selected": false,
"text": "ES6 // Get the Object's methods names:\nfunction getMethodsNames(obj = this) {\n return Object.keys(obj)\n .filter((key) => typeof obj[key] === 'function');\n}\n\n// Get the Object's methods (functions):\nfunction getMethods(obj = this) {\n return Object.keys(obj)\n .filter((key) => typeof obj[key] === 'function')\n .map((key) => obj[key]);\n}\n obj = this this Object.keys Object window [..., 'localStorage', ...'location'] (param) => ... function(param) {\n return ...\n}\n Array.filter typeof obj[key] === 'function' Array.map obj[key]"
},
{
"answer_id": 46610382,
"author": "mrded",
"author_id": 1264409,
"author_profile": "https://Stackoverflow.com/users/1264409",
"pm_score": 4,
"selected": false,
"text": "console.log(Object.keys(obj));\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21132/"
] |
152,487
|
<p>There is a MSBuild script, that includes number if Delphi and C# projects, unit tests etc. </p>
<p>The problem is: how to mark build failed if warnings were raised (for testing purposes, not for release builds)? Using LogError instead of LogWarning in custom tasks seems to be not a good option, because the build should test as much as it's able (until real error) to report as much warnings as possible in a time (build project is using in CruiseControl.NET).</p>
<p>May be, the solution is to create my own logger that would store warnings flag inside, but I cannot find if there is a way to read this flag in the end of build?</p>
<p>P.S. There is no problem to fail the build immediately after receiving a warning (Delphi compiler output is processed by custom task, and /warnaserror could be used for C#), but the desired behavior is "build everything; collect all warnings; fail the build" to report about all warnings, not only about the first one.</p>
<p><strong>P.P.S. As far as I really need not number of warnings, but just flag of their presence, I decided to simplify signaling mechanism, and use trivial Mutex instead of shared memory. Code is below:</strong></p>
<pre><code>using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.Threading;
namespace Intrahealth.Build.WarningLogger
{
public sealed class WarningLoggerCheck : Task
{
public override bool Execute()
{
Log.LogMessage("WarningLoggerCheck:" + mutexName + "...");
result = false;
Mutex m = null;
try
{
m = Mutex.OpenExisting(mutexName);
}
catch (WaitHandleCannotBeOpenedException)
{
result = true;
}
catch (Exception)
{
}
if (result)
Log.LogMessage("WarningLoggerCheck PASSED");
else
Log.LogError("Build log contains warnings. Build is FAILED");
return result;
}
private bool result = true;
[Output]
public bool Result
{
get { return result; }
}
private string mutexName = "WarningLoggerMutex";
public string MutexName
{
get { return mutexName; }
set { mutexName = value ?? "WarningLoggerMutex"; }
}
}
public class WarningLogger : Logger
{
internal static int warningsCount = 0;
private string mutexName = String.Empty;
private Mutex mutex = null;
public override void Initialize(IEventSource eventSource)
{
eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);
}
private void SetMutex()
{
if (mutexName == String.Empty)
{
mutexName = "WarningLoggerMutex";
if (this.Parameters != null && this.Parameters != String.Empty)
{
mutexName = this.Parameters;
}
}
mutex = new Mutex(false, mutexName);
}
void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)
{
if (e.Message != null && e.Message.Contains("MSB3146"))
return;
if (e.Code != null && e.Code.Equals("MSB3146"))
return;
if (warningsCount == 0)
SetMutex();
warningsCount++;
}
}
}
</code></pre>
|
[
{
"answer_id": 152538,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 1,
"selected": false,
"text": "msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release >> %MrB-BUILDLOG%\nfindstr /r /c:\"[1-9][0-9]* Error(s)\" >> %MrB-BUILDLOG%\nif not errorlevel 1 (\n echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-BUILDLOG%\n) else (\n findstr /r /c:\"[1-9][0-9]* Warning(s)\" >> %MrB-BUILDLOG%\n if not errorlevel 1 (\n echo ERROR: sending notification email for build warnings in '%~nx1'. >>\n"
},
{
"answer_id": 152685,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 4,
"selected": true,
"text": "namespace SampleLogger\n{\n using System;\n using Microsoft.Build.Utilities;\n using Microsoft.Build.Framework;\n using DM.SharedMemory;\n\n public class MySimpleLogger : Logger\n {\n private Segment s;\n private int warningCount;\n\n public override void Initialize(IEventSource eventSource)\n {\n eventSource.WarningRaised += new BuildWarningEventHandler(eventSource_WarningRaised);\n\n this.s = new Segment(\"MSBuildMetadata\", SharedMemoryCreationFlag.Create, 65535);\n this.s.SetData(this.warningCount.ToString());\n }\n\n void eventSource_WarningRaised(object sender, BuildWarningEventArgs e)\n {\n this.warningCount++;\n this.s.SetData(this.warningCount.ToString());\n }\n\n public override void Shutdown()\n {\n this.s.Dispose();\n base.Shutdown();\n }\n }\n}\n namespace SampleTasks\n{\n using System;\n using Microsoft.Build.Utilities;\n using Microsoft.Build.Framework;\n using DM.SharedMemory;\n\n public class BuildMetadata : Task\n {\n public int warningCount;\n\n [Output]\n public int WarningCount\n {\n get\n {\n Segment s = new Segment(\"MSBuildMetadata\", SharedMemoryCreationFlag.Attach, 0);\n int warningCount = Int32.Parse(s.GetData() as string);\n return warningCount;\n }\n }\n\n public override bool Execute()\n {\n return true;\n }\n }\n}\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\" DefaultTargets=\"Main\">\n <UsingTask TaskName=\"BuildMetadata\" AssemblyFile=\"F:\\temp\\SampleLogger\\bin\\debug\\SampleTasks.dll\" />\n\n <Target Name=\"Main\">\n <Warning Text=\"Sample warning #1\" />\n <Warning Text=\"Sample warning #2\" />\n\n <BuildMetadata>\n <Output\n TaskParameter=\"WarningCount\"\n PropertyName=\"WarningCount\" />\n </BuildMetadata>\n\n <Error Text=\"A total of $(WarningCount) warning(s) were raised.\" Condition=\"$(WarningCount) > 0\" />\n </Target>\n</Project>\n c:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\MSBuild test.xml /logger:SampleLogger.dll\n Microsoft (R) Build Engine Version 2.0.50727.3053\n[Microsoft .NET Framework, Version 2.0.50727.3053]\nCopyright (C) Microsoft Corporation 2005. All rights reserved.\n\nBuild started 30-09-2008 13:04:39.\n__________________________________________________\nProject \"F:\\temp\\SampleLogger\\bin\\debug\\test.xml\" (default targets):\n\nTarget Main:\n F:\\temp\\SampleLogger\\bin\\debug\\test.xml : warning : Sample warning #1\n F:\\temp\\SampleLogger\\bin\\debug\\test.xml : warning : Sample warning #2\n F:\\temp\\SampleLogger\\bin\\debug\\test.xml(15,3): error : A total of 2 warning(s) were raised.\nDone building target \"Main\" in project \"test.xml\" -- FAILED.\n\nDone building project \"test.xml\" -- FAILED.\n\nBuild FAILED.\nF:\\temp\\SampleLogger\\bin\\debug\\test.xml : warning : Sample warning #1\nF:\\temp\\SampleLogger\\bin\\debug\\test.xml : warning : Sample warning #2\nF:\\temp\\SampleLogger\\bin\\debug\\test.xml(15,3): error : A total of 2 warning(s) were raised.\n 2 Warning(s)\n 1 Error(s)\n\nTime Elapsed 00:00:00.01\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11391/"
] |
152,514
|
<p>I have to rename a complete folder tree recursively so that no uppercase letter appears anywhere (it's C++ source code, but that shouldn't matter).</p>
<p>Bonus points for ignoring CVS and Subversion version control files/folders. The preferred way would be a shell script, since a shell should be available on any Linux box.</p>
<p>There were some valid arguments about details of the file renaming.</p>
<ol>
<li><p>I think files with the same lowercase names should be overwritten; it's the user's problem. When checked out on a case-ignoring file system, it would overwrite the first one with the latter, too.</p></li>
<li><p>I would consider A-Z characters and transform them to a-z, everything else is just calling for problems (at least with source code).</p></li>
<li><p>The script would be needed to run a build on a Linux system, so I think changes to CVS or Subversion version control files should be omitted. After all, it's just a scratch checkout. Maybe an "export" is more appropriate.</p></li>
</ol>
|
[
{
"answer_id": 152519,
"author": "vividos",
"author_id": 23740,
"author_profile": "https://Stackoverflow.com/users/23740",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\n# First, rename all folders\nfor f in `find . -depth ! -name CVS -type d`; do\n g=`dirname \"$f\"`/`basename \"$f\" | tr '[A-Z]' '[a-z]'`\n if [ \"xxx$f\" != \"xxx$g\" ]; then\n echo \"Renaming folder $f\"\n mv -f \"$f\" \"$g\"\n fi\ndone\n\n# Now, rename all files\nfor f in `find . ! -type d`; do\n g=`dirname \"$f\"`/`basename \"$f\" | tr '[A-Z]' '[a-z]'`\n if [ \"xxx$f\" != \"xxx$g\" ]; then\n echo \"Renaming file $f\"\n mv -f \"$f\" \"$g\"\n fi\ndone\n mv"
},
{
"answer_id": 152531,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 7,
"selected": false,
"text": "for f in `find`; do mv -v \"$f\" \"`echo $f | tr '[A-Z]' '[a-z]'`\"; done\n"
},
{
"answer_id": 152560,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 3,
"selected": false,
"text": "$op = shift or die $help;\nchomp(@ARGV = <STDIN>) unless @ARGV;\nfor (@ARGV) {\n $was = $_;\n eval $op;\n die $@ if $@;\n rename($was,$_) unless $was eq $_;\n}\n find | fix 'tr/A-Z/a-z/'\n fix"
},
{
"answer_id": 152571,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "root_directory=\"${1?-please specify parent directory}\"\ndo_it () {\n awk '{ lc= tolower($0); if (lc != $0) print \"mv \\\"\" $0 \"\\\" \\\"\" lc \"\\\"\" }' | sh\n}\n# first the folders\nfind \"$root_directory\" -depth -type d | do_it\nfind \"$root_directory\" ! -type d | do_it\n"
},
{
"answer_id": 152598,
"author": "Ian Dickinson",
"author_id": 6716,
"author_profile": "https://Stackoverflow.com/users/6716",
"pm_score": 3,
"selected": false,
"text": "find . -name CVS -prune -o -exec mv '{}' `echo {} | tr '[A-Z]' '[a-z]'` \\; -print\n $> cat > tolower\n#!/bin/bash\nmv $1 `echo $1 | tr '[:upper:]' '[:lower:]'`\n^D\n$> chmod u+x tolower \n$> find . -name CVS -prune -o -exec tolower '{}' \\;\n"
},
{
"answer_id": 152636,
"author": "pklausner",
"author_id": 22700,
"author_profile": "https://Stackoverflow.com/users/22700",
"pm_score": 0,
"selected": false,
"text": "( find YOURDIR -type d | sort -r;\n find yourdir -type f ) |\ngrep -v /CVS | grep -v /SVN |\nwhile read f; do mv -v $f `echo $f | tr '[A-Z]' '[a-z]'`; done\n"
},
{
"answer_id": 152741,
"author": "Alex B",
"author_id": 23643,
"author_profile": "https://Stackoverflow.com/users/23643",
"pm_score": 9,
"selected": true,
"text": "\"rename\" find my_root_dir -depth -exec rename 's/(.*)\\/([^\\/]*)/$1\\/\\L$2/' {} \\;\n \"A/A\" \"a/a\" \"rename\" for SRC in `find my_root_dir -depth`\ndo\n DST=`dirname \"${SRC}\"`/`basename \"${SRC}\" | tr '[A-Z]' '[a-z]'`\n if [ \"${SRC}\" != \"${DST}\" ]\n then\n [ ! -e \"${DST}\" ] && mv -T \"${SRC}\" \"${DST}\" || echo \"${SRC} was not renamed\"\n fi\ndone\n \"svn mv\""
},
{
"answer_id": 152836,
"author": "niXar",
"author_id": 19979,
"author_profile": "https://Stackoverflow.com/users/19979",
"pm_score": 4,
"selected": false,
"text": "find -print0 find find . -type f -print0 | xargs -0n 1 bash -c \\\n's=$(dirname \"$0\")/$(basename \"$0\");\nd=$(dirname \"$0\")/$(basename \"$0\"|tr \"[A-Z]\" \"[a-z]\"); mv -f \"$s\" \"$d\"'\n touch \\;\\ echo\\ hacker::0:0:hacker:\\$\\'\\057\\'root:\\$\\'\\057\\'bin\\$\\'\\057\\'bash\n"
},
{
"answer_id": 8167105,
"author": "tristanbailey",
"author_id": 6096,
"author_profile": "https://Stackoverflow.com/users/6096",
"pm_score": 8,
"selected": false,
"text": "rename 'y/A-Z/a-z/' *\n -f rename -f 'y/A-Z/a-z/' *\n"
},
{
"answer_id": 17730002,
"author": "benjwadams",
"author_id": 1914300,
"author_profile": "https://Stackoverflow.com/users/1914300",
"pm_score": 3,
"selected": false,
"text": "zmv autoload -U zmv\n extendedglob setopt extendedglob\n zmv '(**/)(*)~CVS~**/CVS' '${1}${(L)2}'\n"
},
{
"answer_id": 25590300,
"author": "Ginhing",
"author_id": 3209127,
"author_profile": "https://Stackoverflow.com/users/3209127",
"pm_score": 7,
"selected": false,
"text": "zip -r foo.zip foo/*\nunzip -LL foo.zip\n"
},
{
"answer_id": 27969656,
"author": "jacanterbury",
"author_id": 765827,
"author_profile": "https://Stackoverflow.com/users/765827",
"pm_score": 1,
"selected": false,
"text": "ls | while read upName; do loName=`echo \"${upName}\" | tr '[:upper:]' '[:lower:]'`; mv \"$upName\" \"$loName\"; done\n for f in *\\ *; do mv \"$f\" \"${f// /_}\"; done\n"
},
{
"answer_id": 28777455,
"author": "cwd",
"author_id": 288032,
"author_profile": "https://Stackoverflow.com/users/288032",
"pm_score": 1,
"selected": false,
"text": "rename \"s/[^a-zA-Z0-9\\.]+/-/g\" filename\n"
},
{
"answer_id": 29248837,
"author": "Jonghee Park",
"author_id": 319911,
"author_profile": "https://Stackoverflow.com/users/319911",
"pm_score": 2,
"selected": false,
"text": "mv -f for i in `find . -name \"*\" -type f |grep -e \"[A-Z]\"`; do j=`echo $i | tr '[A-Z]' '[a-z]' | sed s/\\-1$//`; mv $i $i-1; mv $i-1 $j; done\n"
},
{
"answer_id": 33618314,
"author": "alemol",
"author_id": 1668293,
"author_profile": "https://Stackoverflow.com/users/1668293",
"pm_score": 4,
"selected": false,
"text": "rename --lower-case --force somedir/*\n"
},
{
"answer_id": 35117352,
"author": "John Foley",
"author_id": 1057048,
"author_profile": "https://Stackoverflow.com/users/1057048",
"pm_score": 1,
"selected": false,
"text": "python2 rename #!/usr/bin/env python2\nimport sys, os\n\ndef rename_dir(directory):\n print('DEBUG: rename('+directory+')')\n\n # Rename current directory if needed\n os.rename(directory, directory.lower())\n directory = directory.lower()\n\n # Rename children\n for fn in os.listdir(directory):\n path = os.path.join(directory, fn)\n os.rename(path, path.lower())\n path = path.lower()\n\n # Rename children within, if this child is a directory\n if os.path.isdir(path):\n rename_dir(path)\n\n# Run program, using the first argument passed to this Python script as the name of the folder\nrename_dir(sys.argv[1])\n"
},
{
"answer_id": 35561366,
"author": "Chris Schierkolk",
"author_id": 5964664,
"author_profile": "https://Stackoverflow.com/users/5964664",
"pm_score": 2,
"selected": false,
"text": "for f in `find -depth`; do mv ${f} ${f,,} ; done\n find -depth ${f,,}"
},
{
"answer_id": 36359928,
"author": "Pere",
"author_id": 1391963,
"author_profile": "https://Stackoverflow.com/users/1391963",
"pm_score": 4,
"selected": false,
"text": "rename for i in $( ls | grep [A-Z] ); do mv -i \"$i\" \"`echo $i | tr 'A-Z' 'a-z'`\"; done\n rename"
},
{
"answer_id": 42314201,
"author": "Stephen",
"author_id": 1018614,
"author_profile": "https://Stackoverflow.com/users/1018614",
"pm_score": 5,
"selected": false,
"text": "rename 'y/A-Z/a-z/' *\n"
},
{
"answer_id": 44709747,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "rename AUR renamexm /usr/bin/renamexm rename -l Developers.mp3 # or --lowcase\n rename -u developers.mp3 # or --upcase, long option\n -R --recursive # directory and its children\n\n-t --test # Dry run, output but don't rename\n\n-o --owner # Change file owner as well to user specified\n\n-v --verbose # Output what file is renamed and its new name\n\n-s/str/str2 # Substitute string on pattern\n\n--yes # Confirm all actions\n"
},
{
"answer_id": 46492911,
"author": "Paul Hodges",
"author_id": 8656552,
"author_profile": "https://Stackoverflow.com/users/8656552",
"pm_score": 2,
"selected": false,
"text": "typeset -l new # Always lowercase\nfind $topPoint | # Not using xargs to make this more readable\n while read old\n do new=\"$old\" # $new is a lowercase version of $old\n mv \"$old\" \"$new\" # Quotes for those annoying embedded spaces\n done\n mv $new"
},
{
"answer_id": 49705900,
"author": "akilesh raj",
"author_id": 4336570,
"author_profile": "https://Stackoverflow.com/users/4336570",
"pm_score": 2,
"selected": false,
"text": "rename brew install rename\n find . -iname \"*.py\" -type f | xargs -I% rename -c -f \"%\" \n *.py `f` - forces a rename\n $ find . -iname \"*.py\" -type f\n./sample/Sample_File.py\n./sample_file.py\n$ find . -iname \"*.py\" -type f | xargs -I% rename -c -f \"%\"\n$ find . -iname \"*.py\" -type f\n./sample/sample_file.py\n./sample_file.py\n"
},
{
"answer_id": 52479152,
"author": "ndemou",
"author_id": 1011025,
"author_profile": "https://Stackoverflow.com/users/1011025",
"pm_score": 2,
"selected": false,
"text": "tr # adapt the following command _IF_ you want to deal with specific files/dirs\nfind . -depth -mindepth 1 -exec bash -c '\n for file do\n # adapt the awk command if you wish to rename to something other than lowercase\n newname=$(dirname \"$file\")/$(basename \"$file\" | awk \"{print tolower(\\$0)}\")\n if [ \"$file\" != \"$newname\" ] ; then\n # the extra step with the temp filename is for case-insensitive filesystems\n if [ ! -e \"$newname\" ] && [ ! -e \"$newname.lcrnm.tmp\" ] ; then\n mv -T \"$file\" \"$newname.lcrnm.tmp\" && mv -T \"$newname.lcrnm.tmp\" \"$newname\" \n else\n echo \"ERROR: Name already exists: $newname\"\n fi\n fi \n done\n' sh {} +\n"
},
{
"answer_id": 53918698,
"author": "Chris",
"author_id": 59198,
"author_profile": "https://Stackoverflow.com/users/59198",
"pm_score": 2,
"selected": false,
"text": "ruby -e \"Dir['*'].each { |p| File.rename(p, p.downcase) }\"\n"
},
{
"answer_id": 54694950,
"author": "oisyn",
"author_id": 8951473,
"author_profile": "https://Stackoverflow.com/users/8951473",
"pm_score": 0,
"selected": false,
"text": "find . -depth -name '*[A-Z]*'|sed -n 's/\\(.*\\/\\)\\(.*\\)/mv -n -v -T \\1\\2 \\1\\L\\2/p'|sh\n rename find ./FOO ./FOO/BAR ./FOO ./foo ./FOO/BAR find . -depth -name '*[A-Z]*'\n . ./foo/bar ./foo -name ./FOO/BAR ./FOO/bar ./FOO/bar ./FOO -depth sed -n 's/\\(.*\\/\\)\\(.*\\)/mv -n -v -T \\1\\2 \\1\\L\\2/p'\n find mv -n sed p find ./FOO/BAR mv -n -v -T ./FOO/BAR ./FOO/bar -n mv -v mv ./FOO/bar ./FOO/BAR -> ./FOO/BAR -T ./FOO/BAR ./FOO/bar find sh\n mv bash"
},
{
"answer_id": 56063878,
"author": "Kim T",
"author_id": 2068766,
"author_profile": "https://Stackoverflow.com/users/2068766",
"pm_score": 4,
"selected": false,
"text": "brew install rename\nrename --force --lower-case --nows *\n"
},
{
"answer_id": 63917612,
"author": "Sebastian Schmied",
"author_id": 7563639,
"author_profile": "https://Stackoverflow.com/users/7563639",
"pm_score": 1,
"selected": false,
"text": "find . -depth -exec sh -c '\n t=${0%/*}/$(printf %s \"${0##*/}\" | tr \"[:upper:]\" \"[:lower:]\");\n [ \"$t\" = \"$0\" ] || mv -i \"$0\" \"$t\"\n' {} \\;\n"
},
{
"answer_id": 64899100,
"author": "Eduardo",
"author_id": 9823,
"author_profile": "https://Stackoverflow.com/users/9823",
"pm_score": 3,
"selected": false,
"text": "for F in K*; do NEWNAME=$(echo \"$F\" | tr '[:upper:]' '[:lower:]'); mv \"$F\" \"$NEWNAME\"; done\n for F in K*; do mv \"$F\" \"${F,,}\"; done\n"
},
{
"answer_id": 71063134,
"author": "TransferOrbit",
"author_id": 4943071,
"author_profile": "https://Stackoverflow.com/users/4943071",
"pm_score": 1,
"selected": false,
"text": "for f in **/*; do mv \"$f\" \"${f:l}\"; done"
},
{
"answer_id": 74678376,
"author": "Felix",
"author_id": 3803047,
"author_profile": "https://Stackoverflow.com/users/3803047",
"pm_score": 0,
"selected": false,
"text": "rename find . -exec bash -c 'mv $0 ${0,,}' {} \\;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152514",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23740/"
] |
152,537
|
<p>I need to add the ability for users of my software to select records by character ranges.<br>
How can I write a query that returns all widgets from a table whose name falls in the range Ba-Bi for example?</p>
<p>Currently I'm using greater than and less than operators, so the above example would become:</p>
<pre><code>select * from widget
where name >= 'ba' and name < 'bj'
</code></pre>
<p>Notice how I have "incremented" the last character of the upper bound from i to j so that "bike" would not be left out.</p>
<p>Is there a generic way to find the next character after a given character based on the field's collation or would it be safer to create a second condition?</p>
<pre><code>select * from widget
where name >= 'ba'
and (name < 'bi' or name like 'bi%')
</code></pre>
<p>My application needs to support localization. How sensitive is this kind of query to different character sets?</p>
<p>I also need to support both MSSQL and Oracle. What are my options for ensuring that character casing is ignored no matter what language appears in the data?</p>
|
[
{
"answer_id": 152728,
"author": "cagcowboy",
"author_id": 19629,
"author_profile": "https://Stackoverflow.com/users/19629",
"pm_score": 0,
"selected": false,
"text": "MY_SUBSTRING(name, 2) >= 'ba' AND MY_SUBSTRING(name, 2) <= 'bi'\n"
},
{
"answer_id": 152786,
"author": "George Mastros",
"author_id": 1408129,
"author_profile": "https://Stackoverflow.com/users/1408129",
"pm_score": 0,
"selected": false,
"text": "select * from widget\nwhere name Like 'b[a-i]%'\n"
},
{
"answer_id": 152879,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 0,
"selected": false,
"text": "select * from widgetwhere name >= 'ba' and name <= 'bi'||'~'\n"
},
{
"answer_id": 153190,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 0,
"selected": false,
"text": "select * from widget\nwhere left(name, 2) between 'ba' and 'bi'\n declare @CriteriaLength int\nset @CriteriaLength = 4\nselect * from widget\nwhere left(name, @CriteriaLength) between 'baaa' and 'bike'\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8799/"
] |
152,541
|
<p>I have a stored procedure that looks like:</p>
<pre><code>CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND CASE WHEN @AdditionalFilter = 1 THEN
T.Column2 IS NOT NULL
</code></pre>
<p>Needless to say, this doesn't work. How can I activate the additional where clause that checks for the @AdditionalFilter parameter? Thanks for any help.</p>
|
[
{
"answer_id": 152551,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 1,
"selected": false,
"text": "CREATE PROCEDURE dbo.usp_TestFilter\n @AdditionalFilter BIT = 1\nAS\n SELECT *\n FROM dbo.SomeTable T\n WHERE\n T.Column1 IS NOT NULL\n AND (NOT @AdditionalFilter OR T.Column2 IS NOT NULL)\n"
},
{
"answer_id": 152552,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 0,
"selected": false,
"text": "select *\nfrom SomeTable t\nwhere t.Column1 is null\nand (@AdditionalFilter = 0 or t.Column2 is not null)\n"
},
{
"answer_id": 152553,
"author": "Johan",
"author_id": 11347,
"author_profile": "https://Stackoverflow.com/users/11347",
"pm_score": 4,
"selected": true,
"text": "CREATE PROCEDURE dbo.usp_TestFilter\n @AdditionalFilter BIT = 1\nAS\n SELECT *\n FROM dbo.SomeTable T\n WHERE\n T.Column1 IS NOT NULL\n AND (@AdditionalFilter = 0 OR\n T.Column2 IS NOT NULL)\n"
},
{
"answer_id": 152748,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "WITH RECOMPILE EXEC WITH RECOMPILE CREATE PROCEDURE"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6651/"
] |
152,555
|
<p>I've always used a <code>*.h</code> file for my class definitions, but after reading some boost library code, I realised they all use <code>*.hpp</code>. I've always had an aversion to that file extension, I think mainly because I'm not used to it.</p>
<p>What are the advantages and disadvantages of using <code>*.hpp</code> over <code>*.h</code>?</p>
|
[
{
"answer_id": 152557,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 6,
"selected": false,
"text": "*.h *.hpp"
},
{
"answer_id": 152565,
"author": "slashmais",
"author_id": 15161,
"author_profile": "https://Stackoverflow.com/users/15161",
"pm_score": 3,
"selected": false,
"text": "#include .h .hpp"
},
{
"answer_id": 152641,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 4,
"selected": false,
"text": "*.hpp *.h *.hpp *.h *.hpp"
},
{
"answer_id": 152654,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 1,
"selected": false,
"text": ".cpp .c cl.exe #include .c /P /E stdout /EP #line /C .hpp"
},
{
"answer_id": 153301,
"author": "Perculator",
"author_id": 21254,
"author_profile": "https://Stackoverflow.com/users/21254",
"pm_score": 6,
"selected": false,
"text": ".hpp .h .cpp .hpp .cpp .hpp"
},
{
"answer_id": 154445,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 8,
"selected": false,
"text": "__cplusplus extern \"C\" #ifndef MY_HEADER_H\n#define MY_HEADER_H\n\n #ifdef __cplusplus\n extern \"C\"\n {\n #endif\n\n void myCFunction() ;\n\n #ifdef __cplusplus\n } // extern \"C\"\n #endif\n\n#endif // MY_HEADER_H\n extern \"C\" #ifndef MY_HEADER_HPP\n#define MY_HEADER_HPP\n\nextern \"C\"\n{\n#include \"my_header.h\"\n}\n\n#endif // MY_HEADER_HPP\n #ifndef MY_HEADER_H\n#define MY_HEADER_H\n\nvoid myCFunction() ;\n\n#endif // MY_HEADER_H\n"
},
{
"answer_id": 35096893,
"author": "FrankHB",
"author_id": 2307646,
"author_profile": "https://Stackoverflow.com/users/2307646",
"pm_score": 2,
"selected": false,
"text": ".hpp .h .hpp .hh .hxx .h .hpp .h .hpp .h .cpp"
},
{
"answer_id": 35868424,
"author": "dhein",
"author_id": 2003898,
"author_profile": "https://Stackoverflow.com/users/2003898",
"pm_score": 4,
"selected": false,
"text": "C++ .h .hpp C++ C++ header-name:\n < h-char-sequence >\n \" q-char-sequence \"\nh-char-sequence:\n h-char\n h-char-sequence h-char\nh-char:\n any member of the source character set except new-line and >\nq-char-sequence:\n q-char\n q-char-sequence q-char\nq-char:\n any member of the source character set except new-line and \"\n '\\n' <> > \"\" \" prettyStupidIdea.> #include \"prettyStupidIdea.>\"\n #include <prettyStupidIdea.>>\n #include <<.<>\n C++ .hpp .hpp .cc .mm .hpp C++ .h .h .hpp .h .hpp .hpp"
},
{
"answer_id": 37825776,
"author": "Justin Time - Reinstate Monica",
"author_id": 5386374,
"author_profile": "https://Stackoverflow.com/users/5386374",
"pm_score": 2,
"selected": false,
"text": "header.h header.hpp header.hh header.hx h.header this.is.not.a.valid.header ihjkflajfajfklaf .h .h .hpp .hh .h .tpp .h .tpp .h .h .hpp .hh .hxx .h .hpp"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
152,580
|
<p>How do I check if an object is of a given type, or if it inherits from a given type?</p>
<p>How do I check if the object <code>o</code> is of type <code>str</code>?</p>
<hr />
<p><sub>Beginners often wrongly expect the string to <em>already be</em> "a number" - either expecting Python 3.x <code>input</code> to convert type, or expecting that a string like <code>'1'</code> is <em>also simultaneously</em> an integer. This is the wrong canonical for those questions. Please carefully read the question and then use <a href="https://stackoverflow.com/questions/354038">How do I check if a string represents a number (float or int)?</a>, <a href="https://stackoverflow.com/questions/20449427/">How can I read inputs as numbers?</a> and/or <a href="https://stackoverflow.com/questions/23294658/">Asking the user for input until they give a valid response</a> as appropriate.</sub></p>
|
[
{
"answer_id": 152583,
"author": "Alexander Kojevnikov",
"author_id": 712,
"author_profile": "https://Stackoverflow.com/users/712",
"pm_score": 4,
"selected": false,
"text": "isinstance(o, str)\n"
},
{
"answer_id": 152592,
"author": "Herge",
"author_id": 14102,
"author_profile": "https://Stackoverflow.com/users/14102",
"pm_score": 6,
"selected": false,
"text": "isinstance(o, str) True o str str type(o) is str True o False o str"
},
{
"answer_id": 152596,
"author": "Fredrik Johansson",
"author_id": 1163767,
"author_profile": "https://Stackoverflow.com/users/1163767",
"pm_score": 12,
"selected": true,
"text": "isinstance o str str if isinstance(o, str):\n o str str if type(o) is str:\n if issubclass(type(o), str):\n o if isinstance(o, basestring):\n unicode str str unicode basestring basestring str bytes isinstance True o (str, unicode) if isinstance(o, (str, unicode)):\n"
},
{
"answer_id": 153032,
"author": "Will Harding",
"author_id": 23508,
"author_profile": "https://Stackoverflow.com/users/23508",
"pm_score": 3,
"selected": false,
"text": "AttributeError urllib2.urlopen() read() isinstance()"
},
{
"answer_id": 154156,
"author": "Dan Lenski",
"author_id": 20789,
"author_profile": "https://Stackoverflow.com/users/20789",
"pm_score": 8,
"selected": false,
"text": "try...except file .write() isinstance(obj, cls)"
},
{
"answer_id": 11763264,
"author": "Chris Barker",
"author_id": 1569130,
"author_profile": "https://Stackoverflow.com/users/1569130",
"pm_score": 3,
"selected": false,
"text": "list array try:\n my_sequence.extend(o)\nexcept TypeError:\n my_sequence.append(o)\n [ ]"
},
{
"answer_id": 37076991,
"author": "Praxeolitic",
"author_id": 1128289,
"author_profile": "https://Stackoverflow.com/users/1128289",
"pm_score": 5,
"selected": false,
"text": "def foo(i: int):\n return i\n\nfoo(5)\nfoo('oops')\n foo('oops') int mypy mypy script.py\nscript.py:12: error: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\n mypy list typing Iterable Callable"
},
{
"answer_id": 54720728,
"author": "Granitosaurus",
"author_id": 3737009,
"author_profile": "https://Stackoverflow.com/users/3737009",
"pm_score": 3,
"selected": false,
"text": "from typeguard import check_type\nfrom typing import List\n\ntry:\n check_type('mylist', [1, 2], List[int])\nexcept TypeError as e:\n print(e)\n check_type('foo', [1, 3.14], List[Union[int, float]])\n# vs\nisinstance(foo, list) and all(isinstance(a, (int, float)) for a in foo) \n"
},
{
"answer_id": 57099789,
"author": "Yerramsetty Rohit",
"author_id": 10548228,
"author_profile": "https://Stackoverflow.com/users/10548228",
"pm_score": 4,
"selected": false,
"text": ">>> a = [1,2,3,4] \n>>> b = 1 \n>>> type(a).__name__\n'list'\n>>> type(a).__name__ == 'list'\nTrue\n>>> type(b).__name__ == 'list'\nFalse\n>>> type(b).__name__\n'int'\n"
},
{
"answer_id": 59466517,
"author": "cherah30",
"author_id": 4887530,
"author_profile": "https://Stackoverflow.com/users/4887530",
"pm_score": -1,
"selected": false,
"text": "from typing import NewType\nUserId = NewType ('UserId', int)\nsome_id = UserId (524313`)\n"
},
{
"answer_id": 62122230,
"author": "Ultrablendz",
"author_id": 5006125,
"author_profile": "https://Stackoverflow.com/users/5006125",
"pm_score": -1,
"selected": false,
"text": ">>> a = 1\n>>> type(a) == type(1)\nTrue\n>>> b = 'abc'\n>>> type(b) == type('')\nTrue\n"
},
{
"answer_id": 67462404,
"author": "Simply Beautiful Art",
"author_id": 7741591,
"author_profile": "https://Stackoverflow.com/users/7741591",
"pm_score": 3,
"selected": false,
"text": "isinstance, issubclass, type def sum(nums):\n \"\"\"Expect an iterable of integers and return the sum.\"\"\"\n result = 0\n for n in nums:\n result += n\n return result\n __iter__ def sum(nums):\n \"\"\"Try to catch exceptions?\"\"\"\n try:\n result = 0\n for n in nums:\n result += n\n return result\n except TypeError as e:\n print(e)\n TypeError specific types specific behaviors nums n float int int nums TypeError def sum(nums):\n \"\"\"\n Try to catch all of our exceptions only.\n Re-raise them with more specific details.\n \"\"\"\n result = 0\n\n try:\n iter(nums)\n except TypeError as e:\n raise TypeError(\"nums must be iterable\")\n\n for n in nums:\n try:\n result += int(n)\n except TypeError as e:\n raise TypeError(\"stopped mid iteration since a non-integer was found\")\n\n return result\n from typing import Iterable\n\ndef sum(nums: Iterable[int]) -> int:\n result = 0\n for n in nums:\n result += n\n return result\n typeguard dataclasses help(...)"
},
{
"answer_id": 68052807,
"author": "SuperNova",
"author_id": 3464971,
"author_profile": "https://Stackoverflow.com/users/3464971",
"pm_score": 5,
"selected": false,
"text": "| isinstance >>> isinstance('1223', int | str) \nTrue\n\n>>> isinstance('abcd', int | str) \nTrue\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14102/"
] |
152,585
|
<p>What is the simplest way to identify and separate GET and POST parameters from a controller in Ruby on Rails, which will be equivalent to $_GET and $_POST variables in PHP?</p>
|
[
{
"answer_id": 152599,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 6,
"selected": false,
"text": "request.get? request.post?"
},
{
"answer_id": 152652,
"author": "Ben Scofield",
"author_id": 6478,
"author_profile": "https://Stackoverflow.com/users/6478",
"pm_score": 6,
"selected": true,
"text": "request.query_string.split(/&/).inject({}) do |hash, setting|\n key, val = setting.split(/=/)\n hash[key.to_sym] = val\n hash\nend\n"
},
{
"answer_id": 152872,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 2,
"selected": false,
"text": "map.connect '/posts/:post_id', :controller => 'posts', :action => 'update', :conditions => {:method => :post} \n map.resources :posts, :conditions => {:method => :post} \n"
},
{
"answer_id": 152922,
"author": "domgblackwell",
"author_id": 16954,
"author_profile": "https://Stackoverflow.com/users/16954",
"pm_score": 1,
"selected": false,
"text": "params[:foo] config/routes.rb"
},
{
"answer_id": 8364866,
"author": "wiseland",
"author_id": 1078483,
"author_profile": "https://Stackoverflow.com/users/1078483",
"pm_score": 4,
"selected": false,
"text": "request.POST request.GET"
},
{
"answer_id": 9586443,
"author": "Ryan Barton",
"author_id": 204148,
"author_profile": "https://Stackoverflow.com/users/204148",
"pm_score": 4,
"selected": false,
"text": "request.query_parameters request.path_parameters request.request_parameters Hash#reject"
},
{
"answer_id": 13389109,
"author": "Rod McLaughlin",
"author_id": 1495955,
"author_profile": "https://Stackoverflow.com/users/1495955",
"pm_score": 0,
"selected": false,
"text": "routes.rb post 'ctrllr/:a/:b' => 'ctrllr#an_action'\n request.GET request.POST"
},
{
"answer_id": 16123963,
"author": "betoharres",
"author_id": 1254111,
"author_profile": "https://Stackoverflow.com/users/1254111",
"pm_score": 0,
"selected": false,
"text": "if request.query_parameters().to_a.empty?\n"
},
{
"answer_id": 39448933,
"author": "Navin",
"author_id": 3522082,
"author_profile": "https://Stackoverflow.com/users/3522082",
"pm_score": 3,
"selected": false,
"text": "request.get? request.post?"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18768/"
] |
152,586
|
<p>I want to test ASP.NET application using NUnit, but it seems WebConfigurationManager.ConnectionStrings collection is empty when running from NUnit GUI.</p>
<p>Could you tell me how to initialize this collection (probably in [SetUp] function of [TestFixture])? Should I copy Web.config somethere?</p>
<p>Thank you!</p>
|
[
{
"answer_id": 266119,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 3,
"selected": false,
"text": "\\bin\\debug\\MyTests.dll \\bin\\Debug\\MyTests.dll.config \\MyNUnitProject.nunit \\MyNUnitProject.config \\App.config \\bin\\Debug\\MyTests.dll.config \\bin\\Release\\MyTests.dll.config bin\\Debug\\ MyTests.dll.config"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152586",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
152,602
|
<p>Which of theese two alternatives do you find yourself using most often, and which is more "idiomatic"?</p>
<ol>
<li>f arg (obj.DoStuff())</li>
<li>f arg <| obj.DoStuff()</li>
</ol>
|
[
{
"answer_id": 152933,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 4,
"selected": true,
"text": "raise <| new FooException(\"blah\")\n f arg (g x y)\n f arg (g(x,y))\n f g()\n f g ()\n f (g())\n"
},
{
"answer_id": 300465,
"author": "namin",
"author_id": 34596,
"author_profile": "https://Stackoverflow.com/users/34596",
"pm_score": 2,
"selected": false,
"text": "|> [1; 2; 3] |> (fun x -> x.Length*2)\n (fun x -> x.Length*2) [1; 2; 3]\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21182/"
] |
152,613
|
<p>I have a specialized list that holds items of type <code>IThing</code>:</p>
<pre><code>public class ThingList : IList<IThing>
{...}
public interface IThing
{
Decimal Weight { get; set; }
Decimal Velocity { get; set; }
Decimal Distance { get; set; }
Decimal Age { get; set; }
Decimal AnotherValue { get; set; }
[...even more properties and methods...]
}
</code></pre>
<p>Sometimes I need to know the maximum or minimum of a certain property of all the things in the list. Because of "Tell don't ask" we let the List figure it out:</p>
<pre><code>public class ThingList : IList<IThing>
{
public Decimal GetMaximumWeight()
{
Decimal result = 0;
foreach (IThing thing in this) {
result = Math.Max(result, thing.Weight);
}
return result;
}
}
</code></pre>
<p>Thats very nice. But sometimes I need the minimum weight, sometimes the maximum velocity and so on. I don't want a <code>GetMaximum*()/GetMinimum*()</code> pair for every single property.</p>
<p>One solution would be reflection. Something like (hold your nose, strong code smell!):</p>
<pre><code>Decimal GetMaximum(String propertyName);
Decimal GetMinimum(String propertyName);
</code></pre>
<p>Are there any better, less smelly ways to accomplish this?</p>
<p>Thanks,
Eric</p>
<p>Edit: @Matt: .Net 2.0</p>
<p><strike>Conclusion: There is no better way for .Net 2.0 (with Visual Studio 2005). Maybe we should move to .Net 3.5 and Visual Studio 2008 sometime soon. Thanks, guys.</strike></p>
<p>Conclusion: There are diffent ways that are far better than reflection. Depending on runtime and C# version. Have a look at Jon Skeets answer for the differences. All answers are are very helpful.</p>
<p>I will go for Sklivvz suggestion (anonymous methods). There are several code snippets from other people (Konrad Rudolph, Matt Hamilton and Coincoin) which implement Sklivvz idea. I can only "accept" one answer, unfortunately.</p>
<p>Thank you very much. You can all feel "accepted", altough only Sklivvz gets the credits ;-)</p>
|
[
{
"answer_id": 152619,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 4,
"selected": false,
"text": "Decimal result = myThingList.Max(i => i.Weight);\n"
},
{
"answer_id": 152624,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "public Decimal GetMaximum(Func<IThing, Decimal> prop) {\n Decimal result = Decimal.MinValue;\n foreach (IThing thing in this)\n result = Math.Max(result, prop(thing));\n\n return result;\n}\n Decimal result = list.GetMaximum(x => x.Weight);\n"
},
{
"answer_id": 152625,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "decimal maxWeight = list.Max(thing => thing.Weight);\ndecimal minWeight = list.Min(thing => thing.Weight);\n decimal maxWeight = Enumerable.Max(list, delegate(IThing thing) \n { return thing.Weight; }\n);\ndecimal minWeight = Enumerable.Min(list, delegate(IThing thing)\n { return thing.Weight; }\n);\n"
},
{
"answer_id": 152626,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 4,
"selected": true,
"text": "public class Thing\n{\n public int theInt;\n public char theChar;\n public DateTime theDateTime;\n \n public Thing(int theInt, char theChar, DateTime theDateTime)\n {\n this.theInt = theInt;\n this.theChar = theChar;\n this.theDateTime = theDateTime;\n }\n \n public string Dump()\n {\n return string.Format(\"I: {0}, S: {1}, D: {2}\", \n theInt, theChar, theDateTime);\n }\n}\n\npublic class ThingCollection: List<Thing>\n{\n public delegate Thing AggregateFunction(Thing Best, \n Thing Candidate);\n \n public Thing Aggregate(Thing Seed, AggregateFunction Func)\n {\n Thing res = Seed;\n foreach (Thing t in this) \n {\n res = Func(res, t);\n }\n return res;\n }\n}\n\nclass MainClass\n{\n public static void Main(string[] args)\n {\n Thing a = new Thing(1,'z',DateTime.Now);\n Thing b = new Thing(2,'y',DateTime.Now.AddDays(1));\n Thing c = new Thing(3,'x',DateTime.Now.AddDays(-1));\n Thing d = new Thing(4,'w',DateTime.Now.AddDays(2));\n Thing e = new Thing(5,'v',DateTime.Now.AddDays(-2));\n \n ThingCollection tc = new ThingCollection();\n \n tc.AddRange(new Thing[]{a,b,c,d,e});\n \n Thing result;\n\n //Max by date\n result = tc.Aggregate(tc[0], \n delegate (Thing Best, Thing Candidate) \n { \n return (Candidate.theDateTime.CompareTo(\n Best.theDateTime) > 0) ? \n Candidate : \n Best; \n }\n );\n Console.WriteLine(\"Max by date: {0}\", result.Dump());\n \n //Min by char\n result = tc.Aggregate(tc[0], \n delegate (Thing Best, Thing Candidate) \n { \n return (Candidate.theChar < Best.theChar) ? \n Candidate : \n Best; \n }\n );\n Console.WriteLine(\"Min by char: {0}\", result.Dump()); \n }\n}\n Max by date: I: 4, S: w, D: 10/3/2008 12:44:07 AM Min by char: I: 5, S: v, D: 9/29/2008 12:44:07 AM"
},
{
"answer_id": 152756,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "Max delegate Decimal PropertyValue(IThing thing);\n\npublic class ThingList : IList<IThing> {\n public Decimal Max(PropertyValue prop) {\n Decimal result = Decimal.MinValue;\n foreach (IThing thing in this) {\n result = Math.Max(result, prop(thing));\n }\n return result;\n }\n}\n ThingList lst;\nlst.Max(delegate(IThing thing) { return thing.Age; });\n"
},
{
"answer_id": 152763,
"author": "Coincoin",
"author_id": 42,
"author_profile": "https://Stackoverflow.com/users/42",
"pm_score": 2,
"selected": false,
"text": "public delegate Decimal GetProperty<TElement>(TElement element);\n\npublic static Decimal Max<TElement>(IEnumerable<TElement> enumeration, \n GetProperty<TElement> getProperty)\n{\n Decimal max = Decimal.MinValue;\n\n foreach (TElement element in enumeration)\n {\n Decimal propertyValue = getProperty(element);\n max = Math.Max(max, propertyValue);\n }\n\n return max;\n}\n string[] array = new string[] {\"s\",\"sss\",\"ddsddd\",\"333\",\"44432333\"};\n\nMax(array, delegate(string e) { return e.Length;});\n string[] array = new string[] {\"s\",\"sss\",\"ddsddd\",\"333\",\"44432333\"};\narray.Max( e => e.Length);\n"
},
{
"answer_id": 152778,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "public delegate T GetPropertyValueDelegate<T>(IThing t);\n\npublic T GetMaximum<T>(GetPropertyValueDelegate<T> getter)\n where T : IComparable\n{\n if (this.Count == 0) return default(T);\n\n T max = getter(this[0]);\n for (int i = 1; i < this.Count; i++)\n {\n T ti = getter(this[i]);\n if (max.CompareTo(ti) < 0) max = ti;\n }\n return max;\n}\n ThingList list;\nDecimal maxWeight = list.GetMaximum(delegate(IThing t) { return t.Weight; });\n"
},
{
"answer_id": 152976,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 2,
"selected": false,
"text": "public delegate A AggregateAction<A, B>( A prevResult, B currentElement );\n\npublic static Tagg Aggregate<Tcoll, Tagg>( \n IEnumerable<Tcoll> source, Tagg seed, AggregateAction<Tagg, Tcoll> func )\n{\n Tagg result = seed;\n\n foreach ( Tcoll element in source ) \n result = func( result, element );\n\n return result;\n}\n\n//this makes max easy\npublic static int Max( IEnumerable<int> source )\n{\n return Aggregate<int,int>( source, 0, \n delegate( int prev, int curr ) { return curr > prev ? curr : prev; } );\n}\n\n//but you could also do sum\npublic static int Sum( IEnumerable<int> source )\n{\n return Aggregate<int,int>( source, 0, \n delegate( int prev, int curr ) { return curr + prev; } );\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8976/"
] |
152,643
|
<p>For an <code>std::map<std::string, std::string> variables</code>, I'd like to do this:</p>
<pre><code>BOOST_CHECK_EQUAL(variables["a"], "b");
</code></pre>
<p>The only problem is, in this context <code>variables</code> is <code>const</code>, so <code>operator[]</code> won't work :(</p>
<p>Now, there are several workarounds to this; casting away the <code>const</code>, using <code>variables.count("a") ? variables.find("a")->second : std::string()</code> or even making a function wrapping that. None of these seem to me to be as nice as <code>operator[]</code>. What should I do? Is there a standard way of doing this (beautifully)?</p>
<p><strong>Edit:</strong> Just to state the answer that none of you want to give: No, there is no convenient, beautiful, standard way of doing this in C++. I will have to implement a support function.</p>
|
[
{
"answer_id": 152658,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "find const count T const& item(map<TKey, T> const& m, TKey const& key, T const& def = T()) {\n map<TKey, T>::const_iterator i = m.find(key);\n return i == m.end() ? def : i->second;\n}\n T def"
},
{
"answer_id": 152660,
"author": "xtofl",
"author_id": 6610,
"author_profile": "https://Stackoverflow.com/users/6610",
"pm_score": 1,
"selected": false,
"text": "map::find != map.end() second map<int, int> m;\nm[1]=5; m[2]=6; // fill in some couples\n...\nmap<int,int>::const_iterator it = m.find( 3 );\nif( it != m.end() ) {\n int value = it->second;\n // ... do stuff with value\n}\n map::operator[]( const key_type& key ) const it->second"
},
{
"answer_id": 152665,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 5,
"selected": true,
"text": "template <typename K, typename V>\nV get(std::map<K, V> const& map, K const& key)\n{\n std::map<K, V>::const_iterator iter(map.find(key));\n return iter != map.end() ? iter->second : V();\n}\n template <typename T>\ntypename T::mapped_type get(T const& map, typename T::key_type const& key)\n{\n typename T::const_iterator iter(map.find(key));\n return iter != map.end() ? iter->second : typename T::mapped_type();\n}\n"
},
{
"answer_id": 152680,
"author": "janm",
"author_id": 7256,
"author_profile": "https://Stackoverflow.com/users/7256",
"pm_score": 4,
"selected": false,
"text": "template<typename CONT>\nbool check_equal(const CONT& m, const typename CONT::key_type& k,\n const typename CONT::mapped_type& v)\n{\n CONT::const_iterator i(m.find(k));\n if (i == m.end()) return false;\n return i->second == v;\n}\n if (nonmutating_get(m, \"key\") == \"value\") { ... }\n if (check_equal(m, \"key\", \"value\")) { ... }\n"
},
{
"answer_id": 153145,
"author": "Matt Price",
"author_id": 852,
"author_profile": "https://Stackoverflow.com/users/852",
"pm_score": 3,
"selected": false,
"text": "template <typename K, typename V>\nV get1(const std::map<K, V>& theMap, const K const key)\n{\n std::map<K, V>::const_iterator iter(theMap.find(key));\n return iter != theMap.end() ? iter->second : V();\n}\n template<typename T>\ntypename T::mapped_type\nget2(const T& theMap, const typename T::key_type& key)\n{\n typename T::const_iterator itr = theMap.find(key);\n return itr != theMap.end() ? itr->second : typename T::mapped_type();\n}\n std::map<std::string, int> data;\nget1(data, \"hey\"); // doesn't compile because the key type is ambiguous\nget2(data, \"hey\"); // just fine, a const char* can be converted to a string\n"
},
{
"answer_id": 153913,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 0,
"selected": false,
"text": "std::map<std::string, std::string>::const_iterator it( m.find(\"a\") );\nBOOST_CHECK_EQUAL( \n ( it == m.end() ? std::string(\"\") : it->second ), \n \"b\" \n );\n"
},
{
"answer_id": 1000076,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "template <typename K,typename V> \nstruct Dictionary:public std::map<K,V> \n{ \n const V& operator[] (const K& key) const \n { \n std::map<K,V>::const_iterator iter(this->find(key)); \n BOOST_VERIFY(iter!=this->end()); \n return iter->second; \n } \n}; \n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2971/"
] |
152,664
|
<p>I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?</p>
|
[
{
"answer_id": 152779,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 5,
"selected": true,
"text": "ItemTemplateSelector DataTemplate DataType DataTemplate <DataTemplate DataType={x:Type local:ObjectA}>\n ...\n</DataTemplate>\n x:Key DataTemplate"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6276/"
] |
152,670
|
<p>Is it possible to prevent the Windows Installer from running every time Access 2003 and Access 2007 are started, when they are both installed on the same machine at the same time..?</p>
<p>Like many developers I need to run more than 1 version of MS Access. I have just installed Access 2007. If I open Access 2003 and then open Access 2007 I have to wait 3mins for the 'Configuring Microsoft Office Enterprise 2007..." dialog. Then if I open Access 2003 again it takes another 30secs or so to configure that. </p>
<p>PLEASE NOTE: I am using shortcuts to open the files that include the full path to Access. Eg to open Access 2007:</p>
<pre><code> "C:\program files\microsoft office 12\office12\msaccess.exe" "C:\test.accdb"
</code></pre>
<p>and for 2003:</p>
<pre><code> "C:\program files\microsoft office 11\office11\msaccess.exe" "C:\test.mdb"
</code></pre>
|
[
{
"answer_id": 1450798,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "reg add HKCU\\Software\\Microsoft\\Office\\11.0\\Word\\Options /v NoReReg /t REG_DWORD /d 1\n\nreg add HKCU\\Software\\Microsoft\\Office\\12.0\\Word\\Options /v NoReReg /t REG_DWORD /d 1\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10422/"
] |
152,675
|
<p>There is probably is simple fix for this but I currently have code similar to </p>
<pre><code>dim dr as dbDataReader
try
dr = connection.getDataReader(sql_str)
Catch ex as sqlClientException
log.error(ex)
finally
if not IsNothing(dr) then
dr.close
end if
end try
</code></pre>
<p>However Visual Studio still warns me that the </p>
<pre><code>if not IsNothing(dr) then
dr.close
end if
</code></pre>
<p>Can cause a NullReferenceException. What is the best way to mitigate this? I can't move the declaration into the try block.</p>
|
[
{
"answer_id": 152715,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 0,
"selected": false,
"text": "finally"
},
{
"answer_id": 152718,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "dim dr as dbDataReader\n\ntry\n dr = connection.getDataReader(sql_str)\nCatch ex as sqlClientException\n log.error(ex)\n dr = Nothing ' there is the change '\n' finaly block is not necesary '\nend try\n\nif not IsNothing(dr) then\n dr.close\nend if\n"
},
{
"answer_id": 152719,
"author": "Jason Stangroome",
"author_id": 20819,
"author_profile": "https://Stackoverflow.com/users/20819",
"pm_score": 4,
"selected": true,
"text": "Dim dr As DbDataReader = Nothing\n"
},
{
"answer_id": 152862,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "GetDataReader dr Nothing Using Using dr As DbDataReader = connection.GetDataReader(sql_str)\n Try\n ' Do something with dr '\n Catch ex As SqlClientException\n log.error(ex)\n End Try\nEnd Using\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
152,693
|
<p>I have an <strong>if</strong> condition which checks for value and the it throws new <strong>NumberFormatException</strong></p>
<p>Is there any other way to code this</p>
<pre><code>if (foo)
{
throw new NumberFormatException
}
// ..
catch (NumberFormatException exc)
{
// some msg...
}
</code></pre>
|
[
{
"answer_id": 152709,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 2,
"selected": false,
"text": "if(foo)\n{\n //some msg...\n} else\n{\n //do something else\n}\n"
},
{
"answer_id": 152716,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 0,
"selected": false,
"text": "try { if (foo) throw new NumberFormatException(); }\ncatch(NumberFormatexception) {/* ... */}\n"
},
{
"answer_id": 152720,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 2,
"selected": false,
"text": "try\n{\n // some stuff\n if (foo)\n {\n throw new NumberFormatException();\n }\n}\ncatch (NumberFormatException exc)\n{\n do something;\n}\n"
},
{
"answer_id": 152751,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 1,
"selected": false,
"text": "if(myObject.value != null && Checkformat(myObject.Value)\n{\n // good to go\n}\nelse\n{\n // not a good place to be. Prompt the user rather than raise an exception?\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11114/"
] |
152,694
|
<p>I'm setting up a new project using CruiseControl.net 1.4.</p>
<p>I see from <a href="http://confluence.public.thoughtworks.org/display/CCNETCOMM/Contributions" rel="nofollow noreferrer">ccnet contributions</a>
that there are two options for a subversion repository number labeller - a
feature that I would really like to make use of.</p>
<p>1) SVNLabeller available from <a href="http://www.jcxsoftware.com/jcx/ccnet-dev" rel="nofollow noreferrer">jcxsoftware</a></p>
<p>and</p>
<p>2) Svnrevisionlabeller available from <a href="http://code.google.com/p/svnrevisionlabeller/" rel="nofollow noreferrer">google code</a></p>
<p>My problem is that (1) claims support for ccnet 1.4 but I can't find
any documentation on how to configure it.</p>
<p>(2) comes with documentation but does not claim to support ccnet 1.4</p>
<p>Can anyone help me with either how to configure SVNLabeller or tell me
if Svnrevisionlabeller works with 1.4? </p>
|
[
{
"answer_id": 2017464,
"author": "VS.Php",
"author_id": 245085,
"author_profile": "https://Stackoverflow.com/users/245085",
"pm_score": 1,
"selected": false,
"text": " <labeller type=\"SvnLabeller\">\n <MajorVersion>1</MajorVersion>\n <MinorVersion>2</MinorVersion>\n <BuildNumber>3</BuildNumber>\n <workingDirectory>c:\\path to your code</workingDirectory>\n <executable>c:\\path to\\svn.exe</executable>\n </labeller>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5427/"
] |
152,699
|
<p>In Python, you can do this:</p>
<pre><code>import webbrowser
webbrowser.open_new("http://example.com/")
</code></pre>
<p>It will open the passed in url in the default browser</p>
<p>Is there a ruby equivalent?</p>
|
[
{
"answer_id": 152765,
"author": "Ken",
"author_id": 20621,
"author_profile": "https://Stackoverflow.com/users/20621",
"pm_score": 2,
"selected": false,
"text": "require 'win32ole'\nshell = WIN32OLE.new('Shell.Application')\nshell.ShellExecute(...)\n"
},
{
"answer_id": 152951,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 5,
"selected": false,
"text": "system(\"open\", \"http://stackoverflow.com/\")\n `open http://stackoverflow.com/`\n"
},
{
"answer_id": 152996,
"author": "Ryan McGeary",
"author_id": 8985,
"author_profile": "https://Stackoverflow.com/users/8985",
"pm_score": 8,
"selected": true,
"text": "$ gem install launchy\n require 'launchy'\n\nLaunchy.open(\"http://stackoverflow.com\")\n"
},
{
"answer_id": 153558,
"author": "palmsey",
"author_id": 521,
"author_profile": "https://Stackoverflow.com/users/521",
"pm_score": 2,
"selected": false,
"text": "system(\"start #{link}\")\n"
},
{
"answer_id": 12702115,
"author": "damage3025",
"author_id": 1656173,
"author_profile": "https://Stackoverflow.com/users/1656173",
"pm_score": 3,
"selected": false,
"text": "system(\"xdg-open\", \"http://stackoverflow.com/\")\n"
},
{
"answer_id": 14053693,
"author": "user1931928",
"author_id": 1931928,
"author_profile": "https://Stackoverflow.com/users/1931928",
"pm_score": 5,
"selected": false,
"text": "link = \"Insert desired link location here\"\nif RbConfig::CONFIG['host_os'] =~ /mswin|mingw|cygwin/\n system \"start #{link}\"\nelsif RbConfig::CONFIG['host_os'] =~ /darwin/\n system \"open #{link}\"\nelsif RbConfig::CONFIG['host_os'] =~ /linux|bsd/\n system \"xdg-open #{link}\"\nend\n"
},
{
"answer_id": 58855763,
"author": "Felix",
"author_id": 1680728,
"author_profile": "https://Stackoverflow.com/users/1680728",
"pm_score": 2,
"selected": false,
"text": "require 'os'\n\nsystem(OS.open_file_command, 'https://stackoverflow.com')\n# ~ like `xdg-open stackoverflow.com` on most modern unixoids,\n# but should work on most other operating systems, too.\n system"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
] |
152,708
|
<p>I needed to find all the files that contained a specific string pattern. The first solution that comes to mind is using <em>find</em> piped with <em>xargs grep</em>:</p>
<pre><code>find . -iname '*.py' | xargs grep -e 'YOUR_PATTERN'
</code></pre>
<p>But if I need to find patterns that spans on more than one line, I'm stuck because vanilla grep can't find multiline patterns.</p>
|
[
{
"answer_id": 152711,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 8,
"selected": true,
"text": "find . -iname '*.py' | xargs pcregrep -M '_name.*\\n.*_description'\n"
},
{
"answer_id": 152755,
"author": "ayaz",
"author_id": 23191,
"author_profile": "https://Stackoverflow.com/users/23191",
"pm_score": 7,
"selected": false,
"text": "grep grep -Pzo '_name.*\\n.*_description'\n -z --null-data -z"
},
{
"answer_id": 152848,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 5,
"selected": false,
"text": "pcregrep -Mi \"<title>(.*\\n){0,5}</title>\" afile.html\n pcregrep -Mi \"(?s)<title>.*</title>\" example.html \n"
},
{
"answer_id": 3718035,
"author": "Amit",
"author_id": 448436,
"author_profile": "https://Stackoverflow.com/users/448436",
"pm_score": 7,
"selected": false,
"text": "awk '/Start pattern/,/End pattern/' filename\n"
},
{
"answer_id": 11676024,
"author": "bukzor",
"author_id": 146821,
"author_profile": "https://Stackoverflow.com/users/146821",
"pm_score": 5,
"selected": false,
"text": "grep -P title grep -P '(?s)<title>.*</title>' example.html\n"
},
{
"answer_id": 27931490,
"author": "Shwaydogg",
"author_id": 722738,
"author_profile": "https://Stackoverflow.com/users/722738",
"pm_score": 4,
"selected": false,
"text": "ag 'abc.*(\\n|.)*efg'\n"
},
{
"answer_id": 31589471,
"author": "Martin",
"author_id": 5148382,
"author_profile": "https://Stackoverflow.com/users/5148382",
"pm_score": 3,
"selected": false,
"text": "awk '{if ($0 ~ /Start pattern/) {triggered=1;}if (triggered) {print; if ($0 ~ /End pattern/) { exit;}}}' filename\n"
},
{
"answer_id": 33180874,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 2,
"selected": false,
"text": "ex vi awk sed ex +\"/string1/,/string3/p\" -R -scq! file.txt\n aaa bbb ex +\"/aaa/,/bbb/p\" -scq! **/*.py\n ** shopt -s globstar"
},
{
"answer_id": 36393093,
"author": "pbal",
"author_id": 5905959,
"author_profile": "https://Stackoverflow.com/users/5905959",
"pm_score": 2,
"selected": false,
"text": "perl -ne 'print if (/begin pattern/../end pattern/)' filename\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22035/"
] |
152,714
|
<p>I am relatively new to matchers. I am toying around with <a href="http://code.google.com/p/hamcrest/" rel="noreferrer">hamcrest</a> in combination with JUnit and I kinda like it.</p>
<p>Is there a way, to state that one of multiple choices is correct?</p>
<p>Something like</p>
<pre><code>assertThat( result, is( either( 1, or( 2, or( 3 ) ) ) ) ) //does not work in hamcrest
</code></pre>
<p>The method I am testing returns one element of a collection. The list may contain multiple candidates. My current implementation returns the first hit, but that is not a requirement. I would like my testcase to succeed, if any of the possible candidates is returned. How would you express this in Java?</p>
<p>(I am open to hamcrest-alternatives)</p>
|
[
{
"answer_id": 153198,
"author": "marcospereira",
"author_id": 4600,
"author_profile": "https://Stackoverflow.com/users/4600",
"pm_score": 8,
"selected": true,
"text": "assertThat(result, anyOf(equalTo(1), equalTo(2), equalTo(3)))\n anyOf"
},
{
"answer_id": 6554732,
"author": "Tyler",
"author_id": 65977,
"author_profile": "https://Stackoverflow.com/users/65977",
"pm_score": 6,
"selected": false,
"text": "assertThat(result, either(is(1)).or(is(2)));\n assertThat(result, isOneOf(1, 2, 3))\n assertThat(result, isIn(theCollection))\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1870/"
] |
152,729
|
<p>If you use Image.Save Method to save an image to a EMF/WMF, you get an exception (<a href="http://msdn.microsoft.com/en-us/library/ktx83wah.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ktx83wah.aspx</a>)</p>
<p>Is there another way to save the image to an EMF/WMF?
Are there any encoders available?</p>
|
[
{
"answer_id": 152830,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 2,
"selected": false,
"text": "Metafile Graphics Graphics.FromImage Graphics.DrawImage StretchBlt"
},
{
"answer_id": 688593,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " Graphics grfx = CreateGraphics();\n MemoryStream ms = new MemoryStream();\n IntPtr ipHdc = grfx.GetHdc();\n\n Metafile mf = new Metafile(ms, ipHdc);\n\n grfx.ReleaseHdc(ipHdc);\n grfx.Dispose();\n grfx = Graphics.FromImage(mf);\n\n grfx.FillEllipse(Brushes.Gray, 0, 0, 100, 100);\n grfx.DrawEllipse(Pens.Black, 0, 0, 100, 100);\n grfx.DrawArc(new Pen(Color.Red, 10), 20, 20, 60, 60, 30, 120);\n grfx.Dispose();\n\n mf.Save(@\"C:\\file.emf\", ImageFormat.Emf);\n mf.Save(@\"C:\\file.png\", ImageFormat.Png);\n"
},
{
"answer_id": 733465,
"author": "erikkallen",
"author_id": 47161,
"author_profile": "https://Stackoverflow.com/users/47161",
"pm_score": 4,
"selected": false,
"text": "[DllImport(\"gdi32\")] static extern uint GetEnhMetaFileBits(IntPtr hemf, uint cbBuffer, byte[] lpbBuffer);\n\n\nIntPtr h = metafile.GetHenhMetafile();\nint size = GetEnhMetaFileBits(h, 0, null);\nbyte[] data = new byte[size];\nGetEnhMetaFileBits(h, size, data);\nusing (FileStream w = File.Create(\"out.emf\")) {\n w.Write(data, 0, size);\n}\n// TODO: I don't remember whether the handle needs to be closed, but I guess not.\n"
},
{
"answer_id": 895204,
"author": "Han",
"author_id": 6473,
"author_profile": "https://Stackoverflow.com/users/6473",
"pm_score": 2,
"selected": false,
"text": "<System.Runtime.InteropServices.DllImportAttribute(\"gdi32.dll\", EntryPoint:=\"GetEnhMetaFileBits\")> _\n Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData As IntPtr) As UInteger\nEnd Function\n\n <System.Runtime.InteropServices.DllImportAttribute(\"gdi32.dll\", EntryPoint:=\"GetEnhMetaFileBits\")> _\n Public Shared Function GetEnhMetaFileBits(<System.Runtime.InteropServices.InAttribute()> ByVal hEMF As System.IntPtr, ByVal nSize As UInteger, ByVal lpData() As Byte) As UInteger\nEnd Function\n Dim h As IntPtr = mf.GetHenhmetafile()\nCopyEnhMetaFileW(h, FileName)\n"
},
{
"answer_id": 978346,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "Image Metafile Bitmap Metafile var path = @\"c:\\foo.emf\"\nvar g = CreateGraphics(); // get a graphics object from your form, or wherever\nvar img = new Metafile(path, g.GetHdc()); // file is created here\nvar ig = Graphics.FromImage(img);\n// call drawing methods on ig, causing writes to the file\nig.Dispose(); img.Dispose(); g.ReleaseHdc(); g.Dispose();\n Bitmap ig.DrawImage(your_bitmap)"
},
{
"answer_id": 10509475,
"author": "Alex",
"author_id": 1383581,
"author_profile": "https://Stackoverflow.com/users/1383581",
"pm_score": 2,
"selected": false,
"text": "CopyEnhMetaFile IntPtr ptr2 = CopyEnhMetaFile(iptrMetafileHandle, \"image.emf\");\nDeleteEnhMetaFile(ptr2);\n\n// Delete the metafile from memory\nDeleteEnhMetaFile(iptrMetafileHandle);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12192/"
] |
152,744
|
<p>in Erlang I have a supervisor-tree of processes, containing one that accepts tcp/ip connections. For each incoming connection I spawn a new process. Should this process be added to the supervisor tree or not?</p>
<p>Regards,
Steve</p>
|
[
{
"answer_id": 154457,
"author": "Adam Lindberg",
"author_id": 2457,
"author_profile": "https://Stackoverflow.com/users/2457",
"pm_score": 2,
"selected": false,
"text": "simple_one_for_one"
},
{
"answer_id": 178426,
"author": "archaelus",
"author_id": 9040,
"author_profile": "https://Stackoverflow.com/users/9040",
"pm_score": 3,
"selected": true,
"text": "simple_one_for_one yourapp_client_sup {Id, {yourapp_client_connection, start_link_with_socket, []}, Restart, Shutdown, worker, temporary} temporary temporary gen_tcp:accept supervisor:start_child(yourapp_client_sup, [Socket,Options,...]) yourapp_client_sup:start_link(Socket, Options, ...) youreapp_client_connection:start_link_with_socket gen_server proc_lib supervisor gen_tcp:controlling_process yourapp_client_sup yourclient_connection_handler yourapp_client_sup EXIT EXIT simple_one_for_one"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23760/"
] |
152,745
|
<p>I need a way to represent a 2-D array (a dense matrix) of doubles in C++, with absolute minimum accessing overhead. </p>
<p>I've done some timing on various linux/unix machines and gcc versions. An STL vector of vectors, declared as:</p>
<pre><code>vector<vector<double> > matrix(n,vector<double>(n));
</code></pre>
<p>and accessed through <code>matrix[i][j]</code> is between 5% and 100% slower to access than an array declared as:</p>
<pre><code>double *matrix = new double[n*n];
</code></pre>
<p>accessed through an inlined index function <code>matrix[index(i,j)]</code>, where <code>index(i,j)</code> evaluates to i+n*j. Other ways of arranging a 2-D array without STL - an array of n pointers to the start of each row, or defining the whole thing on the stack as a constant size <code>matrix[n][n]</code> - run at almost exactly the same speed as the index function method.</p>
<p>Recent GCC versions (> 4.0) seem to be able to compile the STL vector-of-vectors to nearly the same efficiency as the non-STL code when optimisations are turned on, but this is somewhat machine-dependent.</p>
<p>I'd like to use STL if possible, but will have to choose the fastest solution. Does anyone have any experience in optimising STL with GCC?</p>
|
[
{
"answer_id": 152761,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 3,
"selected": false,
"text": "valarray<double> a;\n"
},
{
"answer_id": 152776,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 3,
"selected": false,
"text": "vector new vector"
},
{
"answer_id": 152784,
"author": "Nils Pipenbrinck",
"author_id": 15955,
"author_profile": "https://Stackoverflow.com/users/15955",
"pm_score": 4,
"selected": true,
"text": "-fipa-matrix-reorg\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152745",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23732/"
] |
152,757
|
<p>I am wondering whether it is safe to mix jdk 1.5 and 1.6 (Java 6) object serialization (biderctional communication). I searched for an explicit statement from sun concerning this question but did not succeed. So, besides the technical feasability I am searching for an "official" statement concerning the problem.</p>
|
[
{
"answer_id": 152792,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 4,
"selected": false,
"text": "private static final long serialVersionUID = 8683452581122892189L;\n"
},
{
"answer_id": 155521,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 0,
"selected": false,
"text": "XMLEncoder XMLDecoder"
},
{
"answer_id": 359336,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "java.io.InvalidClassException: javax.swing.JComponent; local class incompatible: stream classdesc serialVersionUID = 7917968344860800289, local class serialVersionUID = -1030230214076481435\n at java.io.ObjectStreamClass.initNonProxy(Unknown Source)\n at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)\n at java.io.ObjectInputStream.readClassDesc(Unknown Source)\n at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)\n at java.io.ObjectInputStream.readClassDesc(Unknown Source)\n at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)\n at java.io.ObjectInputStream.readClassDesc(Unknown Source)\n at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.readArray(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.defaultReadFields(Unknown Source)\n at java.io.ObjectInputStream.readSerialData(Unknown Source)\n at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.defaultReadFields(Unknown Source)\n at java.io.ObjectInputStream.readSerialData(Unknown Source)\n at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.readArray(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.defaultReadFields(Unknown Source)\n at java.io.ObjectInputStream.readSerialData(Unknown Source)\n at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)\n at java.io.ObjectInputStream.readObject0(Unknown Source)\n at java.io.ObjectInputStream.readObject(Unknown Source)\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
152,770
|
<p>Is there any facility of transposing rows to columns in SQL Server (it is possible in MS-Access)?
I was befuddled because this facility is available in MS-Access but not in SQL Server. Is it by design that this feature has not been included in SQL Server?</p>
|
[
{
"answer_id": 152963,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 3,
"selected": true,
"text": "color red\nsize big\ncity Chicago\n"
},
{
"answer_id": 169412,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 2,
"selected": false,
"text": "SELECT\n RowValueNowAColumn = \n CONVERT(varchar,\n MAX(\n SUBSTRING(myTable.MyVarCharColumn,1,DATALENGTH(myTable.MyVarCharColumn)\n * CHARINDEX(sa.SearchAttributeName,'MyRowValue'))))\nFROM\n myTable\n"
},
{
"answer_id": 2520747,
"author": "SimonH_UK",
"author_id": 302228,
"author_profile": "https://Stackoverflow.com/users/302228",
"pm_score": 1,
"selected": false,
"text": "IF EXISTS (SELECT * FROM SYSOBJECTS WHERE XTYPE = 'P' AND NAME = 'USP_LIST_CONCAT')\nDROP PROCEDURE USP_LIST_CONCAT\nGO\n\nCREATE PROCEDURE USP_LIST_CONCAT (@SourceTable NVARCHAR(1000) = '' ,@SplitColumn NVARCHAR(1000) = '' , @Deli NVARCHAR(10) = '', @KeyColumns NVARCHAR(2000) = '' , @Condition NVARCHAR(1000) = '')\nAS\nBEGIN\nSET NOCOUNT ON\n\n/* PROCEDURE CREATED 2010 FOR SQL SERVER 2000. SIMON HUGHES. */\n/* NOTES: REMOVE --'s BELOW TO LIST GENERATED SQL. */\n\nIF @SourceTable = '' OR @SourceTable = '?' OR @SourceTable = '/?' OR @SplitColumn = '' OR @KeyColumns = ''\nBEGIN\nPRINT 'Format for use:'\nPRINT ' USP_LIST_CONCAT ''SourceTable'', ''SplitColumn'', ''Deli'', ''KeyColumn1,...'', ''Column1 = 12345 AND ...'''\nPRINT ''\nPRINT 'Description:'\nPRINT 'The SourceTable should contain a number of records acting as a list of values.'\nPRINT 'The SplitColumn should be the name of the column holding the values wanted.'\nPRINT 'The Delimiter may be any single character or string ie ''/'''\nPRINT 'The KeyColumn may contain a comma separated list of columns that will be returned before the concatenated list.'\nPRINT 'The optional Conditions may be left blank or may include the following as examples:'\nPRINT ' ''Column1 = 12334 AND (Column2 = ''ABC'' OR Column3 = ''DEF'')'''\nPRINT ''\nPRINT 'A standard list in the format:'\nPRINT ' Store1, Employee1, Rabbits'\nPRINT ' Store1, Employee1, Dogs'\nPRINT ' Store1, Employee1, Cats'\nPRINT ' Store1, Employee2, Dogs'\nPRINT ''\nPRINT 'Will be returned as:'\nPRINT ' Store1, Employee1, Cats/Dogs/Rabbits'\nPRINT ' Store1, Employee2, Dogs'\nPRINT ''\nPRINT 'A full ORDER BY and DISTINCT is included'\nRETURN -1\nEND\n\n\nDECLARE @SQLStatement NVARCHAR(4000)\n\nSELECT @SQLStatement = '\nDECLARE @DynamicSQLStatement NVARCHAR(4000)\n\nSELECT @DynamicSQLStatement = ''SELECT '+@KeyColumns+', SUBSTRING(''\n\nSELECT @DynamicSQLStatement = @DynamicSQLStatement + '' + '' + CHAR(10) +\n'' MAX(CASE WHEN '+@SplitColumn+' = ''''''+RTRIM('+@SplitColumn+')+'''''' THEN '''''+@Deli+'''+RTRIM('+@SplitColumn+')+'''''' ELSE '''''''' END)''\nFROM '+ @SourceTable +' ORDER BY '+@SplitColumn+'\n\nSELECT @DynamicSQLStatement = @DynamicSQLStatement + '' ,2,7999) List'' + CHAR(10) + ''FROM '+ @SourceTable+''' + CHAR(10) +'''+CASE WHEN @Condition = '' THEN '/* WHERE */' ELSE 'WHERE '+@Condition END+ '''+ CHAR(10) + ''GROUP BY '+@KeyColumns+'''\n\nSELECT @DynamicSQLStatement = REPLACE(@DynamicSQLStatement,''( +'',''('')\n\n-- SELECT @DynamicSQLStatement -- DEBUG ONLY\nEXEC (@DynamicSQLStatement)'\n\nEXEC (@SQLStatement)\n\nEND\nGO\n\nEXEC USP_LIST_CONCAT 'MyTableName', 'ColumnForListing', 'Delimiter', 'KeyCol1, KeyCol2', 'Column1 = 123456'\n"
},
{
"answer_id": 2894501,
"author": "Vikas Baweja",
"author_id": 348617,
"author_profile": "https://Stackoverflow.com/users/348617",
"pm_score": 0,
"selected": false,
"text": "DROP TABLE #tmp\n\nDECLARE @tmpTable TABLE\n(\nemailno NUMERIC,\nquestion1 VARCHAR(80),\nquestion2 VARCHAR(80),\nquestion3 VARCHAR(80),\nquestion4 VARCHAR(80),\nquestion5 VARCHAR(80),\nquestion6 VARCHAR(80),\nquestion7 VARCHAR(80),\nquestion8 VARCHAR(80),\nquestion9 VARCHAR(80),\nquestion10 VARCHAR(80),\nquestion11 VARCHAR(80),\nquestion12 VARCHAR(80),\nquestion13 VARCHAR(8000)\n)\n\nDECLARE @tmpTable2 TABLE\n(\nemailNumber NUMERIC\n)\n\nDECLARE @counter INT\nDECLARE @Email INT\n\nSELECT @counter =COUNT(DISTINCT ans.email) FROM answers ans WHERE ans.surveyname=100430 AND ans.qnpkey BETWEEN 233702 AND 233714\nSELECT * INTO #tmp FROM @tmpTable\nINSERT INTO @tmpTable2 (emailNumber) SELECT DISTINCT CAST(ans.email AS NUMERIC) FROM answers ans WHERE ans.surveyname=100430 AND ans.qnpkey BETWEEN 233702 AND 233714\n\nWHILE @counter >0\n\nBEGIN\n\n SELECT TOP 1 @Email= emailNumber FROM @tmpTable2\n INSERT INTO @tmpTable (emailno) VALUES (@Email )\n\n\n Update @tmpTable set question1=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233702 and ans.email=@Email\n Update @tmpTable set question2=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233703 and email=@email\n Update @tmpTable set question3=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233704 and email=@email\n Update @tmpTable set question4=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233705 and email=@email\n Update @tmpTable set question5=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233706 and email=@email\n Update @tmpTable set question6=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233707 and email=@email\n Update @tmpTable set question7=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233708 and email=@email\n Update @tmpTable set question8=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233709 and email=@email\n Update @tmpTable set question9=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233710 and email=@email\n Update @tmpTable set question10=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233711 and email=@email\n Update @tmpTable set question11=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233712 and email=@email\n Update @tmpTable set question12=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233713 and email=@email\n Update @tmpTable set question13=CAST(answer as VARCHAR(8000)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233714 and email=@email\n\n insert into #tmp select * from @tmpTable \n\n DELETE FROM @tmpTable \n DELETE FROM @tmpTable2 WHERE emailNumber= @Email\n\n set @counter =@counter -1\n\nEnd\n\nselect * from #tmp\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4021/"
] |
152,774
|
<p>What's the best way to trim a DateTime object to a specific precision? For instance, if I have a DateTime with a value of '2008-09-29 09:41:43', but I only want it's precision to be to the minute, is there any better way to do it than this?</p>
<pre><code>private static DateTime TrimDateToMinute(DateTime date)
{
return new DateTime(
date.Year,
date.Month,
date.Day,
date.Hour,
date.Minute,
0);
}
</code></pre>
<p>What I would really want is to make it variable so that I could set its precision to the second, minute, hour, or day.</p>
|
[
{
"answer_id": 152803,
"author": "Rikalous",
"author_id": 4271,
"author_profile": "https://Stackoverflow.com/users/4271",
"pm_score": 3,
"selected": false,
"text": "public enum DateTimePrecision\n{\n Hour, Minute, Second\n}\n\npublic static DateTime TrimDate(DateTime date, DateTimePrecision precision)\n{\n switch (precision)\n {\n case DateTimePrecision.Hour:\n return new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);\n case DateTimePrecision.Minute:\n return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0);\n case DateTimePrecision.Second:\n return new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second);\n default:\n break;\n }\n}\n"
},
{
"answer_id": 153014,
"author": "Bartek Szabat",
"author_id": 23774,
"author_profile": "https://Stackoverflow.com/users/23774",
"pm_score": 8,
"selected": true,
"text": "static class Program\n{\n //using extension method:\n static DateTime Trim(this DateTime date, long roundTicks)\n {\n return new DateTime(date.Ticks - date.Ticks % roundTicks, date.Kind);\n }\n\n //sample usage:\n static void Main(string[] args)\n {\n Console.WriteLine(DateTime.Now);\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerDay));\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerHour));\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMillisecond));\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerMinute));\n Console.WriteLine(DateTime.Now.Trim(TimeSpan.TicksPerSecond));\n Console.ReadLine();\n }\n\n}\n"
},
{
"answer_id": 10848875,
"author": "Gunarathinam",
"author_id": 885942,
"author_profile": "https://Stackoverflow.com/users/885942",
"pm_score": -1,
"selected": false,
"text": "DateTime dt = new DateTime()\ndt = dt.AddSeconds(-dt.Second)\n"
},
{
"answer_id": 15751093,
"author": "rocketsarefast",
"author_id": 544958,
"author_profile": "https://Stackoverflow.com/users/544958",
"pm_score": 3,
"selected": false,
"text": "public static DateTime FloorTime(DateTime dt, TimeSpan interval) \n{\n return dt.AddTicks(-1 * (dt.Ticks % interval.Ticks));\n}\n dt = FloorTime(dt, TimeSpan.FromMinutes(5)); // floor to the nearest 5min interval\ndt = FloorTime(dt, TimeSpan.FromSeconds(1)); // floor to the nearest second\ndt = FloorTime(dt, TimeSpan.FromDays(1)); // floor to the nearest day\n"
},
{
"answer_id": 26807751,
"author": "Marcos Arruda",
"author_id": 2479173,
"author_profile": "https://Stackoverflow.com/users/2479173",
"pm_score": 1,
"selected": false,
"text": "DateTime truncDate;\ntruncDate = date.Date; // trim to day\ntruncDate = date.Date + TimeSpan.Parse(string.Format(\"{0:HH:00:00}\", date)); // trim to hour\ntruncDate = date.Date + TimeSpan.Parse(string.Format(\"{0:HH:mm}\", date)); // trim to minute\ntruncDate = date.Date + TimeSpan.Parse(string.Format(\"{0:HH:mm:ss}\", date)); // trim to second\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21807/"
] |
152,807
|
<p><strong>UPDATE:</strong> i updated the code and problem description to reflect my changes. </p>
<p>I know now that i'm trying a Socket operation on nonsocket. or that my fd_set is not valid since:</p>
<p><code>select</code> returns -1 and
<code>WSAGetLastError()</code>returns 10038. </p>
<p>But i can't seem to figure out what it is. Platform is Windows. I have not posted the <code>WSAStartup</code> part.</p>
<pre><code>int loop = 0;
FILE *output
int main()
{
fd_set fd;
output = _popen("tail -f test.txt","r");
while(forceExit == 0)
{
FD_ZERO(&fd);
FD_SET(_fileno(output),&fd);
int returncode = select(_fileno(output)+1,&fd,NULL,NULL,NULL);
if(returncode == 0)
{
printf("timed out");
}
else if (returncode < 0)
{
printf("returncode: %d\n",returncode);
printf("Last Error: %d\n",WSAGetLastError());
}
else
{
if(FD_ISSET(_fileno(output),&fd))
{
if(fgets(buff, sizeof(buff), output) != NULL )
{
printf("Output: %s\n", buff);
}
}
else
{
printf(".");
}
}
Sleep(500);
}
return 0;
}
</code></pre>
<p>The new outcome now is of course the print out of the returncode and the last error.</p>
|
[
{
"answer_id": 152831,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": " int select(int nfds, fd_set *readfds, fd_set *writefds,\n fd_set *exceptfds, struct timeval *timeout);\n if(FD_ISSET(filePointer,&exceptfds))\n {\n printf(\"i have data\\n\");\n }\n if(FD_ISSET(filePointer,&fd))\n {\n printf(\"i have data\\n\");\n }\n // Reset fd, exceptfds, and timeout before each select()...\nint result = select(maxFDPlusOne, &fd, NULL, &exceptfds, &timeout);\n\nif (result == 0)\n{\n // timeout\n}\nelse if (result < 0)\n{\n // error\n}\nelse\n{\n // something happened\n if (FD_ISSET(filePointer,&fd))\n {\n // Need to read the data, otherwise you'll get notified each time.\n }\n}\n"
},
{
"answer_id": 152876,
"author": "Mark",
"author_id": 4405,
"author_profile": "https://Stackoverflow.com/users/4405",
"pm_score": 0,
"selected": false,
"text": "if (FD_ISSET(filePointer,&fd))\n{\n printf(\"i have data\\n\");\n}\nelse ....\n"
},
{
"answer_id": 153029,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 0,
"selected": false,
"text": "select() FD_ISSET(...) fd_set"
},
{
"answer_id": 157988,
"author": "SinisterDex",
"author_id": 10010,
"author_profile": "https://Stackoverflow.com/users/10010",
"pm_score": 0,
"selected": false,
"text": "select _beginthread _beginthreadex"
},
{
"answer_id": 160420,
"author": "mhawke",
"author_id": 21945,
"author_profile": "https://Stackoverflow.com/users/21945",
"pm_score": 1,
"selected": false,
"text": "select() select() _popen() int main( void )\n{\n\n char psBuffer[128];\n FILE *pPipe;\n\n if( (pPipe = _popen(\"tail -f test.txt\", \"rt\" )) == NULL )\n exit( 1 );\n\n /* Read pipe until end of file, or an error occurs. */\n\n while(fgets(psBuffer, 128, pPipe))\n {\n printf(psBuffer);\n }\n\n\n /* Close pipe and print return value of pPipe. */\n if (feof( pPipe))\n {\n printf( \"\\nProcess returned %d\\n\", _pclose( pPipe ) );\n }\n else\n {\n printf( \"Error: Failed to read the pipe to the end.\\n\");\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10010/"
] |
152,822
|
<p>I want something like this:</p>
<pre><code><msxsl:script language="C#">
??? getNodes() { ... return ... }
</msxsl:script>
<xsl:for-each select="user:getNodes()">
...
</xsl:for-each>
</code></pre>
<p>What return type should i use for <code>getNodes()</code> and what should i put in it's body?</p>
|
[
{
"answer_id": 414009,
"author": "Boaz",
"author_id": 2892,
"author_profile": "https://Stackoverflow.com/users/2892",
"pm_score": 4,
"selected": true,
"text": "<msxsl:script language=\"C#\">\n XPathNodeIterator getNodes() \n { \n XmlDocument doc = new XmlDocument();\n doc.PreserveWhitespace = true;\n doc.LoadXml(\"<root><fld>val</fld><fld>val2</fld></root>\");\n return doc.CreateNavigator().Select(\"/root/fld\");\n }\n</msxsl:script>\n <msxsl:script language=\"C#\">\n XPathNodeIterator getNodes(XPathNodeIterator NodesToFilter, string Criteria)\n {\n XPathNodeIterator x = NodesToFilter.Current.Select(\"SOMEVERYCOMPLEXPATH[\"+Criteria+\"]\");\n return x;\n }\n </msxsl:script>\n <xsl:for-each select=\"user:getNodes(values/val,'SomeCriteria')\">\n ...\n </xsl:for-each>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20310/"
] |
152,823
|
<p>XAMPP makes configuring a local LAMP stack for windows a breeze. So it's quite disappointing that enabling <code>.htaccess</code> files is such a nightmare.</p>
<p>My problem:
I've got a PHP application that requires apache/php to search for an <code>/includes/</code> directory contained within the application. To do this, <code>.htaccess</code> files must be allowed in Apache and the <code>.htaccess</code> file must specify exactly where the includes directory is.</p>
<p>Problem is, I can't get my Apache config to view these <code>.htaccess</code> files. I had major hassles installing this app at uni and getting the admins there to help with the setup. This shouldn't be so hard but for some reason I just can't get Apache to play nice.</p>
<p>This is my setup:</p>
<p><code>c:\xampp</code>
<code>c:\xampp\htdocs</code>
<code>c:\xampp\apache\conf\httpd.conf</code> - where I've made the changes listed below
<code>c:\xampp\apache\bin\php.ini</code> - where changes to this file affect the PHP installation
It is interesting to note that <code>c:\xampp\php\php.ini</code> changes mean nothing - this is NOT the ini that affects the PHP installation.</p>
<p>The following lines are additions I've made to the <code>httpd.conf</code> file</p>
<pre><code>#AccessFileName .htaccess
AccessFileName htaccess.txt
#
# The following lines prevent .htaccess and .htpasswd
# files from being viewed by Web clients.
#
#<Files ~ "^\.ht">
<Files ~ "^htaccess\.">
Order allow,deny
Deny from all
</Files>
<Directory "c:/xampp/htdocs">
#
# AllowOverride controls what directives may be placed in
# .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Order allow,deny
Allow from all
</Directory>
</code></pre>
<p>The following is the entire <code>.htaccess</code> file contained in:
<code>c:\xampp\htdocs\application\htaccess.txt</code></p>
<pre><code><Files ~ "\.inc$">
Order deny,allow
Deny from all
</Files>
php_value default_charset "UTF-8"
php_value include_path ".;c:\xampp\htdocs\application\includes"
php_value register_globals 0
php_value magic_quotes_gpc 0
php_value magic_quotes_runtime 0
php_value magic_quotes_sybase 0
php_value session.use_cookies 1
php_value session.use_only_cookies 0
php_value session.use_trans_sid 1
php_value session.gc_maxlifetime 3600
php_value arg_separator.output "&amp;"
php_value url_rewriter.tags "a=href,area=href,frame=src,input=src,fieldset="
</code></pre>
<p>The includes directory exists at the location specified.</p>
<p>When I try to access the application I receive the following error:</p>
<pre><code>Warning: require(include.general.inc) [function.require]: failed to open stream: No such file or directory in C:\xampp\htdocs\application\menu\logon.php on line 21
</code></pre>
<p>Fatal error: require() [function.require]: Failed opening required <code>include.general.inc</code> (include_path='.;C:\xampp\php\pear\random') in <code>C:\xampp\htdocs\application\menu\logon.php</code> on line 21</p>
<p>The include path <code>c..\random\</code> is specified in the <code>php.ini</code> file listed above. The XAMPP install fails to allow another include path as specified in the <code>htaccess.txt</code> file.</p>
<p>I'm guessing there's probably an error with the <code>httpd.conf</code> OR the <code>htaccess.txt</code> file.. but it doesn't seem to be reading the <code>.htaccess</code> file. I've tried to be as thorough as possible so forgive the verbosity of the post.</p>
<p>Now I know a workaround could be to simply add the include_path to the PHP file, but I'm not going to have access to the <code>php.ini</code> file on the location I plan to deploy my app. I will, however, be able to request the server admin allows <code>.htaccess</code> files.</p>
<p>renamed <code>htacces.txt</code> to <code>.htaccess</code> and ammended the appropriate directives in the <code>httpd.conf</code> file and all seems to work. The application suggested the naming of <code>htaccess.txt</code> and the ammended directives in the httpd. These are obviously wrong (at least for a XAMPP stack).</p>
<p>By the way, using ini_set() is a much friendlier way if the app needs to be deployed to multiple locations so thanks especially for that pointer.</p>
|
[
{
"answer_id": 32487080,
"author": "Deepak",
"author_id": 4490437,
"author_profile": "https://Stackoverflow.com/users/4490437",
"pm_score": 1,
"selected": false,
"text": "open file ...\\xampp\\apache\\conf\\httpd.conf\n\nfind line \"LoadModule rewrite_module modules/mod_rewrite.so\"\n\nif here is a # before this line remove it.(remove comment)\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152823",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10583/"
] |
152,834
|
<p>I need to know the default port settings for the following services</p>
<ol>
<li>SQL Server</li>
<li>SQL Browser</li>
<li>SQL Reporting services</li>
<li>SQL Analysis services</li>
</ol>
<p>I need to know the port settings for these services for different versions of SQL Server (2000,2005,2008)</p>
<p>Also let me know whether the default port setting will change based on sql server versions.</p>
|
[
{
"answer_id": 152902,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 3,
"selected": false,
"text": "cliconfg"
},
{
"answer_id": 5035845,
"author": "Jared Moore",
"author_id": 425852,
"author_profile": "https://Stackoverflow.com/users/425852",
"pm_score": 4,
"selected": false,
"text": "select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null\n"
},
{
"answer_id": 29284661,
"author": "leolegas",
"author_id": 3519855,
"author_profile": "https://Stackoverflow.com/users/3519855",
"pm_score": 2,
"selected": false,
"text": "Protocol | Port\n---------------------\nUDP | 1050\nTCP | 1050\nTCP | 1433\nUDP | 1434\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
152,837
|
<p>How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database.</p>
<p>I'm not sure if it makes a difference, but I'm using Oracle 9i.</p>
|
[
{
"answer_id": 152849,
"author": "stjohnroe",
"author_id": 2985,
"author_profile": "https://Stackoverflow.com/users/2985",
"pm_score": 0,
"selected": false,
"text": "SET SCAN OFF\n"
},
{
"answer_id": 152852,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 4,
"selected": false,
"text": "SET DEFINE OFF \n"
},
{
"answer_id": 152856,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 0,
"selected": false,
"text": "SET ESCAPE ON;\nINSERT VALUES(\"J\\&J Construction\") INTO custnames;\n"
},
{
"answer_id": 152859,
"author": "Andrew Hampton",
"author_id": 466,
"author_profile": "https://Stackoverflow.com/users/466",
"pm_score": 2,
"selected": false,
"text": "SET DEF OFF SET SCAN OFF"
},
{
"answer_id": 152971,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 3,
"selected": false,
"text": "set def off;\ninsert into tablename values( 'J&J');\n"
},
{
"answer_id": 410490,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 7,
"selected": true,
"text": "set define on\nset escape on\n\ndefine myvar=/forth\n\nselect 'back\\\\ \\& &myvar' as swing from dual;\n old 1: select 'back\\\\ \\& &myvar' from dual\nnew 1: select 'back\\ & /forth' from dual\n\nSWING\n--------------\nback\\ & /forth\n set define on\nset escape '#'\n\ndefine myvar=/forth\n\nselect 'back\\ #& &myvar' as swing from dual;\n set escape off\nset escape '#'\n"
},
{
"answer_id": 15975677,
"author": "C. J.",
"author_id": 2275117,
"author_profile": "https://Stackoverflow.com/users/2275117",
"pm_score": 4,
"selected": false,
"text": "select 'J' || chr(38) || 'J Construction' from dual;\n"
},
{
"answer_id": 36443549,
"author": "lokesh kumar",
"author_id": 4506183,
"author_profile": "https://Stackoverflow.com/users/4506183",
"pm_score": 3,
"selected": false,
"text": "insert into table_name (col_name) values('J'||'&'||'Construction');\n"
},
{
"answer_id": 45959353,
"author": "Alberto Cerqueira",
"author_id": 5004526,
"author_profile": "https://Stackoverflow.com/users/5004526",
"pm_score": 0,
"selected": false,
"text": "SELECT CONCAT('J', CONCAT(CHR(38), 'J Construction')) FROM DUAL;\n"
},
{
"answer_id": 48382464,
"author": "aemre",
"author_id": 4582867,
"author_profile": "https://Stackoverflow.com/users/4582867",
"pm_score": 3,
"selected": false,
"text": "INSERT INTO TEST_TABLE VALUES('Jonhy''s Sport &'||' Fitness')\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/466/"
] |
152,866
|
<p>For simplicity, I generally split a lot of my configuration (i.e. the contents of app.config and web.config) out into separate .config files, and then reference them from the main config file using the 'configSource' attribute. For example:</p>
<pre><code><appSettings configSource="appSettings.config"/>
</code></pre>
<p>and then placing all of the key/value pairs in that appSettings.config file instead of having this in-line in the main config file:</p>
<pre><code><appSettings>
<add key="FirstKey" value="FirstValue"/>
<add key="SecondKey" value="SecondValue"/>
...
</appSettings>
</code></pre>
<p>This typically works great with the application itself, but I run into problems when attempting to write unit tests that, for whatever reason, need to get at some value from a configuration section that is stored in one of these external files. (I understand that most of these would likley be considered "integration tests", as they are relying on the Configuration system, and I do have "pure unit tests" as well, but those are the not the problem. I'm really looking to test that these configuration values are retrieved correctly and impact behavior in the correct way).</p>
<p>Due to how MSTest compiles and copies the output to obfuscated-looking folders that are different from every test run (rather than to the 'bin' folder like you might think), it never seems to be able to find those external files while the tests are executing. I've tried messing around with post build actions to make this work but with no luck. Is there a way to have these external files copied over into the correct output folder at run time?</p>
|
[
{
"answer_id": 638298,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "DeploymentItem [TestMethod]\n[DeploymentItem(@\"test_data.file\")]\npublic void FooTest()\n{...}\n"
},
{
"answer_id": 42199914,
"author": "Ghebrehiywet",
"author_id": 4915864,
"author_profile": "https://Stackoverflow.com/users/4915864",
"pm_score": 1,
"selected": false,
"text": "mklink \"C:\\Link To Folder\\....\\ConnectionString.config\" \"C:\\Users\\Name\\Original Folder\\.....\\...\\Secure ConnectionString.config\""
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1680/"
] |
152,869
|
<p>It is easy to highlight a selected datagrid row, by for example using toggleClass in the tr's click event. But how best to later remove the highlight after a different row has been selected? Iterating over all the rows to unhighlight them could become expensive for larger datagrids. I'd be interested in the simplest solution, as well as the most performant.</p>
<p>Thanks,<br>
Mike </p>
|
[
{
"answer_id": 152877,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 2,
"selected": false,
"text": "$('.toggledClass').removeClass('toggledClass');\n"
},
{
"answer_id": 153102,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "var $activeRow;\n\n$('#myGrid tr').click(function() {\n if ($activeRow) $activeRow.removeClass('active');\n $activeRow = $(this).addClass('active');\n});\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/785/"
] |
152,871
|
<p>When you think about it, doesn't the REST paradigm of being resource-oriented boil down to being object-oriented (with constrained functionality, leveraging HTTP as much as possible)?</p>
<p>I'm not necessarily saying it's a bad thing, but rather that if they are <strike>essentially the same</strike> very similar then it becomes much easier to understand REST and the implications that such an architecture entails.</p>
<p><strong>Update:</strong> Here are more specific details:</p>
<ol>
<li>REST resources are equivalent to public classes. Private classes/resources are simply not exposed.</li>
<li>Resource state is equivalent to class public methods or fields. Private methods/fields/state is simply not exposed (this doesn't mean it's not there).</li>
<li>While it is certainly true that REST does not retain client-specific state across requests, it <strong>does</strong> retain resource state across all clients. Resources <strong>have</strong> state, the same way classes have state.</li>
<li>REST resources are are globally uniquely identified by a URI in the same way that server objects are globally uniquely identified by their database address, table name and primary key. Granted there isn't (yet) a URI to represent this, but you can easily construct one.</li>
</ol>
|
[
{
"answer_id": 153200,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": true,
"text": "ToString()"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14731/"
] |
152,887
|
<p>This has been bugging me for a long time -- how do I properly resolve a merge conflict within the SVN properties set on a directory? Say for instance there are two developers working on a project where svn:ignore is set on some directory. If both developers make changes to this property, when the second one updates, they will see a merge conflict.</p>
<p>Unlike file merge conflicts, a single file is generated in the directory called "dir_conflicts.prej", which the second developer must read and manually correct. Usually, what I end up doing is reverting all my changes to the local copy, then re-setting these properties manually with the info in dir_conflicts.prej. However, this is rather cumbersome when dealing with a big list of URLs in an svn:externals property, as many of our projects use.</p>
<p>There has got to be a better way to do this -- does anybody know how?</p>
|
[
{
"answer_id": 36070180,
"author": "jpllosa",
"author_id": 5797400,
"author_profile": "https://Stackoverflow.com/users/5797400",
"pm_score": 0,
"selected": false,
"text": "dir_conflicts.prej svn ignore list TortoiseSVN 1.9.3 TortoiseSVN -> Resolve..."
},
{
"answer_id": 41954466,
"author": "Ashwani Kumar",
"author_id": 3522181,
"author_profile": "https://Stackoverflow.com/users/3522181",
"pm_score": 2,
"selected": false,
"text": "dir_conflicts.prej"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152887",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302/"
] |
152,893
|
<p>We have a form that allows a user to dynamically add inputs for fields. For example if you have a form for tracking projects, you want to dynamically add tasks to that project. Just to clarify my language: you dynamically add inputs for the task field. The problem is, we have 50 of those fields. Our current solution presents all 50 fields with a plus (+) next to the field to allow them to add another input box for that field. The labels for the field are to the left of the field and each input box that is added goes below the current input box. </p>
<p>Please trust that dynamically adding inputs is the right solution, please trust that it has been thought out, please trust that this is what the users wants, please trust that we have gone down various other roads and this is the best solution. </p>
<p>My question is about presentation: How would you do it?</p>
<p>Please keep the answers to UI design. We already have the database schema figured out.</p>
<hr>
<p><strong>Update</strong></p>
<p><em>Current Solution is a web based application that uses JavaScript to dynamically add new inputs and looks very similar to Corey Trager's drawing:</em></p>
<pre><code>Task [.............] +
[.............] +
[.............] +
[.............] +
Foo [.............] +
[.............] +
[.............] +
Repeat 50 times...
</code></pre>
|
[
{
"answer_id": 152931,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 1,
"selected": false,
"text": "Task [.............] + \n [.............] + \n [.............] + \n [.............] +\n\nFoo [.............] +\n [.............] +\n [.............] +\n"
},
{
"answer_id": 153299,
"author": "garrow",
"author_id": 21095,
"author_profile": "https://Stackoverflow.com/users/21095",
"pm_score": 1,
"selected": false,
"text": "Name : Joe Blogs\nPhone : 555-1234\nCheese : Stilton\n -----------\nFoo | SNAFU | \n -----------\nBar : fubar\nFifty : Whatever\n\n(+) Add new field...\n -------------------------------------------------\nDefine Fields | name, phone, cheese, foo, bar ..(etc).. fifty |\n -------------------------------------------------\n"
},
{
"answer_id": 156080,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 0,
"selected": false,
"text": "[task][foo][another tab][another tab][etc][etc][etc][etc][etc][etc]\n[row2][fred][another tab][etc][etc][etc][etc][etc][etc][etc]\n[row3][another tab][wilma][etc][etc][etc][etc][etc][etc][etc]\n\n[task1 ]+\n[task2 }+\n[task3 ]+ \n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1681/"
] |
152,900
|
<p>When loading XML into an XmlDocument, i.e.</p>
<pre>
XmlDocument document = new XmlDocument();
document.LoadXml(xmlData);
</pre>
<p>is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol)</p>
<p>Thanks</p>
|
[
{
"answer_id": 152935,
"author": "Andy",
"author_id": 3585,
"author_profile": "https://Stackoverflow.com/users/3585",
"pm_score": 0,
"selected": false,
"text": "<root>\n<testnode>\n<![CDATA[some text ™]]>\n</testnode>\n</root>\n"
},
{
"answer_id": 152936,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": " XmlDocument doc = new XmlDocument();\n doc.LoadXml(@\"<xml>™</xml>\");\n using (MemoryStream ms = new MemoryStream())\n {\n XmlWriterSettings settings = new XmlWriterSettings();\n settings.Encoding = Encoding.GetEncoding(\"ISO-8859-1\");\n XmlWriter xw = XmlWriter.Create(ms, settings);\n doc.Save(xw);\n xw.Close();\n Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));\n }\n <?xml version=\"1.0\" encoding=\"iso-8859-1\"?><xml>™</xml>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21299/"
] |
152,919
|
<p>I need to get a listing of a server-side directory inside SAP. How do I achieve this in ABAP? Are there any built-in SAP functions I can call?</p>
<p>Ideally I want a function which I can pass a path as input, and which will return a list of filenames in an internal table.</p>
|
[
{
"answer_id": 165295,
"author": "Chris Carruthers",
"author_id": 1119,
"author_profile": "https://Stackoverflow.com/users/1119",
"pm_score": 3,
"selected": false,
"text": "FUNCTION RZL_READ_DIR_LOCAL.\n*\"----------------------------------------------------------------------\n*\"Lokale Schnittstelle:\n*\" IMPORTING\n*\" NAME LIKE SALFILE-LONGNAME\n*\" TABLES\n*\" FILE_TBL STRUCTURE SALFLDIR\n*\" EXCEPTIONS\n*\" ARGUMENT_ERROR\n*\" NOT_FOUND\n*\"----------------------------------------------------------------------\n"
},
{
"answer_id": 187586,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "fill_file_list"
},
{
"answer_id": 8255130,
"author": "Mark",
"author_id": 1063678,
"author_profile": "https://Stackoverflow.com/users/1063678",
"pm_score": 3,
"selected": false,
"text": "EPS2_GET_DIRECTORY_LISTING EPS_GET_DIRECTORY_LISTING"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1119/"
] |
152,926
|
<p>In Visual Studio with TFS as source control, when I view the history and double click a cs file, the file is loaded in notepad. How can i change the application to be notepad++? </p>
<p>I also would like the OS's default application for the file to still be visual studio</p>
|
[
{
"answer_id": 3944620,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 4,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\SystemFileAssociations\\text\\shell\\edit\\command"
},
{
"answer_id": 5238869,
"author": "acidRain",
"author_id": 290141,
"author_profile": "https://Stackoverflow.com/users/290141",
"pm_score": 0,
"selected": false,
"text": "C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\devenv.exe\n"
},
{
"answer_id": 10926791,
"author": "Krozen",
"author_id": 1441452,
"author_profile": "https://Stackoverflow.com/users/1441452",
"pm_score": 2,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\SystemFileAssociations"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
152,946
|
<p>There is a GUI ADM2 Progress v9 application using AppServer. </p>
<p>It needs to give users an ability to view MS Excel files stored on the AppServer. So far it:</p>
<ol>
<li>Pulls .xls file from AppServer to a local drive.</li>
<li>Fires up a copy of MS Excel and opens the file.</li>
</ol>
<p>The problem is that the temporary file on the local drive needs to be removed once it's no longer required. Any hints?</p>
|
[
{
"answer_id": 155122,
"author": "BKimmel",
"author_id": 13776,
"author_profile": "https://Stackoverflow.com/users/13776",
"pm_score": 0,
"selected": false,
"text": "Excel.exe \"http://myserver/myexcelbook.xls\" Application.WorkBookBeforeClose ThisMethodHandlesTheWorkbookBeforeCloseEvent()\n{\n DeleteTheFile();\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
152,968
|
<p>Do you know an easy and straight-forward method/sub/module which allows me to convert a number (say 1234567.89) to an easily readable form - something like 1.23M?</p>
<p>Right now I can do this by making several comparisons, but I'm not happy with my method:</p>
<pre><code>if($bytes > 1000000000){
$bytes = ( sprintf( "%0.2f", $bytes/1000000000 )). " Gb/s";
}
elsif ($bytes > 1000000){
$bytes = ( sprintf( "%0.2f", $bytes/1000000 )). " Mb/s";
}
elsif ($bytes > 1000){
$bytes = ( sprintf( "%0.2f", $bytes/1000 )). " Kb/s";
}
else{
$bytes = sprintf( "%0.2f", $bytes ). "b/s";
}
</code></pre>
<p>Thank you for your help!</p>
|
[
{
"answer_id": 152978,
"author": "WalkingRandomly",
"author_id": 1856916,
"author_profile": "https://Stackoverflow.com/users/1856916",
"pm_score": 5,
"selected": true,
"text": " use Number::Bytes::Human qw(format_bytes);\n\n $size = format_bytes(0); # '0'\n $size = format_bytes(2*1024); # '2.0K'\n\n $size = format_bytes(1_234_890, bs => 1000); # '1.3M'\n $size = format_bytes(1E9, bs => 1000); # '1.0G'\n\n # the OO way\n $human = Number::Bytes::Human->new(bs => 1000, si => 1);\n $size = $human->format(1E7); # '10MB'\n $human->set_options(zero => '-');\n $size = $human->format(0); # '-'\n"
},
{
"answer_id": 153017,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "sub BytesToReadableString($) {\n my $c = shift;\n $c >= 1073741824 ? sprintf(\"%0.2fGB\", $c/1073741824)\n : $c >= 1048576 ? sprintf(\"%0.2fMB\", $c/1048576)\n : $c >= 1024 ? sprintf(\"%0.2fKB\", $c/1024)\n : $c . \"bytes\";\n}\n\nprint BytesToReadableString(225939) . \"/s\\n\";\n"
},
{
"answer_id": 153026,
"author": "Mnebuerquo",
"author_id": 5114,
"author_profile": "https://Stackoverflow.com/users/5114",
"pm_score": 0,
"selected": false,
"text": "function formatNumberThousands($a,$dig)\n{\n $unim = array(\"\",\"k\",\"m\",\"g\");\n $c = 0;\n while ($a>=1000 && $c<=3) {\n $c++;\n $a = $a/1000;\n }\n $d = $dig-ceil(log10($a));\n return number_format($a,($c ? $d : 0)).\"\".$unim[$c];\n}\n"
},
{
"answer_id": 153268,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 2,
"selected": false,
"text": "sub magnitudeformat {\n my $val = shift;\n my $expstr;\n\n my $exp = log($val) / log(10);\n if ($exp < 3) { return $val; }\n elsif ($exp < 6) { $exp = 3; $expstr = \"K\"; }\n elsif ($exp < 9) { $exp = 6; $expstr = \"M\"; }\n elsif ($exp < 12) { $exp = 9; $expstr = \"G\"; } # Or \"B\".\n else { $exp = 12; $expstr = \"T\"; }\n\n return sprintf(\"%0.1f%s\", $val/(10**$exp), $expstr);\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23780/"
] |
152,975
|
<p>I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.</p>
<p>Is something like this possible with jQuery?</p>
<pre><code>$("#menuscontainer").clickOutsideThisElement(function() {
// Hide the menus
});
</code></pre>
|
[
{
"answer_id": 153047,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 12,
"selected": true,
"text": "stopPropagation $(window).click(function() {\n //Hide the menus if visible\n});\n\n$('#menucontainer').click(function(event){\n event.stopPropagation();\n});\n"
},
{
"answer_id": 154268,
"author": "Joe Lencioni",
"author_id": 18986,
"author_profile": "https://Stackoverflow.com/users/18986",
"pm_score": 7,
"selected": false,
"text": "$('#menucontainer').click(function(event) {\n $('html').one('click',function() {\n // Hide the menus\n });\n\n event.stopPropagation();\n});\n one()"
},
{
"answer_id": 1089622,
"author": "Dennis",
"author_id": 81976,
"author_profile": "https://Stackoverflow.com/users/81976",
"pm_score": 7,
"selected": false,
"text": "if(!$(event.target).is('#foo'))\n{\n // hide menu\n}\n const className = `dropdown-${Date.now()}-${Math.random() * 100}`;\n show false const onClickOutside = (e) => {\n if (!e.target.className.includes(className)) {\n show = false;\n }\n};\n // add when widget loads\nwindow.addEventListener(\"click\", onClickOutside);\n // remove listener when destroying the widget\nwindow.removeEventListener(\"click\", onClickOutside);\n"
},
{
"answer_id": 1278068,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "this.outsideElementClick = function(objEvent, objElement) {\n var objCurrentElement = objEvent.target || objEvent.srcElement;\n var blnInsideX = false;\n var blnInsideY = false;\n\n if (objCurrentElement.getBoundingClientRect().left >= objElement.getBoundingClientRect().left && objCurrentElement.getBoundingClientRect().right <= objElement.getBoundingClientRect().right)\n blnInsideX = true;\n\n if (objCurrentElement.getBoundingClientRect().top >= objElement.getBoundingClientRect().top && objCurrentElement.getBoundingClientRect().bottom <= objElement.getBoundingClientRect().bottom)\n blnInsideY = true;\n\n if (blnInsideX && blnInsideY)\n return false;\n else\n return true;\n}"
},
{
"answer_id": 1746926,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "$(\"#menuscontainer\").click(function() {\n $(this).focus();\n});\n$(\"#menuscontainer\").blur(function(){\n $(this).hide();\n});\n"
},
{
"answer_id": 2960848,
"author": "govind",
"author_id": 356804,
"author_profile": "https://Stackoverflow.com/users/356804",
"pm_score": 2,
"selected": false,
"text": "$('body').click(function() {\n // Hide the menus if visible.\n});\n"
},
{
"answer_id": 3028037,
"author": "Art",
"author_id": 62194,
"author_profile": "https://Stackoverflow.com/users/62194",
"pm_score": 11,
"selected": false,
"text": "document #menucontainer .closest() #menucontainer $(document).click(function(event) { \n var $target = $(event.target);\n if(!$target.closest('#menucontainer').length && \n $('#menucontainer').is(\":visible\")) {\n $('#menucontainer').hide();\n } \n});\n document export function hideOnClickOutside(selector) {\n const outsideClickListener = (event) => {\n const $target = $(event.target);\n if (!$target.closest(selector).length && $(selector).is(':visible')) {\n $(selector).hide();\n removeClickListener();\n }\n }\n\n const removeClickListener = () => {\n document.removeEventListener('click', outsideClickListener);\n }\n\n document.addEventListener('click', outsideClickListener);\n}\n function hideOnClickOutside(element) {\n const outsideClickListener = event => {\n if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null\n element.style.display = 'none';\n removeClickListener();\n }\n }\n\n const removeClickListener = () => {\n document.removeEventListener('click', outsideClickListener);\n }\n\n document.addEventListener('click', outsideClickListener);\n}\n\nconst isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js \n !element.contains(event.target) element.closest() ...\n let lastMouseDownX = 0;\n let lastMouseDownY = 0;\n let lastMouseDownWasOutside = false;\n\n const mouseDownListener = (event: MouseEvent) => {\n lastMouseDownX = event.offsetX;\n lastMouseDownY = event.offsetY;\n lastMouseDownWasOutside = !$(event.target).closest(element).length;\n }\n document.addEventListener('mousedown', mouseDownListener);\n outsideClickListener const outsideClickListener = event => {\n const deltaX = event.offsetX - lastMouseDownX;\n const deltaY = event.offsetY - lastMouseDownY;\n const distSq = (deltaX * deltaX) + (deltaY * deltaY);\n const isDrag = distSq > 3;\n const isDragException = isDrag && !lastMouseDownWasOutside;\n\n if (!element.contains(event.target) && isVisible(element) && !isDragException) { // or use: event.target.closest(selector) === null\n element.style.display = 'none';\n removeClickListener();\n document.removeEventListener('mousedown', mouseDownListener); // Or add this line to removeClickListener()\n }\n }\n"
},
{
"answer_id": 3062825,
"author": "Neco",
"author_id": 369448,
"author_profile": "https://Stackoverflow.com/users/369448",
"pm_score": 2,
"selected": false,
"text": "$(function() {\n $.fn.click_inout = function(clickin_handler, clickout_handler) {\n var item = this;\n var is_me = false;\n item.click(function(event) {\n clickin_handler(event);\n is_me = true;\n });\n $(document).click(function(event) {\n if (is_me) {\n is_me = false;\n } else {\n clickout_handler(event);\n }\n });\n return this;\n }\n});\n this.input = $('<input>')\n .click_inout(\n function(event) { me.ShowTree(event); },\n function() { me.Hide(); }\n )\n .appendTo(this.node);\n ShowTree: function(event) {\n this.data_span.show();\n}\nHide: function() {\n this.data_span.hide();\n}\n"
},
{
"answer_id": 4333616,
"author": "Chu Yeow",
"author_id": 25226,
"author_profile": "https://Stackoverflow.com/users/25226",
"pm_score": 4,
"selected": false,
"text": "var $menuscontainer = ...;\n\n$('#trigger').click(function() {\n $menuscontainer.show();\n\n $('body').click(function(event) {\n var $target = $(event.target);\n\n if ($target.parents('#menuscontainer').length == 0) {\n $menuscontainer.hide();\n }\n });\n});\n #menuscontainer #menuscontainer"
},
{
"answer_id": 4642622,
"author": "webenformasyon",
"author_id": 550597,
"author_profile": "https://Stackoverflow.com/users/550597",
"pm_score": 3,
"selected": false,
"text": "var go = false;\n$(document).click(function(){\n if(go){\n $('#divID').hide();\n go = false;\n }\n})\n\n$(\"#divID\").mouseover(function(){\n go = false;\n});\n\n$(\"#divID\").mouseout(function (){\n go = true;\n});\n\n$(\"btnID\").click( function(){\n if($(\"#divID:visible\").length==1)\n $(\"#divID\").hide(); // Toggle\n $(\"#divID\").show();\n});\n"
},
{
"answer_id": 6051126,
"author": "34m0",
"author_id": 342783,
"author_profile": "https://Stackoverflow.com/users/342783",
"pm_score": 5,
"selected": false,
"text": "body { margin-left:auto; margin-right: auto; width:960px;}"
},
{
"answer_id": 6860287,
"author": "nazar kuliyev",
"author_id": 386073,
"author_profile": "https://Stackoverflow.com/users/386073",
"pm_score": 4,
"selected": false,
"text": "function ClickOutsideCheck(e)\n{\n var el = e.target;\n var popup = $('.popup:visible')[0];\n if (popup==undefined)\n return true;\n\n while (true){\n if (el == popup ) {\n return true;\n } else if (el == document) {\n $(\".popup\").hide();\n return false;\n } else {\n el = $(el).parent()[0];\n }\n }\n};\n\n$(document).bind('mousedown.popup', ClickOutsideCheck);\n"
},
{
"answer_id": 7490132,
"author": "Rowan",
"author_id": 933754,
"author_profile": "https://Stackoverflow.com/users/933754",
"pm_score": 3,
"selected": false,
"text": "$(document).click(function() {\n $(\".overlay-window\").hide();\n});\n$(\".overlay-window\").click(function() {\n return false;\n});\n"
},
{
"answer_id": 8400851,
"author": "Satya Prakash",
"author_id": 192545,
"author_profile": "https://Stackoverflow.com/users/192545",
"pm_score": 3,
"selected": false,
"text": "// Detect the click anywhere other than the overlay element to close it.\nY.one(document).on('click', function (e) {\n if (e.target.ancestor('#overlay') === null && e.target.get('id') != 'show' && overlay.get('visible') == true) {\n overlay.hide();\n }\n});\n"
},
{
"answer_id": 8603563,
"author": "benb",
"author_id": 473101,
"author_profile": "https://Stackoverflow.com/users/473101",
"pm_score": 5,
"selected": false,
"text": "$('#menuscontainer').click(function(event) {\n //your code that shows the menus fully\n\n //now set up an event listener so that clicking anywhere outside will close the menu\n $('html').click(function(event) {\n //check up the tree of the click target to check whether user has clicked outside of menu\n if ($(event.target).parents('#menuscontainer').length==0) {\n // your code to hide menu\n\n //this event listener has done its job so we can unbind it.\n $(this).unbind(event);\n }\n\n })\n});\n"
},
{
"answer_id": 9584414,
"author": "netdjw",
"author_id": 972828,
"author_profile": "https://Stackoverflow.com/users/972828",
"pm_score": 2,
"selected": false,
"text": "// Listen to every click\n$('html').click(function(event) {\n if ( $('#mypopupmenu').is(':visible') ) {\n if (event.target.id != 'click_this_to_show_mypopupmenu') {\n $('#mypopupmenu').hide();\n }\n }\n});\n\n// Listen to selector's clicks\n$('#click_this_to_show_mypopupmenu').click(function() {\n\n // If the menu is visible, and you clicked the selector again we need to hide\n if ( $('#mypopupmenu').is(':visible') {\n $('#mypopupmenu').hide();\n return true;\n }\n\n // Else we need to show the popup menu\n $('#mypopupmenu').show();\n});\n"
},
{
"answer_id": 9808743,
"author": "Spencer Fry",
"author_id": 1088642,
"author_profile": "https://Stackoverflow.com/users/1088642",
"pm_score": 2,
"selected": false,
"text": "$(document).ready(function() {\n $('#user-toggle').click(function(e) {\n $('#user-nav').toggle();\n e.stopPropagation();\n });\n\n $('body').click(function() {\n $('#user-nav').hide(); \n });\n\n $('#user-nav').click(function(e){\n e.stopPropagation();\n });\n});\n"
},
{
"answer_id": 10074361,
"author": "Toogy",
"author_id": 1322001,
"author_profile": "https://Stackoverflow.com/users/1322001",
"pm_score": 2,
"selected": false,
"text": "jQuery().ready(function(){\n $('#nav').click(function (event) {\n $(this).addClass('activ');\n event.stopPropagation();\n });\n\n $('html').click(function () {\n if( $('#nav').hasClass('activ') ){\n $('#nav').removeClass('activ');\n }\n });\n});\n"
},
{
"answer_id": 10428503,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 3,
"selected": false,
"text": "$(document).click(function(e){\n if ($(e.target).closest(\"#menuscontainer\").length == 0) {\n // .closest can help you determine if the element \n // or one of its ancestors is #menuscontainer\n console.log(\"hide\");\n }\n});\n"
},
{
"answer_id": 10882727,
"author": "srinath",
"author_id": 490962,
"author_profile": "https://Stackoverflow.com/users/490962",
"pm_score": 5,
"selected": false,
"text": "$('html').click(function (e) {\n if (e.target.id == 'YOUR-DIV-ID') {\n //do something\n } else {\n //do something\n }\n});\n"
},
{
"answer_id": 13555176,
"author": "Alexandre T.",
"author_id": 1093596,
"author_profile": "https://Stackoverflow.com/users/1093596",
"pm_score": 2,
"selected": false,
"text": "<a id='theButton' href=\"#\">Toggle the menu</a><br/>\n<div id='theMenu'>\n I should be toggled when the above menu is clicked,\n and hidden when user clicks outside.\n</div>\n\n<script>\n$('#theButton').click(function(){\n $('#theMenu').slideDown();\n});\n$(\"#theMenu\").dClickOutside({ ignoreList: $(\"#theButton\") }, function(clickedObj){\n $(this).slideUp();\n});\n</script>\n"
},
{
"answer_id": 13877279,
"author": "mlangenberg",
"author_id": 587208,
"author_profile": "https://Stackoverflow.com/users/587208",
"pm_score": 0,
"selected": false,
"text": "$('html').click(function() {\n // Hide the menus if visible\n});\n\n$('#menucontainer').click(function(event){\n event.stopPropagation();\n});\n link_to 'click', '/url', :method => :delete $('html').click(function() {\n // Hide the menus if visible\n});\n\n$('#menucontainer').click(function(event){\n if (!$(event.target).data('method')) {\n event.stopPropagation();\n }\n});\n"
},
{
"answer_id": 14293001,
"author": "Bilal Berjawi",
"author_id": 1972286,
"author_profile": "https://Stackoverflow.com/users/1972286",
"pm_score": 2,
"selected": false,
"text": "$('body').click(function (event) {\n var obj = $(event.target);\n obj = obj['context']; // context : clicked element inside body\n if ($(obj).attr('id') != \"menuscontainer\" && $('#menuscontainer').is(':visible') == true) {\n //hide menu\n }\n});\n"
},
{
"answer_id": 14967514,
"author": "constrictus",
"author_id": 2088813,
"author_profile": "https://Stackoverflow.com/users/2088813",
"pm_score": -1,
"selected": false,
"text": " <div class=\"feedbackCont\" onblur=\"hidefeedback();\">\n <div class=\"feedbackb\" onclick=\"showfeedback();\" ></div>\n <div class=\"feedbackhide\" tabindex=\"1\"> </div>\n </div>\n\nfunction hidefeedback(){\n $j(\".feedbackhide\").hide();\n}\n\nfunction showfeedback(){\n $j(\".feedbackhide\").show();\n $j(\".feedbackCont\").attr(\"tabindex\",1).focus();\n}\n"
},
{
"answer_id": 16842824,
"author": "teynon",
"author_id": 697477,
"author_profile": "https://Stackoverflow.com/users/697477",
"pm_score": 2,
"selected": false,
"text": "<div onClick=\"$('#menu').toggle();$('#menu').clickOutside(function() { $(this).hide(); $(this).clickOutside('disable'); });\">Open / Close Menu</div>\n<div id=\"menu\" style=\"display: none; border: 1px solid #000000; background: #660000;\">I am a menu, whoa is me.</div>\n (function($) {\n var clickOutsideElements = [];\n var clickListener = false;\n\n $.fn.clickOutside = function(options, ignoreFirstClick) {\n var that = this;\n if (ignoreFirstClick == null) ignoreFirstClick = true;\n\n if (options != \"disable\") {\n for (var i in clickOutsideElements) {\n if (clickOutsideElements[i].element[0] == $(this)[0]) return this;\n }\n\n clickOutsideElements.push({ element : this, clickDetected : ignoreFirstClick, fnc : (typeof(options) != \"function\") ? function() {} : options });\n\n $(this).on(\"click.clickOutside\", function(event) {\n for (var i in clickOutsideElements) {\n if (clickOutsideElements[i].element[0] == $(this)[0]) {\n clickOutsideElements[i].clickDetected = true;\n }\n }\n });\n\n if (!clickListener) {\n if (options != null && typeof(options) == \"function\") {\n $('html').click(function() {\n for (var i in clickOutsideElements) {\n if (!clickOutsideElements[i].clickDetected) {\n clickOutsideElements[i].fnc.call(that);\n }\n if (clickOutsideElements[i] != null) clickOutsideElements[i].clickDetected = false;\n }\n });\n clickListener = true;\n }\n }\n }\n else {\n $(this).off(\"click.clickoutside\");\n for (var i = 0; i < clickOutsideElements.length; ++i) {\n if (clickOutsideElements[i].element[0] == $(this)[0]) {\n clickOutsideElements.splice(i, 1);\n }\n }\n }\n\n return this;\n }\n})(jQuery);\n"
},
{
"answer_id": 16861422,
"author": "maday",
"author_id": 2441120,
"author_profile": "https://Stackoverflow.com/users/2441120",
"pm_score": 2,
"selected": false,
"text": "$(\"*\").not($(\"#menuscontainer\")).bind(\"click.OutsideMenus\", function ()\n{\n // hide the menus\n\n //then remove all of the handlers\n $(\"*\").unbind(\".OutsideMenus\");\n});\n\n$(\"#menuscontainer\").bind(\"click.OutsideMenus\", function (event) \n{\n event.stopPropagation(); \n});\n"
},
{
"answer_id": 16863056,
"author": "kboom",
"author_id": 1130975,
"author_profile": "https://Stackoverflow.com/users/1130975",
"pm_score": 2,
"selected": false,
"text": "$view.on(\"click\", function(e) {\n\n if(model.isActivated()) return;\n\n var watchUnclick = function() {\n rootView.one(\"mouseleave\", function() {\n $(document).one(\"click\", function() {\n model.deactivate();\n });\n rootView.one(\"mouseenter\", function() {\n watchUnclick();\n });\n });\n };\n watchUnclick();\n model.activate();\n });\n"
},
{
"answer_id": 16943381,
"author": "mems",
"author_id": 470117,
"author_profile": "https://Stackoverflow.com/users/470117",
"pm_score": 3,
"selected": false,
"text": "$(document).on(\"click.menu-outside\", function(event){\n // Test if target and it's parent aren't #menuscontainer\n // That means the click event occur on other branch of document tree\n if(!$(event.target).parents().andSelf().is(\"#menuscontainer\")){\n // Click outisde #menuscontainer\n // Hide the menus (but test if menus aren't already hidden)\n }\n});\n $(document).off(\"click.menu-outside\");\n"
},
{
"answer_id": 17169887,
"author": "Anders",
"author_id": 548048,
"author_profile": "https://Stackoverflow.com/users/548048",
"pm_score": 2,
"selected": false,
"text": "ko.bindingHandlers.clickedIn = (function () {\n function getBounds(element) {\n var pos = element.offset();\n return {\n x: pos.left,\n x2: pos.left + element.outerWidth(),\n y: pos.top,\n y2: pos.top + element.outerHeight()\n };\n }\n\n function hitTest(o, l) {\n function getOffset(o) {\n for (var r = { l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight };\n o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);\n return r.r += r.l, r.b += r.t, r;\n }\n\n for (var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;\n b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))\n && (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));\n return j ? !!r.length : r;\n }\n\n return {\n init: function (element, valueAccessor) {\n var target = valueAccessor();\n $(document).click(function (e) {\n if (element._clickedInElementShowing === false && target()) {\n var $element = $(element);\n var bounds = getBounds($element);\n\n var possibleOverlays = $(\"[style*=z-index],[style*=absolute]\").not(\":hidden\");\n $.each(possibleOverlays, function () {\n if (hitTest(element, this)) {\n var b = getBounds($(this));\n bounds.x = Math.min(bounds.x, b.x);\n bounds.x2 = Math.max(bounds.x2, b.x2);\n bounds.y = Math.min(bounds.y, b.y);\n bounds.y2 = Math.max(bounds.y2, b.y2);\n }\n });\n\n if (e.clientX < bounds.x || e.clientX > bounds.x2 ||\n e.clientY < bounds.y || e.clientY > bounds.y2) {\n\n target(false);\n }\n }\n element._clickedInElementShowing = false;\n });\n\n $(element).click(function (e) {\n e.stopPropagation();\n });\n },\n update: function (element, valueAccessor) {\n var showing = ko.utils.unwrapObservable(valueAccessor());\n if (showing) {\n element._clickedInElementShowing = true;\n }\n }\n };\n})();\n"
},
{
"answer_id": 19091957,
"author": "Roei Bahumi",
"author_id": 1283063,
"author_profile": "https://Stackoverflow.com/users/1283063",
"pm_score": 1,
"selected": false,
"text": " {onPress: someCallbackFunction, onOutsidePress: anotherCallbackFunction}\n window.autoCloseQueue = {} \n\n$(document).click(function(event) {\n for (id in autoCloseQueue){\n var element = autoCloseQueue[id];\n if ( ($(e.target).parents('#' + id).length) > 0) { // This is a click on the element (or its child element)\n console.log('This is a click on an element (or its child element) with id: ' + id);\n if (typeof element.onPress == 'function') element.onPress(event, id);\n } else { //This is a click outside the element\n console.log('This is a click outside the element with id: ' + id);\n if (typeof element.onOutsidePress == 'function') element.onOutsidePress(event, id); //call the outside callback\n delete autoCloseQueue[id]; //remove the element from the queue\n }\n }\n});\n window.autoCloseQueue['menuscontainer'] = {onOutsidePress: clickOutsideThisElement}\n"
},
{
"answer_id": 20061566,
"author": "Webmaster G",
"author_id": 1582942,
"author_profile": "https://Stackoverflow.com/users/1582942",
"pm_score": 2,
"selected": false,
"text": "$(document).on('click', 'body, #msg_count_results .close',function() {\n $(document).find('#msg_count_results').remove();\n});\n$(document).on('click','#msg_count_results',function(e) {\n e.preventDefault();\n return false;\n});\n"
},
{
"answer_id": 21826584,
"author": "lan.ta",
"author_id": 1076974,
"author_profile": "https://Stackoverflow.com/users/1076974",
"pm_score": -1,
"selected": false,
"text": "if ($(event.target).parents().index($('#searchFormEdit')) == -1 &&\n $(event.target).parents().index($('.DynarchCalendar-topCont')) == -1 &&\n (_x < os.left || _x > (os.left + 570) || _y < os.top || _y > (os.top + 155)) &&\n isShowEditForm) {\n\n setVisibleEditForm(false);\n}\n"
},
{
"answer_id": 22387244,
"author": "Yacine Zalouani",
"author_id": 1214294,
"author_profile": "https://Stackoverflow.com/users/1214294",
"pm_score": -1,
"selected": false,
"text": "<div tabindex=\"1\">\n Focus me\n</div>\n\ndocument.querySelector(\"div\").onblur = function(){\n console.log('clicked outside')\n}\ndocument.querySelector(\"div\").onfocus = function(){\n console.log('clicked inside')\n}\n"
},
{
"answer_id": 23398102,
"author": "Awena",
"author_id": 3003977,
"author_profile": "https://Stackoverflow.com/users/3003977",
"pm_score": 0,
"selected": false,
"text": "$(document).on('click', function(e) {\n var elem = $(e.target).closest('#menu'),\n box = $(e.target).closest('#nav');\n if (elem.length) {\n e.preventDefault();\n $('#nav').toggle();\n } else if (!box.length) {\n $('#nav').hide();\n }\n}); <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<li id=\"menu\">\n <a></a>\n</li>\n<ul id=\"nav\">\n <!--Nav will toggle when you Click on Menu(it can be an icon in this example)-->\n <li class=\"page\"><a>Page1</a></li>\n <li class=\"page\"><a>Page2</a></li>\n <li class=\"page\"><a>Page3</a></li>\n <li class=\"page\"><a>Page4</a></li>\n</ul>"
},
{
"answer_id": 24141571,
"author": "Grim",
"author_id": 843943,
"author_profile": "https://Stackoverflow.com/users/843943",
"pm_score": -1,
"selected": false,
"text": "<label>"
},
{
"answer_id": 24612659,
"author": "KyleMit",
"author_id": 1366033,
"author_profile": "https://Stackoverflow.com/users/1366033",
"pm_score": -1,
"selected": false,
"text": "$.fn.clickOutsideThisElement = function (callback) {\n return this.each(function () {\n var self = this;\n $(document).click(function (e) {\n if (!$(e.target).closest(self).length) {\n callback.call(self, e)\n }\n })\n });\n};\n $(\"#menuscontainer\").clickOutsideThisElement(function() {\n // handle menu toggle\n});\n"
},
{
"answer_id": 24930263,
"author": "Bohdan Lyzanets",
"author_id": 223750,
"author_profile": "https://Stackoverflow.com/users/223750",
"pm_score": 4,
"selected": false,
"text": "var $menu = $('#menucontainer');\n$(document).on('click', function (e) {\n\n // If element is opened and click target is outside it, hide it\n if ($menu.is(':visible') && !$menu.is(e.target) && !$menu.has(e.target).length) {\n $menu.hide();\n }\n});\n"
},
{
"answer_id": 26258171,
"author": "Manish Shrivastava",
"author_id": 1133932,
"author_profile": "https://Stackoverflow.com/users/1133932",
"pm_score": 2,
"selected": false,
"text": "$(document).on('touchstart', function (event) {\n var container = $(\"YOUR CONTAINER SELECTOR\");\n\n if (!container.is(e.target) && // If the target of the click isn't the container...\n container.has(e.target).length === 0) // ... nor a descendant of the container\n {\n container.hide();\n }\n});\n"
},
{
"answer_id": 26276051,
"author": "shiv",
"author_id": 2520033,
"author_profile": "https://Stackoverflow.com/users/2520033",
"pm_score": -1,
"selected": false,
"text": "$(\"#id\").not().click(function() {\n alert('Clicked other that #id');\n});\n"
},
{
"answer_id": 26629746,
"author": "Mahesh Gaikwad",
"author_id": 2724353,
"author_profile": "https://Stackoverflow.com/users/2724353",
"pm_score": -1,
"selected": false,
"text": "$(\"body > div:not(#dvid)\").click(function (e) {\n //your code\n}); \n"
},
{
"answer_id": 27537666,
"author": "aroykos",
"author_id": 3019696,
"author_profile": "https://Stackoverflow.com/users/3019696",
"pm_score": -1,
"selected": false,
"text": "$(\"html\").click(function(){\n if($('#info').css(\"opacity\")>0.9) {\n $('#info').fadeOut('fast');\n }\n});\n"
},
{
"answer_id": 28198524,
"author": "Iman Sedighi",
"author_id": 2716838,
"author_profile": "https://Stackoverflow.com/users/2716838",
"pm_score": 5,
"selected": false,
"text": "if var flag = \"1\";\n$('#menucontainer').click(function(event){\n flag = \"0\"; // flag 0 means click happened in the area where we should not do any action\n});\n\n$('html').click(function() {\n if(flag != \"0\"){\n // Hide the menus if visible\n }\n else {\n flag = \"1\";\n }\n});\n if $(document).on('click', function(event){\n var container = $(\"#menucontainer\");\n if (!container.is(event.target) && // If the target of the click isn't the container...\n container.has(event.target).length === 0) // ... nor a descendant of the container\n {\n // Do whatever you want to do when click is outside the element\n }\n});\n"
},
{
"answer_id": 30337498,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "(function () {\n \"use strict\";\n var hidden = document.getElementById('hidden');\n document.addEventListener('click', function (e) {\n if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';\n }, false);\n})();\n (function () {\n \"use strict\";\n var hidden = document.getElementById('hidden');\n document.addEventListener('click', function (e) {\n if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';\n }, false);\n})(); <a href=\"javascript:void(0)\" id=\"toggle\">Toggle Hidden Div</a>\n<div id=\"hidden\" style=\"display: none;\">This content is normally hidden. click anywhere other than this content to make me disappear</div> hidden (function () {\n \"use strict\";\n var hiddenItems = document.getElementsByClassName('hidden'), hidden;\n document.addEventListener('click', function (e) {\n for (var i = 0; hidden = hiddenItems[i]; i++) {\n if (!hidden.contains(e.target) && hidden.style.display != 'none')\n hidden.style.display = 'none';\n }\n if (e.target.getAttribute('data-toggle')) {\n var toggle = document.querySelector(e.target.getAttribute('data-toggle'));\n toggle.style.display = toggle.style.display == 'none' ? 'block' : 'none';\n }\n }, false);\n})(); <a href=\"javascript:void(0)\" data-toggle=\"#hidden1\">Toggle Hidden Div</a>\n<div class=\"hidden\" id=\"hidden1\" style=\"display: none;\" data-hidden=\"true\">This content is normally hidden</div>\n<a href=\"javascript:void(0)\" data-toggle=\"#hidden2\">Toggle Hidden Div</a>\n<div class=\"hidden\" id=\"hidden2\" style=\"display: none;\" data-hidden=\"true\">This content is normally hidden</div>\n<a href=\"javascript:void(0)\" data-toggle=\"#hidden3\">Toggle Hidden Div</a>\n<div class=\"hidden\" id=\"hidden3\" style=\"display: none;\" data-hidden=\"true\">This content is normally hidden</div>"
},
{
"answer_id": 31281896,
"author": "Scott Richardson",
"author_id": 981280,
"author_profile": "https://Stackoverflow.com/users/981280",
"pm_score": 3,
"selected": false,
"text": "// HIDE SEARCH BOX IF CLICKING OUTSIDE\n$(document).click(function(event){ \n // IF NOT CLICKING THE SEARCH BOX OR ITS CONTENTS OR SEARCH ICON \n if ($(\"#search-holder\").is(\":visible\") && !$(event.target).is(\"#search-holder *, #search\")) {\n $(\"#search-holder\").fadeOut('fast');\n $(\"#search\").removeClass('active');\n }\n});\n"
},
{
"answer_id": 31631355,
"author": "bbe",
"author_id": 4582452,
"author_profile": "https://Stackoverflow.com/users/4582452",
"pm_score": 3,
"selected": false,
"text": "&& (e.target != $('html').get(0)) // ignore the scrollbar\n"
},
{
"answer_id": 31813540,
"author": "martinedwards",
"author_id": 1485447,
"author_profile": "https://Stackoverflow.com/users/1485447",
"pm_score": -1,
"selected": false,
"text": "$('.header, .footer, .main-content').click(function() {\n//Hide the menus if visible\n});\n"
},
{
"answer_id": 31868754,
"author": "Daniel Tonon",
"author_id": 1611058,
"author_profile": "https://Stackoverflow.com/users/1611058",
"pm_score": 0,
"selected": false,
"text": "$('.target-element').outsideClick(function(event){\n //code that fires when user clicks outside the element\n //event = the click event\n //$(this) = the '.target-element' that is firing this function \n}, '.excluded-element')\n (function($) {\n\n//when the user hits the escape key, it will trigger all outsideClick functions\n$(document).on(\"keyup\", function (e) {\n if (e.which == 27) $('body').click(); //escape key\n});\n\n//The actual plugin\n$.fn.outsideClick = function(callback, exclusions) {\n var subject = this;\n\n //test if exclusions have been set\n var hasExclusions = typeof exclusions !== 'undefined';\n\n //switches click event with touch event if on a touch device\n var ClickOrTouchEvent = \"ontouchend\" in document ? \"touchend\" : \"click\";\n\n $('body').on(ClickOrTouchEvent, function(event) {\n //click target does not contain subject as a parent\n var clickedOutside = !$(event.target).closest(subject).length;\n\n //click target was on one of the excluded elements\n var clickedExclusion = $(event.target).closest(exclusions).length;\n\n var testSuccessful;\n\n if (hasExclusions) {\n testSuccessful = clickedOutside && !clickedExclusion;\n } else {\n testSuccessful = clickedOutside;\n }\n\n if(testSuccessful) {\n callback.call(subject, event);\n }\n });\n\n return this;\n};\n\n}(jQuery));\n"
},
{
"answer_id": 33473515,
"author": "Rameez Rami",
"author_id": 2251701,
"author_profile": "https://Stackoverflow.com/users/2251701",
"pm_score": 6,
"selected": false,
"text": "<script>\n //The good thing about this solution is it doesn't stop event propagation.\n\n var clickFlag = 0;\n $('body').on('click', function () {\n if(clickFlag == 0) {\n console.log('hide element here');\n /* Hide element here */\n }\n else {\n clickFlag=0;\n }\n });\n $('body').on('click','#testDiv', function (event) {\n clickFlag = 1;\n console.log('showed the element');\n /* Show the element */\n });\n</script>\n <script>\n $('body').on('click', function(e) {\n if($(e.target).closest('#testDiv').length == 0) {\n /* Hide dropdown here */\n }\n });\n</script>\n <script>\n var specifiedElement = document.getElementById('testDiv');\n document.addEventListener('click', function(event) {\n var isClickInside = specifiedElement.contains(event.target);\n if (isClickInside) {\n console.log('You clicked inside')\n }\n else {\n console.log('You clicked outside')\n }\n });\n</script>\n"
},
{
"answer_id": 34218425,
"author": "Nitekurs",
"author_id": 4827540,
"author_profile": "https://Stackoverflow.com/users/4827540",
"pm_score": -1,
"selected": false,
"text": " $('#menucontainer').click(function(e){\n e.stopPropagation();\n });\n\n $(document).on('click', function(e){\n // code\n });\n"
},
{
"answer_id": 34280828,
"author": "Jitendra Damor",
"author_id": 4686674,
"author_profile": "https://Stackoverflow.com/users/4686674",
"pm_score": 5,
"selected": false,
"text": "$(document).mouseup(function (e)\n{\n var container = $(\"YOUR SELECTOR\"); // Give you class or ID\n\n if (!container.is(e.target) && // If the target of the click is not the desired div or section\n container.has(e.target).length === 0) // ... nor a descendant-child of the container\n {\n container.hide();\n }\n});\n div div"
},
{
"answer_id": 35055176,
"author": "wsc",
"author_id": 5824173,
"author_profile": "https://Stackoverflow.com/users/5824173",
"pm_score": 0,
"selected": false,
"text": "$('html').click(function() {\n//Hide the menus if visible\n});\n\n$('#menucontainer').click(function(event){\n event.stopPropagation();\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<html>\n <button id='#menucontainer'>Ok</button> \n</html>"
},
{
"answer_id": 35846430,
"author": "Yishu Fang",
"author_id": 1253826,
"author_profile": "https://Stackoverflow.com/users/1253826",
"pm_score": 0,
"selected": false,
"text": "$('html').click(function(e) {\n if($(e.target).parents('#menuscontainer').length == 0) {\n $('#menuscontainer').hide();\n }\n});\n html stopPropagation()"
},
{
"answer_id": 36549967,
"author": "Qwertiy",
"author_id": 4928642,
"author_profile": "https://Stackoverflow.com/users/4928642",
"pm_score": 0,
"selected": false,
"text": "preventDefault click-anywhere document.addEventListener('click', function (event) {\n event = $.event.fix(event);\n event.type = 'click-anywhere';\n $document.trigger(event);\n}, true);\n click-anywhere document $(document).on('click-anywhere', function (event) {\n if (!$(event.target).closest('#smth').length) {\n // Do anything you need here\n }\n});\n document document body"
},
{
"answer_id": 36779401,
"author": "Matthew Goodwin",
"author_id": 2030888,
"author_profile": "https://Stackoverflow.com/users/2030888",
"pm_score": 3,
"selected": false,
"text": "$('div.my-element').clickOut(function(target) { \n //do something here... \n});\n $.fn.clickOut = function (parent, fn) {\n var context = this;\n fn = (typeof parent === 'function') ? parent : fn;\n parent = (parent instanceof jQuery) ? parent : $(document);\n\n context.each(function () {\n var that = this;\n parent.on('click', function (e) {\n var clicked = $(e.target);\n if (!clicked.is(that) && !clicked.parents().is(that)) {\n if (typeof fn === 'function') {\n fn.call(that, clicked);\n }\n }\n });\n\n });\n return context;\n};\n $('div.my-element').clickOut($('div.my-parent'), function(target) { \n //do something here...\n});\n"
},
{
"answer_id": 37173398,
"author": "FDisk",
"author_id": 175404,
"author_profile": "https://Stackoverflow.com/users/175404",
"pm_score": 0,
"selected": false,
"text": "$(document).on('click.menu.hide', function(e){\n if ( !$(e.target).closest('#my_menu').length ) {\n $('#my_menu').find('ul').toggleClass('active', false);\n }\n});\n\n$(document).on('click.menu.show', '#my_menu li', function(e){\n $(this).find('ul').toggleClass('active');\n});\n div {\n float: left;\n}\n\nul {\n padding: 0;\n position: relative;\n}\nul li {\n padding: 5px 25px 5px 10px;\n border: 1px solid silver;\n cursor: pointer;\n list-style: none;\n margin-top: -1px;\n white-space: nowrap;\n}\nul li ul:before {\n margin-right: -20px;\n position: absolute;\n top: -17px;\n right: 0;\n content: \"\\25BC\";\n}\nul li ul li {\n visibility: hidden;\n height: 0;\n padding-top: 0;\n padding-bottom: 0;\n border-width: 0 0 1px 0;\n}\nul li ul li:last-child {\n border: none;\n}\nul li ul.active:before {\n content: \"\\25B2\";\n}\nul li ul.active li {\n display: list-item;\n visibility: visible;\n height: inherit;\n padding: 5px 25px 5px 10px;\n}\n <script src=\"https://code.jquery.com/jquery-2.1.4.js\"></script>\n<div>\n <ul id=\"my_menu\">\n <li>Menu 1\n <ul>\n <li>subMenu 1</li>\n <li>subMenu 2</li>\n <li>subMenu 3</li>\n <li>subMenu 4</li>\n </ul>\n </li>\n <li>Menu 2\n <ul>\n <li>subMenu 1</li>\n <li>subMenu 2</li>\n <li>subMenu 3</li>\n <li>subMenu 4</li>\n </ul>\n </li>\n <li>Menu 3</li>\n <li>Menu 4</li>\n <li>Menu 5</li>\n <li>Menu 6</li>\n </ul>\n</div>\n"
},
{
"answer_id": 38317768,
"author": "zzzzBov",
"author_id": 497418,
"author_profile": "https://Stackoverflow.com/users/497418",
"pm_score": 9,
"selected": false,
"text": "click click userisfinishedwiththedialog focusout blur blur focusout blur element.addEventListener('blur', ..., true);\n// use capture: ^^^^\n tabindex=\"-1\" $('a').on('click', function () {\n $(this.hash).toggleClass('active').focus();\n});\n\n$('div').on('focusout', function () {\n $(this).removeClass('active');\n}); div {\n display: none;\n}\n.active {\n display: block;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a href=\"#example\">Example</a>\n<div id=\"example\" tabindex=\"-1\">\n Lorem ipsum <a href=\"http://example.com\">dolor</a> sit amet.\n</div> focusout focusin setImmediate(...) setTimeout(..., 0) setImmediate focusin $('.submenu').on({\n focusout: function (e) {\n $(this).data('submenuTimer', setTimeout(function () {\n $(this).removeClass('submenu--active');\n }.bind(this), 0));\n },\n focusin: function (e) {\n clearTimeout($(this).data('submenuTimer'));\n }\n});\n $('a').on('click', function () {\n $(this.hash).toggleClass('active').focus();\n});\n\n$('div').on({\n focusout: function () {\n $(this).data('timer', setTimeout(function () {\n $(this).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this).data('timer'));\n }\n}); div {\n display: none;\n}\n.active {\n display: block;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a href=\"#example\">Example</a>\n<div id=\"example\" tabindex=\"-1\">\n Lorem ipsum <a href=\"http://example.com\">dolor</a> sit amet.\n</div> $('a').on({\n focusout: function () {\n $(this.hash).data('timer', setTimeout(function () {\n $(this.hash).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this.hash).data('timer')); \n }\n});\n $('a').on('click', function () {\n $(this.hash).toggleClass('active').focus();\n});\n\n$('div').on({\n focusout: function () {\n $(this).data('timer', setTimeout(function () {\n $(this).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this).data('timer'));\n }\n});\n\n$('a').on({\n focusout: function () {\n $(this.hash).data('timer', setTimeout(function () {\n $(this.hash).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this.hash).data('timer')); \n }\n}); div {\n display: none;\n}\n.active {\n display: block;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a href=\"#example\">Example</a>\n<div id=\"example\" tabindex=\"-1\">\n Lorem ipsum <a href=\"http://example.com\">dolor</a> sit amet.\n</div> keydown: function (e) {\n if (e.which === 27) {\n $(this).removeClass('active');\n e.preventDefault();\n }\n}\n $('a').on('click', function () {\n $(this.hash).toggleClass('active').focus();\n});\n\n$('div').on({\n focusout: function () {\n $(this).data('timer', setTimeout(function () {\n $(this).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this).data('timer'));\n },\n keydown: function (e) {\n if (e.which === 27) {\n $(this).removeClass('active');\n e.preventDefault();\n }\n }\n});\n\n$('a').on({\n focusout: function () {\n $(this.hash).data('timer', setTimeout(function () {\n $(this.hash).removeClass('active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this.hash).data('timer')); \n }\n}); div {\n display: none;\n}\n.active {\n display: block;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a href=\"#example\">Example</a>\n<div id=\"example\" tabindex=\"-1\">\n Lorem ipsum <a href=\"http://example.com\">dolor</a> sit amet.\n</div> click: function (e) {\n $(this.hash)\n .toggleClass('submenu--active')\n .find('a:first')\n .focus();\n e.preventDefault();\n}\n $('.menu__link').on({\n click: function (e) {\n $(this.hash)\n .toggleClass('submenu--active')\n .find('a:first')\n .focus();\n e.preventDefault();\n },\n focusout: function () {\n $(this.hash).data('submenuTimer', setTimeout(function () {\n $(this.hash).removeClass('submenu--active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this.hash).data('submenuTimer')); \n }\n});\n\n$('.submenu').on({\n focusout: function () {\n $(this).data('submenuTimer', setTimeout(function () {\n $(this).removeClass('submenu--active');\n }.bind(this), 0));\n },\n focusin: function () {\n clearTimeout($(this).data('submenuTimer'));\n },\n keydown: function (e) {\n if (e.which === 27) {\n $(this).removeClass('submenu--active');\n e.preventDefault();\n }\n }\n}); .menu {\n list-style: none;\n margin: 0;\n padding: 0;\n}\n.menu:after {\n clear: both;\n content: '';\n display: table;\n}\n.menu__item {\n float: left;\n position: relative;\n}\n\n.menu__link {\n background-color: lightblue;\n color: black;\n display: block;\n padding: 0.5em 1em;\n text-decoration: none;\n}\n.menu__link:hover,\n.menu__link:focus {\n background-color: black;\n color: lightblue;\n}\n\n.submenu {\n border: 1px solid black;\n display: none;\n left: 0;\n list-style: none;\n margin: 0;\n padding: 0;\n position: absolute;\n top: 100%;\n}\n.submenu--active {\n display: block;\n}\n\n.submenu__item {\n width: 150px;\n}\n\n.submenu__link {\n background-color: lightblue;\n color: black;\n display: block;\n padding: 0.5em 1em;\n text-decoration: none;\n}\n\n.submenu__link:hover,\n.submenu__link:focus {\n background-color: black;\n color: lightblue;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<ul class=\"menu\">\n <li class=\"menu__item\">\n <a class=\"menu__link\" href=\"#menu-1\">Menu 1</a>\n <ul class=\"submenu\" id=\"menu-1\" tabindex=\"-1\">\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#1\">Example 1</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#2\">Example 2</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#3\">Example 3</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#4\">Example 4</a></li>\n </ul>\n </li>\n <li class=\"menu__item\">\n <a class=\"menu__link\" href=\"#menu-2\">Menu 2</a>\n <ul class=\"submenu\" id=\"menu-2\" tabindex=\"-1\">\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#1\">Example 1</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#2\">Example 2</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#3\">Example 3</a></li>\n <li class=\"submenu__item\"><a class=\"submenu__link\" href=\"http://example.com/#4\">Example 4</a></li>\n </ul>\n </li>\n</ul>\nlorem ipsum <a href=\"http://example.com/\">dolor</a> sit amet."
},
{
"answer_id": 38997381,
"author": "Thamaraiselvam",
"author_id": 2975952,
"author_profile": "https://Stackoverflow.com/users/2975952",
"pm_score": 1,
"selected": false,
"text": "fileTreeClass jQuery(document).mouseup(function (e) {\n var container = $(\".fileTreeClass\");\n if (!container.is(e.target) // if the target of the click isn't the container...\n && container.has(e.target).length === 0) // ... nor a descendant of the container\n {\n container.hide();\n }\n });\n"
},
{
"answer_id": 39418566,
"author": "froilanq",
"author_id": 1895877,
"author_profile": "https://Stackoverflow.com/users/1895877",
"pm_score": 1,
"selected": false,
"text": "$.fn.clickOff = function(callback, selfDestroy) {\n var clicked = false;\n var parent = this;\n var destroy = selfDestroy || true;\n\n parent.click(function() {\n clicked = true;\n });\n\n $(document).click(function(event) {\n if (!clicked && parent.is(':visible')) {\n if(callback) callback.call(parent, event)\n }\n if (destroy) {\n //parent.clickOff = function() {};\n //parent.off(\"click\");\n //$(document).off(\"click\");\n parent.off(\"clickOff\");\n }\n clicked = false;\n });\n};\n $(\"#myDiv\").clickOff(function() {\n alert('clickOff');\n});\n"
},
{
"answer_id": 40357679,
"author": "Waheed",
"author_id": 225796,
"author_profile": "https://Stackoverflow.com/users/225796",
"pm_score": 2,
"selected": false,
"text": "$(\".menu_link\").click(function(){\n // show menu code\n});\n\n$(\".menu_link\").mouseleave(function(){\n //hide menu code, you may add a timer for 3 seconds before code to be run\n});\n menu_link"
},
{
"answer_id": 40563576,
"author": "Waltur Buerk",
"author_id": 3601474,
"author_profile": "https://Stackoverflow.com/users/3601474",
"pm_score": 2,
"selected": false,
"text": "$(document).on(\"click\", function(event) {\n clickedtarget = $(event.target).closest('#menuscontainer');\n $(\"#menuscontainer\").not(clickedtarget).hide();\n});\n"
},
{
"answer_id": 42126292,
"author": "Lucas",
"author_id": 2005787,
"author_profile": "https://Stackoverflow.com/users/2005787",
"pm_score": 2,
"selected": false,
"text": "$(\"#show-trigger\").click(function(){\n $(\"#element\").animate({width: 'toggle'});\n $(\"#outside-element\").show();\n});\n$(\"#outside-element\").click(function(){\n $(\"#element\").hide();\n $(\"#outside-element\").hide();\n}); #outside-element {\n position:fixed;\n width:100%;\n height:100%;\n z-index:1;\n display:none;\n}\n#element {\n display:none;\n padding:20px;\n background-color:#ccc;\n width:300px;\n z-index:2;\n position:relative;\n}\n#show-trigger {\n padding:20px;\n background-color:#ccc;\n margin:20px auto;\n z-index:2;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div id=\"outside-element\"></div>\n<div id=\"element\">\n <div class=\"menu-item\"><a href=\"#1\">Menu Item 1</a></div>\n <div class=\"menu-item\"><a href=\"#2\">Menu Item 1</a></div>\n <div class=\"menu-item\"><a href=\"#3\">Menu Item 1</a></div>\n <div class=\"menu-item\"><a href=\"#4\">Menu Item 1</a></div>\n</div>\n<div id=\"show-trigger\">Show Menu</div>"
},
{
"answer_id": 42448663,
"author": "Karthikeyan Ganesan",
"author_id": 3462686,
"author_profile": "https://Stackoverflow.com/users/3462686",
"pm_score": 2,
"selected": false,
"text": "$(document).on(\"click\",function (event) \n { \n console.log(event);\n if ($(event.target).closest('.element').length == 0)\n {\n //your code here\n if ($(\".element\").hasClass(\"active\"))\n {\n $(\".element\").removeClass(\"active\");\n }\n }\n });\n"
},
{
"answer_id": 43405204,
"author": "Dan Philip Bejoy",
"author_id": 6412847,
"author_profile": "https://Stackoverflow.com/users/6412847",
"pm_score": 4,
"selected": false,
"text": "OR some $(\"body\").click(function() {\n target = document.getElementById(\"main\");\n flag = event.path.some(function(el, i, arr) {\n return (el == target)\n })\n if (flag) {\n console.log(\"Inside\")\n } else {\n console.log(\"Outside\")\n }\n}); #main {\n display: inline-block;\n background:yellow;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div id=\"main\">\n <ul>\n <li>Test-Main</li>\n <li>Test-Main</li>\n <li>Test-Main</li>\n <li>Test-Main</li>\n <li>Test-Main</li>\n </ul>\n</div>\n<div id=\"main2\">\n Outside Main\n</div> $(\"body\").click(function() {\n target = $(\"#menuscontainer\")[0];\n flag = event.path.some(function(el, i, arr) {\n return (el == target)\n });\n if (!flag) {\n // Hide the menus\n }\n});\n"
},
{
"answer_id": 45155703,
"author": "Walt",
"author_id": 6562729,
"author_profile": "https://Stackoverflow.com/users/6562729",
"pm_score": 3,
"selected": false,
"text": "window.addEventListener('mouseup', e => {\n if (e.target != yourDiv && e.target.parentNode != yourDiv) {\n yourDiv.classList.remove('show-menu');\n //or yourDiv.style.display = 'none';\n }\n })\n window.addEventListener('mouseup', function (e) {\nif (e.target != yourDiv && e.target.parentNode != yourDiv) {\n yourDiv.classList.remove('show-menu'); \n //or yourDiv.style.display = 'none';\n}\n"
},
{
"answer_id": 45353059,
"author": "Fabian",
"author_id": 7033353,
"author_profile": "https://Stackoverflow.com/users/7033353",
"pm_score": 2,
"selected": false,
"text": "$(window).click(function (event) {\n //To improve performance add a checklike \n //if(myElement.isClosed) return;\n var isClickedElementChildOfMyBox = isChildOfElement(event,'#id-of-my-element');\n\n if (isClickedElementChildOfMyBox)\n return;\n\n //your code to hide the element \n});\n\nvar isChildOfElement = function (event, selector) {\n if (event.originalEvent.path) {\n return event.originalEvent.path[0].closest(selector) !== null;\n }\n\n return event.originalEvent.originalTarget.closest(selector) !== null;\n}\n"
},
{
"answer_id": 46187785,
"author": "hienbt88",
"author_id": 1431934,
"author_profile": "https://Stackoverflow.com/users/1431934",
"pm_score": 2,
"selected": false,
"text": "$(\"body\").mouseup(function(e) {\n var subject = $(\".main-menu\");\n if(e.target.id != subject.attr('id') && !subject.has(e.target).length) {\n $('.sub-menu').hide();\n }\n});\n"
},
{
"answer_id": 47090854,
"author": "Duannx",
"author_id": 4254681,
"author_profile": "https://Stackoverflow.com/users/4254681",
"pm_score": 3,
"selected": false,
"text": "var isMenuClick = false;\nvar menu = document.getElementById('menuscontainer');\ndocument.addEventListener('click',()=>{\n if(!isMenuClick){\n //Hide the menu here\n }\n //Reset isMenuClick \n isMenuClick = false;\n})\nmenu.addEventListener('click',()=>{\n isMenuClick = true;\n})\n"
},
{
"answer_id": 47729165,
"author": "Aominé",
"author_id": 7731859,
"author_profile": "https://Stackoverflow.com/users/7731859",
"pm_score": 0,
"selected": false,
"text": "document.body.onclick = function() { undisp_menu(); };\nvar menu_on = 0;\n\nfunction menu_trigger(event){\n\n if (menu_on == 0)\n {\n // otherwise u will call the undisp on body when \n // click on the button\n event.stopPropagation(); \n\n disp_menu();\n }\n\n else{\n undisp_menu();\n }\n\n}\n\n\nfunction disp_menu(){\n\n menu_on = 1;\n var e = document.getElementsByClassName(\"menu\")[0];\n e.className = \"menu on\";\n\n}\n\nfunction undisp_menu(){\n\n menu_on = 0;\n var e = document.getElementsByClassName(\"menu\")[0];\n e.className = \"menu\";\n\n}\n <div class=\"button\" onclick=\"menu_trigger(event)\">\n\n<div class=\"menu\">\n .menu{\n display: none;\n}\n\n.on {\n display: inline-block;\n}\n"
},
{
"answer_id": 47755925,
"author": "Muhammet Can TONBUL",
"author_id": 6478359,
"author_profile": "https://Stackoverflow.com/users/6478359",
"pm_score": 2,
"selected": false,
"text": "window.onload=function(){\ndocument.getElementById(\"inside-div\").focus();\n}\nfunction loseFocus(){\nalert(\"Clicked outside\");\n} #container{\nbackground-color:lightblue;\nwidth:200px;\nheight:200px;\n}\n\n#inside-div{\nbackground-color:lightgray;\nwidth:100px;\nheight:100px;\n\n} <div id=\"container\">\n<input type=\"text\" id=\"inside-div\" onfocusout=\"loseFocus()\">\n</div>"
},
{
"answer_id": 48161126,
"author": "chea sotheara",
"author_id": 5392288,
"author_profile": "https://Stackoverflow.com/users/5392288",
"pm_score": 2,
"selected": false,
"text": "$('#propertyType').on(\"click\",function(e){\n self.propertyTypeDialog = !self.propertyTypeDialog;\n b = true;\n e.stopPropagation();\n console.log(\"input clicked\");\n });\n\n $(document).on('click','body:not(#propertyType)',function (e) {\n e.stopPropagation();\n if(b == true) {\n if ($(e.target).closest(\"#configuration\").length == 0) {\n b = false;\n self.propertyTypeDialog = false;\n console.log(\"outside clicked\");\n }\n }\n // console.log($(e.target).closest(\"#configuration\").length);\n });\n"
},
{
"answer_id": 48247865,
"author": "Rinto George",
"author_id": 510754,
"author_profile": "https://Stackoverflow.com/users/510754",
"pm_score": 3,
"selected": false,
"text": "jQuery(document).click(function(e) {\n var target = e.target; //target div recorded\n if (!jQuery(target).is('#tobehide') ) {\n jQuery(this).fadeOut(); //if the click element is not the above id will hide\n }\n})\n <div class=\"main-container\">\n<div> Hello I am the title</div>\n<div class=\"tobehide\">I will hide when you click outside of me</div>\n</div>\n"
},
{
"answer_id": 48744452,
"author": "Jovanni G",
"author_id": 2090288,
"author_profile": "https://Stackoverflow.com/users/2090288",
"pm_score": 5,
"selected": false,
"text": "focusout var button = document.getElementById('button');\nbutton.addEventListener('click', function(e){\n e.target.style.backgroundColor = 'green';\n});\nbutton.addEventListener('focusout', function(e){\n e.target.style.backgroundColor = '';\n}); <!DOCTYPE html>\n<html>\n<head>\n <meta charset=\"utf-8\">\n</head>\n<body>\n <button id=\"button\">Click</button>\n</body>\n</html>"
},
{
"answer_id": 49147573,
"author": "DaniG2k",
"author_id": 1741325,
"author_profile": "https://Stackoverflow.com/users/1741325",
"pm_score": 2,
"selected": false,
"text": "var elementToToggle = $('.some-element');\n$(document).click( function(event) {\n if( $(event.target).closest(elementToToggle).length === 0 ) {\n elementToToggle.hide();\n }\n});\n elementToToggle = $('.some-element')\n$(document).click (event) ->\n if $(event.target).closest(elementToToggle).length == 0\n elementToToggle.hide()\n"
},
{
"answer_id": 54633092,
"author": "Yair Cohen",
"author_id": 4424888,
"author_profile": "https://Stackoverflow.com/users/4424888",
"pm_score": 2,
"selected": false,
"text": "document.body.addEventListener('click', (e) => {\n if (isInsideMySpecialWidget(e.target, \"my-special-widget\")) {\n console.log(\"user clicked INSIDE the widget\");\n }\n console.log(\"user clicked OUTSIDE the widget\");\n});\n\nfunction isInsideMySpecialWidget(elem, mySpecialWidgetId){\n while (elem.parentElement) {\n if (elem.id === mySpecialWidgetId) {\n return true;\n }\n elem = elem.parentElement;\n }\n return false;\n}\n"
},
{
"answer_id": 56757369,
"author": "Rivenfall",
"author_id": 2234156,
"author_profile": "https://Stackoverflow.com/users/2234156",
"pm_score": -1,
"selected": false,
"text": "import ClickOverlay from './ClickOverlay.js'\n\n/* CSS */\n// .unselect-helper {\n// position: fixed; left: -100vw; top: -100vh;\n// width: 200vw; height: 200vh;\n// }\n// .selected {outline: 1px solid black}\n\nexport default class ResizeOverlay extends ClickOverlay {\n _init(_opts) {\n this.enterListener = () => this.onEnter()\n this.innerElement.addEventListener('mouseenter', this.enterListener)\n this.leaveListener = () => this.onLeave()\n this.innerElement.addEventListener('mouseleave', this.leaveListener)\n this.selectListener = () => {\n if (this.unselectHelper)\n return\n this.unselectHelper = document.createElement('div')\n this.unselectHelper.classList.add('unselect-helper')\n this.unselectListener = () => {\n if (this.mouseInside)\n return\n this.clearUnselectHelper()\n this.onUnselect()\n }\n this.unselectHelper.addEventListener('pointerdown'\n , this.unselectListener)\n this.outerElement.parentNode.appendChild(this.unselectHelper)\n this.onSelect()\n }\n this.innerElement.addEventListener('pointerup', this.selectListener)\n }\n\n _release() {\n this.innerElement.removeEventListener('mouseenter', this.enterListener)\n this.innerElement.removeEventListener('mouseleave', this.leaveListener)\n this.innerElement.removeEventListener('pointerup', this.selectListener)\n this.clearUnselectHelper()\n }\n\n clearUnselectHelper() {\n if (!this.unselectHelper)\n return\n this.unselectHelper.removeEventListener('pointerdown'\n , this.unselectListener)\n this.unselectHelper.remove()\n delete this.unselectListener\n delete this.unselectHelper\n }\n\n onEnter() {\n this.mouseInside = true\n }\n\n onLeave() {\n delete this.mouseInside\n }\n\n onSelect() {\n this.innerElement.classList.add('selected')\n }\n\n onUnselect() {\n this.innerElement.classList.remove('selected')\n }\n}\n"
},
{
"answer_id": 59504665,
"author": "Marcelo Ribeiro",
"author_id": 7043201,
"author_profile": "https://Stackoverflow.com/users/7043201",
"pm_score": 2,
"selected": false,
"text": "const button = document.querySelector('button')\nconst box = document.querySelector('.box');\n\nconst toggle = event => {\n event.stopPropagation();\n \n if (!event.target.closest('.box')) {\n console.log('Click outside');\n\n box.classList.toggle('active');\n\n box.classList.contains('active')\n ? document.addEventListener('click', toggle)\n : document.removeEventListener('click', toggle);\n } else {\n console.log('Click inside');\n }\n}\n\nbutton.addEventListener('click', toggle); .box {\n position: absolute;\n display: none;\n margin-top: 8px;\n padding: 20px;\n background: lightgray;\n}\n\n.box.active {\n display: block;\n} <button>Toggle box</button>\n\n<div class=\"box\">\n <form action=\"\">\n <input type=\"text\">\n <button type=\"button\">Search</button>\n </form>\n</div>"
},
{
"answer_id": 61892470,
"author": "JBarros",
"author_id": 4044566,
"author_profile": "https://Stackoverflow.com/users/4044566",
"pm_score": -1,
"selected": false,
"text": "mouseleave(function())"
},
{
"answer_id": 62657409,
"author": "Илья Зеленько",
"author_id": 5286034,
"author_profile": "https://Stackoverflow.com/users/5286034",
"pm_score": 4,
"selected": false,
"text": "document.addEventListener('click', ({ target }) => {\n if (!target.closest('#menupop')) {\n document.querySelector('#menupop').style.display = 'none'\n }\n}) #menupop {\n width: 300px;\n height: 300px;\n background-color: red;\n} <div id=\"menupop\">\nclicking outside will close this\n</div>"
},
{
"answer_id": 63617118,
"author": "Mu-Tsun Tsai",
"author_id": 9953396,
"author_profile": "https://Stackoverflow.com/users/9953396",
"pm_score": 2,
"selected": false,
"text": "onclickout .addEventListener('clickout') .on('clickout') v-on:clickout addEventListener <div onclickout=\"console.log('clickout detected')\">...</div>\n document.getElementById('myId').addEventListener('clickout', myListener);\n $('#myId').on('clickout', myListener);\n <div v-on:clickout=\"open=false\">...</div>\n <div (clickout)=\"close()\">...</div>\n"
},
{
"answer_id": 64103587,
"author": "online Thomas",
"author_id": 2754599,
"author_profile": "https://Stackoverflow.com/users/2754599",
"pm_score": 2,
"selected": false,
"text": "window.clickOutSide = (element, clickOutside, clickInside) => {\n document.addEventListener('click', (event) => {\n if (!element.contains(event.target)) {\n if (typeof clickInside === 'function') {\n clickOutside();\n }\n } else {\n if (typeof clickInside === 'function') {\n clickInside();\n }\n }\n });\n};\n\nwindow.clickOutSide(document.querySelector('.block'), () => alert('clicked outside'), () => alert('clicked inside')); .block {\n width: 400px;\n height: 400px;\n background-color: red;\n} <div class=\"block\"></div>"
},
{
"answer_id": 64342309,
"author": "aksl",
"author_id": 9619861,
"author_profile": "https://Stackoverflow.com/users/9619861",
"pm_score": 0,
"selected": false,
"text": "$(document).click(function(event) {\n var $target = $(event.target);\n if(!$target.closest('#hamburger, a').length &&\n $('#hamburger, a').is(\":visible\")) {\n $('nav').slideToggle();\n }\n});\n"
},
{
"answer_id": 64665817,
"author": "Cezar Augusto",
"author_id": 4902448,
"author_profile": "https://Stackoverflow.com/users/4902448",
"pm_score": 7,
"selected": false,
"text": "event.composedPath() const target = document.querySelector('#myTarget')\n\ndocument.addEventListener('click', (event) => {\n const withinBoundaries = event.composedPath().includes(target)\n\n if (withinBoundaries) {\n target.innerText = 'Click happened inside element'\n } else {\n target.innerText = 'Click happened **OUTSIDE** element'\n } \n}) /* just to make it good looking. you don't need this */\n#myTarget {\n margin: 50px auto;\n width: 500px;\n height: 500px;\n background: gray;\n border: 10px solid black;\n} <div id=\"myTarget\">\n click me (or not!)\n</div>"
},
{
"answer_id": 66228309,
"author": "ale",
"author_id": 13005954,
"author_profile": "https://Stackoverflow.com/users/13005954",
"pm_score": 0,
"selected": false,
"text": "<div id=\"container\" style=\"display:none\"><h1>my menu is nice but disappear if i click outside it</h1></div>\n\n<script>\n function printPopup(){\n $(\"#container\").css({ \"display\":\"block\" });\n var remListener = $(document).mouseup(function (e) {\n if ($(e.target).closest(\"#container\").length === 0 && (e.target != $('html').get(0))) \n {\n //alert('closest call');\n $(\"#container\").css({ \"display\":\"none\" });\n remListener.unbind('mouseup'); // isn't it?\n } \n });\n }\n\n printPopup();\n\n</script>\n"
},
{
"answer_id": 67036853,
"author": "tim-mccurrach",
"author_id": 7549907,
"author_profile": "https://Stackoverflow.com/users/7549907",
"pm_score": 4,
"selected": false,
"text": "focusout click focusout focusout event.relatedTarget dialog = document.getElementById(\"dialogElement\")\n\ndialog.addEventListener(\"focusout\", function (event) {\n if (\n // we are still inside the dialog so don't close\n dialog.contains(event.relatedTarget) ||\n // we have switched to another tab so probably don't want to close \n !document.hasFocus() \n ) {\n return;\n }\n dialog.close(); // or whatever logic you want to use to close\n});\n relatedTarget null tabIndex=0"
},
{
"answer_id": 67482066,
"author": "Normajean",
"author_id": 11930305,
"author_profile": "https://Stackoverflow.com/users/11930305",
"pm_score": 2,
"selected": false,
"text": "window.addEventListener('click', close_window = function () {\n if(event.target !== windowEl){\n windowEl.style.display = \"none\";\n window.removeEventListener('click', close_window, false);\n }\n});\n"
},
{
"answer_id": 68273207,
"author": "Sommelier",
"author_id": 7230858,
"author_profile": "https://Stackoverflow.com/users/7230858",
"pm_score": 2,
"selected": false,
"text": "let menu = document.getElementById(\"menu\");\n\ndocument.addEventListener(\"click\", function(){\n // Hide the menus\n menu.style.display = \"none\";\n}, false);\n\ndocument.getElementById(\"menuscontainer\").addEventListener(\"click\", function(e){\n // Show the menus\n menu.style.display = \"block\";\n e.stopPropagation();\n}, false);\n"
},
{
"answer_id": 69855641,
"author": "jameshfisher",
"author_id": 229792,
"author_profile": "https://Stackoverflow.com/users/229792",
"pm_score": 0,
"selected": false,
"text": ":focus-within .sidebar:focus-within tabindex=-1 sidebarEl.focus() document.body.focus() const menuButton = document.querySelector('.menu-button');\nconst sidebar = document.querySelector('.sidebar');\n\nmenuButton.onmousedown = ev => {\n ev.preventDefault();\n (sidebar.contains(document.activeElement) ?\n document.body : sidebar).focus();\n}; * { box-sizing: border-box; }\n\n.sidebar {\n position: fixed;\n width: 15em;\n left: -15em;\n top: 0;\n bottom: 0;\n transition: left 0.3s ease-in-out;\n background-color: #eef;\n padding: 3em 1em;\n}\n\n.sidebar:focus-within {\n left: 0;\n}\n\n.sidebar:focus {\n outline: 0;\n}\n\n.menu-button {\n position: fixed;\n top: 0;\n left: 0;\n padding: 1em;\n background-color: #eef;\n border: 0;\n}\n\nbody {\n max-width: 30em;\n margin: 3em;\n} <body tabindex='-1'>\n <nav class='sidebar' tabindex='-1'>\n Sidebar content\n <input type=\"text\"/>\n </nav>\n <button class=\"menu-button\">☰</button>\n Body content goes here, Lorem ipsum sit amet, etc\n</body>"
},
{
"answer_id": 71228065,
"author": "Felix Furtmayr",
"author_id": 6818578,
"author_profile": "https://Stackoverflow.com/users/6818578",
"pm_score": 0,
"selected": false,
"text": "// demo code\nvar htmlElem = document.getElementById('my-element')\nfunction doSomething(){ console.log('outside click') }\n\n// use the lib\nvar removeListener = new elemOutsideClickListener(htmlElem, doSomething);\n\n// deregister on your wished event\n$scope.$on('$destroy', removeListener);\n\n \nfunction elemOutsideClickListener (element, outsideClickFunc, insideClickFunc) {\n function onClickOutside (e) {\n var targetEl = e.target; // clicked element\n do {\n // click inside\n if (targetEl === element) {\n if (insideClickFunc) insideClickFunc();\n return;\n\n // Go up the DOM\n } else {\n targetEl = targetEl.parentNode;\n }\n } while (targetEl);\n\n // click outside\n if (!targetEl && outsideClickFunc) outsideClickFunc();\n }\n\n window.addEventListener('click', onClickOutside);\n\n return function () {\n window.removeEventListener('click', onClickOutside);\n };\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/152975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
153,021
|
<p>I need to generate an XML file in C#.</p>
<p>I want to write the code that generates this in a file that is mostly XML with code inside of it as I can in an ASP.NET MVC page. </p>
<p>So I want a code file that looks like:</p>
<pre><code><lots of angle brackets...>
<% foreach(data in myData)
{ %>
< <%= data.somefield %>
<% } %>
More angle brackets>
</code></pre>
<p>This would generate my XML file. I would not mind using part of <code>System.Web</code> if someone tells me how I can do it without IIS overhead or kludging a generation of a web file.</p>
<p><strong>I want to use templating and I want templating that is similar to ASP.NET</strong></p>
|
[
{
"answer_id": 153232,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": -1,
"selected": false,
"text": "XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.IndentChars = (\" \");\nusing (XmlWriter writer = XmlWriter.Create(\"books.xml\", settings))\n{\n // Write XML data.\n writer.WriteStartElement(\"book\");\n writer.WriteElementString(\"price\", \"19.95\");\n writer.WriteEndElement();\n writer.Flush();\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5189/"
] |
153,023
|
<p>I'm using C# and Microsoft.Jet.OLEDB.4.0 provider to insert rows into an Access mdb.</p>
<p>Yes, I know Access sucks. It's a huge legacy app, and everything else works OK.</p>
<p>The table has an autonumber column. I insert the rows, but the autonumber column is set to zero.</p>
<p>I Googled the question and read all the articles I could find on this subject. One suggested inserting -1 for the autonumber column, but this didn't work. None of the other suggestions I could find worked.</p>
<p>I am using OleDbParameter's, not concatenating a big SQL text string.</p>
<p>I've tried the insert with and without a transaction. No difference.</p>
<p>How do I get this insert to work (i.e. set the autonumber column contents correctly)?</p>
<p>Thanks very much in advance,</p>
<p>Adam Leffert</p>
|
[
{
"answer_id": 157815,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 3,
"selected": true,
"text": "INSERT INTO (<column list>) ... \n CREATE Table Test1 \n(\n ID INTEGER IDENTITY(0, -2147483648) NOT NULL, \n data_col INTEGER\n);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6783/"
] |
153,046
|
<p>Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more portable way to do it I'd like to know that, too.</p>
|
[
{
"answer_id": 153058,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 5,
"selected": true,
"text": "#include <windows.h>\n\nvoid main()\n{\n ShellExecute(NULL, \"open\", \"http://yourwebpage.com\",\n NULL, NULL, SW_SHOWNORMAL);\n}\n"
},
{
"answer_id": 153059,
"author": "zakker",
"author_id": 23783,
"author_profile": "https://Stackoverflow.com/users/23783",
"pm_score": 2,
"selected": false,
"text": "ShellExecute( NULL, \"open\", \"http://stackoverflow.com\", \"\", \".\", SW_SHOWDEFAULT );\n"
},
{
"answer_id": 6546609,
"author": "nico",
"author_id": 824666,
"author_profile": "https://Stackoverflow.com/users/824666",
"pm_score": 2,
"selected": false,
"text": "#include <unistd.h>\n#include <stdlib.h>\n\nvoid launch(const std::string &url)\n{\n std::string browser = getenv(\"BROWSER\");\n if(browser == \"\") return;\n\n char *args[3];\n args[0] = (char*)browser.c_str();\n args[1] = (char*)url.c_str();\n args[2] = 0;\n\n pid_t pid = fork();\n if(!pid)\n execvp(browser.c_str(), args);\n}\n launch(\"http://example.com\");\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17693/"
] |
153,048
|
<p>I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them.</p>
<p>The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface. </p>
<p>What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?</p>
|
[
{
"answer_id": 153056,
"author": "Grundlefleck",
"author_id": 4120,
"author_profile": "https://Stackoverflow.com/users/4120",
"pm_score": 6,
"selected": true,
"text": "private static final MethodObject methodObject = new MethodObject();\n\npublic static void doSomething(){\n methodObject.doSomething();\n}\n public class MethodObject {\n public void doSomething() {\n // do your thang\n }\n}\n"
},
{
"answer_id": 153119,
"author": "Carlton Jenke",
"author_id": 1215,
"author_profile": "https://Stackoverflow.com/users/1215",
"pm_score": 3,
"selected": false,
"text": "public object GetData()\n{\n object obj1 = GetDataFromWherever();\n object obj2 = TransformData(obj1);\n return obj2;\n} \nprivate static object TransformData(object obj)\n{\n//Do whatever\n}\n"
},
{
"answer_id": 153195,
"author": "asterite",
"author_id": 20459,
"author_profile": "https://Stackoverflow.com/users/20459",
"pm_score": 0,
"selected": false,
"text": "class ClassWithStatics {\n\n private IClassWithStaticsImpl implementation = new DefaultClassWithStaticsImpl();\n\n // Should only be invoked for testing purposes\n public static void overrideImplementation(IClassWithStaticsImpl implementation) {\n ClassWithStatics.implementation = implementation;\n }\n\n public static Foo someMethod() {\n return implementation.someMethod();\n }\n\n}\n overrideImplementation"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4219/"
] |
153,053
|
<h2>The problem:</h2>
<p>We use a program written by our biggest customer to receive orders, book tranports and do other order-related stuff. We have no other chance but to use the program and the customer is very unsupportive when it comes to problems with their program. We just have to live with the program.</p>
<p>Now this program is most of the time extremely slow when using it with two or more user so I tried to look behind the curtain and find the source of the problem.</p>
<h2>Some points about the program I found out so far:</h2>
<ul>
<li>It's written in VB 6.0</li>
<li>It uses a password-protected Access-DB (Access 2000 MDB) that is located a folder on one user's machine.</li>
<li>That folder is shared over the network and used by all other users.</li>
<li>It uses the msjet40.dll version 4.00.9704 to communicate with access. I guess it's ADO?</li>
</ul>
<p>I also used <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="noreferrer">Process Monitor</a> to monitor file access and found out why the program is so slow: it is doing thousands of read operations on the mdb-file, even when the program is idle. Over the network this is of course tremendously slow:</p>
<p><a href="http://img217.imageshack.us/img217/1456/screenshothw5.png" rel="noreferrer">Process Monitor Trace http://img217.imageshack.us/img217/1456/screenshothw5.png</a></p>
<h2>The real question:</h2>
<p>Is there any way to monitor the queries that are responsible for the read activity? Is there a trace flag I can set? Hooking the JET DLL's? I guess the program is doing some expensive queries that are causing JET to read lots of data in the process.</p>
<p>PS: I already tried to put the mdb on our company's file server with the success that accessing it was even slower than over the local share. I also tried changing the locking mechanisms (opportunistic locking) on the client with no success.</p>
<p>I want to know what's going on and need some hard facts and suggestions for our customer's developer to help him/her make the programm faster.</p>
|
[
{
"answer_id": 168993,
"author": "Tim Lara",
"author_id": 3469,
"author_profile": "https://Stackoverflow.com/users/3469",
"pm_score": 0,
"selected": false,
"text": "\"Path to MSACCESS.EXE\" \"Path To foo.mdb\" /wrkgrp \"Path to foo.mdw\"\n"
},
{
"answer_id": 781916,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "showplan.out \\\\HKEY_LOCAL_MACHINE\\SOFTWARE\\MICROSOFT\\JET\\4.0\\Engines\\Debug\n JETSHOWPLAN ON SHOWPLAN.OUT My Documents OFF"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21038/"
] |
153,054
|
<p>I need to change the app name based on what configuration I'm using in Visual Studio. For example, if I'm in Debug configuration, I want the app name to show as 'App_Debug' in the Application field in the Elmah_Error table. Does anyone have any experience with this? Or is there another way to do it?</p>
|
[
{
"answer_id": 317442,
"author": "JamesEggers",
"author_id": 28540,
"author_profile": "https://Stackoverflow.com/users/28540",
"pm_score": 4,
"selected": true,
"text": "HttpRuntime.AppDomainAppId public virtual string ApplicationName\n{\n get \n {\n if (_applicationName == null) { _applicationName = HttpRuntime.AppDomainAppId; }\n return _applicationName;\n }\n set { _applicationName = value; }\n}\n HttpRuntime.AppDomainAppId ErrorLog.Log(ex)"
},
{
"answer_id": 9329364,
"author": "Stephen Kennedy",
"author_id": 397817,
"author_profile": "https://Stackoverflow.com/users/397817",
"pm_score": 6,
"selected": false,
"text": "applicationName errorLog <elmah> <errorLog type=\"Elmah.SqlErrorLog, Elmah\" \n connectionStringName=\"connectionString\" applicationName=\"myApp\" />\n Elmah.axd"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
] |
153,061
|
<p>I'm currently writing an edit-in-place script for MooTools and I'm a little stumped as to how I can make it degrade gracefully without JavaScript while still having some functionality. I would like to use progressive enhancement in some way. I'm not looking for code, but more a concept as to how one would approach the situation. If you have any ideas or know of any edit-in-place scripts that degrade gracefully, please share.</p>
|
[
{
"answer_id": 153214,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<li>\n <span id=\"editable\">Editable text</span> <a class=\"edit_button\"> </a>\n</li>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13281/"
] |
153,062
|
<p>How do I escape '<' and '>' character in sed.</p>
<p>I have some xml files which needs some text between the tags to be replaced. How do I escape the '>' and '<' characters.</p>
<p>The problem with > and < is it has special meaning in the shell to redirect the output to a file. So backslash doesn't work.</p>
|
[
{
"answer_id": 153070,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 0,
"selected": false,
"text": "sed -re 's@(<TAG.*?>).*?(</TAG>)@\\1hi\\2@' test.xml\n"
},
{
"answer_id": 153075,
"author": "cnu",
"author_id": 1448,
"author_profile": "https://Stackoverflow.com/users/1448",
"pm_score": 4,
"selected": true,
"text": "$ sed -i \"s/>foo</>bar</g\" file\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1448/"
] |
153,065
|
<p>I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example:</p>
<pre><code>void function(MESSAGE_ID id, void* param)
{
if(id == FOO) {
int real_param = (int)param;
// ...
}
}
</code></pre>
<p>Of course, on a 64 bit machine, I get the error:</p>
<pre><code>error: cast from 'void*' to 'int' loses precision
</code></pre>
<p>I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?</p>
|
[
{
"answer_id": 153077,
"author": "Milan Babuškov",
"author_id": 14690,
"author_profile": "https://Stackoverflow.com/users/14690",
"pm_score": 7,
"selected": true,
"text": "intptr_t uintptr_t #if defined(__BORLANDC__)\n typedef unsigned char uint8_t;\n typedef __int64 int64_t;\n typedef unsigned long uintptr_t;\n#elif defined(_MSC_VER)\n typedef unsigned char uint8_t;\n typedef __int64 int64_t;\n#else\n #include <stdint.h>\n#endif\n stdint.h"
},
{
"answer_id": 153083,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 4,
"selected": false,
"text": "uintptr_t"
},
{
"answer_id": 153243,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "uintptr_t #include <stdint.h> $ cat kk.c\n#include <stdio.h>\nstatic void function(int n, void *p)\n{\n unsigned long z = *(unsigned long *)p;\n printf(\"%d - %lu\\n\", n, z);\n}\n\nint main(void)\n{\n function(1, 2);\n return(0);\n}\n$ rmk kk\n gcc -m64 -g -O -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith \\\n -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \\\n -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE kk.c -o kk \nkk.c: In function 'main':\nkk.c:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast\n$\n main() function() function() unsigned long i = 0x2341;\nfunction(1, &i);\n void * <inttypes.h> stdint.h inttypes.h stdint.h <inttypes.h> <stdint.h>"
},
{
"answer_id": 4143934,
"author": "Michael S.",
"author_id": 342290,
"author_profile": "https://Stackoverflow.com/users/342290",
"pm_score": 2,
"selected": false,
"text": "#include <stdint.h> uintptr_t"
},
{
"answer_id": 8075684,
"author": "Craig Hicks",
"author_id": 1039128,
"author_profile": "https://Stackoverflow.com/users/1039128",
"pm_score": 1,
"selected": false,
"text": "int x = (char*)p - (char*)0;\n"
},
{
"answer_id": 26586211,
"author": "Alexander Oh",
"author_id": 887836,
"author_profile": "https://Stackoverflow.com/users/887836",
"pm_score": 7,
"selected": false,
"text": "#include <cstdint>\nvoid *p;\nauto i = reinterpret_cast<std::uintptr_t>(p);\n uintptr_t intptr_t <stdint.h> std <cstdint> #include <cstdint>\nstd::uintptr_t i;\n extern \"C\" {\n#include <stdint.h>\n}\n\nuintptr_t i;\n #include <stdint.h>\nuintptr_t i;\n reinterpret_cast auto i = reinterpret_cast<std::uintptr_t>(p);\n uintptr_t i = reinterpret_cast<uintptr_t>(p);\n uintptr_t i = (uintptr_t)p; // C Version\n"
},
{
"answer_id": 43019398,
"author": "B.Mr.W.",
"author_id": 1953475,
"author_profile": "https://Stackoverflow.com/users/1953475",
"pm_score": 2,
"selected": false,
"text": "#if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */\n# define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))\n# define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))\n#elif !defined(__GNUC__) /* Works for compilers other than LLVM */\n# define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])\n# define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))\n#elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */\n# define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))\n# define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))\n#else /* Generates a warning - but it always works */\n# define SQLITE_INT_TO_PTR(X) ((void*)(X))\n# define SQLITE_PTR_TO_INT(X) ((int)(X))\n#endif\n /*\n** The following macros are used to cast pointers to integers and\n** integers to pointers. The way you do this varies from one compiler\n** to the next, so we have developed the following set of #if statements\n** to generate appropriate macros for a wide range of compilers.\n**\n** The correct \"ANSI\" way to do this is to use the intptr_t type.\n** Unfortunately, that typedef is not available on all compilers, or\n** if it is available, it requires an #include of specific headers\n** that vary from one machine to the next.\n**\n** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on\n** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).\n** So we have to define the macros in different ways depending on the\n** compiler.\n*/\n"
},
{
"answer_id": 49330632,
"author": "Antonio",
"author_id": 2436175,
"author_profile": "https://Stackoverflow.com/users/2436175",
"pm_score": 0,
"selected": false,
"text": "uintptr_t uintmax_t <cstdint> auto real_param = reinterpret_cast<uintmax_t>(param);\n static_assert(sizeof (uintmax_t) >= sizeof (void *) ,\n \"No suitable integer type for conversion from pointer type\");\n"
},
{
"answer_id": 70092093,
"author": "Tomer Shalev",
"author_id": 2779007,
"author_profile": "https://Stackoverflow.com/users/2779007",
"pm_score": 0,
"selected": false,
"text": "template<bool B, class T, class F> struct cond { typedef T type; };\ntemplate<class T, class F> struct cond<false, T, F> { typedef F type;};\nstatic constexpr unsigned int PS = sizeof (void *);\n\nusing uintptr_type = typename cond<\n PS==sizeof(unsigned short), unsigned short ,\n typename cond<\n PS==sizeof(unsigned int), unsigned int,\n typename cond<\n PS==sizeof(unsigned long), unsigned long, unsigned long long>::type>::type>::type;\n\n static uintptr_type ptr_to_int(const void *pointer) { \n return reinterpret_cast<uintptr_type>(pointer); \n}\nstatic void *int_to_ptr(uintptr_type integer) { \n return reinterpret_cast<void *>(integer); \n}\n\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153065",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7136/"
] |
153,079
|
<p>The interop library is slow and needs MS Office installed.
Many times you don't want to install MS Office on servers.</p>
<p>I'd like to use <a href="http://en.wikipedia.org/wiki/Apache_POI" rel="nofollow noreferrer">Apache POI</a>, but I'm on .NET.</p>
<p>I need only to extract the text portion of the files, not creating nor "storing information" in Office files.</p>
<p>I need to tell you that I've got a very large document library, and I can't convert it to newer XML files.</p>
<p>I don't want to write a parser for the binaries files.
A library like Apache POI does this for us. Unfortunately, it is only for the Java platform. Maybe I should consider writing this application in Java.</p>
<p>I am still not finding an open source alternative to POI in .NET, I think I'll write my own application in Java.</p>
|
[
{
"answer_id": 153182,
"author": "ahin4114",
"author_id": 11579,
"author_profile": "https://Stackoverflow.com/users/11579",
"pm_score": 2,
"selected": false,
"text": "System.IO.Packaging XmlDocument"
},
{
"answer_id": 153203,
"author": "Ilya Kochetov",
"author_id": 15329,
"author_profile": "https://Stackoverflow.com/users/15329",
"pm_score": 3,
"selected": true,
"text": "system.io.packaging"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4206/"
] |
153,087
|
<p>I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers?</p>
<p>After a quick google, I found only <a href="http://web.archive.org/web/20061116233324/http://www.softinsight.com/bnoyes/PermaLink.aspx?guid=8edc9d4c-0f2c-4006-8186-a3697ebc7476" rel="noreferrer">the WMI solution</a> and a suggestion to PInvoke GetSecurityInfo</p>
|
[
{
"answer_id": 153146,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 7,
"selected": true,
"text": "const string FILE = @\"C:\\test.txt\";\n\nvar fs = File.GetAccessControl(FILE);\n\nvar sid = fs.GetOwner(typeof(SecurityIdentifier));\nConsole.WriteLine(sid); // SID\n\nvar ntAccount = sid.Translate(typeof(NTAccount));\nConsole.WriteLine(ntAccount); // DOMAIN\\username\n var ntAccount = new NTAccount(\"DOMAIN\", \"username\");\nfs.SetOwner(ntAccount);\n\ntry {\n File.SetAccessControl(FILE, fs);\n} catch (InvalidOperationException ex) {\n Console.WriteLine(\"You cannot assign ownership to that user.\" +\n \"Either you don't have TakeOwnership permissions, or it is not your user account.\"\n );\n throw;\n}\n"
},
{
"answer_id": 58906456,
"author": "Teemo",
"author_id": 6782249,
"author_profile": "https://Stackoverflow.com/users/6782249",
"pm_score": 0,
"selected": false,
"text": "FileInfo fi = new FileInfo(@\"C:\\test.txt\");\nstring user = fi.GetAccessControl().GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5363/"
] |
153,123
|
<p>I am looking for pointers to the solution of the following problem: I have a set of rectangles, whose height is known and x-positions also and I want to pack them in the more compact form. With a little drawing (where all rectangles are of the same width, but the width may vary in real life), i would like, instead of. </p>
<pre><code>-r1-
-r2--
-r3--
-r4-
-r5--
</code></pre>
<p>something like.</p>
<pre><code>-r1- -r3--
-r2-- -r4-
-r5--
</code></pre>
<p>All hints will be appreciated. I am not necessarily looking for "the" best solution.</p>
|
[
{
"answer_id": 153357,
"author": "Jasper",
"author_id": 18702,
"author_profile": "https://Stackoverflow.com/users/18702",
"pm_score": 1,
"selected": false,
"text": "Collection<Rectangle> overlaps (int startx, int endx, Collection<Rectangle> rects){\n...\n}\n Collection<Rectangle> toDraw;\nCollection<Rectangle> drawn;\nforeach (Rectangle r in toDraw){\nCollection<Rectangle> overlapping = overlaps (r.x, r.x+r.width, drawn);\nint y = 0;\nforeach(Rectangle overlapRect in overlapping){\ny += overlapRect.height;\n}\ndrawRectangle(y, Rectangle);\ndrawn.add(r);\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8776/"
] |
153,151
|
<p>I recently upgraded my oracle client to 10g (10.2.0.1.0).</p>
<p>Now when I try to connect to a legacy 8.0 database, I get</p>
<pre><code>ORA-03134: Connections to this server version are no longer supported.
</code></pre>
<p>Is there any workaround for this problem, or do I have to install two clients on my local machine?</p>
|
[
{
"answer_id": 153191,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 4,
"selected": true,
"text": "selecthome.bat C:\\Oracle\\Client1_8i\\bin\\selecthome.bat C:\\Oracle\\Client2_10g\\bin\\selecthome.bat"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
153,152
|
<p>I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes. </p>
<p>How do I resize the iframes to fit the height of the iframes' content?</p>
<p>I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far.</p>
<p><strong>Update:</strong> Please note that content is loaded from other domains, so the <a href="https://en.wikipedia.org/wiki/Same-origin_policy" rel="noreferrer">same-origin policy</a> applies.</p>
|
[
{
"answer_id": 153196,
"author": "Ólafur Waage",
"author_id": 22459,
"author_profile": "https://Stackoverflow.com/users/22459",
"pm_score": -1,
"selected": false,
"text": "parent.document.getElementById(iFrameID).style.height=framedPage.scrollHeight;\n"
},
{
"answer_id": 250275,
"author": "Macho Matt",
"author_id": 1446,
"author_profile": "https://Stackoverflow.com/users/1446",
"pm_score": 3,
"selected": false,
"text": "<script type=”text/javascript”>\n $(document).ready(function() {\n var theFrame = $(”#iFrameToAdjust”, parent.document.body);\n theFrame.height($(document.body).height() + 30);\n });\n</script>\n"
},
{
"answer_id": 362564,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 10,
"selected": true,
"text": " www.foo.com/home.html, which iframes\n |-> www.bar.net/framed.html, which iframes\n |-> www.foo.com/helper.html\n home.html framed.html helper.html Communication options for each page:\n +-------------------------+-----------+-------------+-------------+\n | | home.html | framed.html | helper.html |\n +-------------------------+-----------+-------------+-------------+\n | www.foo.com/home.html | N/A | YES | YES |\n | www.bar.net/framed.html | NO | N/A | YES |\n | www.foo.com/helper.html | YES | YES | N/A |\n +-------------------------+-----------+-------------+-------------+\n framed.html helper.html home.html helper.html framed.html home.html framed.html helper.html home.html framed.html framed.html helper.html framed.html src='' onload helper.html?height=N www.foo.com/home.html <script>\n // Resize iframe to full height\n function resizeIframe(height)\n {\n // \"+60\" is a general rule of thumb to allow for differences in\n // IE & and FF height reporting, can be adjusted as required..\n document.getElementById('frame_name_here').height = parseInt(height)+60;\n }\n</script>\n<iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe>\n www.bar.net/framed.html <body onload=\"iframeResizePipe()\">\n<iframe id=\"helpframe\" src='' height='0' width='0' frameborder='0'></iframe>\n\n<script type=\"text/javascript\">\n function iframeResizePipe()\n {\n // What's the page height?\n var height = document.body.scrollHeight;\n\n // Going to 'pipe' the data to the parent through the helpframe..\n var pipe = document.getElementById('helpframe');\n\n // Cachebuster a precaution here to stop browser caching interfering\n pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random();\n\n }\n</script>\n www.foo.com/helper.html <html> \n<!-- \nThis page is on the same domain as the parent, so can\ncommunicate with it to order the iframe window resizing\nto fit the content \n--> \n <body onload=\"parentIframeResize()\"> \n <script> \n // Tell the parent iframe what height the iframe needs to be\n function parentIframeResize()\n {\n var height = getParam('height');\n // This works as our parent's parent is on our domain..\n parent.parent.resizeIframe(height);\n }\n\n // Helper function, parse param from request string\n function getParam( name )\n {\n name = name.replace(/[\\[]/,\"\\\\\\[\").replace(/[\\]]/,\"\\\\\\]\");\n var regexS = \"[\\\\?&]\"+name+\"=([^&#]*)\";\n var regex = new RegExp( regexS );\n var results = regex.exec( window.location.href );\n if( results == null )\n return \"\";\n else\n return results[1];\n }\n </script> \n </body> \n</html>\n"
},
{
"answer_id": 701521,
"author": "Ahmy",
"author_id": 74298,
"author_profile": "https://Stackoverflow.com/users/74298",
"pm_score": 6,
"selected": false,
"text": "<script language=\"JavaScript\">\n<!--\nfunction autoResize(id){\n var newheight;\n var newwidth;\n\n if(document.getElementById){\n newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;\n newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;\n }\n\n document.getElementById(id).height= (newheight) + \"px\";\n document.getElementById(id).width= (newwidth) + \"px\";\n}\n//-->\n</script>\n\n<iframe src=\"usagelogs/default.aspx\" width=\"100%\" height=\"200px\" id=\"iframe1\" marginheight=\"0\" frameborder=\"0\" onLoad=\"autoResize('iframe1');\"></iframe>\n"
},
{
"answer_id": 3002873,
"author": "Vaughan Rowsell",
"author_id": 362007,
"author_profile": "https://Stackoverflow.com/users/362007",
"pm_score": 2,
"selected": false,
"text": "<link href=\"http://your.site/path/to/css?contents_id=1234&dom_id=iframe_widget\" rel=\"stylesheet\" type=\"text/css\" />
\n<iframe id=\"iframe_widget\" src=\"http://your.site/path/to/content?content_id=1234\" frameborder=\"0\" width=\"100%\" scrolling=\"no\"></iframe>"
},
{
"answer_id": 6197254,
"author": "kaw",
"author_id": 778860,
"author_profile": "https://Stackoverflow.com/users/778860",
"pm_score": 0,
"selected": false,
"text": "<div id=\"wrap\">\n <IFRAME ID=\"frame\" name=\"Main\" src =\"http://www.google.com\" />\n</div>\n <style type=\"text/css\">\n #wrap { width: 130px; height: 130px; padding: 0; overflow: hidden; }\n #frame { width: 900px; height: 600px; border: 1px solid black; }\n #frame { zoom:0.15; -moz-transform:scale(0.15);-moz-transform-origin: 0 0; }\n</style>\n"
},
{
"answer_id": 9356798,
"author": "فيصل خلبوص",
"author_id": 1220267,
"author_profile": "https://Stackoverflow.com/users/1220267",
"pm_score": -1,
"selected": false,
"text": "<a href='#' onClick=\" document.getElementById('myform').src='t2.htm';document.getElementById('myform').width='500px'; document.getElementById('myform').height='400px'; return false\">500x400</a>\n"
},
{
"answer_id": 9796214,
"author": "Tor Händevik",
"author_id": 774043,
"author_profile": "https://Stackoverflow.com/users/774043",
"pm_score": 1,
"selected": false,
"text": "var height = document.body.scrollHeight;\n function getDim () {\n var body = document.body,\n html = document.documentElement;\n\n var bc = body.clientHeight;\n var bo = body.offsetHeight;\n var bs = body.scrollHeight;\n var hc = html.clientHeight;\n var ho = html.offsetHeight;\n var hs = html.scrollHeight;\n\n var h = Math.max(bc, bo, bs, hc, hs, ho);\n\n var bd = getBrowserData();\n\n // Select height property to use depending on browser\n if (bd.isGecko) {\n // FF 11\n h = hc;\n } else if (bd.isChrome) {\n // CH 17\n h = hc;\n } else if (bd.isIE) {\n // IE 9\n h = bs;\n }\n\n return h;\n}\n function resize () {\n // Reset the iframes height to a low value.\n // Otherwise Chrome won't detect the content height of the iframe.\n setIframeHeight(150);\n\n // Delay getting the dimensions because Chrome needs\n // a few moments to get the correct height.\n setTimeout(\"getDimAndResize()\", 100);\n}\n"
},
{
"answer_id": 12202664,
"author": "Omer Arshad",
"author_id": 1636793,
"author_profile": "https://Stackoverflow.com/users/1636793",
"pm_score": 3,
"selected": false,
"text": "$(\"iframe\")\n.attr({\"scrolling\": \"no\", \"src\":\"http://www.someotherlink.com/\"})\n.load(function() {\n $(this).css(\"height\", $(this).contents().height() + \"px\");\n});\n"
},
{
"answer_id": 14486904,
"author": "chad steele",
"author_id": 1669091,
"author_profile": "https://Stackoverflow.com/users/1669091",
"pm_score": 0,
"selected": false,
"text": "function updateLocation(){\n\n var loc = window.location.href;\n window.location.href = loc.replace(/#{.*}#/,\"\") \n + \"#{docHeight:\"+$(document).height() \n + \",windowHeight:\"+$(window).height()\n + \",scrollHeight:\"+$(window).scrollTop()\n +\"}#\";\n\n};\n\n//setInterval(updateLocation,500);\n\n$(window).resize(updateLocation);\n$(window).scroll(updateLocation);\n"
},
{
"answer_id": 18323772,
"author": "webd3sign",
"author_id": 2697914,
"author_profile": "https://Stackoverflow.com/users/2697914",
"pm_score": 1,
"selected": false,
"text": "<html>\n<head>\n<script>\nfunction frameSize(id){\nvar frameHeight;\n\ndocument.getElementById(id).height=0 + \"px\";\nif(document.getElementById){\n newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; \n}\n\ndocument.getElementById(id).height= (frameHeight) + \"px\";\n}\n</script>\n</head>\n\n<body>\n\n<iframe id=\"frame\" src=\"startframe.html\" frameborder=\"0\" marginheight=\"0\" hspace=20 width=\"100%\" \n\nonload=\"javascript:frameSize('frame');\">\n\n<p>This will work, but you need to host it on an http server, you can do it locally. </p>\n</body>\n</html>\n"
},
{
"answer_id": 20509636,
"author": "YellowGlue",
"author_id": 2585688,
"author_profile": "https://Stackoverflow.com/users/2585688",
"pm_score": 0,
"selected": false,
"text": " var iframes = document.getElementsByTagName(\"iframe\");\n for(var i = 0, len = iframes.length; i<len; i++){\n window.frames[i].onload = function(_i){\n return function(){\n iframes[_i].style.height = window.frames[_i].document.body.scrollHeight + \"px\";\n }\n }(i);\n }\n"
},
{
"answer_id": 20777751,
"author": "ddlab",
"author_id": 1150871,
"author_profile": "https://Stackoverflow.com/users/1150871",
"pm_score": 2,
"selected": false,
"text": "iframe {border:0; overflow:hidden;}\n $(document).ready(function(){\n $(\"iframe\").load( function () {\n var c = (this.contentWindow || this.contentDocument);\n if (c.document) d = c.document;\n var ih = $(d).outerHeight();\n var iw = $(d).outerWidth();\n $(this).css({\n height: ih,\n width: iw\n });\n });\n});\n"
},
{
"answer_id": 24179165,
"author": "Selvamani",
"author_id": 1514776,
"author_profile": "https://Stackoverflow.com/users/1514776",
"pm_score": 3,
"selected": false,
"text": "window.postMessage(message, targetOrigin); window.parent.postMessage(\"Hello From IFrame\", \"*\"); \n window.parent.postMessage(\"Hello From IFrame\", \"http://foo.com\");\n // Here \"addEventListener\" is for standards-compliant web browsers and \"attachEvent\" is for IE Browsers.\nvar eventMethod = window.addEventListener ? \"addEventListener\" : \"attachEvent\";\nvar eventer = window[eventMethod];\n\n\nvar messageEvent = eventMethod == \"attachEvent\" ? \"onmessage\" : \"message\";\n\n// Listen to message from child IFrame window\neventer(messageEvent, function (e) {\n alert(e.data);\n // Do whatever you want to do with the data got from IFrame in Parent form.\n}, false); \n eventer(messageEvent, function (e) {}) if (e.origin == 'http://iframe.example.com') {\n alert(e.data); \n // Do whatever you want to do with the data got from IFrame in Parent form.\n}\n window.parent.postMessage('{\"key\":\"value\"}','*');\n eventer(messageEvent, function (e) {\n var data = jQuery.parseJSON(e.data);\n doSomething(data.key);\n }, false);\n"
},
{
"answer_id": 24252773,
"author": "Mario Gonzales Flores",
"author_id": 2360106,
"author_profile": "https://Stackoverflow.com/users/2360106",
"pm_score": 0,
"selected": false,
"text": " <iframe src=\"your_url\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"No\" frameborder=\"0\" hspace=\"0\" vspace=\"0\" id=\"containiframe\" onload=\"loaderIframe();\" height=\"100%\" width=\"100%\"></iframe>\n\nfunction loaderIframe(){\nvar heightIframe = $('#containiframe').contents().find('body').height();\n$('#frame').css(\"height\", heightFrame);\n } \n $(window).resize(function(){\nif($('#containiframe').length !== 0) {\nvar heightIframe = $('#containiframe').contents().find('body').height();\n $('#frame').css(\"height\", heightFrame);\n}\n});\n"
},
{
"answer_id": 28290960,
"author": "Razan Paul",
"author_id": 1037073,
"author_profile": "https://Stackoverflow.com/users/1037073",
"pm_score": 2,
"selected": false,
"text": "<!-- 16:9 aspect ratio -->\n<div class=\"embed-responsive embed-responsive-16by9\">\n <iframe class=\"embed-responsive-item\" src=\"http://www.youtube.com/embed/WsFWhL4Y84Y\"></iframe>\n</div>\n"
},
{
"answer_id": 32621754,
"author": "The Onin",
"author_id": 1325575,
"author_profile": "https://Stackoverflow.com/users/1325575",
"pm_score": -1,
"selected": false,
"text": "<body>\n<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.4.min.js\"></script>\n<style>\niframe {\n width: 100%;\n border: 1px solid black;\n}\n</style>\n<script>\nfunction foo(w, h) {\n $(\"iframe\").css({width: w, height: h});\n return true; // for debug purposes\n}\n</script>\n<iframe src=\"child.html\"></iframe>\n</body>\n <body>\n<script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-2.1.4.min.js\"></script>\n<script>\n$(function() {\n var w = $(\"#container\").css(\"width\");\n var h = $(\"#container\").css(\"height\");\n\n var req = parent.foo(w, h);\n console.log(req); // for debug purposes\n});\n</script>\n<style>\nbody, html {\n margin: 0;\n}\n#container {\n width: 500px;\n height: 500px;\n background-color: red;\n}\n</style>\n<div id=\"container\"></div>\n</body>\n"
},
{
"answer_id": 64110306,
"author": "geekhunger",
"author_id": 4383587,
"author_profile": "https://Stackoverflow.com/users/4383587",
"pm_score": 1,
"selected": false,
"text": "postMessage scrollHeight offsetHeight Math.max iframe.height = 0 scrollHeight requestAnimationFrame getComputedStyle function fit() {\n var iframes = document.querySelectorAll(\"iframe.gh-fit\")\n\n for(var id = 0; id < iframes.length; id++) {\n var win = iframes[id].contentWindow\n var doc = win.document\n var html = doc.documentElement\n var body = doc.body\n var ifrm = iframes[id] // or win.frameElement\n\n if(body) {\n body.style.overflowX = \"scroll\" // scrollbar-jitter fix\n body.style.overflowY = \"hidden\"\n }\n if(html) {\n html.style.overflowX = \"scroll\" // scrollbar-jitter fix\n html.style.overflowY = \"hidden\"\n var style = win.getComputedStyle(html)\n ifrm.width = parseInt(style.getPropertyValue(\"width\")) // round value\n ifrm.height = parseInt(style.getPropertyValue(\"height\"))\n }\n }\n\n requestAnimationFrame(fit)\n}\n\naddEventListener(\"load\", requestAnimationFrame.bind(this, fit))\n <iframe src=\"page.html\" class=\"gh-fit gh-fullwidth\"></iframe> gh-fit gh-fullwidth width: 100%; .gh-fit document.getComputedStyle(iframe)"
},
{
"answer_id": 66190993,
"author": "hanshenrik",
"author_id": 1067003,
"author_profile": "https://Stackoverflow.com/users/1067003",
"pm_score": -1,
"selected": false,
"text": " iframe.addEventListener(\"load\",function(){\n // inlineSize, length, perspectiveOrigin, width\n let heightMax = 0;\n // this seems to work best with images...\n heightMax = Math.max(heightMax,iframe.contentWindow.getComputedStyle(iframe.contentWindow.document.body).perspectiveOrigin.split(\"px\")[0]);\n // this seems to work best with text...\n heightMax = Math.max(heightMax,iframe.contentWindow.document.body.scrollHeight);\n // some large 1920x1080 images always gets a little bit off on firefox =/\n const isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;\n if(isFirefox && heightMax >= 900){\n // grrr..\n heightMax = heightMax + 100;\n }\n\n iframe.style.height = heightMax+\"px\";\n //console.log(heightMax);\n });\n\n"
},
{
"answer_id": 67044630,
"author": "latitov",
"author_id": 11729048,
"author_profile": "https://Stackoverflow.com/users/11729048",
"pm_score": 0,
"selected": false,
"text": "<body onload=\"docResizePipe()\">\n<script>\nvar v = 0;\nconst docResizeObserver = new ResizeObserver(() => {\n docResizePipe();\n});\ndocResizeObserver.observe(document.querySelector(\"body\"));\nfunction docResizePipe() {\n v += 1;\n if (v > 5) {\n return;\n }\n var w = document.body.scrollWidth;\n var h = document.body.scrollHeight;\n window.parent.postMessage([w,h], \"*\");\n}\nsetInterval(function() {\n v -= 1;\n if (v < 0) {\n v = 0;\n }\n}, 300);\n</script>\n <iframe id=\"rpa-frame\" src=\"3.html\" style=\"border: none;\"></iframe>\n<script>\nvar rpaFrame = document.getElementById(\"rpa-frame\");\n\nwindow.addEventListener(\"message\", (event) => {\n var width = event.data[0];\n var height = event.data[1];\n rpaFrame.width = parseInt(width)+60;\n rpaFrame.height = parseInt(height)+60;\n console.log(event);\n}, false);\n</script>\n"
},
{
"answer_id": 69226071,
"author": "Ogglas",
"author_id": 3850405,
"author_profile": "https://Stackoverflow.com/users/3850405",
"pm_score": 0,
"selected": false,
"text": "iFrame Resizer width=\"100%\" iframe iframe iframe <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"description\"\n content=\"Web site\" />\n <title>Test with embedded iframe</title>\n</head>\n<body>\n <noscript>You need to enable JavaScript to run this app.</noscript>\n <div id=\"root\"></div>\n <iframe id=\"ifrm\" src=\"https://localhost:44335/package/details?key=123\" width=\"100%\"></iframe>\n <script type=\"text/javascript\">\n window.addEventListener('message', receiveMessage, false);\n\n function receiveMessage(evt) {\n console.log(\"Got message: \" + JSON.stringify(evt.data) + \" from origin: \" + evt.origin);\n // Do we trust the sender of this message?\n if (evt.origin !== \"https://localhost:44335\") {\n return;\n }\n\n if (evt.data.type === \"frame-resized\") {\n document.getElementById(\"ifrm\").style.height = evt.data.value + \"px\";\n }\n }\n </script>\n</body>\n</html>\n iframe source Create React App HTML JS <!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\" />\n <meta name=\"description\"\n content=\"Web site created using create-react-app\" />\n <title>React App</title>\n</head>\n<body>\n <noscript>You need to enable JavaScript to run this app.</noscript>\n <div id=\"root\"></div>\n <script type=\"text/javascript\">\n //Don't run unless in an iframe\n if (self !== top) {\n var rootHeight;\n setInterval(function () {\n var rootElement = document.getElementById(\"root\");\n if (rootElement) {\n var currentRootHeight = rootElement.offsetHeight;\n //Only send values if height has changed since last time\n if (rootHeight !== currentRootHeight) {\n //postMessage to set iframe height\n window.parent.postMessage({ \"type\": \"frame-resized\", \"value\": currentRootHeight }, '*');\n rootHeight = currentRootHeight;\n }\n }\n }\n , 1000);\n }\n </script>\n</body>\n</html>\n setInterval setInterval iframe postMessage Window.postMessage()"
},
{
"answer_id": 70334190,
"author": "iMath",
"author_id": 1485853,
"author_profile": "https://Stackoverflow.com/users/1485853",
"pm_score": 2,
"selected": false,
"text": "srcdoc iframe <script type=\"text/javascript\">\nvar ro = new ResizeObserver(entries => {\n for (let entry of entries) {\n const cr = entry.contentRect;\n // console.log(window.frameElement);\n window.frameElement.style.height =cr.height +30+ \"px\";\n }\n});\n\nro.observe(document.body);\n</script>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153152",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3842/"
] |
153,156
|
<p>How to count distinct values in a node in XSLT?</p>
<p>Example: I want to count the number of existing countries in Country nodes, in this case, it would be 3.</p>
<pre><code><Artists_by_Countries>
<Artist_by_Country>
<Location_ID>62</Location_ID>
<Artist_ID>212</Artist_ID>
<Country>Argentina</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>4</Location_ID>
<Artist_ID>108</Artist_ID>
<Country>Australia</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>4</Location_ID>
<Artist_ID>111</Artist_ID>
<Country>Australia</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>12</Location_ID>
<Artist_ID>78</Artist_ID>
<Country>Germany</Country>
</Artist_by_Country>
</Artists_by_Countries>
</code></pre>
|
[
{
"answer_id": 153204,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 3,
"selected": false,
"text": "count(//Country[not(following::Country/text() = text())])\n /text() ."
},
{
"answer_id": 153218,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 3,
"selected": false,
"text": "count(//Artist_by_Country[not(Location_ID=preceding-sibling::Artist_by_Country/Location_ID)]/Location_ID)\n"
},
{
"answer_id": 153254,
"author": "Nick Allen",
"author_id": 12918,
"author_profile": "https://Stackoverflow.com/users/12918",
"pm_score": 0,
"selected": false,
"text": "<xsl:for-each select=\"Artists_by_Countries/Artist_by_Country/Country[@distinct='true']\" />\n"
},
{
"answer_id": 153969,
"author": "JeniT",
"author_id": 6739,
"author_profile": "https://Stackoverflow.com/users/6739",
"pm_score": 6,
"selected": true,
"text": "<xsl:key name=\"artists-by-country\" match=\"Artist_by_Country\" use=\"Country\" />\n <Artist_by_Country> /Artists_by_Countries\n /Artist_by_Country\n [generate-id(.) =\n generate-id(key('artists-by-country', Country)[1])]\n count() count(distinct-values(/Artists_by_Countries/Artist_by_Country/Country))\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153156",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1100/"
] |
153,166
|
<p>I'm trying to find out whether there is a way to reliably determine when a managed thread is about to terminate. I'm using a third-party library that includes support for PDF documents and the problem is that in order to use the PDF functionality, I have to explicitly initialize the PDF component, do the work, then explicitly uninitialize the component before the thread terminates. If the uninitialize is not called, exceptions are thrown because unmanaged resources are not being released correctly. Since the thread class is sealed and has no events, I have to wrap the thread instance into a class and only allow instances of this class to do the work. </p>
<p>I should point out that this is part of a shared library used by multiple Windows applications. I may not always have control of threads making calls into this library.</p>
<p>Since a PDF object may be the output of a call to this library, and since the calling thread may do some other work with that object, I don't want to call the cleanup function immediately; I need to try to do it right before the thread terminates. Ideally I'd like to be able to subscribe to something like a Thread.Dispose event, but that's what I'm missing. </p>
|
[
{
"answer_id": 153219,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 2,
"selected": false,
"text": "System.Thread PDFWidget class PDFWidget\n{\n private Thread pdfWorker;\n public void DoPDFStuff()\n {\n pdfWorker = new Thread(new ThreadStart(ProcessPDF));\n pdfWorker.Start();\n }\n\n private void ProcessPDF()\n {\n OtherGuysPDFThingie pdfLibrary = new OtherGuysPDFThingie();\n // Use the library to do whatever...\n pdfLibrary.Cleanup();\n }\n}\n ThreadPool"
},
{
"answer_id": 153428,
"author": "stefano m",
"author_id": 19261,
"author_profile": "https://Stackoverflow.com/users/19261",
"pm_score": 1,
"selected": false,
"text": "//declare a delegate with same firmature of your method\npublic delegete string LongMethodDelegate ();\n\n//register a callback func\nAsyncCallback callbackFunc = new AsyncCallback (this.callTermined); \n\n//create delegate for async operations\nLongMethodDelegate th = new LongMethodDelegate (yourObject.metyodWichMakeWork);\n\n//invoke method asnync.\n// pre last parameter is callback delegate.\n//the last parameter is an object wich you re-find in your callback function. to recovery return value, we assign delegate itSelf, see \"callTermined\" method\nlongMethod.beginInvoke(callbackFunc,longMethod); \n\n//follow function is called at the end of thr method\npublic static void callTermined(IAsyincResult result) {\nLongMethodDelegate method = (LongMethodDelegate ) result.AsyncState; \nstring output = method.endInvoke(result);\nConsole.WriteLine(output);\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22239/"
] |
153,183
|
<p>I am working on the admin section of a new rails app and i'm trying to setup some routes to do things "properly". I have the following controller:</p>
<pre><code>class Admin::BlogsController < ApplicationController
def index
@blogs = Blog.find(:all)
end
def show
@blog = Blog.find(params[:id])
end
...
end
</code></pre>
<p>in routes.rb:</p>
<pre><code>map.namespace :admin do |admin|
admin.resources :blogs
end
</code></pre>
<p>in views/admin/blogs/index.html.erb:</p>
<pre><code><% for blog in @blogs %>
<%= link_to 'Delete', admin_blog(blog), :method => :delete
<% end %>
</code></pre>
<p>i have verified that the routes exist:</p>
<pre><code>admin_blogs GET /admin/blogs {:action => "index", :controller=>"admin/blogs"}
admin_blog GET /admin/blogs/:id {:action => "show", :controller => "admin/blogs"}
....
</code></pre>
<p>but when i try to view <a href="http://localhost:3000/admin/blogs" rel="nofollow noreferrer">http://localhost:3000/admin/blogs</a> i get this error:</p>
<pre><code>undefined method 'admin_blog' for #<ActionView::Base:0xb7213da8>
</code></pre>
<p>where am i going wrong and why?</p>
|
[
{
"answer_id": 153228,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 2,
"selected": false,
"text": "admin_blog_path(blog) \n blog_path(blog)\n"
},
{
"answer_id": 153245,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 4,
"selected": true,
"text": "<%= link_to 'Delete', admin_blog_path(blog), :method => :delete %>\n"
},
{
"answer_id": 688244,
"author": "Paulo Delgado",
"author_id": 1864,
"author_profile": "https://Stackoverflow.com/users/1864",
"pm_score": 1,
"selected": false,
"text": "class Admin::BlogsController < ApplicationController\n class Admin::BlogsController < Admin::ApplicationController\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18811/"
] |
153,227
|
<p>When I call</p>
<pre><code>help(Mod.Cls.f)
</code></pre>
<p>(Mod is a C extension module), I get the output</p>
<pre>Help on method_descriptor:
f(...)
doc_string</pre>
<p>What do I need to do so that the help output is of the form</p>
<pre>Help on method f in module Mod:
f(x, y, z)
doc_string</pre>
<p>like it is for random.Random.shuffle, for example?</p>
<p>My PyMethodDef entry is currently:</p>
<pre><code>{ "f", f, METH_VARARGS, "doc_string" }
</code></pre>
|
[
{
"answer_id": 153284,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 3,
"selected": true,
"text": ">>> help(range)\nHelp on built-in function range in module __builtin__:\n\nrange(...)\n range([start,] stop[, step]) -> list of integers\n\n...\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11828/"
] |
153,234
|
<p>The thing I've found about TDD is that its takes time to get your tests set up and being naturally lazy I always want to write as little code as possible. The first thing I seem do is test my constructor has set all the properties but is this overkill?</p>
<p>My question is to what level of granularity do you write you unit tests at?</p>
<p>..and is there a case of testing too much?</p>
|
[
{
"answer_id": 153429,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "TestFixture [TestFixture]\npublic class Test_MyObject_SomeProperty : PropertyTest<int>\n{\n\n private MyObject obj = null;\n\n public override void SetUp() { obj = new MyObject(); }\n public override void TearDown() { obj = null; }\n\n public override int Get() { return obj.SomeProperty; }\n public override Set(int value) { obj.SomeProperty = value; }\n\n public override IEnumerable<int> SomeValidValues() { return new List() { 1,3,5,7 }; }\n public override IEnumerable<int> SomeInvalidValues() { return new List() { 2,4,6 }; }\n\n}\n"
},
{
"answer_id": 759143,
"author": "j_random_hacker",
"author_id": 47984,
"author_profile": "https://Stackoverflow.com/users/47984",
"pm_score": 4,
"selected": false,
"text": "int square(int x) void setX(int newX) x obj.y obj.z obj.setX(42);"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153234",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1116/"
] |
153,248
|
<p>I'm trying to create Excel 2007 Documents programmatically. Now, there are two ways I've found:</p>
<ul>
<li>Manually creating the XML, as outlined in <a href="https://stackoverflow.com/questions/150339/generating-an-excel-file-in-aspnet#150368">this post</a></li>
<li>Using a Third Party Library like <a href="http://www.codeplex.com/ExcelPackage" rel="nofollow noreferrer">ExcelPackage</a>.</li>
</ul>
<p>Currently, I use ExcelPackage, which has some really serious drawbacks and issues. As I do not need to create overly complex Excel sheets (the most "complicated" thing is that I explicitely need to set a cell type to numeric or text), I 'm looking towards Option 1 next, but I just wonder if there are any other good and supported ways to generate Excel 2007 Sheets? Bonus Points if they can be created without having to save them to the harddrive, i.e. generate and directly output them into a stream.</p>
<p>.net 3.0 is the target here, no 3.5 goodness :(</p>
<p><strong>Edit:</strong> Thanks so far. The XML SDK is indeed 3.5 only, but Russian Roulet... erm... COM Interop is also something I want to avoid whenever possible, especially since Excel 2007 has a somewhat complicated but still rather easy to create document format. I'll have a look at the various links and hints posted.</p>
|
[
{
"answer_id": 153277,
"author": "Compile This",
"author_id": 4048,
"author_profile": "https://Stackoverflow.com/users/4048",
"pm_score": 4,
"selected": true,
"text": "MemoryStream"
},
{
"answer_id": 155072,
"author": "BKimmel",
"author_id": 13776,
"author_profile": "https://Stackoverflow.com/users/13776",
"pm_score": 0,
"selected": false,
"text": "Set myxlapp = CreateObject(\"Excel.Application\")\nSet mywb = myxlapp.Workbooks.Add\nmyxlapp.Visible = true\n"
},
{
"answer_id": 155189,
"author": "CtrlDot",
"author_id": 19487,
"author_profile": "https://Stackoverflow.com/users/19487",
"pm_score": 1,
"selected": false,
"text": "On Error Resume Next\nSet myxlApp = GetObject(, \"Excel.Application\")\nIf Err.Number <> 0 Then\n Err.Clear\n Set myxlApp = CreateObject(\"Excel.Application\")\n If Err.Number <> 0 Then\n ' return False, show message, etc.\n End If\nEnd If\n"
},
{
"answer_id": 156705,
"author": "Tometzky",
"author_id": 15862,
"author_profile": "https://Stackoverflow.com/users/15862",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<title>Wnioski</title>\n<style type=\"text/css\">\n<!--\nbr { mso-data-placement: same-cell; }\ntd { mso-number-format: \\@; mso-displayed-decimal-separator: \".\"; }\n-->\n</style>\n\n<table>\n<tr style=\"height:15.0pt\">\n<td style=\"mso-number-format: general\">474</td>\n<td>474</td>\n\n<tr>\n<td>data2</td>\n<td>data3</td>\n\n<tr>\n<td style=\"mso-number-format: "yyyy-mm-dd"\">2008-10-01</td>\n<td style=\"mso-number-format: standard\">0.00</td>\n\n<tr>\n<td style=\"mso-number-format: general\">line1<br>line2<br>line3</td>\n<td></td>\n\n</table>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
153,266
|
<p>In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number.
e.g long x = 0l;</p>
<p>How can I tell the C# compiler that a number is a byte?</p>
|
[
{
"answer_id": 153271,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 3,
"selected": false,
"text": "byte b = (byte) 123; \n byte b = 123;\n int a = 42;\nbyte b = (byte) a;\n"
},
{
"answer_id": 153280,
"author": "casademora",
"author_id": 5619,
"author_profile": "https://Stackoverflow.com/users/5619",
"pm_score": 2,
"selected": false,
"text": "byte b = (byte)300;\n"
},
{
"answer_id": 153308,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 1,
"selected": false,
"text": "object someValue = (byte) 123;\n"
},
{
"answer_id": 153310,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": true,
"text": "byte b = (byte) 0x10;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9516/"
] |
153,287
|
<p>I have implemented a simple file upload-download mechanism. When a user clicks a file name, the file is downloaded with these HTTP headers:</p>
<pre><code>HTTP/1.1 200 OK
Date: Tue, 30 Sep 2008 14:00:39 GMT
Server: Microsoft-IIS/6.0
Content-Disposition: attachment; filename=filename.doc;
Content-Type: application/octet-stream
Content-Length: 10754
</code></pre>
<p>I also support Japanese file names. In order to do that, I encode the file name with this java method:</p>
<pre><code>private String encodeFileName(String name) throws Exception{
String agent = request.getHeader("USER-AGENT");
if(agent != null && agent.indexOf("MSIE") != -1){ // is IE
StringBuffer res = new StringBuffer();
char[] chArr = name.toCharArray();
for(int j = 0; j < chArr.length; j++){
if(chArr[j] < 128){ // plain ASCII char
if (chArr[j] == '.' && j != name.lastIndexOf("."))
res.append("%2E");
else
res.append(chArr[j]);
}
else{ // non-ASCII char
byte[] byteArr = name.substring(j, j + 1).getBytes("UTF8");
for(int i = 0; i < byteArr.length; i++){
// byte must be converted to unsigned int
res.append("%").append(Integer.toHexString((byteArr[i]) & 0xFF));
}
}
}
return res.toString();
}
// Firefox/Mozilla
return MimeUtility.encodeText(name, "UTF8", "B");
}
</code></pre>
<p>It worked well so far, until someone found out that it doesn't work well with long file names. For example: <code>あああああああああああああああ2008.10.1あ.doc</code>. If I change one of the single-byte dots to a single-byte underline , or if I remove the first character, it works OK. i.e., it depends on length and URL-encoding of a dot character.
Following are a few examples. </p>
<p>This is broken (<code>あああああああああああああああ2008.10.1あ.doc</code>):</p>
<pre><code>Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008%2E10%2E1%e3%81%82.doc;
</code></pre>
<p>This is OK (<code>あああああああああああああああ2008_10.1あ.doc</code>):</p>
<pre><code>Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008_10%2E1%e3%81%82.doc;
</code></pre>
<p>This is also fine (<code>あああああああああああああああ2008.10.1あ.doc</code>):</p>
<pre><code>Content-Disposition: attachment; filename=%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%82%e3%81%822008%2E10%2E1%e3%81%82.doc;
</code></pre>
<p>Anybody have a clue?</p>
|
[
{
"answer_id": 153400,
"author": "Ovesh",
"author_id": 3751,
"author_profile": "https://Stackoverflow.com/users/3751",
"pm_score": 4,
"selected": true,
"text": "Content-Disposition: attachment; filename=\"%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%82%E3%81%822008.10.1%E3%81%82.doc\"\n"
},
{
"answer_id": 1938772,
"author": "Gavin Brock",
"author_id": 235855,
"author_profile": "https://Stackoverflow.com/users/235855",
"pm_score": 2,
"selected": false,
"text": "http://www.xyz.com/cgi-bin/dynamic.php/あああああああああああああああ2008.10.1あ.doc\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751/"
] |
153,291
|
<p>I have a question at <a href="https://stackoverflow.com/questions/150038/how-to-wire-a-middle-tier-of-objects-to-a-data-tier-consisting-of-a-dataset#151255">SO</a> asking how to wire a middle tier to a DataSet.</p>
<p>I put up an answer showing what I had come up with, but I am not happy with the tight coupling. I have just started to get into testing and find it a good goal for my code.</p>
<p>How would this code be de-coupled to allow for unit testing? </p>
<p>Thank you,<br>
Keith</p>
|
[
{
"answer_id": 237138,
"author": "Thomas Eyde",
"author_id": 3282,
"author_profile": "https://Stackoverflow.com/users/3282",
"pm_score": 0,
"selected": false,
"text": "var order = repository.GetOrderBy(id);\n var dataset = orderDatabase.GetOrderAndDetailsBy(id);\n var order = orderBuilder.CreateOrderAndDetailsFrom(dataset);\n var repository = new OrderRepository(orderDatabase, orderBuilder);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] |
153,354
|
<p>I have the following code that I wrote but it the SQLBindCol does not seem to work correctly (of course I could have screwed up the whole program too!.) The connection works, it creates the table in the DB, addes the record fine and they all look good in SQL Enterprise Manager. So what I need help with is after the comment "Part 3 & 4: Searchs based on criteria." Perhaps I should have done this assignment completely different or is this an acceptable method?</p>
<pre><code>#include <iostream>
#include <cstdio>
#include <string>
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <sqltypes.h>
using namespace std; // to save us having to type std::
const int MAX_CHAR = 1024;
int main ( )
{
SQLCHAR SQLStmt[MAX_CHAR];
char strSQL[MAX_CHAR];
char chrTemp;
SQLVARCHAR rtnFirstName[50];
SQLVARCHAR rtnLastName[50];
SQLVARCHAR rtnAddress[30];
SQLVARCHAR rtnCity[30];
SQLVARCHAR rtnState[3];
SQLDOUBLE rtnSalary;
SQLVARCHAR rtnGender[1];
SQLINTEGER rtnAge;
// Get a handle to the database
SQLHENV EnvironmentHandle;
RETCODE retcode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvironmentHandle );
// Set the SQL environment flags
retcode = SQLSetEnvAttr( EnvironmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER );
// create handle to the SQL database
SQLHDBC ConnHandle;
retcode = SQLAllocHandle( SQL_HANDLE_DBC, EnvironmentHandle, &ConnHandle );
// Open the database using a System DSN
retcode = SQLDriverConnect(ConnHandle,
NULL,
(SQLCHAR*)"DSN=PRG411;UID=myUser;PWD=myPass;",
SQL_NTS,
NULL,
SQL_NTS,
NULL,
SQL_DRIVER_NOPROMPT);
if (!retcode)
{
cout << "SQLConnect() Failed";
}
else
{
// create a SQL Statement variable
SQLHSTMT StatementHandle;
retcode = SQLAllocHandle(SQL_HANDLE_STMT, ConnHandle, &StatementHandle);
// Part 1: Create the Employee table (Database)
do
{
cout << "Create the new table? ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == 'y' || chrTemp == 'Y')
{
strcpy((char *) SQLStmt, "CREATE TABLE [dbo].[Employee]([pkEmployeeID] [int] IDENTITY(1,1) NOT NULL,[FirstName] [varchar](50) NOT NULL,[LastName] [varchar](50) NOT NULL,[Address] [varchar](30) NOT NULL,[City] [varchar](30) NOT NULL,[State] [varchar](3) NOT NULL, [Salary] [double] NOT NULL,[Gender] [varchar](1) NOT NULL, [Age] [int] NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([pkEmployeeID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
}
// Part 2: Hardcode records into the table
do
{
cout << "Add records to the table? ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == 'y' || chrTemp == 'Y')
{
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Mike','Slentz','123 Torrey Dr.','North Clairmont','CA', 48000.00 ,'M',34)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sue','Vander Hayden','46 East West St.','San Diego','CA', 36000.00 ,'F',28)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sharon','Stonewall','756 West Olive Garden Way','Plymouth','MA', 56000.00 ,'F',58)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('James','Bartholemew','777 Praying Way','Falls Church','VA', 51000.00 ,'M',45)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Joe','Smith','111 North 43rd Ave','Peoria','AZ', 44000.00 ,'M', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Michael','Smith','20344 North Swan Park','Phoenix','AZ', 24000.00 ,'M', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Jennifer','Jones','123 West North Ave','Flagstaff','AZ', 40000.00 ,'F', 40)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Cora','York','33rd Park Way Drive','Mayville','MI', 30000.00 ,'F', 61)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
strcpy((char *) SQLStmt, "INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Tom','Jefferson','234 Friendship Way','Battle Creek','MI', 41000.00 ,'M', 31)");
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
}
// Part 3 & 4: Searchs based on criteria
do
{
cout << "1. Display all records in the database" << endl;
cout << "2. Display all records with age greater than 40" << endl;
cout << "3. Display all records with salary over $30K" << endl;
cout << "4. Exit" << endl << endl;
do
{
cout << "Please enter a selection: ";
cin >> chrTemp;
} while (cin.fail());
if (chrTemp == '1')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE");
}
else if (chrTemp == '2')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [AGE] > 40");
}
else if (chrTemp == '3')
{
strcpy((char *) SQLStmt, "SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [Salary] > 30000");
}
if (chrTemp == '1' || chrTemp == '2' || chrTemp == '3')
{
retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);
SQLBindCol(StatementHandle, 1, SQL_C_CHAR, &rtnFirstName, sizeof(rtnFirstName), NULL );
SQLBindCol(StatementHandle, 2, SQL_C_CHAR, &rtnLastName, sizeof(rtnLastName), NULL );
SQLBindCol(StatementHandle, 3, SQL_C_CHAR, &rtnAddress, sizeof(rtnAddress), NULL );
SQLBindCol(StatementHandle, 4, SQL_C_CHAR, &rtnCity, sizeof(rtnCity), NULL );
SQLBindCol(StatementHandle, 5, SQL_C_CHAR, &rtnState, sizeof(rtnState), NULL );
SQLBindCol(StatementHandle, 6, SQL_C_DOUBLE, &rtnSalary, sizeof(rtnSalary), NULL );
SQLBindCol(StatementHandle, 7, SQL_C_CHAR, &rtnGender, sizeof(rtnGender), NULL );
SQLBindCol(StatementHandle, 8, SQL_C_NUMERIC, &rtnAge, sizeof(rtnAge), NULL );
for(;;)
{
retcode = SQLFetch(StatementHandle);
if (retcode == SQL_NO_DATA_FOUND) break;
cout << rtnFirstName << " " << rtnLastName << " " << rtnAddress << " " << rtnCity << " " << rtnState << " " << rtnSalary << " " << rtnGender << "" << rtnAge << endl;
}
}
} while (chrTemp != '4');
SQLFreeStmt(StatementHandle, SQL_CLOSE );
SQLFreeConnect(ConnHandle);
SQLFreeEnv(EnvironmentHandle);
printf( "Done.\n" );
}
return 0;
}
</code></pre>
|
[
{
"answer_id": 153386,
"author": "antik",
"author_id": 1625,
"author_profile": "https://Stackoverflow.com/users/1625",
"pm_score": 2,
"selected": false,
"text": "SQL_SUCCESS SQL_SUCCESS_WITH_INFO SQLGetDiagRec( SQL_HANDLE_STMT, StatementHandle, req, state, &error, (SQLCHAR*) buffer, (SQLINTEGER) MAX_CHAR, (SQLSMALLINT*) &output_length ); SQLGetDiagRec state"
},
{
"answer_id": 155047,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "using namespace std; // to save us having to type std::\n\nconst int MAX_CHAR = 1024;\n\nint main ( )\n{\n SQLSMALLINT RecNumber;\n SQLCHAR * SQLState;\n SQLINTEGER * NativeErrorPtr;\n SQLCHAR * MessageText;\n SQLSMALLINT BufferLength;\n SQLSMALLINT * TextLengthPtr;\n\n SQLCHAR SQLStmt[MAX_CHAR];\n char strSQL[MAX_CHAR];\n char chrTemp;\n\n SQLVARCHAR rtnFirstName[50];\n SQLVARCHAR rtnLastName[50];\n SQLVARCHAR rtnAddress[30];\n SQLVARCHAR rtnCity[30];\n SQLVARCHAR rtnState[3];\n SQLDOUBLE rtnSalary;\n SQLVARCHAR rtnGender[2];\n SQLINTEGER rtnAge;\n\n // Get a handle to the database\n\n SQLHENV EnvironmentHandle;\n RETCODE retcode = SQLAllocHandle( SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvironmentHandle );\n\n // Set the SQL environment flags\n\n retcode = SQLSetEnvAttr( EnvironmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER) SQL_OV_ODBC3, SQL_IS_INTEGER );\n\n // create handle to the SQL database\n\n SQLHDBC ConnHandle;\n retcode = SQLAllocHandle( SQL_HANDLE_DBC, EnvironmentHandle, &ConnHandle );\n\n // Open the database using a System DSN\n\n retcode = SQLDriverConnect(ConnHandle, \n NULL, \n (SQLCHAR*)\"DSN=PRG411;UID=myUser;PWD=myPass;\", \n SQL_NTS,\n NULL, \n SQL_NTS, \n NULL, \n SQL_DRIVER_NOPROMPT);\n if (!retcode) \n {\n cout << \"SQLConnect() Failed\";\n }\n else\n {\n // create a SQL Statement variable\n\n SQLHSTMT StatementHandle;\n retcode = SQLAllocHandle(SQL_HANDLE_STMT, ConnHandle, &StatementHandle);\n\n // Part 1: Create the Employee table (Database)\n\n do\n {\n cout << \"Create the new table? \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == 'y' || chrTemp == 'Y')\n {\n strcpy((char *) SQLStmt, \"CREATE TABLE [dbo].[Employee]([pkEmployeeID] [int] IDENTITY(1,1) NOT NULL,[FirstName] [varchar](50) NOT NULL,[LastName] [varchar](50) NOT NULL,[Address] [varchar](30) NOT NULL,[City] [varchar](30) NOT NULL,[State] [varchar](3) NOT NULL, [Salary] [decimal] NOT NULL,[Gender] [varchar](1) NOT NULL, [Age] [int] NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([pkEmployeeID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n }\n\n // Part 2: Hardcode records into the table\n\n do\n {\n cout << \"Add records to the table? \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == 'y' || chrTemp == 'Y')\n {\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Mike','Slentz','123 Torrey Dr.','North Clairmont','CA', 48000.00 ,'M',34)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sue','Vander Hayden','46 East West St.','San Diego','CA', 36000.00 ,'F',28)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sharon','Stonewall','756 West Olive Garden Way','Plymouth','MA', 56000.00 ,'F',58)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('James','Bartholemew','777 Praying Way','Falls Church','VA', 51000.00 ,'M',45)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Joe','Smith','111 North 43rd Ave','Peoria','AZ', 44000.00 ,'M', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Michael','Smith','20344 North Swan Park','Phoenix','AZ', 24000.00 ,'M', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Jennifer','Jones','123 West North Ave','Flagstaff','AZ', 40000.00 ,'F', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Cora','York','33rd Park Way Drive','Mayville','MI', 30000.00 ,'F', 61)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy((char *) SQLStmt, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Tom','Jefferson','234 Friendship Way','Battle Creek','MI', 41000.00 ,'M', 31)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n }\n\n // Part 3 & 4: Searchs based on criteria\n\n do\n {\n cout << \"1. Display all records in the database\" << endl;\n cout << \"2. Display all records with age 40 or over\" << endl;\n cout << \"3. Display all records with salary $30K or over\" << endl;\n cout << \"4. Exit\" << endl << endl;\n\n do\n {\n cout << \"Please enter a selection: \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == '1')\n {\n strcpy((char *) SQLStmt, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE\");\n }\n else if (chrTemp == '2')\n {\n strcpy((char *) SQLStmt, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [AGE] >= 40\");\n }\n else if (chrTemp == '3')\n {\n strcpy((char *) SQLStmt, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [Salary] >= 30000\");\n }\n\n if (chrTemp == '1' || chrTemp == '2' || chrTemp == '3')\n {\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n //SQLGetDiagRec(SQL_HANDLE_STMT, StatementHandle, RecNumber, SQLState, NativeErrorPtr, (SQLCHAR*) MessageText, (SQLINTEGER) BufferLength, (SQLSMALLINT*) &TextLengthPtr);\n\n SQLBindCol(StatementHandle, 1, SQL_C_CHAR, &rtnFirstName, sizeof(rtnFirstName), NULL );\n SQLBindCol(StatementHandle, 2, SQL_C_CHAR, &rtnLastName, sizeof(rtnLastName), NULL );\n SQLBindCol(StatementHandle, 3, SQL_C_CHAR, &rtnAddress, sizeof(rtnAddress), NULL );\n SQLBindCol(StatementHandle, 4, SQL_C_CHAR, &rtnCity, sizeof(rtnCity), NULL );\n SQLBindCol(StatementHandle, 5, SQL_C_CHAR, &rtnState, sizeof(rtnState), NULL );\n SQLBindCol(StatementHandle, 6, SQL_C_DOUBLE, &rtnSalary, sizeof(rtnSalary), NULL );\n SQLBindCol(StatementHandle, 7, SQL_C_CHAR, &rtnGender, sizeof(rtnGender), NULL );\n SQLBindCol(StatementHandle, 8, SQL_C_LONG, &rtnAge, sizeof(rtnAge), NULL );\n\n for(;;) \n {\n retcode = SQLFetch(StatementHandle);\n if (retcode == SQL_NO_DATA_FOUND) break;\n\n cout << rtnFirstName << \" \" << rtnLastName << \" \" << rtnAddress << \" \" << rtnCity << \" \" << rtnState << \" \" << rtnSalary << \" \" << rtnGender << \" \" << rtnAge << endl;\n }\n\n SQLFreeStmt(StatementHandle, SQL_CLOSE);\n\n }\n } while (chrTemp != '4');\n\n SQLFreeStmt(StatementHandle, SQL_CLOSE );\n SQLFreeHandle(SQL_HANDLE_STMT, StatementHandle);\n\n SQLDisconnect(ConnHandle);\n\n SQLFreeHandle(SQL_HANDLE_DBC, ConnHandle);\n SQLFreeHandle(SQL_HANDLE_ENV, EnvironmentHandle);\n\n printf( \"Done.\\n\" );\n }\n\n return 0;\n}\n"
},
{
"answer_id": 28044976,
"author": "Satheesh",
"author_id": 4473897,
"author_profile": "https://Stackoverflow.com/users/4473897",
"pm_score": 0,
"selected": false,
"text": " #include <iostream>\n #include <cstdio>\n #include <string>\n\n #include <windows.h>\n #include <sql.h>\n #include <sqlext.h>\n #include <sqltypes.h> \n\n using namespace std; // to save us having to type std::\n\n const int MAX_CHAR = 1024;\n\n int main()\n {\n SQLSMALLINT RecNumber;\n SQLCHAR * SQLState;\n SQLINTEGER * NativeErrorPtr;\n SQLCHAR * MessageText;\n SQLSMALLINT BufferLength;\n SQLSMALLINT * TextLengthPtr;\n\n SQLCHAR SQLStmt[MAX_CHAR];\n char strSQL[MAX_CHAR];\n char chrTemp;\n\n SQLVARCHAR rtnFirstName[50];\n SQLVARCHAR rtnLastName[50];\n SQLVARCHAR rtnAddress[30];\n SQLVARCHAR rtnCity[30];\n SQLVARCHAR rtnState[3];\n SQLDOUBLE rtnSalary;\n SQLVARCHAR rtnGender[2];\n SQLINTEGER rtnAge;\n\n // Get a handle to the database\n\n SQLHENV EnvironmentHandle;\n RETCODE retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &EnvironmentHandle);\n\n // Set the SQL environment flags\n HWND desktopHandle = GetDesktopWindow();\n retcode = SQLSetEnvAttr(EnvironmentHandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER);\n\n // create handle to the SQL database\n\n SQLHDBC ConnHandle;\n retcode = SQLAllocHandle(SQL_HANDLE_DBC, EnvironmentHandle, &ConnHandle);\n SQLSetConnectAttr(ConnHandle, SQL_LOGIN_TIMEOUT, (SQLPOINTER)5, 0);\n // Open the database using a System DSN\n\n retcode = SQLDriverConnect(ConnHandle,\n desktopHandle,\n (SQLCHAR*)\"DSN=PRG411;UID=myUser;PWD=myPass;\",\n SQL_NTS,\n NULL,\n SQL_NTS,\n NULL,\n SQL_DRIVER_NOPROMPT);\n if (retcode != SQL_SUCCESS || retcode != SQL_SUCCESS_WITH_INFO)\n {\n cout << \"SQLConnect() Failed\";\n } \n else\n {\n // create a SQL Statement variable\n\n SQLHSTMT StatementHandle;\n retcode = SQLAllocHandle(SQL_HANDLE_STMT, ConnHandle, &StatementHandle);\n\n // Part 1: Create the Employee table (Database)\n\n do\n {\n cout << \"Create the new table? \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == 'y' || chrTemp == 'Y')\n {\n strcpy_s((char *)SQLStmt,1024, \"CREATE TABLE [dbo].[Employee]([pkEmployeeID] [int] IDENTITY(1,1) NOT NULL,[FirstName] [varchar](50) NOT NULL,[LastName] [varchar](50) NOT NULL,[Address] [varchar](30) NOT NULL,[City] [varchar](30) NOT NULL,[State] [varchar](3) NOT NULL, [Salary] [decimal] NOT NULL,[Gender] [varchar](1) NOT NULL, [Age] [int] NOT NULL, CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([pkEmployeeID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n }\n\n // Part 2: Hardcode records into the table\n\n do\n {\n cout << \"Add records to the table? \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == 'y' || chrTemp == 'Y')\n {\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Mike','Slentz','123 Torrey Dr.','North Clairmont','CA', 48000.00 ,'M',34)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sue','Vander Hayden','46 East West St.','San Diego','CA', 36000.00 ,'F',28)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Sharon','Stonewall','756 West Olive Garden Way','Plymouth','MA', 56000.00 ,'F',58)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('James','Bartholemew','777 Praying Way','Falls Church','VA', 51000.00 ,'M',45)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Joe','Smith','111 North 43rd Ave','Peoria','AZ', 44000.00 ,'M', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Michael','Smith','20344 North Swan Park','Phoenix','AZ', 24000.00 ,'M', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Jennifer','Jones','123 West North Ave','Flagstaff','AZ', 40000.00 ,'F', 40)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Cora','York','33rd Park Way Drive','Mayville','MI', 30000.00 ,'F', 61)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n strcpy_s((char *)SQLStmt,1024, \"INSERT INTO employee([FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age]) VALUES ('Tom','Jefferson','234 Friendship Way','Battle Creek','MI', 41000.00 ,'M', 31)\");\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n }\n\n // Part 3 & 4: Searchs based on criteria\n\n do\n {\n cout << \"1. Display all records in the database\" << endl;\n cout << \"2. Display all records with age 40 or over\" << endl;\n cout << \"3. Display all records with salary $30K or over\" << endl;\n cout << \"4. Exit\" << endl << endl;\n\n do\n {\n cout << \"Please enter a selection: \";\n cin >> chrTemp;\n } while (cin.fail());\n\n if (chrTemp == '1')\n {\n strcpy_s((char *)SQLStmt,1024, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE\");\n }\n else if (chrTemp == '2')\n {\n strcpy_s((char *)SQLStmt,1024, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [AGE] >= 40\");\n }\n else if (chrTemp == '3')\n {\n strcpy_s((char *)SQLStmt,1024, \"SELECT [FirstName], [LastName], [Address], [City], [State], [Salary], [Gender],[Age] FROM EMPLOYEE WHERE [Salary] >= 30000\");\n }\n\n if (chrTemp == '1' || chrTemp == '2' || chrTemp == '3')\n {\n retcode = SQLExecDirect(StatementHandle, SQLStmt, SQL_NTS);\n\n //SQLGetDiagRec(SQL_HANDLE_STMT, StatementHandle, RecNumber, SQLState, NativeErrorPtr, (SQLCHAR*) MessageText, (SQLINTEGER) BufferLength, (SQLSMALLINT*) &TextLengthPtr);\n\n SQLBindCol(StatementHandle, 1, SQL_C_CHAR, &rtnFirstName, sizeof(rtnFirstName), NULL);\n SQLBindCol(StatementHandle, 2, SQL_C_CHAR, &rtnLastName, sizeof(rtnLastName), NULL);\n SQLBindCol(StatementHandle, 3, SQL_C_CHAR, &rtnAddress, sizeof(rtnAddress), NULL);\n SQLBindCol(StatementHandle, 4, SQL_C_CHAR, &rtnCity, sizeof(rtnCity), NULL);\n SQLBindCol(StatementHandle, 5, SQL_C_CHAR, &rtnState, sizeof(rtnState), NULL);\n SQLBindCol(StatementHandle, 6, SQL_C_DOUBLE, &rtnSalary, sizeof(rtnSalary), NULL);\n SQLBindCol(StatementHandle, 7, SQL_C_CHAR, &rtnGender, sizeof(rtnGender), NULL);\n SQLBindCol(StatementHandle, 8, SQL_C_LONG, &rtnAge, sizeof(rtnAge), NULL);\n\n for (;;)\n {\n retcode = SQLFetch(StatementHandle);\n if (retcode == SQL_NO_DATA_FOUND) break;\n\n cout << rtnFirstName << \" \" << rtnLastName << \" \" << rtnAddress << \" \" << rtnCity << \" \" << rtnState << \" \" << rtnSalary << \" \" << rtnGender << \" \" << rtnAge << endl;\n }\n\n SQLFreeStmt(StatementHandle, SQL_CLOSE);\n\n }\n } while (chrTemp != '4');\n\n SQLFreeStmt(StatementHandle, SQL_CLOSE);\n SQLFreeHandle(SQL_HANDLE_STMT, StatementHandle);\n\n SQLDisconnect(ConnHandle);\n\n SQLFreeHandle(SQL_HANDLE_DBC, ConnHandle);\n SQLFreeHandle(SQL_HANDLE_ENV, EnvironmentHandle);\n\n printf(\"Done.\\n\");\n }\n\n return 0;\n }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
153,372
|
<p>I am trying to create a StringNameSpaceBinding using the wsadmin tool of Websphere 6.1</p>
<p>Here are the steps i take
set cell [$AdminConfig getid /Cell:cell/]
$AdminConfig create StringNameSpaceBinding $cell { {name bindname} {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }</p>
<p>But when i run this last step i get an error like this:
WASX7015E: Exception running command: "$AdminConfig create StringNameSpaceBinding $cell { {name bindname} {nameInNameSpace Bindings/string} {stringToBind "This is the String value that gets bound"} }"; exception information:
com.ibm.ws.scripting.ScriptingException: WASX7444E: Invalid parameter value "" for parameter "parent config id" on command "create"</p>
<p>Any idea what could be up with this?</p>
<p>Thanks
Damien</p>
|
[
{
"answer_id": 3836682,
"author": "Isaac",
"author_id": 443716,
"author_profile": "https://Stackoverflow.com/users/443716",
"pm_score": 3,
"selected": true,
"text": "set cell [$AdminConfig getid /Cell:cell/]\n cell set cell [$AdminConfig getid /Cell:/]\n"
},
{
"answer_id": 4406507,
"author": "jitendra",
"author_id": 537509,
"author_profile": "https://Stackoverflow.com/users/537509",
"pm_score": 1,
"selected": false,
"text": "cell = AdminConfig.getid('/Cell:/Node:/Server:WebSphere_Portal/')\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612/"
] |
153,381
|
<p>I have to concatenate a bunch of Strings in Javascript and am searching for the fastest way to do so. Let's assume that the Javascript has to create a large XML-"file" that, naturally, consists of many small Strings. So I came up with:</p>
<pre><code> var sbuffer = [];
for (var idx=0; idx<10000; idx=idx+1) {
sbuffer.push(‘<xmltag>Data comes here... bla... </xmltag>’);
}
// Now we "send" it to the browser...
alert(sbuffer.join(”));
</code></pre>
<p>Do not pay any attention to the loop or the other "sophisticated" code which builds the example. </p>
<p>My question is: For an unknown number of Strings, do you have a faster algorithm / method / idea to concatenate many small Strings to a huge one?</p>
|
[
{
"answer_id": 153646,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": 5,
"selected": true,
"text": "sbuffer.push(‘Data comes here... bla... ’); sbuffer[sbuffer.length] = ‘Data comes here... bla... ’; "
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13209/"
] |
153,388
|
<p>I'm really sick of this problem. Google searches always seem to suggest "delete all bpls for the package", "delete all dcus". Sometimes this just-does-not-work. Hopefully I can get some other ideas here.</p>
<p>I have a package written in-house, which had been installed without issue a few months ago. Having made a few changes to the source, I figured it was time to recompile/reinstall the package. Now I get two errors, the first if I choose "install" is</p>
<p><em>Access violation at address 02422108 in module 'dcc100.dll'. Read of address 00000000.</em></p>
<p>...or if I try to build/compile the package, I get</p>
<p><em>[Pascal Fatal Error] F2084 Internal Error: LA33</em></p>
<p>This is one of those Delphi problems that seems to occur time and time again for many of us. Would be great if we could collate a response something along the lines of "any one or combination of these steps <em>might</em> fix it, but if you do <em>all</em> these steps it <em>will</em> fix it...."</p>
<p>At the moment, I've removed all references to the bpl/dcp files for this package, but still getting the same error...</p>
<p>Using BDS2006 (Delphi)</p>
<p><em>Update 01-Oct-2008: I managed to solve this - see my post below. As I can't accept my own answer, I'm not entirely sure what to do here. Obviously these types of issues occur frequently for some people, so I'll leave it open for a while to get other suggestions. Then I guess if someone collates all the info into a super-post, I can accept the answer</em></p>
|
[
{
"answer_id": 156746,
"author": "Graza",
"author_id": 11820,
"author_profile": "https://Stackoverflow.com/users/11820",
"pm_score": 5,
"selected": true,
"text": "TMyClass = class(TComponent)\nprivate\n const ErrStrs: array[TErrEnum] of string\n = ('', //erOK\n 'Invalid user name or password', //erInvUserPass\n 'Trial Period has Expired'); //erTrialExp\nprotected\n ...\npublic\n ...\nend;\n"
},
{
"answer_id": 4734548,
"author": "Biz",
"author_id": 581317,
"author_profile": "https://Stackoverflow.com/users/581317",
"pm_score": 2,
"selected": false,
"text": "TMyArray = array[TErrEnum] of string;\n\nTMyClass = class(TComponent)\nprivate\n const ErrStrs: TMyArray\n = ('', //erOK\n 'Invalid user name or password', //erInvUserPass\n 'Trial Period has Expired'); //erTrialExp\nprotected\n ...\npublic\n ...\nend;\n"
},
{
"answer_id": 24932745,
"author": "TmTron",
"author_id": 1041641,
"author_profile": "https://Stackoverflow.com/users/1041641",
"pm_score": 1,
"selected": false,
"text": "procedure TMyClass<TContainerItem, TTarget>.Foo();\ntype\n TCacheInfo = record\n UniqueList: TStringList;\n UniqueInfo: TUniqueInfo;\n end;\nvar\n CacheInfo: TCacheInfo;\n unit A.pas;\ninterface\ntype\n TTest<T> = class\n public\n type\n TTestProc = procedure (X: T) of object;\n constructor Create(TestProc_: TTestProc = nil);\n end;\n...\n unit B.pas:\n\nuses A;\nvar\n Test: TTest<TObject>;\n TestProc_"
},
{
"answer_id": 27182471,
"author": "SeeMoreGain",
"author_id": 1793348,
"author_profile": "https://Stackoverflow.com/users/1793348",
"pm_score": 0,
"selected": false,
"text": "function X(someString:String) : Boolean; someString := X(someString);"
},
{
"answer_id": 37021664,
"author": "Ash",
"author_id": 2462453,
"author_profile": "https://Stackoverflow.com/users/2462453",
"pm_score": 0,
"selected": false,
"text": " if (DataType in ASet) \n begin\n //do work\n end\n else if (DataType = B)\n begin\n //do work\n end\n else \n begin\n //do work\n end;\n if (DataType = B)\n begin\n //do work\n end\n else if (DataType in ASet) \n begin\n //do work\n end\n else \n begin\n //do work\n end;\n"
},
{
"answer_id": 52420271,
"author": "Christian",
"author_id": 5935208,
"author_profile": "https://Stackoverflow.com/users/5935208",
"pm_score": 0,
"selected": false,
"text": "const cLogFileName : string = 'logfilename.log'; const cLogFileName = 'logfilename.log';"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11820/"
] |
153,394
|
<p>I believe in OO, but not to the point where inappropriate designs/implementations should be used just to be "OO Compliant".</p>
<p>So, how to deal with the Serlvet/EJB/DataContainer layered architecture:</p>
<ul>
<li>Servlets receive requests and call a "business layer" (e.g. session EJBs)</li>
<li>The business layer locates DataContainers from the database and manipulates them to implement the business logic</li>
<li>DataContainers contain no real code, just get/set corresponding to the database.</li>
</ul>
<p>This approach has appeal; the DataContainers are clear in what they do and it's very easy to know where data comes from.</p>
<p>Aside from not being OO, this leads to unclear Business Layer classes that can be hard to name and hard to organize.</p>
<p>Even if we <strong>were</strong> trying to be more "OO" (e.g. putting some of these methods in the DataConatiners), some of these operations operate on more than one set of data.</p>
<p>How do you keep your Business Layer from getting confusingly procedural, but without polluting your DataContainers with business logic?</p>
<h3>Example</h3>
<pre><code>class UserServlet {
handleRequest() {
String id = request.get("id");
String name = request.get("name");
if (UserBizLayer.updateUserName(id,name))
response.setStatus(OK);
else
response.setStatus(BAD_REQUEST);
}
}
class UseBizLayer {
updateUserName(String id, String name) {
long key = toLong(id);
user = userDAO.find(key);
if user == null
return false;
if (!validateUserName(name))
return false;
user.setName(name);
userDAO.update(user);
return true;
}
validateUserName(String name) {
// do some validations and return
}
}
class User {
long key;
String name;
String email;
// imagine getters/setters here
}
</code></pre>
<ul>
<li>We don't want <code>validateUserName</code> on the user, since it only operates on a name; I guess it could go into another class, but then we have <strong>another</strong> procedural "uti" type class</li>
<li>We don't want persistence methods on the User, since there's value in decoupling data structures from their persistence strategy</li>
<li>We don't want business logic in our Servlet, since we may need to re-use that logic elsewhere</li>
<li>We don't want our business logic in our User, as this draws in way too much to the User class, making re-use of the business logic difficult and coupling the user with its persistence strategy</li>
</ul>
<p>I realize this example isn't that bad, but imagine 10 DataContainers and 20 BizLayer objects with several methods each. Imagine that some of those operations aren't "centered" on a particular data container.</p>
<p>How do we keep this from being a procedural mess?</p>
|
[
{
"answer_id": 153510,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "\npublic class UserModel extends DatabaseModel implements XMLable, CRUDdy, Serializable, Fooable, Barloney, Baznatchy, Wibbling, Validating {\n // member fields\n // getters and setters\n // 100 interface methods\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3029/"
] |
153,407
|
<p>I am upgrading a silverlight beta 2 app to RC0 and have a function that translates a point from a child element to it's parent. The purpose of the function is to ensure that an element appears exactly on top of the child even though they are not on the same canvas and don't share a parent.</p>
<p>Here is the current function:</p>
<pre><code> protected Point TranslatePosition(Point current, Panel from, Panel to, MouseEventArgs e)
{
Point rtn = new Point(-1, -1);
// get point relative to existing parent
Point fromPoint = e.GetPosition(from);
// get point relative to new parent
Point toPoint = e.GetPosition(to);
// calculate delta
double deltaX = fromPoint.X - toPoint.X;
double deltaY = fromPoint.Y - toPoint.Y;
// calculate new position
rtn = new Point(current.X - deltaX, current.Y - deltaY);
return rtn;
}
</code></pre>
<p>Notice that it relies on the MouseEventArgs.GetPosition function to get the position relative to existing and new parent. In cases where there is no MouseEventArgs available, we were creating a new instance and passing it in. This was a hack but seemed to work. Now, in RC0, the MouseEventArgs constructor is internal so this hack no longer works.</p>
<p>Any ideas on how to write a method to do the translation of a point in RC0 that doesn't rely on MouseEventArgs.GetPosition? </p>
|
[
{
"answer_id": 154150,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 3,
"selected": true,
"text": "var transform = from.TransformToVisual(to);\nreturn transform.Transform(current);\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21818/"
] |
153,413
|
<p>I'm trying to extract the polygons from placemarks in a KML file. So far so good:</p>
<pre><code>Imports <xmlns:g='http://earth.google.com/kml/2.0'>
Imports System.Xml.Linq
Partial Class Test_ImportPolygons
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim Kml As XDocument = XDocument.Load(Server.MapPath("../kmlimport/ga.kml"))
For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>
Dim Name As String = Placemark.<g:name>.Value
...
Next
End Sub
End Class
</code></pre>
<p>I'd like to capture the entire <code><polygon>...</polygon></code> block as a string. I tried something like this (where the ... is above):</p>
<pre><code> Dim Polygon as String = Placemark.<g:Polygon>.InnerText
</code></pre>
<p>but the XElement object doesn't have an InnerText property, or any equivalent as far as I can tell. How do I grab the raw XML that defines an XElement?</p>
|
[
{
"answer_id": 153486,
"author": "tbrownell",
"author_id": 1981,
"author_profile": "https://Stackoverflow.com/users/1981",
"pm_score": 1,
"selected": false,
"text": "Placemark.ToString()\n"
},
{
"answer_id": 153519,
"author": "Herb Caudill",
"author_id": 239663,
"author_profile": "https://Stackoverflow.com/users/239663",
"pm_score": 2,
"selected": true,
"text": "Placemark.<g:Polygon> For Each Placemark As XElement In Kml.<g:Document>.<g:Folder>.<g:Placemark>\n Dim Name As String = Placemark.<g:name>.Value\n Dim PolygonsXml As String = \"\"\n For Each Polygon As XElement In Placemark.<g:Polygon>\n PolygonsXml &= Polygon.ToString\n Next\n Next\n"
},
{
"answer_id": 153597,
"author": "tbrownell",
"author_id": 1981,
"author_profile": "https://Stackoverflow.com/users/1981",
"pm_score": 0,
"selected": false,
"text": "(string)Placemark.<g:name>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
153,420
|
<p>I'm starting a project using a Restful architecture implemented in Java (using the new JAX-RS standard)</p>
<p>We are planning to develop the GUI with a Flex application. I have already found some problems with this implementation using the HTTPService component (the response error codes, headers access...).</p>
<p>Any of you guys have some experience in a similar project. Is it feasible?</p>
|
[
{
"answer_id": 157532,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 3,
"selected": false,
"text": "HTTPService HTTPService flash.net.* URLLoader URLRequest URLRequestHeader"
},
{
"answer_id": 163228,
"author": "Guerry",
"author_id": 9190,
"author_profile": "https://Stackoverflow.com/users/9190",
"pm_score": 6,
"selected": true,
"text": " // Flex doesn't know how to generate an HTTP DELETE.\n// Fortunately, sMash/Zero will interpret an HTTP POST with\n// an X-Method-Override: DELETE header as a DELETE.\ndeleteTodoHS.headers['X-Method-Override'] = 'DELETE';"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2937/"
] |
153,427
|
<p>I am currently using JUnit 4 and have a need to divide my tests into groups that can be run selectively in any combination. I know TestNG has a feature to annotate tests to assign them to groups, but I can't migrate to TestNG right now. It seems this could easily be accomplished in JUnit with some custom annotations and a custom JUnit TestRunner. I've checked both the JUnit docs and searched the web but couldn't find such a thing. Is anyone aware of such a TestRunner?</p>
<p>Update: Thanks for your replies regarding test suites. I should have addressed these in my original question. Here we go: I don't want to use test suites because they would require me to manually create and manage them, which means touching ALL my tests and arranging them into suites manually (too much work and a maintenance nightmare). All I need to do is run all unit tests, except a few that are really integration tests. So I want to annotate these, and run all others. At other times, I want to just run the integration tests. I also have the need to put a unit test into multiple groups, which is not possible with suites. Hope this helps to clear things up.</p>
<p>Update 2: If JUnit doesn't have this OOB, I'm looking for an Open Source library that adds this to JUnit (annotations + custom JUnit Test Runner).</p>
|
[
{
"answer_id": 153538,
"author": "flicken",
"author_id": 12880,
"author_profile": "https://Stackoverflow.com/users/12880",
"pm_score": 4,
"selected": true,
"text": "@IfProfileValue(name=\"test-groups\", values={\"unit-tests\", \"integration-tests\"})\n public void testWhichRunsForUnitOrIntegrationTestGroups() {\n // ...\n }\n @Category @Prerequisite"
},
{
"answer_id": 153625,
"author": "krakatoa",
"author_id": 12223,
"author_profile": "https://Stackoverflow.com/users/12223",
"pm_score": 2,
"selected": false,
"text": "project/\n src/\n com.example.project/\n tsrc/\n com.example.project/\n com.example.project.tests/\n @RunWith(Suite.class)\n@Suite.SuiteClasses( { \n TestAlpha.class, \n TestBeta.class })\npublic class GreekLetterUnitTests {\n}\n <target name=\"tests.unit\">\n <junit>\n <batchtest>\n <fileset dir=\"tsrc\">\n <include name=\"**/Test*.java\"/>\n <exclude name=\"**/tests/*.java\"/>\n </fileset>\n </batchtest>\n </junit>\n</target>\n<target name=\"tests.integration\">\n <junit>\n <batchtest>\n <fileset dir=\"tsrc\">\n <include name=\"**/tests/Test*.java\"/>\n </fileset>\n </batchtest>\n </junit>\n</target>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13041/"
] |
153,438
|
<p>I have a VB6 COM component which I need to call from my .Net method. I use reflection to create an instance of the COM object and activate it in the following manner:</p>
<pre><code>f_oType = Type.GetTypeFromProgID(MyProgId);
f_oInstance = Activator.CreateInstance(f_oType);
</code></pre>
<p>I need to use GetTypeFromProgID rather than using tlbimp to create a library against the COM DLL as the ProgId of the type I need to instantiate can vary. I then use Type.InvokeMember to call the COM method in my code like:</p>
<pre><code>f_oType.InvokeMember("Process", BindingFlags.InvokeMethod, null, f_oInstance, new object[] { param1, param2, param3, param4 });
</code></pre>
<p>I catch any raised TargetInvocationException's for logging and can get the detailed error description from the TargetInvocationException.InnerException field. However, I know that the COM component uses Error.Raise to generate an error number and I need to somehow get hold of this in my calling .Net application.</p>
<p>The problem seems to stem from the TargetInvocationException not containing the error number as I'd expect if it were a normal COMException so:</p>
<p><em><strong>How can I get the Error Number from the COM object in my .Net code?</strong></em></p>
<p>or</p>
<p><em><strong>Can I make this same call in a way that would cause a COMException (containing the error number) rather than a TargetInvocationException when the COM component fails?</strong></em></p>
<p>Please also note that the target platform is .Net 2.0 and I do have access to the VB6 source code but would regard altering the error message raised from VB6 to contain the error code as part of the text to be a bit of a hack.</p>
|
[
{
"answer_id": 153538,
"author": "flicken",
"author_id": 12880,
"author_profile": "https://Stackoverflow.com/users/12880",
"pm_score": 4,
"selected": true,
"text": "@IfProfileValue(name=\"test-groups\", values={\"unit-tests\", \"integration-tests\"})\n public void testWhichRunsForUnitOrIntegrationTestGroups() {\n // ...\n }\n @Category @Prerequisite"
},
{
"answer_id": 153625,
"author": "krakatoa",
"author_id": 12223,
"author_profile": "https://Stackoverflow.com/users/12223",
"pm_score": 2,
"selected": false,
"text": "project/\n src/\n com.example.project/\n tsrc/\n com.example.project/\n com.example.project.tests/\n @RunWith(Suite.class)\n@Suite.SuiteClasses( { \n TestAlpha.class, \n TestBeta.class })\npublic class GreekLetterUnitTests {\n}\n <target name=\"tests.unit\">\n <junit>\n <batchtest>\n <fileset dir=\"tsrc\">\n <include name=\"**/Test*.java\"/>\n <exclude name=\"**/tests/*.java\"/>\n </fileset>\n </batchtest>\n </junit>\n</target>\n<target name=\"tests.integration\">\n <junit>\n <batchtest>\n <fileset dir=\"tsrc\">\n <include name=\"**/tests/Test*.java\"/>\n </fileset>\n </batchtest>\n </junit>\n</target>\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15570/"
] |
153,439
|
<p>I'm trying to place 4 of my image containers into a new pane, having a total of 16 images. The jQuery below is what I came up with to do it. The first pane comes out correctly with 4 images in it. But the second has 4 images, plus the 3rd pane. And the 3rd pane has 4 images plus the 4th pane. I don't know exactly why the nesting is occurring. My wrapping can't be causing their index to change. I added css borders to them and it appears to be indexed correctly. How should I be going about this? What I want is to have 1-4 in one pane, 5-8 in another, 9-12, and 13-16. It needs to be dynamic so that I can change the number in each pane, so just doing it in the HTML isn't an option.</p>
<p>A demo of the issue can be seen here: <a href="http://beta.whipplehill.com/mygal/rotate.html" rel="noreferrer">http://beta.whipplehill.com/mygal/rotate.html</a>. I'm using firebug to view the DOM.</p>
<p>Any help would be splentabulous!</p>
<p>The jQuery Code</p>
<pre><code>$(function() {
$(".digi_image:gt(-1):lt(4)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid red");
$(".digi_image:gt(3):lt(8)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid blue");
$(".digi_image:gt(7):lt(12)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid green");
$(".digi_image:gt(11):lt(16)").wrapAll("<div class=\"digi_pane\"></div>").css("border", "2px solid orange");
$(".digi_pane").append("<div style=\"clear: both;\"></div>");
});
</code></pre>
<p>The HTML (abbreviated), but essentially repeated 16 times.</p>
<pre><code><div class="digi_image">
<div class="space_holder"><img src="images/n883470064_4126667_9320.jpg" width="100" /></div>
</div>
</code></pre>
|
[
{
"answer_id": 153624,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 1,
"selected": false,
"text": "$(\".digi_image\").slice(0, 4).wrapAll(\"<div class=\\\"digi_pane\\\"></div>\").css(\"border\", \"2px solid red\");\n$(\".digi_image\").slice(4, 8).wrapAll(\"<div class=\\\"digi_pane\\\"></div>\").css(\"border\", \"2px solid blue\");\n$(\".digi_image\").slice(8, 12).wrapAll(\"<div class=\\\"digi_pane\\\"></div>\").css(\"border\", \"2px solid green\");\n$(\".digi_image\").slice(12, 16).wrapAll(\"<div class=\\\"digi_pane\\\"></div>\").css(\"border\", \"2px solid orange\");\n$(\".digi_pane\").append(\"<div style=\\\"clear: both;\\\"></div>\");\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
153,445
|
<p><strong>Introduction</strong></p>
<p>In my current organisation, we have many desktop and web applications all feeding into each other at some point. When looking after older applications or creating new applications, it's proving very difficult to try and remember which system rely on other systems in order to work. I'm not talking about software dependencies like DLL's and images, I'm talking about entire systems like a Finance system dependant on the HR system etc.</p>
<p><strong>My Question</strong></p>
<p>Which is the one best way to track how one entire system is dependant on another?</p>
<p><sub>The answer can suggest either a method of doing the above, a software package or documentation techniques.</sub></p>
<p><sub>In my particular case, <em>Many</em> means over 20 web and desktop application over a dozen servers.</sub></p>
|
[
{
"answer_id": 6228754,
"author": "MetalOx",
"author_id": 782905,
"author_profile": "https://Stackoverflow.com/users/782905",
"pm_score": 1,
"selected": false,
"text": "digraph g {\n rankdir=LR;\n app1->app2->db1;\n app1->app3;\n}\n"
},
{
"answer_id": 47445354,
"author": "Jeff Silverman",
"author_id": 1928764,
"author_profile": "https://Stackoverflow.com/users/1928764",
"pm_score": 0,
"selected": false,
"text": "netstat -pant netstat -panu"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
153,451
|
<p>I am trying to use <code>WebClient</code> to download a file from web using a WinForms application. However, I really only want to download HTML file. Any other type I will want to ignore.</p>
<p>I checked the <code>WebResponse.ContentType</code>, but its value is always <code>null</code>. </p>
<p>Anyone have any idea what could be the cause?</p>
|
[
{
"answer_id": 153694,
"author": "mdb",
"author_id": 8562,
"author_profile": "https://Stackoverflow.com/users/8562",
"pm_score": 0,
"selected": false,
"text": "Dim wc As New Net.WebClient()\nDim LocalFile As String = IO.Path.Combine(Environment.GetEnvironmentVariable(\"TEMP\"), Guid.NewGuid.ToString)\nwc.DownloadFile(\"http://example.com/somefile\", LocalFile)\nIf Not wc.ResponseHeaders(\"Content-Type\") Is Nothing AndAlso wc.ResponseHeaders(\"Content-Type\") <> \"text/html\" Then\n IO.File.Delete(LocalFile)\nElse\n '//Process the file\nEnd If\n"
},
{
"answer_id": 156101,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class MyWebClient : WebClient\n{\n private CookieContainer _cookieContainer;\n private string _userAgent;\n private int _timeout;\n private WebReponse _response;\n\n public MyWebClient()\n {\n this._cookieContainer = new CookieContainer();\n this.SetTimeout(60 * 1000);\n }\n\n public MyWebClient SetTimeout(int timeout)\n {\n this.Timeout = timeout;\n return this;\n }\n\n public WebResponse Response\n {\n get { return this._response; }\n }\n\n protected override WebRequest GetWebRequest(Uri address)\n {\n WebRequest request = base.GetWebRequest(address);\n\n if (request.GetType() == typeof(HttpWebRequest))\n {\n ((HttpWebRequest)request).CookieContainer = this._cookieContainer;\n ((HttpWebRequest)request).UserAgent = this._userAgent;\n ((HttpWebRequest)request).Timeout = this._timeout;\n }\n\n this._request = request;\n return request;\n }\n\n protected override WebResponse GetWebResponse(WebRequest request)\n {\n this._response = base.GetWebResponse(request);\n return this._response;\n }\n\n protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)\n {\n this._response = base.GetWebResponse(request, result);\n return this._response;\n }\n\n public MyWebClient ServerCertValidation(bool validate)\n {\n if (!validate) ServicePointManager.ServerCertificateValidationCallback += delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };\n return this;\n }\n}\n"
},
{
"answer_id": 156750,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 7,
"selected": true,
"text": "using System;\nusing System.Net;\nstatic class Program\n{\n static void Main()\n {\n using (MyClient client = new MyClient())\n {\n client.HeadOnly = true;\n string uri = \"http://www.google.com\";\n byte[] body = client.DownloadData(uri); // note should be 0-length\n string type = client.ResponseHeaders[\"content-type\"];\n client.HeadOnly = false;\n // check 'tis not binary... we'll use text/, but could\n // check for text/html\n if (type.StartsWith(@\"text/\"))\n {\n string text = client.DownloadString(uri);\n Console.WriteLine(text);\n }\n }\n }\n\n}\n\nclass MyClient : WebClient\n{\n public bool HeadOnly { get; set; }\n protected override WebRequest GetWebRequest(Uri address)\n {\n WebRequest req = base.GetWebRequest(address);\n if (HeadOnly && req.Method == \"GET\")\n {\n req.Method = \"HEAD\";\n }\n return req;\n }\n}\n protected override WebResponse GetWebResponse(WebRequest request)\n{\n WebResponse resp = base.GetWebResponse(request);\n string type = resp.Headers[\"content-type\"];\n // do something with type\n return resp;\n}\n"
},
{
"answer_id": 8377701,
"author": "RandomInsano",
"author_id": 187769,
"author_profile": "https://Stackoverflow.com/users/187769",
"pm_score": 2,
"selected": false,
"text": " Stream connection = new MemoryStream(\"\"); // Just a placeholder\n WebClient wc = new WebClient();\n string contentType;\n try\n {\n connection = wc.OpenRead(current.Url);\n contentType = wc.ResponseHeaders[\"content-type\"];\n }\n catch (Exception)\n {\n // 404 or what have you\n }\n finally\n {\n connection.Close();\n }\n"
},
{
"answer_id": 51447120,
"author": "Greg",
"author_id": 3934764,
"author_profile": "https://Stackoverflow.com/users/3934764",
"pm_score": 1,
"selected": false,
"text": "var result = false;\ntry {\n using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {\n var asyncResult = socket.BeginConnect(yourUri.AbsoluteUri, 80, null, null);\n result = asyncResult.AsyncWaitHandle.WaitOne(100, true);\n socket.Close();\n }\n}\ncatch { }\nreturn result;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
153,460
|
<p>Most applications only have "Restore, Move, Size, Minimize, Maximize and Close", however <i>MS SQL</i> offers extra options "Help, Customize view". Along those lines, is it possible to add to the right click menu of an application in the task bar? </p>
<p>Note: I'm <b>not</b> referring to an icon in the notification area next to the clock.</p>
|
[
{
"answer_id": 153568,
"author": "C. Ross",
"author_id": 16487,
"author_profile": "https://Stackoverflow.com/users/16487",
"pm_score": 1,
"selected": false,
"text": " private const int WMTaskbarRClick = 0x0313;\n\n protected override void WndProc(ref Message m)\n {\n switch (m.Msg)\n {\n case WMTaskbarRClick:\n {\n // Show your own context menu here, i do it like this\n // there's a context menu present on my main form so i use it\n\n MessageBox.Show(\"I see that.\");\n\n break;\n }\n default:\n {\n base.WndProc(ref m);\n break;\n }\n }\n }\n"
},
{
"answer_id": 58160366,
"author": "Mitch",
"author_id": 138200,
"author_profile": "https://Stackoverflow.com/users/138200",
"pm_score": 0,
"selected": false,
"text": "// License MIT 2019 Mitch Gaffigan\n// https://stackoverflow.com/a/58160366/138200\npublic class SysMenu\n{\n private readonly Window Window;\n private readonly List<MenuItem> Items;\n private bool isInitialized;\n private IntPtr NextID = (IntPtr)1000;\n private int StartPosition = 5;\n\n public SysMenu(Window window)\n {\n this.Items = new List<MenuItem>();\n this.Window = window ?? throw new ArgumentNullException(nameof(window));\n this.Window.SourceInitialized += this.Window_SourceInitialized;\n }\n\n class MenuItem\n {\n public IntPtr ID;\n public string Text;\n public Action OnClick;\n }\n\n public void AddSysMenuItem(string text, Action onClick)\n {\n if (string.IsNullOrWhiteSpace(text))\n {\n throw new ArgumentNullException(nameof(text));\n }\n if (onClick == null)\n {\n throw new ArgumentNullException(nameof(onClick));\n }\n\n var thisId = NextID;\n NextID += 1;\n\n var newItem = new MenuItem()\n {\n ID = thisId,\n Text = text,\n OnClick = onClick\n };\n Items.Add(newItem);\n var thisPosition = StartPosition + Items.Count;\n\n if (isInitialized)\n {\n var hwndSource = PresentationSource.FromVisual(Window) as HwndSource;\n if (hwndSource == null)\n {\n return;\n }\n var hSysMenu = GetSystemMenu(hwndSource.Handle, false);\n InsertMenu(hSysMenu, thisPosition, MF_BYPOSITION, thisId, text);\n }\n }\n\n private void Window_SourceInitialized(object sender, EventArgs e)\n {\n var hwndSource = PresentationSource.FromVisual(Window) as HwndSource;\n if (hwndSource == null)\n {\n return;\n }\n\n hwndSource.AddHook(WndProc);\n\n var hSysMenu = GetSystemMenu(hwndSource.Handle, false);\n\n /// Create our new System Menu items just before the Close menu item\n InsertMenu(hSysMenu, StartPosition, MF_BYPOSITION | MF_SEPARATOR, IntPtr.Zero, string.Empty);\n int pos = StartPosition + 1;\n foreach (var item in Items)\n {\n InsertMenu(hSysMenu, pos, MF_BYPOSITION, item.ID, item.Text);\n pos += 1;\n }\n\n isInitialized = true;\n }\n\n private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)\n {\n if (msg == WM_SYSCOMMAND)\n {\n var item = Items.FirstOrDefault(d => d.ID == wParam);\n if (item != null)\n {\n item.OnClick();\n handled = true;\n return IntPtr.Zero;\n }\n }\n\n return IntPtr.Zero;\n }\n\n #region Win32\n\n private const Int32 WM_SYSCOMMAND = 0x112;\n private const Int32 MF_SEPARATOR = 0x800;\n private const Int32 MF_BYPOSITION = 0x400;\n private const Int32 MF_STRING = 0x0;\n\n [DllImport(\"user32.dll\")]\n private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);\n\n [DllImport(\"user32.dll\")]\n private static extern bool InsertMenu(IntPtr hMenu, int wPosition, int wFlags, IntPtr wIDNewItem, string lpNewItem);\n\n #endregion\n}\n internal partial class MainWindow : Window\n{\n public MainWindow()\n {\n var sysMenu = new SysMenu(this);\n sysMenu.AddSysMenuItem(\"Quit\", miQuit_Click);\n sysMenu.AddSysMenuItem(\"Show debug tools\", miShowDebug_Click);\n }\n\n private void miQuit_Click()\n {\n // \"On-Click\" logic here\n }\n\n private void miShowDebug_Click()\n {\n // \"On-Click\" logic here\n }\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1484/"
] |
153,461
|
<p>I notice that Rails 2.2 (currently edge) supports <a href="http://rails.lighthouseapp.com/projects/8994/tickets/1046-http-only-cookies-in-cookiestore" rel="nofollow noreferrer">setting HttpOnly on the session cookie</a>.</p>
<p>Is there a way of setting it on a Rails 2.1 application without moving to edge/2.2?</p>
|
[
{
"answer_id": 153499,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 0,
"selected": false,
"text": "http_only cookies['visits'] = { :value => '20', :http_only => true }\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19079/"
] |
153,482
|
<p>I have a Tapestry application that is serving its page as UTF-8. That is, server responses have header:</p>
<pre><code>Content-type: text/html;charset=UTF-8
</code></pre>
<p>Now within this application there is a single page that should be served with ISO-8859-1 encoding. That is, server response should have this header:</p>
<pre><code>Content-type: text/html;charset=ISO-8859-1
</code></pre>
<p>How to do this? I don't want to change default encoding for whole application.</p>
<p>Based on google searching I have tried following:</p>
<pre><code> @Meta({ "org.apache.tapestry.output-encoding=ISO-8859-1",
"org.apache.tapestry.response-encoding=ISO-8859-1",
"org.apache.tapestry.template-encoding=ISO-8859-1",
"tapestry.response-encoding=ISO-8859-1"})
abstract class MyPage extends BasePage {
@Override
protected String getOutputEncoding() {
return "ISO-8859-1";
}
}
</code></pre>
<p>But neither setting those values with @Meta annotation or overriding getOutputEncoding method works.</p>
<p>I am using Tapestry 4.0.2.</p>
<p>EDIT: I ended up doing this with a Servlet filter with subclassed HttpServletResposeWrapper. The wrapper overrides setContentType() to force required encoding for the response.</p>
|
[
{
"answer_id": 160706,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 3,
"selected": true,
"text": "public class EncodingFilter implements Filter {\nprivate String encoding;\nprivate FilterConfig filterConfig;\n\n/**\n* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)\n*/\npublic void init(FilterConfig fc) throws ServletException {\nthis.filterConfig = fc;\nthis.encoding = filterConfig.getInitParameter(\"encoding\");\n}\n\n/**\n* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)\n*/\npublic void doFilter(ServletRequest req, ServletResponse resp,\nFilterChain chain) throws IOException, ServletException {\nreq.setCharacterEncoding(encoding);\nchain.doFilter(req, resp);\n}\n\n/**\n* @see javax.servlet.Filter#destroy()\n*/\npublic void destroy() {\n}\n\n}\n"
},
{
"answer_id": 4038022,
"author": "Andreas Andreou",
"author_id": 145404,
"author_profile": "https://Stackoverflow.com/users/145404",
"pm_score": 2,
"selected": false,
"text": " @Override\npublic ContentType getResponseContentType() {\n return new ContentType(\"text/html;charset=\" + someCharEncoding);\n}\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1431/"
] |
153,496
|
<p>.Net Compact Framework</p>
<p>Scenario: User is on a screen. Device can't finds a printer and asks the user if they want to try again. If they click "No", the current screen is closed and they are returned to the parent menu screen. If they click the "No" button multiple times, the first click will be used by the No button and the next click will take effect once the screen has completed redrawing. (In effect clicking a menu item which then takes the user to another screen.)</p>
<p>I don't see a good place to put a wait cursor...there isn't much happening when the user clicks "No" except a form closing. But the CF framework is slow to redraw the screen.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 204298,
"author": "tamberg",
"author_id": 3588,
"author_profile": "https://Stackoverflow.com/users/3588",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Windows.Forms;\n\npublic sealed class Event {\n\n bool forwarding;\n\n public event EventHandler Action;\n\n void Forward (object o, EventArgs a) {\n if ((Action != null) && (!forwarding)) {\n forwarding = true;\n Cursor cursor = Cursor.Current;\n try {\n Cursor.Current = Cursors.WaitCursor;\n Action(o, a);\n } finally {\n Cursor.Current = cursor;\n Application.DoEvents();\n forwarding = false;\n }\n }\n }\n\n public EventHandler Handler {\n get {\n return new EventHandler(Forward);\n }\n }\n\n}\n using System;\nusing System.Threading;\nusing System.Windows.Forms;\n\nclass Program {\n\n static void HandleClick (object o, EventArgs a) {\n Console.WriteLine(\"Click\");\n Thread.Sleep(1000);\n }\n\n static void Main () {\n Form f = new Form();\n Button b = new Button();\n //b.Click += new EventHandler(HandleClick);\n Event e = new Event();\n e.Action += new EventHandler(HandleClick);\n b.Click += e.Handler;\n f.Controls.Add(b);\n Application.Run(f);\n }\n\n}\n b.Click += new EventHandler(HandleClick);\n //Event e = new Event();\n //e.Action += new EventHandler(HandleClick);\n //b.Click += e.Handler;\n"
}
] |
2008/09/30
|
[
"https://Stackoverflow.com/questions/153496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/620435/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.